/*-1* SPDX-License-Identifier: BSD-2-Clause2*3* Copyright (c) 2001 Atsushi Onoe4* Copyright (c) 2002-2008 Sam Leffler, Errno Consulting5* All rights reserved.6*7* Redistribution and use in source and binary forms, with or without8* modification, are permitted provided that the following conditions9* are met:10* 1. Redistributions of source code must retain the above copyright11* notice, this list of conditions and the following disclaimer.12* 2. Redistributions in binary form must reproduce the above copyright13* notice, this list of conditions and the following disclaimer in the14* documentation and/or other materials provided with the distribution.15*16* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR17* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES18* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.19* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,20* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT21* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,22* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY23* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT24* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF25* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.26*/2728#include <sys/cdefs.h>29/*30* IEEE 802.11 generic crypto support.31*/32#include "opt_wlan.h"3334#include <sys/param.h>35#include <sys/kernel.h>36#include <sys/malloc.h>37#include <sys/mbuf.h>3839#include <sys/socket.h>4041#include <net/if.h>42#include <net/if_media.h>43#include <net/ethernet.h> /* XXX ETHER_HDR_LEN */4445#include <net80211/ieee80211_var.h>4647MALLOC_DEFINE(M_80211_CRYPTO, "80211crypto", "802.11 crypto state");4849static int _ieee80211_crypto_delkey(struct ieee80211vap *,50struct ieee80211_key *);5152/*53* Table of registered cipher modules.54*/55static const struct ieee80211_cipher *ciphers[IEEE80211_CIPHER_MAX];5657/*58* Default "null" key management routines.59*/60static int61null_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,62ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)63{6465if (!ieee80211_is_key_global(vap, k)) {66/*67* Not in the global key table, the driver should handle this68* by allocating a slot in the h/w key table/cache. In69* lieu of that return key slot 0 for any unicast key70* request. We disallow the request if this is a group key.71* This default policy does the right thing for legacy hardware72* with a 4 key table. It also handles devices that pass73* packets through untouched when marked with the WEP bit74* and key index 0.75*/76if (k->wk_flags & IEEE80211_KEY_GROUP)77return 0;78*keyix = 0; /* NB: use key index 0 for ucast key */79} else {80*keyix = ieee80211_crypto_get_key_wepidx(vap, k);81}82*rxkeyix = IEEE80211_KEYIX_NONE; /* XXX maybe *keyix? */83return 1;84}85static int86null_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)87{88return 1;89}90static int91null_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k)92{93return 1;94}95static void null_key_update(struct ieee80211vap *vap) {}9697/*98* Write-arounds for common operations.99*/100static __inline void101cipher_detach(struct ieee80211_key *key)102{103key->wk_cipher->ic_detach(key);104}105106static __inline void *107cipher_attach(struct ieee80211vap *vap, struct ieee80211_key *key)108{109return key->wk_cipher->ic_attach(vap, key);110}111112/*113* Wrappers for driver key management methods.114*/115static __inline int116dev_key_alloc(struct ieee80211vap *vap,117struct ieee80211_key *key,118ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)119{120return vap->iv_key_alloc(vap, key, keyix, rxkeyix);121}122123static __inline int124dev_key_delete(struct ieee80211vap *vap,125const struct ieee80211_key *key)126{127return vap->iv_key_delete(vap, key);128}129130static __inline int131dev_key_set(struct ieee80211vap *vap, const struct ieee80211_key *key)132{133return vap->iv_key_set(vap, key);134}135136/*137* Setup crypto support for a device/shared instance.138*/139void140ieee80211_crypto_attach(struct ieee80211com *ic)141{142/* NB: we assume everything is pre-zero'd */143ciphers[IEEE80211_CIPHER_NONE] = &ieee80211_cipher_none;144145/*146* Default set of net80211 supported ciphers.147*148* These are the default set that all drivers are expected to149* support, either/or in hardware and software.150*151* Drivers can add their own support to this and the152* hardware cipher list (ic_cryptocaps.)153*/154ic->ic_sw_cryptocaps = IEEE80211_CRYPTO_WEP |155IEEE80211_CRYPTO_TKIP | IEEE80211_CRYPTO_AES_CCM;156157/*158* Default set of key management types supported by net80211.159*160* These are supported by software net80211 and announced/161* driven by hostapd + wpa_supplicant.162*163* Drivers doing full supplicant offload must not set164* anything here.165*166* Note that IEEE80211_C_WPA1 and IEEE80211_C_WPA2 are the167* "old" style way of drivers announcing key management168* capabilities. There are many, many more key management169* suites in 802.11-2016 (see 9.4.2.25.3 - AKM suites.)170* For now they still need to be set - these flags are checked171* when assembling a beacon to reserve space for the WPA172* vendor IE (WPA 1) and RSN IE (WPA 2).173*/174ic->ic_sw_keymgmtcaps = 0;175}176177/*178* Teardown crypto support.179*/180void181ieee80211_crypto_detach(struct ieee80211com *ic)182{183}184185/*186* Set the supported ciphers for software encryption.187*/188void189ieee80211_crypto_set_supported_software_ciphers(struct ieee80211com *ic,190uint32_t cipher_set)191{192ic->ic_sw_cryptocaps = cipher_set;193}194195/*196* Set the supported ciphers for hardware encryption.197*/198void199ieee80211_crypto_set_supported_hardware_ciphers(struct ieee80211com *ic,200uint32_t cipher_set)201{202ic->ic_cryptocaps = cipher_set;203}204205/*206* Set the supported software key management by the driver.207*208* These are the key management suites that are supported via209* the driver via hostapd/wpa_supplicant.210*211* Key management which is completely offloaded (ie, the supplicant212* runs in hardware/firmware) must not be set here.213*/214void215ieee80211_crypto_set_supported_driver_keymgmt(struct ieee80211com *ic,216uint32_t keymgmt_set)217{218219ic->ic_sw_keymgmtcaps = keymgmt_set;220}221222/*223* Setup crypto support for a vap.224*/225void226ieee80211_crypto_vattach(struct ieee80211vap *vap)227{228int i;229230/* NB: we assume everything is pre-zero'd */231vap->iv_max_keyix = IEEE80211_WEP_NKID;232vap->iv_def_txkey = IEEE80211_KEYIX_NONE;233for (i = 0; i < IEEE80211_WEP_NKID; i++)234ieee80211_crypto_resetkey(vap, &vap->iv_nw_keys[i],235IEEE80211_KEYIX_NONE);236/*237* Initialize the driver key support routines to noop entries.238* This is useful especially for the cipher test modules.239*/240vap->iv_key_alloc = null_key_alloc;241vap->iv_key_set = null_key_set;242vap->iv_key_delete = null_key_delete;243vap->iv_key_update_begin = null_key_update;244vap->iv_key_update_end = null_key_update;245}246247/*248* Teardown crypto support for a vap.249*/250void251ieee80211_crypto_vdetach(struct ieee80211vap *vap)252{253ieee80211_crypto_delglobalkeys(vap);254}255256/*257* Register a crypto cipher module.258*/259void260ieee80211_crypto_register(const struct ieee80211_cipher *cip)261{262if (cip->ic_cipher >= IEEE80211_CIPHER_MAX) {263net80211_printf("%s: cipher %s has an invalid cipher index %u\n",264__func__, cip->ic_name, cip->ic_cipher);265return;266}267if (ciphers[cip->ic_cipher] != NULL && ciphers[cip->ic_cipher] != cip) {268net80211_printf("%s: cipher %s registered with a different template\n",269__func__, cip->ic_name);270return;271}272ciphers[cip->ic_cipher] = cip;273}274275/*276* Unregister a crypto cipher module.277*/278void279ieee80211_crypto_unregister(const struct ieee80211_cipher *cip)280{281if (cip->ic_cipher >= IEEE80211_CIPHER_MAX) {282net80211_printf("%s: cipher %s has an invalid cipher index %u\n",283__func__, cip->ic_name, cip->ic_cipher);284return;285}286if (ciphers[cip->ic_cipher] != NULL && ciphers[cip->ic_cipher] != cip) {287net80211_printf("%s: cipher %s registered with a different template\n",288__func__, cip->ic_name);289return;290}291/* NB: don't complain about not being registered */292/* XXX disallow if references */293ciphers[cip->ic_cipher] = NULL;294}295296int297ieee80211_crypto_available(u_int cipher)298{299return cipher < IEEE80211_CIPHER_MAX && ciphers[cipher] != NULL;300}301302/* XXX well-known names! */303static const char *cipher_modnames[IEEE80211_CIPHER_MAX] = {304[IEEE80211_CIPHER_WEP] = "wlan_wep",305[IEEE80211_CIPHER_TKIP] = "wlan_tkip",306[IEEE80211_CIPHER_AES_OCB] = "wlan_aes_ocb",307[IEEE80211_CIPHER_AES_CCM] = "wlan_ccmp",308[IEEE80211_CIPHER_TKIPMIC] = "#4", /* NB: reserved */309[IEEE80211_CIPHER_CKIP] = "wlan_ckip",310[IEEE80211_CIPHER_NONE] = "wlan_none",311[IEEE80211_CIPHER_AES_CCM_256] = "wlan_ccmp",312[IEEE80211_CIPHER_BIP_CMAC_128] = "wlan_bip_cmac",313[IEEE80211_CIPHER_BIP_CMAC_256] = "wlan_bip_cmac",314[IEEE80211_CIPHER_BIP_GMAC_128] = "wlan_bip_gmac",315[IEEE80211_CIPHER_BIP_GMAC_256] = "wlan_bip_gmac",316[IEEE80211_CIPHER_AES_GCM_128] = "wlan_gcmp",317[IEEE80211_CIPHER_AES_GCM_256] = "wlan_gcmp",318};319320/* NB: there must be no overlap between user-supplied and device-owned flags */321CTASSERT((IEEE80211_KEY_COMMON & IEEE80211_KEY_DEVICE) == 0);322323/*324* Establish a relationship between the specified key and cipher325* and, if necessary, allocate a hardware index from the driver.326* Note that when a fixed key index is required it must be specified.327*328* This must be the first call applied to a key; all the other key329* routines assume wk_cipher is setup.330*331* Locking must be handled by the caller using:332* ieee80211_key_update_begin(vap);333* ieee80211_key_update_end(vap);334*/335int336ieee80211_crypto_newkey(struct ieee80211vap *vap,337int cipher, int flags, struct ieee80211_key *key)338{339struct ieee80211com *ic = vap->iv_ic;340const struct ieee80211_cipher *cip;341ieee80211_keyix keyix, rxkeyix;342void *keyctx;343int oflags;344345IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,346"%s: cipher %u flags 0x%x keyix %u\n",347__func__, cipher, flags, key->wk_keyix);348349/*350* Validate cipher and set reference to cipher routines.351*/352if (cipher >= IEEE80211_CIPHER_MAX) {353IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,354"%s: invalid cipher %u\n", __func__, cipher);355vap->iv_stats.is_crypto_badcipher++;356return 0;357}358cip = ciphers[cipher];359if (cip == NULL) {360/*361* Auto-load cipher module if we have a well-known name362* for it. It might be better to use string names rather363* than numbers and craft a module name based on the cipher364* name; e.g. wlan_cipher_<cipher-name>.365*/366IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,367"%s: unregistered cipher %u, load module %s\n",368__func__, cipher, cipher_modnames[cipher]);369ieee80211_load_module(cipher_modnames[cipher]);370/*371* If cipher module loaded it should immediately372* call ieee80211_crypto_register which will fill373* in the entry in the ciphers array.374*/375cip = ciphers[cipher];376if (cip == NULL) {377IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,378"%s: unable to load cipher %u, module %s\n",379__func__, cipher, cipher_modnames[cipher]);380vap->iv_stats.is_crypto_nocipher++;381return 0;382}383}384385oflags = key->wk_flags;386flags &= IEEE80211_KEY_COMMON;387/* NB: preserve device attributes */388flags |= (oflags & IEEE80211_KEY_DEVICE);389/*390* If the hardware does not support the cipher then391* fallback to a host-based implementation.392*/393if ((ic->ic_cryptocaps & (1<<cipher)) == 0) {394IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,395"%s: no h/w support for cipher %s, falling back to s/w\n",396__func__, cip->ic_name);397flags |= IEEE80211_KEY_SWCRYPT;398}399/*400* Check if the software cipher is available; if not then401* fail it early.402*403* Some devices do not support all ciphers in software404* (for example they don't support a "raw" data path.)405*/406if ((flags & IEEE80211_KEY_SWCRYPT) &&407(ic->ic_sw_cryptocaps & (1<<cipher)) == 0) {408IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,409"%s: no s/w support for cipher %s, rejecting\n",410__func__, cip->ic_name);411vap->iv_stats.is_crypto_swcipherfail++;412return (0);413}414/*415* Hardware TKIP with software MIC is an important416* combination; we handle it by flagging each key,417* the cipher modules honor it.418*/419if (cipher == IEEE80211_CIPHER_TKIP &&420(ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIPMIC) == 0) {421IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,422"%s: no h/w support for TKIP MIC, falling back to s/w\n",423__func__);424flags |= IEEE80211_KEY_SWMIC;425}426427/*428* Bind cipher to key instance. Note we do this429* after checking the device capabilities so the430* cipher module can optimize space usage based on431* whether or not it needs to do the cipher work.432*/433if (key->wk_cipher != cip || key->wk_flags != flags) {434/*435* Fillin the flags so cipher modules can see s/w436* crypto requirements and potentially allocate437* different state and/or attach different method438* pointers.439*/440key->wk_flags = flags;441keyctx = cip->ic_attach(vap, key);442if (keyctx == NULL) {443IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,444"%s: unable to attach cipher %s\n",445__func__, cip->ic_name);446key->wk_flags = oflags; /* restore old flags */447vap->iv_stats.is_crypto_attachfail++;448return 0;449}450cipher_detach(key);451key->wk_cipher = cip; /* XXX refcnt? */452key->wk_private = keyctx;453}454455/*456* Ask the driver for a key index if we don't have one.457* Note that entries in the global key table always have458* an index; this means it's safe to call this routine459* for these entries just to setup the reference to the460* cipher template. Note also that when using software461* crypto we also call the driver to give us a key index.462*/463if ((key->wk_flags & IEEE80211_KEY_DEVKEY) == 0) {464if (!dev_key_alloc(vap, key, &keyix, &rxkeyix)) {465/*466* Unable to setup driver state.467*/468vap->iv_stats.is_crypto_keyfail++;469IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,470"%s: unable to setup cipher %s\n",471__func__, cip->ic_name);472return 0;473}474if (key->wk_flags != flags) {475/*476* Driver overrode flags we setup; typically because477* resources were unavailable to handle _this_ key.478* Re-attach the cipher context to allow cipher479* modules to handle differing requirements.480*/481IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,482"%s: driver override for cipher %s, flags "483"%b -> %b\n", __func__, cip->ic_name,484oflags, IEEE80211_KEY_BITS,485key->wk_flags, IEEE80211_KEY_BITS);486keyctx = cip->ic_attach(vap, key);487if (keyctx == NULL) {488IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,489"%s: unable to attach cipher %s with "490"flags %b\n", __func__, cip->ic_name,491key->wk_flags, IEEE80211_KEY_BITS);492key->wk_flags = oflags; /* restore old flags */493vap->iv_stats.is_crypto_attachfail++;494return 0;495}496cipher_detach(key);497key->wk_cipher = cip; /* XXX refcnt? */498key->wk_private = keyctx;499}500key->wk_keyix = keyix;501key->wk_rxkeyix = rxkeyix;502key->wk_flags |= IEEE80211_KEY_DEVKEY;503}504return 1;505}506507/*508* Remove the key (no locking, for internal use).509*/510static int511_ieee80211_crypto_delkey(struct ieee80211vap *vap, struct ieee80211_key *key)512{513KASSERT(key->wk_cipher != NULL, ("No cipher!"));514515IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,516"%s: %s keyix %u flags %b rsc %ju tsc %ju len %u\n",517__func__, key->wk_cipher->ic_name,518key->wk_keyix, key->wk_flags, IEEE80211_KEY_BITS,519key->wk_keyrsc[IEEE80211_NONQOS_TID], key->wk_keytsc,520key->wk_keylen);521522if (key->wk_flags & IEEE80211_KEY_DEVKEY) {523/*524* Remove hardware entry.525*/526/* XXX key cache */527if (!dev_key_delete(vap, key)) {528IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,529"%s: driver did not delete key index %u\n",530__func__, key->wk_keyix);531vap->iv_stats.is_crypto_delkey++;532/* XXX recovery? */533}534}535cipher_detach(key);536memset(key, 0, sizeof(*key));537ieee80211_crypto_resetkey(vap, key, IEEE80211_KEYIX_NONE);538return 1;539}540541/*542* Remove the specified key.543*/544int545ieee80211_crypto_delkey(struct ieee80211vap *vap, struct ieee80211_key *key)546{547int status;548549ieee80211_key_update_begin(vap);550status = _ieee80211_crypto_delkey(vap, key);551ieee80211_key_update_end(vap);552return status;553}554555/*556* Clear the global key table.557*/558void559ieee80211_crypto_delglobalkeys(struct ieee80211vap *vap)560{561int i;562563ieee80211_key_update_begin(vap);564for (i = 0; i < IEEE80211_WEP_NKID; i++)565(void) _ieee80211_crypto_delkey(vap, &vap->iv_nw_keys[i]);566ieee80211_key_update_end(vap);567}568569/*570* Set the contents of the specified key.571*572* Locking must be handled by the caller using:573* ieee80211_key_update_begin(vap);574* ieee80211_key_update_end(vap);575*/576int577ieee80211_crypto_setkey(struct ieee80211vap *vap, struct ieee80211_key *key)578{579const struct ieee80211_cipher *cip = key->wk_cipher;580581KASSERT(cip != NULL, ("No cipher!"));582583IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,584"%s: %s keyix %u flags %b mac %s rsc %ju tsc %ju len %u\n",585__func__, cip->ic_name, key->wk_keyix,586key->wk_flags, IEEE80211_KEY_BITS, ether_sprintf(key->wk_macaddr),587key->wk_keyrsc[IEEE80211_NONQOS_TID], key->wk_keytsc,588key->wk_keylen);589590if ((key->wk_flags & IEEE80211_KEY_DEVKEY) == 0) {591/* XXX nothing allocated, should not happen */592IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,593"%s: no device key setup done; should not happen!\n",594__func__);595vap->iv_stats.is_crypto_setkey_nokey++;596return 0;597}598/*599* Give cipher a chance to validate key contents.600* XXX should happen before modifying state.601*/602if (!cip->ic_setkey(key)) {603IEEE80211_DPRINTF(vap, IEEE80211_MSG_CRYPTO,604"%s: cipher %s rejected key index %u len %u flags %b\n",605__func__, cip->ic_name, key->wk_keyix,606key->wk_keylen, key->wk_flags, IEEE80211_KEY_BITS);607vap->iv_stats.is_crypto_setkey_cipher++;608return 0;609}610return dev_key_set(vap, key);611}612613/**614* @brief Return index if the key is a WEP key (0..3); -1 otherwise.615*616* This is different to "get_keyid" which defaults to returning617* 0 for unicast keys; it assumes that it won't be used for WEP.618*619* @param vap the current VAP620* @param k ieee80211_key to check621* @returns 0..3 if it's a global/WEP key, -1 otherwise.622*/623int624ieee80211_crypto_get_key_wepidx(const struct ieee80211vap *vap,625const struct ieee80211_key *k)626{627628if (ieee80211_is_key_global(vap, k)) {629return (k - vap->iv_nw_keys);630}631return (-1);632}633634/**635* @brief Return the index of a unicast, global or IGTK key.636*637* Return the index of a key. For unicast keys the index is 0..1.638* For global/WEP keys it's 0..3. For IGTK keys its 4..5.639*640* TODO: support >1 unicast key641* TODO: support IGTK keys642*643* @param vap the current VAP644* @param k ieee80211_key to check645* @returns 0..3 for a WEP/global key, 0..1 for unicast key, 4..5 for IGTK key646*/647uint8_t648ieee80211_crypto_get_keyid(struct ieee80211vap *vap, struct ieee80211_key *k)649{650if (ieee80211_is_key_global(vap, k)) {651return (k - vap->iv_nw_keys);652}653654return (0);655}656657/**658* @param Return the key to use for encrypting an mbuf frame to a node659*660* This routine chooses a suitable key used to encrypt the given frame with.661* It doesn't do the encryption; it only chooses the key. If a key is not662* available then the routine will return NULL.663*664* It's up to the caller to enforce whether a key is absolutely required or not.665*666* @param ni The ieee80211_node to send the frame to667* @param m the mbuf to encrypt668* @returns the ieee80211_key to encrypt with, or NULL if there's no suitable key669*/670struct ieee80211_key *671ieee80211_crypto_get_txkey(struct ieee80211_node *ni, struct mbuf *m)672{673struct ieee80211vap *vap = ni->ni_vap;674struct ieee80211_frame *wh;675676/*677* Multicast traffic always uses the multicast key.678*679* Historically we would fall back to the default680* transmit key if there was no unicast key. This681* behaviour was documented up to IEEE Std 802.11-2016,682* 12.9.2.2 Per-MSDU/Per-A-MSDU Tx pseudocode, in the683* 'else' case but is no longer in later versions of684* the standard. Additionally falling back to the685* group key for unicast was a security risk.686*/687wh = mtod(m, struct ieee80211_frame *);688if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {689if (vap->iv_def_txkey == IEEE80211_KEYIX_NONE) {690IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO,691wh->i_addr1,692"no default transmit key (%s) deftxkey %u",693__func__, vap->iv_def_txkey);694vap->iv_stats.is_tx_nodefkey++;695return NULL;696}697return &vap->iv_nw_keys[vap->iv_def_txkey];698}699700if (IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey))701return NULL;702return &ni->ni_ucastkey;703}704705/**706* @brief Privacy encapsulate and encrypt the given mbuf.707*708* This routine handles the mechanics of encryption - expanding the709* mbuf to add privacy headers, IV, ICV, MIC, MMIC, and then encrypts710* the given mbuf if required.711*712* This should be called by the driver in its TX path as part of713* encapsulation before passing frames to the hardware/firmware714* queues.715*716* Drivers/hardware which does its own entirely offload path717* should still call this for completeness - it indicates to the718* driver that the frame itself should be encrypted.719*720* The driver should have set capability bits in the attach /721* key allocation path to disable various encapsulation/encryption722* features.723*724* @param ni ieee80211_node for this frame725* @param mbuf mbuf to modify726* @returns the key used if the frame is to be encrypted, NULL otherwise727*/728struct ieee80211_key *729ieee80211_crypto_encap(struct ieee80211_node *ni, struct mbuf *m)730{731struct ieee80211_key *k;732const struct ieee80211_cipher *cip;733734if ((k = ieee80211_crypto_get_txkey(ni, m)) != NULL) {735cip = k->wk_cipher;736return (cip->ic_encap(k, m) ? k : NULL);737}738739return NULL;740}741742/**743* @brief Decapsulate and validate an encrypted frame.744*745* This handles an encrypted frame (one with the privacy bit set.)746* It also obeys the key / config / receive packet flags for how747* the driver says its already been processed.748*749* Unlike ieee80211_crypto_encap(), this isn't called in the driver.750* Instead, drivers passed the potentially decrypted frame - fully,751* partial, or not at all - and net80211 will call this as appropriate.752*753* This handles NICs (like ath(4)) which have a variable size between754* the 802.11 header and 802.11 payload due to DMA alignment / encryption755* engine concerns.756*757* If the frame was decrypted and validated successfully then 1 is returned758* and the mbuf can be treated as an 802.11 frame. If it is not decrypted759* successfully or it was decrypted but failed validation/checks, then760* 0 is returned.761*762* @param ni ieee80211_node for received frame763* @param m mbuf frame to receive764* @param hdrlen length of the 802.11 header, including trailing null bytes765* @param key pointer to ieee80211_key that will be set if appropriate766* @returns 0 if the frame wasn't decrypted/validated, 1 if decrypted/validated.767*/768int769ieee80211_crypto_decap(struct ieee80211_node *ni, struct mbuf *m, int hdrlen,770struct ieee80211_key **key)771{772#define IEEE80211_WEP_HDRLEN (IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN)773#define IEEE80211_WEP_MINLEN \774(sizeof(struct ieee80211_frame) + \775IEEE80211_WEP_HDRLEN + IEEE80211_WEP_CRCLEN)776struct ieee80211vap *vap = ni->ni_vap;777struct ieee80211_key *k;778struct ieee80211_frame *wh;779const struct ieee80211_rx_stats *rxs;780const struct ieee80211_cipher *cip;781uint8_t keyid;782783/*784* Check for hardware decryption and IV stripping.785* If the IV is stripped then we definitely can't find a key.786* Set the key to NULL but return true; upper layers787* will need to handle a NULL key for a successful788* decrypt.789*/790rxs = ieee80211_get_rx_params_ptr(m);791if ((rxs != NULL) && (rxs->c_pktflags & IEEE80211_RX_F_DECRYPTED)) {792if (rxs->c_pktflags & IEEE80211_RX_F_IV_STRIP) {793/*794* Hardware decrypted, IV stripped.795* We can't find a key with a stripped IV.796* Return successful.797*/798*key = NULL;799return (1);800}801}802803/* NB: this minimum size data frame could be bigger */804if (m->m_pkthdr.len < IEEE80211_WEP_MINLEN) {805IEEE80211_DPRINTF(vap, IEEE80211_MSG_ANY,806"%s: WEP data frame too short, len %u\n",807__func__, m->m_pkthdr.len);808vap->iv_stats.is_rx_tooshort++; /* XXX need unique stat? */809*key = NULL;810return (0);811}812813/*814* Locate the key. If unicast and there is no unicast815* key then we fall back to the key id in the header.816* This assumes unicast keys are only configured when817* the key id in the header is meaningless (typically 0).818*/819wh = mtod(m, struct ieee80211_frame *);820m_copydata(m, hdrlen + IEEE80211_WEP_IVLEN, sizeof(keyid), &keyid);821if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||822IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey))823k = &vap->iv_nw_keys[keyid >> 6];824else825k = &ni->ni_ucastkey;826827/*828* Ensure crypto header is contiguous and long enough for all829* decap work.830*/831cip = k->wk_cipher;832if (m->m_len < hdrlen + cip->ic_header) {833IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO, wh->i_addr2,834"frame is too short (%d < %u) for crypto decap",835cip->ic_name, m->m_len, hdrlen + cip->ic_header);836vap->iv_stats.is_rx_tooshort++;837*key = NULL;838return (0);839}840841/*842* Attempt decryption.843*844* If we fail then don't return the key - return NULL845* and an error.846*/847if (cip->ic_decap(k, m, hdrlen)) {848/* success */849*key = k;850return (1);851}852853/* Failure */854*key = NULL;855return (0);856#undef IEEE80211_WEP_MINLEN857#undef IEEE80211_WEP_HDRLEN858}859860/**861* @brief Check and remove any post-defragmentation MIC from an MSDU.862*863* This is called after defragmentation. Crypto types that implement864* a MIC/ICV check per MSDU will not implement this function.865*866* As an example, TKIP decapsulation covers both MIC/ICV checks per867* MPDU (the "WEP" ICV) and then a Michael MIC verification on the868* defragmented MSDU. Please see 802.11-2020 12.5.2.1.3 (TKIP decapsulation)869* for more information.870*871* @param vap the current VAP872* @param k the current key873* @param m the mbuf representing the MSDU874* @param f set to 1 to force a MSDU MIC check, even if HW decrypted875* @returns 0 if error / MIC check failed, 1 if OK876*/877int878ieee80211_crypto_demic(struct ieee80211vap *vap, struct ieee80211_key *k,879struct mbuf *m, int force)880{881const struct ieee80211_cipher *cip;882const struct ieee80211_rx_stats *rxs;883struct ieee80211_frame *wh;884885rxs = ieee80211_get_rx_params_ptr(m);886wh = mtod(m, struct ieee80211_frame *);887888/*889* Handle demic / mic errors from hardware-decrypted offload devices.890*/891if ((rxs != NULL) && (rxs->c_pktflags & IEEE80211_RX_F_DECRYPTED)) {892if ((rxs->c_pktflags & IEEE80211_RX_F_FAIL_MMIC) != 0) {893/*894* Hardware has said MMIC failed. We don't care about895* whether it was stripped or not.896*897* Eventually - teach the demic methods in crypto898* modules to handle a NULL key and not to dereference899* it.900*/901ieee80211_notify_michael_failure(vap, wh,902IEEE80211_KEYIX_NONE);903return (0);904}905906if ((rxs->c_pktflags &907(IEEE80211_RX_F_MIC_STRIP|IEEE80211_RX_F_MMIC_STRIP)) != 0) {908/*909* Hardware has decrypted and not indicated a910* MIC failure and has stripped the MIC.911* We may not have a key, so for now just912* return OK.913*/914return (1);915}916}917918/*919* If we don't have a key at this point then we don't920* have to demic anything.921*/922if (k == NULL)923return (1);924925cip = k->wk_cipher;926return (cip->ic_miclen > 0 ? cip->ic_demic(k, m, force) : 1);927}928929static void930load_ucastkey(void *arg, struct ieee80211_node *ni)931{932struct ieee80211vap *vap = ni->ni_vap;933struct ieee80211_key *k;934935if (vap->iv_state != IEEE80211_S_RUN)936return;937k = &ni->ni_ucastkey;938if (k->wk_flags & IEEE80211_KEY_DEVKEY)939dev_key_set(vap, k);940}941942/*943* Re-load all keys known to the 802.11 layer that may944* have hardware state backing them. This is used by945* drivers on resume to push keys down into the device.946*/947void948ieee80211_crypto_reload_keys(struct ieee80211com *ic)949{950struct ieee80211vap *vap;951int i;952953/*954* Keys in the global key table of each vap.955*/956/* NB: used only during resume so don't lock for now */957TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {958if (vap->iv_state != IEEE80211_S_RUN)959continue;960for (i = 0; i < IEEE80211_WEP_NKID; i++) {961const struct ieee80211_key *k = &vap->iv_nw_keys[i];962if (k->wk_flags & IEEE80211_KEY_DEVKEY)963dev_key_set(vap, k);964}965}966/*967* Unicast keys.968*/969ieee80211_iterate_nodes(&ic->ic_sta, load_ucastkey, NULL);970}971972/*973* Set the default key index for WEP, or KEYIX_NONE for no default TX key.974*975* This should be done as part of a key update block (iv_key_update_begin /976* iv_key_update_end.)977*/978void979ieee80211_crypto_set_deftxkey(struct ieee80211vap *vap, ieee80211_keyix kid)980{981982/* XXX TODO: assert we're in a key update block */983984vap->iv_update_deftxkey(vap, kid);985}986987/**988* @brief Calculate the AAD required for this frame for AES-GCM/AES-CCM.989*990* The contents are described in 802.11-2020 12.5.3.3.3 (Construct AAD)991* under AES-CCM and are shared with AES-GCM as covered in 12.5.5.3.3992* (Construct AAD) (AES-GCM).993*994* NOTE: the first two bytes are a 16 bit big-endian length, which are used995* by AES-CCM as part of the Adata field (RFC 3610, section 2.2996* (Authentication)) to indicate the length of the Adata field itself.997* Since this is small and fits in 0xfeff bytes, the length field998* uses the two byte big endian option.999*1000* AES-GCM doesn't require the length at the beginning and will need to1001* skip it.1002*1003* TODO: net80211 currently doesn't support negotiating SPP (Signaling1004* and Payload Protected A-MSDUs) and thus bit 7 of the QoS control field1005* is always masked.1006*1007* TODO: net80211 currently doesn't support DMG (802.11ad) so bit 71008* (A-MSDU present) and bit 8 (A-MSDU type) are always masked.1009*1010* @param wh 802.11 frame to calculate the AAD over1011* @param aad AAD (additional authentication data) buffer1012* @param len The AAD buffer length in bytes.1013* @returns The number of AAD payload bytes (ignoring the first two1014* bytes, which are the AAD payload length in big-endian).1015*/1016uint16_t1017ieee80211_crypto_init_aad(const struct ieee80211_frame *wh, uint8_t *aad,1018int len)1019{1020uint16_t aad_len;10211022memset(aad, 0, len);10231024/*1025* AAD for PV0 MPDUs:1026*1027* FC with bits 4..6 and 11..13 masked to zero; 14 is always one1028* A1 | A2 | A31029* SC with bits 4..15 (seq#) masked to zero1030* A4 (if present)1031* QC (if present)1032*/1033aad[0] = 0; /* AAD length >> 8 */1034/* NB: aad[1] set below */1035aad[2] = wh->i_fc[0] & 0x8f; /* see above for bitfields */1036aad[3] = wh->i_fc[1] & 0xc7; /* see above for bitfields */1037/* mask aad[3] b7 if frame is data frame w/ QoS control field */1038if (IEEE80211_IS_QOS_ANY(wh))1039aad[3] &= 0x7f;10401041/* NB: we know 3 addresses are contiguous */1042memcpy(aad + 4, wh->i_addr1, 3 * IEEE80211_ADDR_LEN);1043aad[22] = wh->i_seq[0] & IEEE80211_SEQ_FRAG_MASK;1044aad[23] = 0; /* all bits masked */1045/*1046* Construct variable-length portion of AAD based1047* on whether this is a 4-address frame/QOS frame.1048* We always zero-pad to 32 bytes before running it1049* through the cipher.1050*/1051if (IEEE80211_IS_DSTODS(wh)) {1052IEEE80211_ADDR_COPY(aad + 24,1053((const struct ieee80211_frame_addr4 *)wh)->i_addr4);1054if (IEEE80211_IS_QOS_ANY(wh)) {1055const struct ieee80211_qosframe_addr4 *qwh4 =1056(const struct ieee80211_qosframe_addr4 *) wh;1057/* TODO: SPP A-MSDU / A-MSDU present bit */1058aad[30] = qwh4->i_qos[0] & 0x0f;/* just priority bits */1059aad[31] = 0;1060aad_len = aad[1] = 22 + IEEE80211_ADDR_LEN + 2;1061} else {1062*(uint16_t *)&aad[30] = 0;1063aad_len = aad[1] = 22 + IEEE80211_ADDR_LEN;1064}1065} else {1066if (IEEE80211_IS_QOS_ANY(wh)) {1067const struct ieee80211_qosframe *qwh =1068(const struct ieee80211_qosframe*) wh;1069/* TODO: SPP A-MSDU / A-MSDU present bit */1070aad[24] = qwh->i_qos[0] & 0x0f; /* just priority bits */1071aad[25] = 0;1072aad_len = aad[1] = 22 + 2;1073} else {1074*(uint16_t *)&aad[24] = 0;1075aad_len = aad[1] = 22;1076}1077*(uint16_t *)&aad[26] = 0;1078*(uint32_t *)&aad[28] = 0;1079}10801081return (aad_len);1082}108310841085