wep.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * Wired Equivalent Privacy (WEP)
  3. * Copyright (c) 2010, Jouni Malinen <j@w1.fi>
  4. *
  5. * This software may be distributed under the terms of the BSD license.
  6. * See README for more details.
  7. */
  8. #include "utils/includes.h"
  9. #include "utils/common.h"
  10. #include "utils/crc32.h"
  11. #include "common/ieee802_11_defs.h"
  12. #include "wlantest.h"
  13. void wep_crypt(u8 *key, u8 *buf, size_t plen)
  14. {
  15. u32 i, j, k;
  16. u8 S[256];
  17. #define S_SWAP(a,b) do { u8 t = S[a]; S[a] = S[b]; S[b] = t; } while(0)
  18. u8 *pos;
  19. /* Setup RC4 state */
  20. for (i = 0; i < 256; i++)
  21. S[i] = i;
  22. j = 0;
  23. for (i = 0; i < 256; i++) {
  24. j = (j + S[i] + key[i & 0x0f]) & 0xff;
  25. S_SWAP(i, j);
  26. }
  27. /* Apply RC4 to data */
  28. pos = buf;
  29. i = j = 0;
  30. for (k = 0; k < plen; k++) {
  31. i = (i + 1) & 0xff;
  32. j = (j + S[i]) & 0xff;
  33. S_SWAP(i, j);
  34. *pos ^= S[(S[i] + S[j]) & 0xff];
  35. pos++;
  36. }
  37. }
  38. static int try_wep(const u8 *key, size_t key_len, const u8 *data,
  39. size_t data_len, u8 *plain)
  40. {
  41. u32 icv, rx_icv;
  42. u8 k[16];
  43. int i, j;
  44. for (i = 0, j = 0; i < sizeof(k); i++) {
  45. k[i] = key[j];
  46. j++;
  47. if (j >= key_len)
  48. j = 0;
  49. }
  50. os_memcpy(plain, data, data_len);
  51. wep_crypt(k, plain, data_len);
  52. icv = crc32(plain, data_len - 4);
  53. rx_icv = WPA_GET_LE32(plain + data_len - 4);
  54. if (icv != rx_icv)
  55. return -1;
  56. return 0;
  57. }
  58. u8 * wep_decrypt(struct wlantest *wt, const struct ieee80211_hdr *hdr,
  59. const u8 *data, size_t data_len, size_t *decrypted_len)
  60. {
  61. u8 *plain;
  62. struct wlantest_wep *w;
  63. int found = 0;
  64. u8 key[16];
  65. if (dl_list_empty(&wt->wep))
  66. return NULL;
  67. if (data_len < 4 + 4)
  68. return NULL;
  69. plain = os_malloc(data_len - 4);
  70. if (plain == NULL)
  71. return NULL;
  72. dl_list_for_each(w, &wt->wep, struct wlantest_wep, list) {
  73. os_memcpy(key, data, 3);
  74. os_memcpy(key + 3, w->key, w->key_len);
  75. if (try_wep(key, 3 + w->key_len, data + 4, data_len - 4, plain)
  76. == 0) {
  77. found = 1;
  78. break;
  79. }
  80. }
  81. if (!found) {
  82. os_free(plain);
  83. return NULL;
  84. }
  85. *decrypted_len = data_len - 4 - 4;
  86. return plain;
  87. }