crypto.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // SPDX-License-Identifier: GPL-2.0
  2. /* Multipath TCP cryptographic functions
  3. * Copyright (c) 2017 - 2019, Intel Corporation.
  4. *
  5. * Note: This code is based on mptcp_ctrl.c, mptcp_ipv4.c, and
  6. * mptcp_ipv6 from multipath-tcp.org, authored by:
  7. *
  8. * Sébastien Barré <[email protected]>
  9. * Christoph Paasch <[email protected]>
  10. * Jaakko Korkeaniemi <[email protected]>
  11. * Gregory Detal <[email protected]>
  12. * Fabien Duchêne <[email protected]>
  13. * Andreas Seelinger <[email protected]>
  14. * Lavkesh Lahngir <[email protected]>
  15. * Andreas Ripke <[email protected]>
  16. * Vlad Dogaru <[email protected]>
  17. * Octavian Purdila <[email protected]>
  18. * John Ronan <[email protected]>
  19. * Catalin Nicutar <[email protected]>
  20. * Brandon Heller <[email protected]>
  21. */
  22. #include <linux/kernel.h>
  23. #include <crypto/sha2.h>
  24. #include <asm/unaligned.h>
  25. #include "protocol.h"
  26. #define SHA256_DIGEST_WORDS (SHA256_DIGEST_SIZE / 4)
  27. void mptcp_crypto_key_sha(u64 key, u32 *token, u64 *idsn)
  28. {
  29. __be32 mptcp_hashed_key[SHA256_DIGEST_WORDS];
  30. __be64 input = cpu_to_be64(key);
  31. sha256((__force u8 *)&input, sizeof(input), (u8 *)mptcp_hashed_key);
  32. if (token)
  33. *token = be32_to_cpu(mptcp_hashed_key[0]);
  34. if (idsn)
  35. *idsn = be64_to_cpu(*((__be64 *)&mptcp_hashed_key[6]));
  36. }
  37. void mptcp_crypto_hmac_sha(u64 key1, u64 key2, u8 *msg, int len, void *hmac)
  38. {
  39. u8 input[SHA256_BLOCK_SIZE + SHA256_DIGEST_SIZE];
  40. u8 key1be[8];
  41. u8 key2be[8];
  42. int i;
  43. if (WARN_ON_ONCE(len > SHA256_DIGEST_SIZE))
  44. len = SHA256_DIGEST_SIZE;
  45. put_unaligned_be64(key1, key1be);
  46. put_unaligned_be64(key2, key2be);
  47. /* Generate key xored with ipad */
  48. memset(input, 0x36, SHA256_BLOCK_SIZE);
  49. for (i = 0; i < 8; i++)
  50. input[i] ^= key1be[i];
  51. for (i = 0; i < 8; i++)
  52. input[i + 8] ^= key2be[i];
  53. memcpy(&input[SHA256_BLOCK_SIZE], msg, len);
  54. /* emit sha256(K1 || msg) on the second input block, so we can
  55. * reuse 'input' for the last hashing
  56. */
  57. sha256(input, SHA256_BLOCK_SIZE + len, &input[SHA256_BLOCK_SIZE]);
  58. /* Prepare second part of hmac */
  59. memset(input, 0x5C, SHA256_BLOCK_SIZE);
  60. for (i = 0; i < 8; i++)
  61. input[i] ^= key1be[i];
  62. for (i = 0; i < 8; i++)
  63. input[i + 8] ^= key2be[i];
  64. sha256(input, SHA256_BLOCK_SIZE + SHA256_DIGEST_SIZE, hmac);
  65. }
  66. #if IS_MODULE(CONFIG_MPTCP_KUNIT_TEST)
  67. EXPORT_SYMBOL_GPL(mptcp_crypto_hmac_sha);
  68. #endif