xref: /freebsd/sys/net80211/ieee80211_crypto.c (revision 6549718b70f0e660a15685369afb4f9caf2215ce)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001 Atsushi Onoe
5  * Copyright (c) 2002-2008 Sam Leffler, Errno Consulting
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 /*
31  * IEEE 802.11 generic crypto support.
32  */
33 #include "opt_wlan.h"
34 
35 #include <sys/param.h>
36 #include <sys/kernel.h>
37 #include <sys/malloc.h>
38 #include <sys/mbuf.h>
39 
40 #include <sys/socket.h>
41 
42 #include <net/if.h>
43 #include <net/if_media.h>
44 #include <net/ethernet.h>		/* XXX ETHER_HDR_LEN */
45 
46 #include <net80211/ieee80211_var.h>
47 
48 MALLOC_DEFINE(M_80211_CRYPTO, "80211crypto", "802.11 crypto state");
49 
50 static	int _ieee80211_crypto_delkey(struct ieee80211vap *,
51 		struct ieee80211_key *);
52 
53 /*
54  * Table of registered cipher modules.
55  */
56 static	const struct ieee80211_cipher *ciphers[IEEE80211_CIPHER_MAX];
57 
58 /*
59  * Default "null" key management routines.
60  */
61 static int
62 null_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
63 	ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
64 {
65 
66 	if (!ieee80211_is_key_global(vap, k)) {
67 		/*
68 		 * Not in the global key table, the driver should handle this
69 		 * by allocating a slot in the h/w key table/cache.  In
70 		 * lieu of that return key slot 0 for any unicast key
71 		 * request.  We disallow the request if this is a group key.
72 		 * This default policy does the right thing for legacy hardware
73 		 * with a 4 key table.  It also handles devices that pass
74 		 * packets through untouched when marked with the WEP bit
75 		 * and key index 0.
76 		 */
77 		if (k->wk_flags & IEEE80211_KEY_GROUP)
78 			return 0;
79 		*keyix = 0;	/* NB: use key index 0 for ucast key */
80 	} else {
81 		*keyix = ieee80211_crypto_get_key_wepidx(vap, k);
82 	}
83 	*rxkeyix = IEEE80211_KEYIX_NONE;	/* XXX maybe *keyix? */
84 	return 1;
85 }
86 static int
87 null_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
88 {
89 	return 1;
90 }
91 static 	int
92 null_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k)
93 {
94 	return 1;
95 }
96 static void null_key_update(struct ieee80211vap *vap) {}
97 
98 /*
99  * Write-arounds for common operations.
100  */
101 static __inline void
102 cipher_detach(struct ieee80211_key *key)
103 {
104 	key->wk_cipher->ic_detach(key);
105 }
106 
107 static __inline void *
108 cipher_attach(struct ieee80211vap *vap, struct ieee80211_key *key)
109 {
110 	return key->wk_cipher->ic_attach(vap, key);
111 }
112 
113 /*
114  * Wrappers for driver key management methods.
115  */
116 static __inline int
117 dev_key_alloc(struct ieee80211vap *vap,
118 	struct ieee80211_key *key,
119 	ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
120 {
121 	return vap->iv_key_alloc(vap, key, keyix, rxkeyix);
122 }
123 
124 static __inline int
125 dev_key_delete(struct ieee80211vap *vap,
126 	const struct ieee80211_key *key)
127 {
128 	return vap->iv_key_delete(vap, key);
129 }
130 
131 static __inline int
132 dev_key_set(struct ieee80211vap *vap, const struct ieee80211_key *key)
133 {
134 	return vap->iv_key_set(vap, key);
135 }
136 
137 /*
138  * Setup crypto support for a device/shared instance.
139  */
140 void
141 ieee80211_crypto_attach(struct ieee80211com *ic)
142 {
143 	/* NB: we assume everything is pre-zero'd */
144 	ciphers[IEEE80211_CIPHER_NONE] = &ieee80211_cipher_none;
145 
146 	/*
147 	 * Default set of net80211 supported ciphers.
148 	 *
149 	 * These are the default set that all drivers are expected to
150 	 * support, either/or in hardware and software.
151 	 *
152 	 * Drivers can add their own support to this and the
153 	 * hardware cipher list (ic_cryptocaps.)
154 	 */
155 	ic->ic_sw_cryptocaps = IEEE80211_CRYPTO_WEP |
156 	    IEEE80211_CRYPTO_TKIP | IEEE80211_CRYPTO_AES_CCM;
157 
158 	/*
159 	 * Default set of key management types supported by net80211.
160 	 *
161 	 * These are supported by software net80211 and announced/
162 	 * driven by hostapd + wpa_supplicant.
163 	 *
164 	 * Drivers doing full supplicant offload must not set
165 	 * anything here.
166 	 *
167 	 * Note that IEEE80211_C_WPA1 and IEEE80211_C_WPA2 are the
168 	 * "old" style way of drivers announcing key management
169 	 * capabilities.  There are many, many more key management
170 	 * suites in 802.11-2016 (see 9.4.2.25.3 - AKM suites.)
171 	 * For now they still need to be set - these flags are checked
172 	 * when assembling a beacon to reserve space for the WPA
173 	 * vendor IE (WPA 1) and RSN IE (WPA 2).
174 	 */
175 	ic->ic_sw_keymgmtcaps = 0;
176 }
177 
178 /*
179  * Teardown crypto support.
180  */
181 void
182 ieee80211_crypto_detach(struct ieee80211com *ic)
183 {
184 }
185 
186 /*
187  * Set the supported ciphers for software encryption.
188  */
189 void
190 ieee80211_crypto_set_supported_software_ciphers(struct ieee80211com *ic,
191     uint32_t cipher_set)
192 {
193 	ic->ic_sw_cryptocaps = cipher_set;
194 }
195 
196 /*
197  * Set the supported ciphers for hardware encryption.
198  */
199 void
200 ieee80211_crypto_set_supported_hardware_ciphers(struct ieee80211com *ic,
201     uint32_t cipher_set)
202 {
203 	ic->ic_cryptocaps = cipher_set;
204 }
205 
206 /*
207  * Set the supported software key management by the driver.
208  *
209  * These are the key management suites that are supported via
210  * the driver via hostapd/wpa_supplicant.
211  *
212  * Key management which is completely offloaded (ie, the supplicant
213  * runs in hardware/firmware) must not be set here.
214  */
215 void
216 ieee80211_crypto_set_supported_driver_keymgmt(struct ieee80211com *ic,
217     uint32_t keymgmt_set)
218 {
219 
220 	ic->ic_sw_keymgmtcaps = keymgmt_set;
221 }
222 
223 /*
224  * Setup crypto support for a vap.
225  */
226 void
227 ieee80211_crypto_vattach(struct ieee80211vap *vap)
228 {
229 	int i;
230 
231 	/* NB: we assume everything is pre-zero'd */
232 	vap->iv_max_keyix = IEEE80211_WEP_NKID;
233 	vap->iv_def_txkey = IEEE80211_KEYIX_NONE;
234 	for (i = 0; i < IEEE80211_WEP_NKID; i++)
235 		ieee80211_crypto_resetkey(vap, &vap->iv_nw_keys[i],
236 			IEEE80211_KEYIX_NONE);
237 	/*
238 	 * Initialize the driver key support routines to noop entries.
239 	 * This is useful especially for the cipher test modules.
240 	 */
241 	vap->iv_key_alloc = null_key_alloc;
242 	vap->iv_key_set = null_key_set;
243 	vap->iv_key_delete = null_key_delete;
244 	vap->iv_key_update_begin = null_key_update;
245 	vap->iv_key_update_end = null_key_update;
246 }
247 
248 /*
249  * Teardown crypto support for a vap.
250  */
251 void
252 ieee80211_crypto_vdetach(struct ieee80211vap *vap)
253 {
254 	ieee80211_crypto_delglobalkeys(vap);
255 }
256 
257 /*
258  * Register a crypto cipher module.
259  */
260 void
261 ieee80211_crypto_register(const struct ieee80211_cipher *cip)
262 {
263 	if (cip->ic_cipher >= IEEE80211_CIPHER_MAX) {
264 		printf("%s: cipher %s has an invalid cipher index %u\n",
265 			__func__, cip->ic_name, cip->ic_cipher);
266 		return;
267 	}
268 	if (ciphers[cip->ic_cipher] != NULL && ciphers[cip->ic_cipher] != cip) {
269 		printf("%s: cipher %s registered with a different template\n",
270 			__func__, cip->ic_name);
271 		return;
272 	}
273 	ciphers[cip->ic_cipher] = cip;
274 }
275 
276 /*
277  * Unregister a crypto cipher module.
278  */
279 void
280 ieee80211_crypto_unregister(const struct ieee80211_cipher *cip)
281 {
282 	if (cip->ic_cipher >= IEEE80211_CIPHER_MAX) {
283 		printf("%s: cipher %s has an invalid cipher index %u\n",
284 			__func__, cip->ic_name, cip->ic_cipher);
285 		return;
286 	}
287 	if (ciphers[cip->ic_cipher] != NULL && ciphers[cip->ic_cipher] != cip) {
288 		printf("%s: cipher %s registered with a different template\n",
289 			__func__, cip->ic_name);
290 		return;
291 	}
292 	/* NB: don't complain about not being registered */
293 	/* XXX disallow if references */
294 	ciphers[cip->ic_cipher] = NULL;
295 }
296 
297 int
298 ieee80211_crypto_available(u_int cipher)
299 {
300 	return cipher < IEEE80211_CIPHER_MAX && ciphers[cipher] != NULL;
301 }
302 
303 /* XXX well-known names! */
304 static const char *cipher_modnames[IEEE80211_CIPHER_MAX] = {
305 	[IEEE80211_CIPHER_WEP]	   = "wlan_wep",
306 	[IEEE80211_CIPHER_TKIP]	   = "wlan_tkip",
307 	[IEEE80211_CIPHER_AES_OCB] = "wlan_aes_ocb",
308 	[IEEE80211_CIPHER_AES_CCM] = "wlan_ccmp",
309 	[IEEE80211_CIPHER_TKIPMIC] = "#4",	/* NB: reserved */
310 	[IEEE80211_CIPHER_CKIP]	   = "wlan_ckip",
311 	[IEEE80211_CIPHER_NONE]	   = "wlan_none",
312 	[IEEE80211_CIPHER_AES_CCM_256] = "wlan_ccmp",
313 	[IEEE80211_CIPHER_BIP_CMAC_128] = "wlan_bip_cmac",
314 	[IEEE80211_CIPHER_BIP_CMAC_256] = "wlan_bip_cmac",
315 	[IEEE80211_CIPHER_BIP_GMAC_128] = "wlan_bip_gmac",
316 	[IEEE80211_CIPHER_BIP_GMAC_256] = "wlan_bip_gmac",
317 	[IEEE80211_CIPHER_AES_GCM_128]  = "wlan_gcmp",
318 	[IEEE80211_CIPHER_AES_GCM_256]  = "wlan_gcmp",
319 };
320 
321 /* NB: there must be no overlap between user-supplied and device-owned flags */
322 CTASSERT((IEEE80211_KEY_COMMON & IEEE80211_KEY_DEVICE) == 0);
323 
324 /*
325  * Establish a relationship between the specified key and cipher
326  * and, if necessary, allocate a hardware index from the driver.
327  * Note that when a fixed key index is required it must be specified.
328  *
329  * This must be the first call applied to a key; all the other key
330  * routines assume wk_cipher is setup.
331  *
332  * Locking must be handled by the caller using:
333  *	ieee80211_key_update_begin(vap);
334  *	ieee80211_key_update_end(vap);
335  */
336 int
337 ieee80211_crypto_newkey(struct ieee80211vap *vap,
338 	int cipher, int flags, struct ieee80211_key *key)
339 {
340 	struct ieee80211com *ic = vap->iv_ic;
341 	const struct ieee80211_cipher *cip;
342 	ieee80211_keyix keyix, rxkeyix;
343 	void *keyctx;
344 	int oflags;
345 
346 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
347 	    "%s: cipher %u flags 0x%x keyix %u\n",
348 	    __func__, cipher, flags, key->wk_keyix);
349 
350 	/*
351 	 * Validate cipher and set reference to cipher routines.
352 	 */
353 	if (cipher >= IEEE80211_CIPHER_MAX) {
354 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
355 		    "%s: invalid cipher %u\n", __func__, cipher);
356 		vap->iv_stats.is_crypto_badcipher++;
357 		return 0;
358 	}
359 	cip = ciphers[cipher];
360 	if (cip == NULL) {
361 		/*
362 		 * Auto-load cipher module if we have a well-known name
363 		 * for it.  It might be better to use string names rather
364 		 * than numbers and craft a module name based on the cipher
365 		 * name; e.g. wlan_cipher_<cipher-name>.
366 		 */
367 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
368 		    "%s: unregistered cipher %u, load module %s\n",
369 		    __func__, cipher, cipher_modnames[cipher]);
370 		ieee80211_load_module(cipher_modnames[cipher]);
371 		/*
372 		 * If cipher module loaded it should immediately
373 		 * call ieee80211_crypto_register which will fill
374 		 * in the entry in the ciphers array.
375 		 */
376 		cip = ciphers[cipher];
377 		if (cip == NULL) {
378 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
379 			    "%s: unable to load cipher %u, module %s\n",
380 			    __func__, cipher, cipher_modnames[cipher]);
381 			vap->iv_stats.is_crypto_nocipher++;
382 			return 0;
383 		}
384 	}
385 
386 	oflags = key->wk_flags;
387 	flags &= IEEE80211_KEY_COMMON;
388 	/* NB: preserve device attributes */
389 	flags |= (oflags & IEEE80211_KEY_DEVICE);
390 	/*
391 	 * If the hardware does not support the cipher then
392 	 * fallback to a host-based implementation.
393 	 */
394 	if ((ic->ic_cryptocaps & (1<<cipher)) == 0) {
395 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
396 		    "%s: no h/w support for cipher %s, falling back to s/w\n",
397 		    __func__, cip->ic_name);
398 		flags |= IEEE80211_KEY_SWCRYPT;
399 	}
400 	/*
401 	 * Hardware TKIP with software MIC is an important
402 	 * combination; we handle it by flagging each key,
403 	 * the cipher modules honor it.
404 	 */
405 	if (cipher == IEEE80211_CIPHER_TKIP &&
406 	    (ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIPMIC) == 0) {
407 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
408 		    "%s: no h/w support for TKIP MIC, falling back to s/w\n",
409 		    __func__);
410 		flags |= IEEE80211_KEY_SWMIC;
411 	}
412 
413 	/*
414 	 * Bind cipher to key instance.  Note we do this
415 	 * after checking the device capabilities so the
416 	 * cipher module can optimize space usage based on
417 	 * whether or not it needs to do the cipher work.
418 	 */
419 	if (key->wk_cipher != cip || key->wk_flags != flags) {
420 		/*
421 		 * Fillin the flags so cipher modules can see s/w
422 		 * crypto requirements and potentially allocate
423 		 * different state and/or attach different method
424 		 * pointers.
425 		 */
426 		key->wk_flags = flags;
427 		keyctx = cip->ic_attach(vap, key);
428 		if (keyctx == NULL) {
429 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
430 				"%s: unable to attach cipher %s\n",
431 				__func__, cip->ic_name);
432 			key->wk_flags = oflags;	/* restore old flags */
433 			vap->iv_stats.is_crypto_attachfail++;
434 			return 0;
435 		}
436 		cipher_detach(key);
437 		key->wk_cipher = cip;		/* XXX refcnt? */
438 		key->wk_private = keyctx;
439 	}
440 
441 	/*
442 	 * Ask the driver for a key index if we don't have one.
443 	 * Note that entries in the global key table always have
444 	 * an index; this means it's safe to call this routine
445 	 * for these entries just to setup the reference to the
446 	 * cipher template.  Note also that when using software
447 	 * crypto we also call the driver to give us a key index.
448 	 */
449 	if ((key->wk_flags & IEEE80211_KEY_DEVKEY) == 0) {
450 		if (!dev_key_alloc(vap, key, &keyix, &rxkeyix)) {
451 			/*
452 			 * Unable to setup driver state.
453 			 */
454 			vap->iv_stats.is_crypto_keyfail++;
455 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
456 			    "%s: unable to setup cipher %s\n",
457 			    __func__, cip->ic_name);
458 			return 0;
459 		}
460 		if (key->wk_flags != flags) {
461 			/*
462 			 * Driver overrode flags we setup; typically because
463 			 * resources were unavailable to handle _this_ key.
464 			 * Re-attach the cipher context to allow cipher
465 			 * modules to handle differing requirements.
466 			 */
467 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
468 			    "%s: driver override for cipher %s, flags "
469 			    "0x%x -> 0x%x\n", __func__, cip->ic_name,
470 			    oflags, key->wk_flags);
471 			keyctx = cip->ic_attach(vap, key);
472 			if (keyctx == NULL) {
473 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
474 				    "%s: unable to attach cipher %s with "
475 				    "flags 0x%x\n", __func__, cip->ic_name,
476 				    key->wk_flags);
477 				key->wk_flags = oflags;	/* restore old flags */
478 				vap->iv_stats.is_crypto_attachfail++;
479 				return 0;
480 			}
481 			cipher_detach(key);
482 			key->wk_cipher = cip;		/* XXX refcnt? */
483 			key->wk_private = keyctx;
484 		}
485 		key->wk_keyix = keyix;
486 		key->wk_rxkeyix = rxkeyix;
487 		key->wk_flags |= IEEE80211_KEY_DEVKEY;
488 	}
489 	return 1;
490 }
491 
492 /*
493  * Remove the key (no locking, for internal use).
494  */
495 static int
496 _ieee80211_crypto_delkey(struct ieee80211vap *vap, struct ieee80211_key *key)
497 {
498 	KASSERT(key->wk_cipher != NULL, ("No cipher!"));
499 
500 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
501 	    "%s: %s keyix %u flags 0x%x rsc %ju tsc %ju len %u\n",
502 	    __func__, key->wk_cipher->ic_name,
503 	    key->wk_keyix, key->wk_flags,
504 	    key->wk_keyrsc[IEEE80211_NONQOS_TID], key->wk_keytsc,
505 	    key->wk_keylen);
506 
507 	if (key->wk_flags & IEEE80211_KEY_DEVKEY) {
508 		/*
509 		 * Remove hardware entry.
510 		 */
511 		/* XXX key cache */
512 		if (!dev_key_delete(vap, key)) {
513 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
514 			    "%s: driver did not delete key index %u\n",
515 			    __func__, key->wk_keyix);
516 			vap->iv_stats.is_crypto_delkey++;
517 			/* XXX recovery? */
518 		}
519 	}
520 	cipher_detach(key);
521 	memset(key, 0, sizeof(*key));
522 	ieee80211_crypto_resetkey(vap, key, IEEE80211_KEYIX_NONE);
523 	return 1;
524 }
525 
526 /*
527  * Remove the specified key.
528  */
529 int
530 ieee80211_crypto_delkey(struct ieee80211vap *vap, struct ieee80211_key *key)
531 {
532 	int status;
533 
534 	ieee80211_key_update_begin(vap);
535 	status = _ieee80211_crypto_delkey(vap, key);
536 	ieee80211_key_update_end(vap);
537 	return status;
538 }
539 
540 /*
541  * Clear the global key table.
542  */
543 void
544 ieee80211_crypto_delglobalkeys(struct ieee80211vap *vap)
545 {
546 	int i;
547 
548 	ieee80211_key_update_begin(vap);
549 	for (i = 0; i < IEEE80211_WEP_NKID; i++)
550 		(void) _ieee80211_crypto_delkey(vap, &vap->iv_nw_keys[i]);
551 	ieee80211_key_update_end(vap);
552 }
553 
554 /*
555  * Set the contents of the specified key.
556  *
557  * Locking must be handled by the caller using:
558  *	ieee80211_key_update_begin(vap);
559  *	ieee80211_key_update_end(vap);
560  */
561 int
562 ieee80211_crypto_setkey(struct ieee80211vap *vap, struct ieee80211_key *key)
563 {
564 	const struct ieee80211_cipher *cip = key->wk_cipher;
565 
566 	KASSERT(cip != NULL, ("No cipher!"));
567 
568 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
569 	    "%s: %s keyix %u flags 0x%x mac %s rsc %ju tsc %ju len %u\n",
570 	    __func__, cip->ic_name, key->wk_keyix,
571 	    key->wk_flags, ether_sprintf(key->wk_macaddr),
572 	    key->wk_keyrsc[IEEE80211_NONQOS_TID], key->wk_keytsc,
573 	    key->wk_keylen);
574 
575 	if ((key->wk_flags & IEEE80211_KEY_DEVKEY)  == 0) {
576 		/* XXX nothing allocated, should not happen */
577 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
578 		    "%s: no device key setup done; should not happen!\n",
579 		    __func__);
580 		vap->iv_stats.is_crypto_setkey_nokey++;
581 		return 0;
582 	}
583 	/*
584 	 * Give cipher a chance to validate key contents.
585 	 * XXX should happen before modifying state.
586 	 */
587 	if (!cip->ic_setkey(key)) {
588 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,
589 		    "%s: cipher %s rejected key index %u len %u flags 0x%x\n",
590 		    __func__, cip->ic_name, key->wk_keyix,
591 		    key->wk_keylen, key->wk_flags);
592 		vap->iv_stats.is_crypto_setkey_cipher++;
593 		return 0;
594 	}
595 	return dev_key_set(vap, key);
596 }
597 
598 /*
599  * Return index if the key is a WEP key (0..3); -1 otherwise.
600  *
601  * This is different to "get_keyid" which defaults to returning
602  * 0 for unicast keys; it assumes that it won't be used for WEP.
603  */
604 int
605 ieee80211_crypto_get_key_wepidx(const struct ieee80211vap *vap,
606     const struct ieee80211_key *k)
607 {
608 
609 	if (ieee80211_is_key_global(vap, k)) {
610 		return (k - vap->iv_nw_keys);
611 	}
612 	return (-1);
613 }
614 
615 /*
616  * Note: only supports a single unicast key (0).
617  */
618 uint8_t
619 ieee80211_crypto_get_keyid(struct ieee80211vap *vap, struct ieee80211_key *k)
620 {
621 	if (ieee80211_is_key_global(vap, k)) {
622 		return (k - vap->iv_nw_keys);
623 	}
624 
625 	return (0);
626 }
627 
628 struct ieee80211_key *
629 ieee80211_crypto_get_txkey(struct ieee80211_node *ni, struct mbuf *m)
630 {
631 	struct ieee80211vap *vap = ni->ni_vap;
632 	struct ieee80211_frame *wh;
633 
634 	/*
635 	 * Multicast traffic always uses the multicast key.
636 	 *
637 	 * Historically we would fall back to the default
638 	 * transmit key if there was no unicast key.  This
639 	 * behaviour was documented up to IEEE Std 802.11-2016,
640 	 * 12.9.2.2 Per-MSDU/Per-A-MSDU Tx pseudocode, in the
641 	 * 'else' case but is no longer in later versions of
642 	 * the standard.  Additionally falling back to the
643 	 * group key for unicast was a security risk.
644 	 */
645 	wh = mtod(m, struct ieee80211_frame *);
646 	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
647 		if (vap->iv_def_txkey == IEEE80211_KEYIX_NONE) {
648 			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO,
649 			    wh->i_addr1,
650 			    "no default transmit key (%s) deftxkey %u",
651 			    __func__, vap->iv_def_txkey);
652 			vap->iv_stats.is_tx_nodefkey++;
653 			return NULL;
654 		}
655 		return &vap->iv_nw_keys[vap->iv_def_txkey];
656 	}
657 
658 	if (IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey))
659 		return NULL;
660 	return &ni->ni_ucastkey;
661 }
662 
663 /*
664  * Add privacy headers appropriate for the specified key.
665  */
666 struct ieee80211_key *
667 ieee80211_crypto_encap(struct ieee80211_node *ni, struct mbuf *m)
668 {
669 	struct ieee80211_key *k;
670 	const struct ieee80211_cipher *cip;
671 
672 	if ((k = ieee80211_crypto_get_txkey(ni, m)) != NULL) {
673 		cip = k->wk_cipher;
674 		return (cip->ic_encap(k, m) ? k : NULL);
675 	}
676 
677 	return NULL;
678 }
679 
680 /*
681  * Validate and strip privacy headers (and trailer) for a
682  * received frame that has the WEP/Privacy bit set.
683  */
684 int
685 ieee80211_crypto_decap(struct ieee80211_node *ni, struct mbuf *m, int hdrlen,
686     struct ieee80211_key **key)
687 {
688 #define	IEEE80211_WEP_HDRLEN	(IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN)
689 #define	IEEE80211_WEP_MINLEN \
690 	(sizeof(struct ieee80211_frame) + \
691 	IEEE80211_WEP_HDRLEN + IEEE80211_WEP_CRCLEN)
692 	struct ieee80211vap *vap = ni->ni_vap;
693 	struct ieee80211_key *k;
694 	struct ieee80211_frame *wh;
695 	const struct ieee80211_rx_stats *rxs;
696 	const struct ieee80211_cipher *cip;
697 	uint8_t keyid;
698 
699 	/*
700 	 * Check for hardware decryption and IV stripping.
701 	 * If the IV is stripped then we definitely can't find a key.
702 	 * Set the key to NULL but return true; upper layers
703 	 * will need to handle a NULL key for a successful
704 	 * decrypt.
705 	 */
706 	rxs = ieee80211_get_rx_params_ptr(m);
707 	if ((rxs != NULL) && (rxs->c_pktflags & IEEE80211_RX_F_DECRYPTED)) {
708 		if (rxs->c_pktflags & IEEE80211_RX_F_IV_STRIP) {
709 			/*
710 			 * Hardware decrypted, IV stripped.
711 			 * We can't find a key with a stripped IV.
712 			 * Return successful.
713 			 */
714 			*key = NULL;
715 			return (1);
716 		}
717 	}
718 
719 	/* NB: this minimum size data frame could be bigger */
720 	if (m->m_pkthdr.len < IEEE80211_WEP_MINLEN) {
721 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ANY,
722 			"%s: WEP data frame too short, len %u\n",
723 			__func__, m->m_pkthdr.len);
724 		vap->iv_stats.is_rx_tooshort++;	/* XXX need unique stat? */
725 		*key = NULL;
726 		return (0);
727 	}
728 
729 	/*
730 	 * Locate the key. If unicast and there is no unicast
731 	 * key then we fall back to the key id in the header.
732 	 * This assumes unicast keys are only configured when
733 	 * the key id in the header is meaningless (typically 0).
734 	 */
735 	wh = mtod(m, struct ieee80211_frame *);
736 	m_copydata(m, hdrlen + IEEE80211_WEP_IVLEN, sizeof(keyid), &keyid);
737 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
738 	    IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey))
739 		k = &vap->iv_nw_keys[keyid >> 6];
740 	else
741 		k = &ni->ni_ucastkey;
742 
743 	/*
744 	 * Insure crypto header is contiguous and long enough for all
745 	 * decap work.
746 	 */
747 	cip = k->wk_cipher;
748 	if (m->m_len < hdrlen + cip->ic_header) {
749 		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO, wh->i_addr2,
750 		    "frame is too short (%d < %u) for crypto decap",
751 		    cip->ic_name, m->m_len, hdrlen + cip->ic_header);
752 		vap->iv_stats.is_rx_tooshort++;
753 		*key = NULL;
754 		return (0);
755 	}
756 
757 	/*
758 	 * Attempt decryption.
759 	 *
760 	 * If we fail then don't return the key - return NULL
761 	 * and an error.
762 	 */
763 	if (cip->ic_decap(k, m, hdrlen)) {
764 		/* success */
765 		*key = k;
766 		return (1);
767 	}
768 
769 	/* Failure */
770 	*key = NULL;
771 	return (0);
772 #undef IEEE80211_WEP_MINLEN
773 #undef IEEE80211_WEP_HDRLEN
774 }
775 
776 /*
777  * Check and remove any MIC.
778  */
779 int
780 ieee80211_crypto_demic(struct ieee80211vap *vap, struct ieee80211_key *k,
781     struct mbuf *m, int force)
782 {
783 	const struct ieee80211_cipher *cip;
784 	const struct ieee80211_rx_stats *rxs;
785 	struct ieee80211_frame *wh;
786 
787 	rxs = ieee80211_get_rx_params_ptr(m);
788 	wh = mtod(m, struct ieee80211_frame *);
789 
790 	/*
791 	 * Handle demic / mic errors from hardware-decrypted offload devices.
792 	 */
793 	if ((rxs != NULL) && (rxs->c_pktflags & IEEE80211_RX_F_DECRYPTED)) {
794 		if (rxs->c_pktflags & IEEE80211_RX_F_FAIL_MIC) {
795 			/*
796 			 * Hardware has said MIC failed.  We don't care about
797 			 * whether it was stripped or not.
798 			 *
799 			 * Eventually - teach the demic methods in crypto
800 			 * modules to handle a NULL key and not to dereference
801 			 * it.
802 			 */
803 			ieee80211_notify_michael_failure(vap, wh, -1);
804 			return (0);
805 		}
806 
807 		if (rxs->c_pktflags & IEEE80211_RX_F_MMIC_STRIP) {
808 			/*
809 			 * Hardware has decrypted and not indicated a
810 			 * MIC failure and has stripped the MIC.
811 			 * We may not have a key, so for now just
812 			 * return OK.
813 			 */
814 			return (1);
815 		}
816 	}
817 
818 	/*
819 	 * If we don't have a key at this point then we don't
820 	 * have to demic anything.
821 	 */
822 	if (k == NULL)
823 		return (1);
824 
825 	cip = k->wk_cipher;
826 	return (cip->ic_miclen > 0 ? cip->ic_demic(k, m, force) : 1);
827 }
828 
829 static void
830 load_ucastkey(void *arg, struct ieee80211_node *ni)
831 {
832 	struct ieee80211vap *vap = ni->ni_vap;
833 	struct ieee80211_key *k;
834 
835 	if (vap->iv_state != IEEE80211_S_RUN)
836 		return;
837 	k = &ni->ni_ucastkey;
838 	if (k->wk_flags & IEEE80211_KEY_DEVKEY)
839 		dev_key_set(vap, k);
840 }
841 
842 /*
843  * Re-load all keys known to the 802.11 layer that may
844  * have hardware state backing them.  This is used by
845  * drivers on resume to push keys down into the device.
846  */
847 void
848 ieee80211_crypto_reload_keys(struct ieee80211com *ic)
849 {
850 	struct ieee80211vap *vap;
851 	int i;
852 
853 	/*
854 	 * Keys in the global key table of each vap.
855 	 */
856 	/* NB: used only during resume so don't lock for now */
857 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
858 		if (vap->iv_state != IEEE80211_S_RUN)
859 			continue;
860 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
861 			const struct ieee80211_key *k = &vap->iv_nw_keys[i];
862 			if (k->wk_flags & IEEE80211_KEY_DEVKEY)
863 				dev_key_set(vap, k);
864 		}
865 	}
866 	/*
867 	 * Unicast keys.
868 	 */
869 	ieee80211_iterate_nodes(&ic->ic_sta, load_ucastkey, NULL);
870 }
871 
872 /*
873  * Set the default key index for WEP, or KEYIX_NONE for no default TX key.
874  *
875  * This should be done as part of a key update block (iv_key_update_begin /
876  * iv_key_update_end.)
877  */
878 void
879 ieee80211_crypto_set_deftxkey(struct ieee80211vap *vap, ieee80211_keyix kid)
880 {
881 
882 	/* XXX TODO: assert we're in a key update block */
883 
884 	vap->iv_update_deftxkey(vap, kid);
885 }
886