xref: /openssl/ssl/quic/quic_srt_gen.c (revision e64ad80c)
1 /*
2  * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 #include "internal/quic_srt_gen.h"
10 #include <openssl/core_names.h>
11 #include <openssl/evp.h>
12 
13 struct quic_srt_gen_st {
14     EVP_MAC         *mac;
15     EVP_MAC_CTX     *mac_ctx;
16 };
17 
18 /*
19  * Simple HMAC-SHA256-based stateless reset token generator.
20  */
21 
ossl_quic_srt_gen_new(OSSL_LIB_CTX * libctx,const char * propq,const unsigned char * key,size_t key_len)22 QUIC_SRT_GEN *ossl_quic_srt_gen_new(OSSL_LIB_CTX *libctx, const char *propq,
23                                     const unsigned char *key, size_t key_len)
24 {
25     QUIC_SRT_GEN *srt_gen;
26     OSSL_PARAM params[3], *p = params;
27 
28     if ((srt_gen = OPENSSL_zalloc(sizeof(*srt_gen))) == NULL)
29         return NULL;
30 
31     if ((srt_gen->mac = EVP_MAC_fetch(libctx, "HMAC", propq)) == NULL)
32         goto err;
33 
34     if ((srt_gen->mac_ctx = EVP_MAC_CTX_new(srt_gen->mac)) == NULL)
35         goto err;
36 
37     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, "SHA256", 7);
38     if (propq != NULL)
39         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_PROPERTIES,
40                                                 (char *)propq, 0);
41     *p++ = OSSL_PARAM_construct_end();
42 
43     if (!EVP_MAC_init(srt_gen->mac_ctx, key, key_len, params))
44         goto err;
45 
46     return srt_gen;
47 
48 err:
49     ossl_quic_srt_gen_free(srt_gen);
50     return NULL;
51 }
52 
ossl_quic_srt_gen_free(QUIC_SRT_GEN * srt_gen)53 void ossl_quic_srt_gen_free(QUIC_SRT_GEN *srt_gen)
54 {
55     if (srt_gen == NULL)
56         return;
57 
58     EVP_MAC_CTX_free(srt_gen->mac_ctx);
59     EVP_MAC_free(srt_gen->mac);
60     OPENSSL_free(srt_gen);
61 }
62 
ossl_quic_srt_gen_calculate_token(QUIC_SRT_GEN * srt_gen,const QUIC_CONN_ID * dcid,QUIC_STATELESS_RESET_TOKEN * token)63 int ossl_quic_srt_gen_calculate_token(QUIC_SRT_GEN *srt_gen,
64                                       const QUIC_CONN_ID *dcid,
65                                       QUIC_STATELESS_RESET_TOKEN *token)
66 {
67     size_t outl = 0;
68     unsigned char mac[SHA256_DIGEST_LENGTH];
69 
70     if (!EVP_MAC_init(srt_gen->mac_ctx, NULL, 0, NULL))
71         return 0;
72 
73     if (!EVP_MAC_update(srt_gen->mac_ctx, (const unsigned char *)dcid->id,
74                         dcid->id_len))
75         return 0;
76 
77     if (!EVP_MAC_final(srt_gen->mac_ctx, mac, &outl, sizeof(mac))
78         || outl != sizeof(mac))
79         return 0;
80 
81     assert(sizeof(mac) >= sizeof(token->token));
82     memcpy(token->token, mac, sizeof(token->token));
83     return 1;
84 }
85