wep.c 2.1 KB

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