aes_gmac.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * AES-GMAC for IEEE 802.11 BIP-GMAC-128 and BIP-GMAC-256
  4. * Copyright 2015, Qualcomm Atheros, Inc.
  5. */
  6. #include <linux/kernel.h>
  7. #include <linux/types.h>
  8. #include <linux/err.h>
  9. #include <crypto/aead.h>
  10. #include <crypto/aes.h>
  11. #include <net/mac80211.h>
  12. #include "key.h"
  13. #include "aes_gmac.h"
  14. int ieee80211_aes_gmac(struct crypto_aead *tfm, const u8 *aad, u8 *nonce,
  15. const u8 *data, size_t data_len, u8 *mic)
  16. {
  17. struct scatterlist sg[5];
  18. u8 *zero, *__aad, iv[AES_BLOCK_SIZE];
  19. struct aead_request *aead_req;
  20. int reqsize = sizeof(*aead_req) + crypto_aead_reqsize(tfm);
  21. const __le16 *fc;
  22. int ret;
  23. if (data_len < GMAC_MIC_LEN)
  24. return -EINVAL;
  25. aead_req = kzalloc(reqsize + GMAC_MIC_LEN + GMAC_AAD_LEN, GFP_ATOMIC);
  26. if (!aead_req)
  27. return -ENOMEM;
  28. zero = (u8 *)aead_req + reqsize;
  29. __aad = zero + GMAC_MIC_LEN;
  30. memcpy(__aad, aad, GMAC_AAD_LEN);
  31. fc = (const __le16 *)aad;
  32. if (ieee80211_is_beacon(*fc)) {
  33. /* mask Timestamp field to zero */
  34. sg_init_table(sg, 5);
  35. sg_set_buf(&sg[0], __aad, GMAC_AAD_LEN);
  36. sg_set_buf(&sg[1], zero, 8);
  37. sg_set_buf(&sg[2], data + 8, data_len - 8 - GMAC_MIC_LEN);
  38. sg_set_buf(&sg[3], zero, GMAC_MIC_LEN);
  39. sg_set_buf(&sg[4], mic, GMAC_MIC_LEN);
  40. } else {
  41. sg_init_table(sg, 4);
  42. sg_set_buf(&sg[0], __aad, GMAC_AAD_LEN);
  43. sg_set_buf(&sg[1], data, data_len - GMAC_MIC_LEN);
  44. sg_set_buf(&sg[2], zero, GMAC_MIC_LEN);
  45. sg_set_buf(&sg[3], mic, GMAC_MIC_LEN);
  46. }
  47. memcpy(iv, nonce, GMAC_NONCE_LEN);
  48. memset(iv + GMAC_NONCE_LEN, 0, sizeof(iv) - GMAC_NONCE_LEN);
  49. iv[AES_BLOCK_SIZE - 1] = 0x01;
  50. aead_request_set_tfm(aead_req, tfm);
  51. aead_request_set_crypt(aead_req, sg, sg, 0, iv);
  52. aead_request_set_ad(aead_req, GMAC_AAD_LEN + data_len);
  53. ret = crypto_aead_encrypt(aead_req);
  54. kfree_sensitive(aead_req);
  55. return ret;
  56. }
  57. struct crypto_aead *ieee80211_aes_gmac_key_setup(const u8 key[],
  58. size_t key_len)
  59. {
  60. struct crypto_aead *tfm;
  61. int err;
  62. tfm = crypto_alloc_aead("gcm(aes)", 0, CRYPTO_ALG_ASYNC);
  63. if (IS_ERR(tfm))
  64. return tfm;
  65. err = crypto_aead_setkey(tfm, key, key_len);
  66. if (!err)
  67. err = crypto_aead_setauthsize(tfm, GMAC_MIC_LEN);
  68. if (!err)
  69. return tfm;
  70. crypto_free_aead(tfm);
  71. return ERR_PTR(err);
  72. }
  73. void ieee80211_aes_gmac_key_free(struct crypto_aead *tfm)
  74. {
  75. crypto_free_aead(tfm);
  76. }