xref: /openbsd-src/sys/net80211/ieee80211_crypto_tkip.c (revision 850e275390052b330d93020bf619a739a3c277ac)
1 /*	$OpenBSD: ieee80211_crypto_tkip.c,v 1.9 2008/09/27 15:00:08 damien Exp $	*/
2 
3 /*-
4  * Copyright (c) 2008 Damien Bergamini <damien.bergamini@free.fr>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /*
20  * This code implements the Temporal Key Integrity Protocol (TKIP) defined
21  * in IEEE Std 802.11-2007 section 8.3.2.
22  */
23 
24 #include <sys/param.h>
25 #include <sys/systm.h>
26 #include <sys/mbuf.h>
27 #include <sys/malloc.h>
28 #include <sys/kernel.h>
29 #include <sys/socket.h>
30 #include <sys/endian.h>
31 #include <sys/syslog.h>
32 
33 #include <net/if.h>
34 #include <net/if_dl.h>
35 #include <net/if_media.h>
36 #include <net/if_arp.h>
37 #include <net/if_llc.h>
38 
39 #ifdef INET
40 #include <netinet/in.h>
41 #include <netinet/if_ether.h>
42 #endif
43 
44 #include <net80211/ieee80211_var.h>
45 #include <net80211/ieee80211_crypto.h>
46 
47 #include <crypto/arc4.h>
48 #include <crypto/michael.h>
49 
50 typedef u_int8_t  byte;	/* 8-bit byte (octet) */
51 typedef u_int16_t u16b;	/* 16-bit unsigned word */
52 typedef u_int32_t u32b;	/* 32-bit unsigned word */
53 
54 static void	Phase1(u16b *, const byte *, const byte *, u32b);
55 static void	Phase2(byte *, const byte *, const u16b *, u16b);
56 
57 /* TKIP software crypto context */
58 struct ieee80211_tkip_ctx {
59 	struct rc4_ctx	rc4;
60 	const u_int8_t	*txmic;
61 	const u_int8_t	*rxmic;
62 	u_int16_t	TTAK1[5];
63 	u_int16_t	TTAK2[5];
64 	u_int8_t	TTAK2ok;
65 };
66 
67 /*
68  * Initialize software crypto context.  This function can be overridden
69  * by drivers doing hardware crypto.
70  */
71 int
72 ieee80211_tkip_set_key(struct ieee80211com *ic, struct ieee80211_key *k)
73 {
74 	struct ieee80211_tkip_ctx *ctx;
75 
76 	ctx = malloc(sizeof(*ctx), M_DEVBUF, M_NOWAIT | M_ZERO);
77 	if (ctx == NULL)
78 		return ENOMEM;
79 	/*
80 	 * Use bits 128-191 as the Michael key for AA->SPA and bits
81 	 * 192-255 as the Michael key for SPA->AA.
82 	 */
83 #ifndef IEEE80211_STA_ONLY
84 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
85 		ctx->txmic = &k->k_key[16];
86 		ctx->rxmic = &k->k_key[24];
87 	} else
88 #endif
89 	{
90 		ctx->rxmic = &k->k_key[16];
91 		ctx->txmic = &k->k_key[24];
92 	}
93 	k->k_priv = ctx;
94 	return 0;
95 }
96 
97 void
98 ieee80211_tkip_delete_key(struct ieee80211com *ic, struct ieee80211_key *k)
99 {
100 	if (k->k_priv != NULL)
101 		free(k->k_priv, M_DEVBUF);
102 	k->k_priv = NULL;
103 }
104 
105 /* pseudo-header used for TKIP MIC computation */
106 struct ieee80211_tkip_frame {
107 	u_int8_t	i_da[IEEE80211_ADDR_LEN];
108 	u_int8_t	i_sa[IEEE80211_ADDR_LEN];
109 	u_int8_t	i_pri;
110 	u_int8_t	i_pad[3];
111 } __packed;
112 
113 /*
114  * Compute TKIP MIC over an mbuf chain starting "off" bytes from the
115  * beginning.  This function should be kept independant from the software
116  * TKIP crypto code so that drivers doing hardware crypto but not MIC can
117  * call it without a software crypto context.
118  */
119 void
120 ieee80211_tkip_mic(struct mbuf *m0, int off, const u_int8_t *key,
121     u_int8_t mic[IEEE80211_TKIP_MICLEN])
122 {
123 	const struct ieee80211_frame *wh;
124 	struct ieee80211_tkip_frame wht;
125 	MICHAEL_CTX ctx;	/* small enough */
126 	struct mbuf *m;
127 	caddr_t pos;
128 	int len;
129 
130 	/* assumes 802.11 header is contiguous */
131 	wh = mtod(m0, struct ieee80211_frame *);
132 
133 	/* construct pseudo-header for TKIP MIC computation */
134 	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
135 	case IEEE80211_FC1_DIR_NODS:
136 		IEEE80211_ADDR_COPY(wht.i_da, wh->i_addr1);
137 		IEEE80211_ADDR_COPY(wht.i_sa, wh->i_addr2);
138 		break;
139 	case IEEE80211_FC1_DIR_TODS:
140 		IEEE80211_ADDR_COPY(wht.i_da, wh->i_addr3);
141 		IEEE80211_ADDR_COPY(wht.i_sa, wh->i_addr2);
142 		break;
143 	case IEEE80211_FC1_DIR_FROMDS:
144 		IEEE80211_ADDR_COPY(wht.i_da, wh->i_addr1);
145 		IEEE80211_ADDR_COPY(wht.i_sa, wh->i_addr3);
146 		break;
147 	case IEEE80211_FC1_DIR_DSTODS:
148 		IEEE80211_ADDR_COPY(wht.i_da, wh->i_addr3);
149 		IEEE80211_ADDR_COPY(wht.i_sa,
150 		    ((const struct ieee80211_frame_addr4 *)wh)->i_addr4);
151 		break;
152 	}
153 	if (ieee80211_has_qos(wh))
154 		wht.i_pri = ieee80211_get_qos(wh) & IEEE80211_QOS_TID;
155 	else
156 		wht.i_pri = 0;
157 	wht.i_pad[0] = wht.i_pad[1] = wht.i_pad[2] = 0;
158 
159 	michael_init(&ctx);
160 	michael_key(key, &ctx);
161 
162 	michael_update(&ctx, (caddr_t)&wht, sizeof(wht));
163 
164 	m = m0;
165 	/* assumes the first "off" bytes are contiguous */
166 	pos = mtod(m, caddr_t) + off;
167 	len = m->m_len - off;
168 	for (;;) {
169 		michael_update(&ctx, pos, len);
170 		if ((m = m->m_next) == NULL)
171 			break;
172 		pos = mtod(m, caddr_t);
173 		len = m->m_len;
174 	}
175 
176 	michael_final(mic, &ctx);
177 }
178 
179 /* shortcuts */
180 #define IEEE80211_TKIP_TAILLEN	\
181 	(IEEE80211_TKIP_MICLEN + IEEE80211_WEP_CRCLEN)
182 #define IEEE80211_TKIP_OVHD	\
183 	(IEEE80211_TKIP_HDRLEN + IEEE80211_TKIP_TAILLEN)
184 
185 struct mbuf *
186 ieee80211_tkip_encrypt(struct ieee80211com *ic, struct mbuf *m0,
187     struct ieee80211_key *k)
188 {
189 	struct ieee80211_tkip_ctx *ctx = k->k_priv;
190 	u_int16_t wepseed[8];	/* needs to be 16-bit aligned for Phase2 */
191 	const struct ieee80211_frame *wh;
192 	u_int8_t *ivp, *mic, *icvp;
193 	struct mbuf *n0, *m, *n;
194 	u_int32_t crc;
195 	int left, moff, noff, len, hdrlen;
196 
197 	MGET(n0, M_DONTWAIT, m0->m_type);
198 	if (n0 == NULL)
199 		goto nospace;
200 	M_DUP_PKTHDR(n0, m0);
201 	n0->m_pkthdr.len += IEEE80211_TKIP_HDRLEN;
202 	n0->m_len = MHLEN;
203 	if (n0->m_pkthdr.len >= MINCLSIZE - IEEE80211_TKIP_TAILLEN) {
204 		MCLGET(n0, M_DONTWAIT);
205 		if (n0->m_flags & M_EXT)
206 			n0->m_len = n0->m_ext.ext_size;
207 	}
208 	if (n0->m_len > n0->m_pkthdr.len)
209 		n0->m_len = n0->m_pkthdr.len;
210 
211 	/* copy 802.11 header */
212 	wh = mtod(m0, struct ieee80211_frame *);
213 	hdrlen = ieee80211_get_hdrlen(wh);
214 	memcpy(mtod(n0, caddr_t), wh, hdrlen);
215 
216 	/* construct TKIP header */
217 	ivp = mtod(n0, u_int8_t *) + hdrlen;
218 	ivp[0] = k->k_tsc >> 8;		/* TSC1 */
219 	/* WEP Seed = (TSC1 | 0x20) & 0x7f (see 8.3.2.2) */
220 	ivp[1] = (ivp[0] | 0x20) & 0x7f;
221 	ivp[2] = k->k_tsc;		/* TSC0 */
222 	ivp[3] = k->k_id << 6 | IEEE80211_WEP_EXTIV;	/* KeyID | ExtIV */
223 	ivp[4] = k->k_tsc >> 16;	/* TSC2 */
224 	ivp[5] = k->k_tsc >> 24;	/* TSC3 */
225 	ivp[6] = k->k_tsc >> 32;	/* TSC4 */
226 	ivp[7] = k->k_tsc >> 40;	/* TSC5 */
227 
228 	/* compute WEP seed */
229 	if ((k->k_tsc & 0xffff) == 0)
230 		Phase1(ctx->TTAK1, k->k_key, wh->i_addr2, k->k_tsc >> 16);
231 	Phase2((u_int8_t *)wepseed, k->k_key, ctx->TTAK1, k->k_tsc & 0xffff);
232 	rc4_keysetup(&ctx->rc4, (u_int8_t *)wepseed, 16);
233 
234 	/* encrypt frame body and compute WEP ICV */
235 	m = m0;
236 	n = n0;
237 	moff = hdrlen;
238 	noff = hdrlen + IEEE80211_TKIP_HDRLEN;
239 	left = m0->m_pkthdr.len - moff;
240 	crc = ~0;
241 	while (left > 0) {
242 		if (moff == m->m_len) {
243 			/* nothing left to copy from m */
244 			m = m->m_next;
245 			moff = 0;
246 		}
247 		if (noff == n->m_len) {
248 			/* n is full and there's more data to copy */
249 			MGET(n->m_next, M_DONTWAIT, n->m_type);
250 			if (n->m_next == NULL)
251 				goto nospace;
252 			n = n->m_next;
253 			n->m_len = MLEN;
254 			if (left >= MINCLSIZE - IEEE80211_TKIP_TAILLEN) {
255 				MCLGET(n, M_DONTWAIT);
256 				if (n->m_flags & M_EXT)
257 					n->m_len = n->m_ext.ext_size;
258 			}
259 			if (n->m_len > left)
260 				n->m_len = left;
261 			noff = 0;
262 		}
263 		len = min(m->m_len - moff, n->m_len - noff);
264 
265 		crc = ether_crc32_le_update(crc, mtod(m, caddr_t) + moff, len);
266 		rc4_crypt(&ctx->rc4, mtod(m, caddr_t) + moff,
267 		    mtod(n, caddr_t) + noff, len);
268 
269 		moff += len;
270 		noff += len;
271 		left -= len;
272 	}
273 
274 	/* reserve trailing space for TKIP MIC and WEP ICV */
275 	if (M_TRAILINGSPACE(n) < IEEE80211_TKIP_TAILLEN) {
276 		MGET(n->m_next, M_DONTWAIT, n->m_type);
277 		if (n->m_next == NULL)
278 			goto nospace;
279 		n = n->m_next;
280 		n->m_len = 0;
281 	}
282 
283 	/* compute TKIP MIC over clear text */
284 	mic = mtod(n, caddr_t) + n->m_len;
285 	ieee80211_tkip_mic(m0, hdrlen, ctx->txmic, mic);
286 	crc = ether_crc32_le_update(crc, mic, IEEE80211_TKIP_MICLEN);
287 	rc4_crypt(&ctx->rc4, mic, mic, IEEE80211_TKIP_MICLEN);
288 	n->m_len += IEEE80211_TKIP_MICLEN;
289 
290 	/* finalize WEP ICV */
291 	icvp = mtod(n, caddr_t) + n->m_len;
292 	crc = ~crc;
293 	icvp[0] = crc;
294 	icvp[1] = crc >> 8;
295 	icvp[2] = crc >> 16;
296 	icvp[3] = crc >> 24;
297 	rc4_crypt(&ctx->rc4, icvp, icvp, IEEE80211_WEP_CRCLEN);
298 	n->m_len += IEEE80211_WEP_CRCLEN;
299 
300 	n0->m_pkthdr.len += IEEE80211_TKIP_TAILLEN;
301 
302 	k->k_tsc++;	/* increment the 48-bit TSC */
303 
304 	m_freem(m0);
305 	return n0;
306  nospace:
307 	ic->ic_stats.is_tx_nombuf++;
308 	m_freem(m0);
309 	if (n0 != NULL)
310 		m_freem(n0);
311 	return NULL;
312 }
313 
314 struct mbuf *
315 ieee80211_tkip_decrypt(struct ieee80211com *ic, struct mbuf *m0,
316     struct ieee80211_key *k)
317 {
318 	struct ieee80211_tkip_ctx *ctx = k->k_priv;
319 	struct ieee80211_frame *wh;
320 	u_int16_t wepseed[8];	/* needs to be 16-bit aligned for Phase2 */
321 	u_int8_t buf[IEEE80211_TKIP_MICLEN + IEEE80211_WEP_CRCLEN];
322 	u_int8_t mic[IEEE80211_TKIP_MICLEN];
323 	u_int64_t tsc, *prsc;
324 	u_int32_t crc, crc0;
325 	u_int8_t *ivp, *mic0;
326 	u_int8_t tid;
327 	struct mbuf *n0, *m, *n;
328 	int hdrlen, left, moff, noff, len;
329 
330 	wh = mtod(m0, struct ieee80211_frame *);
331 	hdrlen = ieee80211_get_hdrlen(wh);
332 
333 	if (m0->m_pkthdr.len < hdrlen + IEEE80211_TKIP_OVHD) {
334 		m_freem(m0);
335 		return NULL;
336 	}
337 
338 	ivp = (u_int8_t *)wh + hdrlen;
339 	/* check that ExtIV bit is be set */
340 	if (!(ivp[3] & IEEE80211_WEP_EXTIV)) {
341 		m_freem(m0);
342 		return NULL;
343 	}
344 
345 	/* retrieve last seen packet number for this frame priority */
346 	tid = ieee80211_has_qos(wh) ?
347 	    ieee80211_get_qos(wh) & IEEE80211_QOS_TID : 0;
348 	prsc = &k->k_rsc[tid];
349 
350 	/* extract the 48-bit TSC from the TKIP header */
351 	tsc = (u_int64_t)ivp[2]       |
352 	      (u_int64_t)ivp[0] <<  8 |
353 	      (u_int64_t)ivp[4] << 16 |
354 	      (u_int64_t)ivp[5] << 24 |
355 	      (u_int64_t)ivp[6] << 32 |
356 	      (u_int64_t)ivp[7] << 40;
357 	if (tsc <= *prsc) {
358 		/* replayed frame, discard */
359 		ic->ic_stats.is_tkip_replays++;
360 		m_freem(m0);
361 		return NULL;
362 	}
363 
364 	MGET(n0, M_DONTWAIT, m0->m_type);
365 	if (n0 == NULL)
366 		goto nospace;
367 	M_DUP_PKTHDR(n0, m0);
368 	n0->m_pkthdr.len -= IEEE80211_TKIP_OVHD;
369 	n0->m_len = MHLEN;
370 	if (n0->m_pkthdr.len >= MINCLSIZE) {
371 		MCLGET(n0, M_DONTWAIT);
372 		if (n0->m_flags & M_EXT)
373 			n0->m_len = n0->m_ext.ext_size;
374 	}
375 	if (n0->m_len > n0->m_pkthdr.len)
376 		n0->m_len = n0->m_pkthdr.len;
377 
378 	/* copy 802.11 header and clear protected bit */
379 	memcpy(mtod(n0, caddr_t), wh, hdrlen);
380 	wh = mtod(n0, struct ieee80211_frame *);
381 	wh->i_fc[1] &= ~IEEE80211_FC1_PROTECTED;
382 
383 	/* compute WEP seed */
384 	if (!ctx->TTAK2ok || ((tsc >> 16) != (*prsc >> 16))) {
385 		Phase1(ctx->TTAK2, k->k_key, wh->i_addr2, tsc >> 16);
386 		ctx->TTAK2ok = 1;
387 	}
388 	Phase2((u_int8_t *)wepseed, k->k_key, ctx->TTAK2, tsc & 0xffff);
389 	rc4_keysetup(&ctx->rc4, (u_int8_t *)wepseed, 16);
390 
391 	/* decrypt frame body and compute WEP ICV */
392 	m = m0;
393 	n = n0;
394 	moff = hdrlen + IEEE80211_TKIP_HDRLEN;
395 	noff = hdrlen;
396 	left = n0->m_pkthdr.len - noff;
397 	crc = ~0;
398 	while (left > 0) {
399 		if (moff == m->m_len) {
400 			/* nothing left to copy from m */
401 			m = m->m_next;
402 			moff = 0;
403 		}
404 		if (noff == n->m_len) {
405 			/* n is full and there's more data to copy */
406 			MGET(n->m_next, M_DONTWAIT, n->m_type);
407 			if (n->m_next == NULL)
408 				goto nospace;
409 			n = n->m_next;
410 			n->m_len = MLEN;
411 			if (left >= MINCLSIZE) {
412 				MCLGET(n, M_DONTWAIT);
413 				if (n->m_flags & M_EXT)
414 					n->m_len = n->m_ext.ext_size;
415 			}
416 			if (n->m_len > left)
417 				n->m_len = left;
418 			noff = 0;
419 		}
420 		len = min(m->m_len - moff, n->m_len - noff);
421 
422 		rc4_crypt(&ctx->rc4, mtod(m, caddr_t) + moff,
423 		    mtod(n, caddr_t) + noff, len);
424 		crc = ether_crc32_le_update(crc, mtod(n, caddr_t) + noff, len);
425 
426 		moff += len;
427 		noff += len;
428 		left -= len;
429 	}
430 
431 	/* extract and decrypt TKIP MIC and WEP ICV from m0's tail */
432 	m_copydata(m, moff, IEEE80211_TKIP_TAILLEN, buf);
433 	rc4_crypt(&ctx->rc4, buf, buf, IEEE80211_TKIP_TAILLEN);
434 
435 	/* include TKIP MIC in WEP ICV */
436 	mic0 = buf;
437 	crc = ether_crc32_le_update(crc, mic0, IEEE80211_TKIP_MICLEN);
438 	crc = ~crc;
439 
440 	/* decrypt ICV and compare it with calculated ICV */
441 	crc0 = *(u_int32_t *)(buf + IEEE80211_TKIP_MICLEN);
442 	if (crc != letoh32(crc0)) {
443 		ic->ic_stats.is_tkip_icv_errs++;
444 		m_freem(m0);
445 		m_freem(n0);
446 		return NULL;
447 	}
448 
449 	/* compute TKIP MIC over decrypted message */
450 	ieee80211_tkip_mic(n0, hdrlen, ctx->rxmic, mic);
451 	/* check that it matches the MIC in received frame */
452 	if (memcmp(mic0, mic, IEEE80211_TKIP_MICLEN) != 0) {
453 		m_freem(m0);
454 		m_freem(n0);
455 		ic->ic_stats.is_rx_locmicfail++;
456 		ieee80211_michael_mic_failure(ic, tsc);
457 		return NULL;
458 	}
459 
460 	/* update last seen packet number (MIC is validated) */
461 	*prsc = tsc;
462 
463 	m_freem(m0);
464 	return n0;
465  nospace:
466 	ic->ic_stats.is_rx_nombuf++;
467 	m_freem(m0);
468 	if (n0 != NULL)
469 		m_freem(n0);
470 	return NULL;
471 }
472 
473 #ifndef IEEE80211_STA_ONLY
474 /*
475  * This function is called in HostAP mode to deauthenticate all STAs using
476  * TKIP as their pairwise or group cipher (as part of TKIP countermeasures).
477  */
478 static void
479 ieee80211_tkip_deauth(void *arg, struct ieee80211_node *ni)
480 {
481 	struct ieee80211com *ic = arg;
482 
483 	if (ni->ni_state == IEEE80211_STA_ASSOC &&
484 	    (ic->ic_bss->ni_rsngroupcipher == IEEE80211_CIPHER_TKIP ||
485 	     ni->ni_rsncipher == IEEE80211_CIPHER_TKIP)) {
486 		/* deauthenticate STA */
487 		IEEE80211_SEND_MGMT(ic, ni, IEEE80211_FC0_SUBTYPE_DEAUTH,
488 		    IEEE80211_REASON_MIC_FAILURE);
489 		ieee80211_node_leave(ic, ni);
490 	}
491 }
492 #endif	/* IEEE80211_STA_ONLY */
493 
494 /*
495  * This function can be called by the software TKIP crypto code or by the
496  * drivers when their hardware crypto engines detect a Michael MIC failure.
497  */
498 void
499 ieee80211_michael_mic_failure(struct ieee80211com *ic, u_int64_t tsc)
500 {
501 	extern int ticks;
502 
503 	if (ic->ic_flags & IEEE80211_F_COUNTERM)
504 		return;	/* countermeasures already active */
505 
506 	log(LOG_WARNING, "%s: Michael MIC failure", ic->ic_if.if_xname);
507 
508 	if (ic->ic_opmode == IEEE80211_M_STA) {
509 		/* send a Michael MIC Failure Report frame to the AP */
510 		(void)ieee80211_send_eapol_key_req(ic, ic->ic_bss,
511 		    EAPOL_KEY_KEYMIC | EAPOL_KEY_ERROR | EAPOL_KEY_SECURE,
512 		    tsc);
513 	}
514 	/*
515 	 * Activate TKIP countermeasures (see 8.3.2.4) if less than 60
516 	 * seconds have passed since the most recent previous MIC failure.
517 	 */
518 	if (ic->ic_tkip_micfail == 0 ||
519 	    ticks >= ic->ic_tkip_micfail + 60 * hz) {
520 		ic->ic_tkip_micfail = ticks;
521 		return;
522 	}
523 	ic->ic_tkip_micfail = ticks;
524 
525 	switch (ic->ic_opmode) {
526 #ifndef IEEE80211_STA_ONLY
527 	case IEEE80211_M_HOSTAP:
528 		/* refuse new TKIP associations for the next 60 seconds */
529 		ic->ic_flags |= IEEE80211_F_COUNTERM;
530 
531 		/* deauthenticate all currently associated STAs using TKIP */
532 		ieee80211_iterate_nodes(ic, ieee80211_tkip_deauth, ic);
533 		break;
534 #endif
535 	case IEEE80211_M_STA:
536 		/* deauthenticate from the AP.. */
537 		IEEE80211_SEND_MGMT(ic, ic->ic_bss,
538 		    IEEE80211_FC0_SUBTYPE_DEAUTH,
539 		    IEEE80211_REASON_MIC_FAILURE);
540 		/* ..and find another one */
541 		(void)ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
542 		break;
543 	default:
544 		break;
545 	}
546 }
547 
548 /***********************************************************************
549    Contents:    Generate IEEE 802.11 per-frame RC4 key hash test vectors
550    Date:        April 19, 2002
551    Notes:
552    This code is written for pedagogical purposes, NOT for performance.
553 ************************************************************************/
554 
555 /* macros for extraction/creation of byte/u16b values */
556 #define RotR1(v16)	((((v16) >> 1) & 0x7FFF) ^ (((v16) & 1) << 15))
557 #define   Lo8(v16)	((byte)( (v16)       & 0x00FF))
558 #define   Hi8(v16)	((byte)(((v16) >> 8) & 0x00FF))
559 #define Lo16(v32)	((u16b)( (v32)       & 0xFFFF))
560 #define Hi16(v32)	((u16b)(((v32) >>16) & 0xFFFF))
561 #define Mk16(hi,lo)	((lo) ^ (((u16b)(hi)) << 8))
562 
563 /* select the Nth 16-bit word of the Temporal Key byte array TK[] */
564 #define TK16(N)		Mk16(TK[2 * (N) + 1], TK[2 * (N)])
565 
566 /* S-box lookup: 16 bits --> 16 bits */
567 #define _S_(v16)	(Sbox[Lo8(v16)] ^ swap16(Sbox[Hi8(v16)]))
568 
569 /* fixed algorithm "parameters" */
570 #define PHASE1_LOOP_CNT	 8	/* this needs to be "big enough"     */
571 #define TA_SIZE		 6	/* 48-bit transmitter address        */
572 #define TK_SIZE		16	/* 128-bit Temporal Key              */
573 #define P1K_SIZE	10	/* 80-bit Phase1 key                 */
574 #define RC4_KEY_SIZE	16	/* 128-bit RC4KEY (104 bits unknown) */
575 
576 /* 2-byte by 2-byte subset of the full AES S-box table */
577 static const u16b Sbox[256]=	/* Sbox for hash */
578 {
579 	0xC6A5, 0xF884, 0xEE99, 0xF68D, 0xFF0D, 0xD6BD, 0xDEB1, 0x9154,
580 	0x6050, 0x0203, 0xCEA9, 0x567D, 0xE719, 0xB562, 0x4DE6, 0xEC9A,
581 	0x8F45, 0x1F9D, 0x8940, 0xFA87, 0xEF15, 0xB2EB, 0x8EC9, 0xFB0B,
582 	0x41EC, 0xB367, 0x5FFD, 0x45EA, 0x23BF, 0x53F7, 0xE496, 0x9B5B,
583 	0x75C2, 0xE11C, 0x3DAE, 0x4C6A, 0x6C5A, 0x7E41, 0xF502, 0x834F,
584 	0x685C, 0x51F4, 0xD134, 0xF908, 0xE293, 0xAB73, 0x6253, 0x2A3F,
585 	0x080C, 0x9552, 0x4665, 0x9D5E, 0x3028, 0x37A1, 0x0A0F, 0x2FB5,
586 	0x0E09, 0x2436, 0x1B9B, 0xDF3D, 0xCD26, 0x4E69, 0x7FCD, 0xEA9F,
587 	0x121B, 0x1D9E, 0x5874, 0x342E, 0x362D, 0xDCB2, 0xB4EE, 0x5BFB,
588 	0xA4F6, 0x764D, 0xB761, 0x7DCE, 0x527B, 0xDD3E, 0x5E71, 0x1397,
589 	0xA6F5, 0xB968, 0x0000, 0xC12C, 0x4060, 0xE31F, 0x79C8, 0xB6ED,
590 	0xD4BE, 0x8D46, 0x67D9, 0x724B, 0x94DE, 0x98D4, 0xB0E8, 0x854A,
591 	0xBB6B, 0xC52A, 0x4FE5, 0xED16, 0x86C5, 0x9AD7, 0x6655, 0x1194,
592 	0x8ACF, 0xE910, 0x0406, 0xFE81, 0xA0F0, 0x7844, 0x25BA, 0x4BE3,
593 	0xA2F3, 0x5DFE, 0x80C0, 0x058A, 0x3FAD, 0x21BC, 0x7048, 0xF104,
594 	0x63DF, 0x77C1, 0xAF75, 0x4263, 0x2030, 0xE51A, 0xFD0E, 0xBF6D,
595 	0x814C, 0x1814, 0x2635, 0xC32F, 0xBEE1, 0x35A2, 0x88CC, 0x2E39,
596 	0x9357, 0x55F2, 0xFC82, 0x7A47, 0xC8AC, 0xBAE7, 0x322B, 0xE695,
597 	0xC0A0, 0x1998, 0x9ED1, 0xA37F, 0x4466, 0x547E, 0x3BAB, 0x0B83,
598 	0x8CCA, 0xC729, 0x6BD3, 0x283C, 0xA779, 0xBCE2, 0x161D, 0xAD76,
599 	0xDB3B, 0x6456, 0x744E, 0x141E, 0x92DB, 0x0C0A, 0x486C, 0xB8E4,
600 	0x9F5D, 0xBD6E, 0x43EF, 0xC4A6, 0x39A8, 0x31A4, 0xD337, 0xF28B,
601 	0xD532, 0x8B43, 0x6E59, 0xDAB7, 0x018C, 0xB164, 0x9CD2, 0x49E0,
602 	0xD8B4, 0xACFA, 0xF307, 0xCF25, 0xCAAF, 0xF48E, 0x47E9, 0x1018,
603 	0x6FD5, 0xF088, 0x4A6F, 0x5C72, 0x3824, 0x57F1, 0x73C7, 0x9751,
604 	0xCB23, 0xA17C, 0xE89C, 0x3E21, 0x96DD, 0x61DC, 0x0D86, 0x0F85,
605 	0xE090, 0x7C42, 0x71C4, 0xCCAA, 0x90D8, 0x0605, 0xF701, 0x1C12,
606 	0xC2A3, 0x6A5F, 0xAEF9, 0x69D0, 0x1791, 0x9958, 0x3A27, 0x27B9,
607 	0xD938, 0xEB13, 0x2BB3, 0x2233, 0xD2BB, 0xA970, 0x0789, 0x33A7,
608 	0x2DB6, 0x3C22, 0x1592, 0xC920, 0x8749, 0xAAFF, 0x5078, 0xA57A,
609 	0x038F, 0x59F8, 0x0980, 0x1A17, 0x65DA, 0xD731, 0x84C6, 0xD0B8,
610 	0x82C3, 0x29B0, 0x5A77, 0x1E11, 0x7BCB, 0xA8FC, 0x6DD6, 0x2C3A
611 };
612 
613 /*
614  **********************************************************************
615  * Routine: Phase 1 -- generate P1K, given TA, TK, IV32
616  *
617  * Inputs:
618  *     TK[]      = Temporal Key                         [128 bits]
619  *     TA[]      = transmitter's MAC address            [ 48 bits]
620  *     IV32      = upper 32 bits of IV                  [ 32 bits]
621  * Output:
622  *     P1K[]     = Phase 1 key                          [ 80 bits]
623  *
624  * Note:
625  *     This function only needs to be called every 2**16 frames,
626  *     although in theory it could be called every frame.
627  *
628  **********************************************************************
629  */
630 static void
631 Phase1(u16b *P1K, const byte *TK, const byte *TA, u32b IV32)
632 {
633 	int i;
634 
635 	/* Initialize the 80 bits of P1K[] from IV32 and TA[0..5] */
636 	P1K[0] = Lo16(IV32);
637 	P1K[1] = Hi16(IV32);
638 	P1K[2] = Mk16(TA[1], TA[0]);	/* use TA[] as little-endian */
639 	P1K[3] = Mk16(TA[3], TA[2]);
640 	P1K[4] = Mk16(TA[5], TA[4]);
641 
642 	/* Now compute an unbalanced Feistel cipher with 80-bit block */
643 	/* size on the 80-bit block P1K[], using the 128-bit key TK[] */
644 	for (i = 0; i < PHASE1_LOOP_CNT; i++) {
645 		/* Each add operation here is mod 2**16 */
646 		P1K[0] += _S_(P1K[4] ^ TK16((i & 1) + 0));
647 		P1K[1] += _S_(P1K[0] ^ TK16((i & 1) + 2));
648 		P1K[2] += _S_(P1K[1] ^ TK16((i & 1) + 4));
649 		P1K[3] += _S_(P1K[2] ^ TK16((i & 1) + 6));
650 		P1K[4] += _S_(P1K[3] ^ TK16((i & 1) + 0));
651 		P1K[4] += i;	/* avoid "slide attacks" */
652 	}
653 }
654 
655 /*
656  **********************************************************************
657  * Routine: Phase 2 -- generate RC4KEY, given TK, P1K, IV16
658  *
659  * Inputs:
660  *     TK[]      = Temporal Key                         [128 bits]
661  *     P1K[]     = Phase 1 output key                   [ 80 bits]
662  *     IV16      = low 16 bits of IV counter            [ 16 bits]
663  * Output:
664  *     RC4KEY[] = the key used to encrypt the frame     [128 bits]
665  *
666  * Note:
667  *     The value {TA,IV32,IV16} for Phase1/Phase2 must be unique
668  *     across all frames using the same key TK value. Then, for a
669  *     given value of TK[], this TKIP48 construction guarantees that
670  *     the final RC4KEY value is unique across all frames.
671  *
672  **********************************************************************
673  */
674 static void
675 Phase2(byte *RC4KEY, const byte *TK, const u16b *P1K, u16b IV16)
676 {
677 	u16b *PPK;	/* temporary key for mixing */
678 	int i;
679 
680 	/*
681 	 * Suggested implementation optimization: if PPK[] is "overlaid"
682 	 * appropriately on RC4KEY[], there is no need for the final for
683 	 * loop that copies the PPK[] result into RC4KEY[].
684 	 */
685 	PPK = (u16b *)&RC4KEY[4];
686 
687 	/* all adds in the PPK[] equations below are mod 2**16 */
688 	for (i = 0; i < 5; i++)
689 		PPK[i] = P1K[i];	/* first, copy P1K to PPK */
690 	PPK[5] = P1K[4] + IV16;		/* next, add in IV16 */
691 
692 	/* Bijective non-linear mixing of the 96 bits of PPK[0..5] */
693 	PPK[0] += _S_(PPK[5] ^ TK16(0)); /* Mix key in each "round" */
694 	PPK[1] += _S_(PPK[0] ^ TK16(1));
695 	PPK[2] += _S_(PPK[1] ^ TK16(2));
696 	PPK[3] += _S_(PPK[2] ^ TK16(3));
697 	PPK[4] += _S_(PPK[3] ^ TK16(4));
698 	PPK[5] += _S_(PPK[4] ^ TK16(5)); /* Total # S-box lookups == 6 */
699 
700 	/* Final sweep: bijective, linear. Rotates kill LSB correlations */
701 	PPK[0] += RotR1(PPK[5] ^ TK16(6));
702 	PPK[1] += RotR1(PPK[0] ^ TK16(7)); /* Use all of TK[] in Phase2 */
703 	PPK[2] += RotR1(PPK[1]);
704 	PPK[3] += RotR1(PPK[2]);
705 	PPK[4] += RotR1(PPK[3]);
706 	PPK[5] += RotR1(PPK[4]);
707 
708 	/* At this point, for a given key TK[0..15], the 96-bit output */
709 	/* value PPK[0..5] is guaranteed to be unique, as a function */
710 	/* of the 96-bit "input" value   {TA,IV32,IV16}. That is, P1K */
711 	/* is now a keyed permutation of {TA,IV32,IV16}. */
712 	/* Set RC4KEY[0..3], which includes cleartext portion of RC4 key  */
713 	RC4KEY[0] = Hi8(IV16);	/* RC4KEY[0..2] is the WEP IV */
714 	RC4KEY[1] =(Hi8(IV16) | 0x20) & 0x7F; /* Help avoid FMS weak keys */
715 	RC4KEY[2] = Lo8(IV16);
716 	RC4KEY[3] = Lo8((PPK[5] ^ TK16(0)) >> 1);
717 
718 #if BYTE_ORDER == BIG_ENDIAN
719 	/* Copy 96 bits of PPK[0..5] to RC4KEY[4..15] (little-endian) */
720 	for (i = 0; i < 6; i++)
721 		PPK[i] = swap16(PPK[i]);
722 #endif
723 }
724