2
0

quic_srt_gen.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. struct quic_srt_gen_st {
  13. EVP_MAC *mac;
  14. EVP_MAC_CTX *mac_ctx;
  15. };
  16. /*
  17. * Simple HMAC-SHA256-based stateless reset token generator.
  18. */
  19. QUIC_SRT_GEN *ossl_quic_srt_gen_new(OSSL_LIB_CTX *libctx, const char *propq,
  20. const unsigned char *key, size_t key_len)
  21. {
  22. QUIC_SRT_GEN *srt_gen;
  23. OSSL_PARAM params[3], *p = params;
  24. if ((srt_gen = OPENSSL_zalloc(sizeof(*srt_gen))) == NULL)
  25. return NULL;
  26. if ((srt_gen->mac = EVP_MAC_fetch(libctx, "HMAC", propq)) == NULL)
  27. goto err;
  28. if ((srt_gen->mac_ctx = EVP_MAC_CTX_new(srt_gen->mac)) == NULL)
  29. goto err;
  30. *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, "SHA256", 7);
  31. if (propq != NULL)
  32. *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_PROPERTIES,
  33. (char *)propq, 0);
  34. *p++ = OSSL_PARAM_construct_end();
  35. if (!EVP_MAC_init(srt_gen->mac_ctx, key, key_len, params))
  36. goto err;
  37. return srt_gen;
  38. err:
  39. ossl_quic_srt_gen_free(srt_gen);
  40. return NULL;
  41. }
  42. void ossl_quic_srt_gen_free(QUIC_SRT_GEN *srt_gen)
  43. {
  44. if (srt_gen == NULL)
  45. return;
  46. EVP_MAC_CTX_free(srt_gen->mac_ctx);
  47. EVP_MAC_free(srt_gen->mac);
  48. OPENSSL_free(srt_gen);
  49. }
  50. int ossl_quic_srt_gen_calculate_token(QUIC_SRT_GEN *srt_gen,
  51. const QUIC_CONN_ID *dcid,
  52. QUIC_STATELESS_RESET_TOKEN *token)
  53. {
  54. size_t outl = 0;
  55. unsigned char mac[SHA256_DIGEST_LENGTH];
  56. if (!EVP_MAC_init(srt_gen->mac_ctx, NULL, 0, NULL))
  57. return 0;
  58. if (!EVP_MAC_update(srt_gen->mac_ctx, (const unsigned char *)dcid->id,
  59. dcid->id_len))
  60. return 0;
  61. if (!EVP_MAC_final(srt_gen->mac_ctx, mac, &outl, sizeof(mac))
  62. || outl != sizeof(mac))
  63. return 0;
  64. assert(sizeof(mac) >= sizeof(token->token));
  65. memcpy(token->token, mac, sizeof(token->token));
  66. return 1;
  67. }