From patchwork Fri Sep 11 04:21:56 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Johannes Berg X-Patchwork-Id: 2302837 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@legolas.ozlabs.org Authentication-Results: legolas.ozlabs.org; dkim=pass (2048-bit key; secure) header.d=lists.infradead.org header.i=@lists.infradead.org header.a=rsa-sha256 header.s=bombadil.20210309 header.b=YJzyCTSd; dkim=fail reason="signature verification failed" (2048-bit key; secure) header.d=sipsolutions.net header.i=@sipsolutions.net header.a=rsa-sha256 header.s=mail header.b=OjkP4uIB; dkim-atps=neutral Authentication-Results: legolas.ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.infradead.org (client-ip=2607:7c80:54:3::133; helo=bombadil.infradead.org; envelope-from=hostap-bounces+incoming=patchwork.ozlabs.org@lists.infradead.org; receiver=patchwork.ozlabs.org) Received: from bombadil.infradead.org (bombadil.infradead.org [IPv6:2607:7c80:54:3::133]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange x25519 server-signature ECDSA (secp384r1) server-digest SHA384) (No client certificate requested) by legolas.ozlabs.org (Postfix) with ESMTPS id 4hhGxP10q6z1xxw for ; Sat, 12 Sep 2026 00:23:37 +1000 (AEST) DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=lists.infradead.org; s=bombadil.20210309; h=Sender: Content-Transfer-Encoding:Content-Type:List-Subscribe:List-Help:List-Post: List-Archive:List-Unsubscribe:List-Id:MIME-Version:Message-ID:Date:Subject:Cc :To:From:Reply-To:Content-ID:Content-Description:Resent-Date:Resent-From: Resent-Sender:Resent-To:Resent-Cc:Resent-Message-ID:In-Reply-To:References: List-Owner; bh=zkXDPIsaFsRgxyUOo8RFtI9bHdfTmlOkeEFCd1xlUDg=; b=YJzyCTSdjsXTxC Jb8mJoPUadlbEkU0bvkBe9fj63+R7rUOyRSJ0moagT7PqECHqmGs/3iBxswYTu2GCsdwQVnLZ8QgH PCgOlkEudbP83UL4DT0nZtaTFUFA6LNrlL68XRSrpW5v8gRAFoThsKVnMy3fFtsPKibO1BuUlb0mn MWTrf6A3GuV208ieZbUNi10HCntnAWyzArqlZuFPqVgYxUcTeBacs7WR07UY1z8scSX61exz45aF3 pvaPLp/sbpoesks+ZdnChVDLWZsjtg1+swm2vMYYcu+syKqL4QANqJRGRDEoHpCVXciXdkEN+VvnV dBuD9NPPWSV36Wa/eORA==; Received: from localhost ([::1] helo=bombadil.infradead.org) by bombadil.infradead.org with esmtp (Exim 4.99.1 #2 (Red Hat Linux)) id 1x528m-0000000GtdP-0Ze6; Fri, 11 Sep 2026 14:22:08 +0000 Received: from s3.sipsolutions.net ([2a01:4f8:242:246e::2] helo=sipsolutions.net) by bombadil.infradead.org with esmtps (Exim 4.99.1 #2 (Red Hat Linux)) id 1x528i-0000000Gtbd-2CHh for hostap@lists.infradead.org; Fri, 11 Sep 2026 14:22:06 +0000 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=sipsolutions.net; s=mail; h=Content-Transfer-Encoding:MIME-Version: Message-ID:Date:Subject:Cc:To:From:Content-Type:Sender:Reply-To:Content-ID: Content-Description:Resent-Date:Resent-From:Resent-To:Resent-Cc: Resent-Message-ID:In-Reply-To:References; bh=/BHVfwTTWCoE/lsRIi663o+jxNs1awXeKL5QTpu1guU=; t=1789136524; x=1790346124; b=OjkP4uIBYnbdbqoxxWLIeQGi/Nw8cNGt37tM0jDdN5UFRS6xrTaLOMpFYuy563ehdbV8Z+Mmho8 eyZwp24Npm2xRsbpX+WEGAiUTCbAQAImIaVqPynNdPRkIy7Ea2uPOSHYNRVQBQWw0bUuPnmE+HIxH sHpAndddjEjMrhUChKKY6KLUBs2tEel5Mroi5RYwVYFOHzrJhtLqAiR6SyBSXGcmUEHbTBk1L+kEc sJ0hcLhGF7mBcTckfcm93F7JsKIa7FLD8OJvSC2hNqdfh1m7eVO9DkgLeKHv1OrRCa6Pz7Tvf0H2/ UYE2CRbgIIB1B/Flninzpcu3svp5rpKM5eMw==; Received: by sipsolutions.net with esmtpsa (TLS1.3:ECDHE_X25519__ECDSA_SECP256R1_SHA256__AES_256_GCM:256) (Exim 4.98.2) (envelope-from ) id 1x528c-0000000C3Fz-0aZy; Fri, 11 Sep 2026 16:21:58 +0200 From: Johannes Berg To: hostap@lists.infradead.org Cc: Johannes Berg Subject: [PATCH 1/3] hostapd: ctrl_iface: add commands to get GTK/IGTK/BIGTK Date: Fri, 11 Sep 2026 16:21:56 +0200 Message-ID: <20260911162155.a68a3333d735.I91a1d4893862b7f2e04707626ba62c2216e835c9@changeid> X-Mailer: git-send-email 2.55.0 MIME-Version: 1.0 X-CRM114-Version: 20100106-BlameMichelson ( TRE 0.9.0 (BSD) ) MR-646709E3 X-CRM114-CacheID: sfid-20260911_072204_845366_843DFB73 X-CRM114-Status: GOOD ( 11.54 ) X-Spam-Score: -2.1 (--) X-Spam-Report: Spam detection software, running on the system "bombadil.infradead.org", has NOT identified this incoming email as spam. The original message has been attached to this so you can view it or label similar future email. If you have any questions, see the administrator of that system for details. Content preview: From: Johannes Berg For some of the tests that the relay module enables we'll have to have beacon protection, so the relay will have to recalculate the MIC in the MME. Add testing commands to get the GTK/IGTK/BIGTK from hostapd. Content analysis details: (-2.1 points, 5.0 required) pts rule name description ---- ---------------------- -------------------------------------------------- -0.0 SPF_HELO_PASS SPF: HELO matches SPF record -0.0 SPF_PASS SPF: sender matches SPF record -0.1 DKIM_VALID_EF Message has a valid DKIM or DK signature from envelope-from domain -0.1 DKIM_VALID Message has at least one valid DKIM or DK signature -0.1 DKIM_VALID_AU Message has a valid DKIM or DK signature from author's domain 0.1 DKIM_SIGNED Message has a DKIM or DK signature, not necessarily valid -1.9 BAYES_00 BODY: Bayes spam probability is 0 to 1% [score: 0.0000] 0.0 DMARC_MISSING Missing DMARC policy X-BeenThere: hostap@lists.infradead.org X-Mailman-Version: 2.1.34 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Sender: "Hostap" Errors-To: hostap-bounces+incoming=patchwork.ozlabs.org@lists.infradead.org From: Johannes Berg For some of the tests that the relay module enables we'll have to have beacon protection, so the relay will have to recalculate the MIC in the MME. Add testing commands to get the GTK/IGTK/BIGTK from hostapd. Signed-off-by: Johannes Berg --- hostapd/ctrl_iface.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/hostapd/ctrl_iface.c b/hostapd/ctrl_iface.c index 380a7bc24b6b..dc36b302de57 100644 --- a/hostapd/ctrl_iface.c +++ b/hostapd/ctrl_iface.c @@ -2559,6 +2559,39 @@ static int hostapd_ctrl_get_pmk(struct hostapd_data *hapd, const char *cmd, } +static int hostapd_ctrl_get_gtk(struct hostapd_data *hapd, char *buf, + size_t buflen) +{ + if (hapd->last_gtk_alg == WPA_ALG_NONE) + return -1; + + return wpa_snprintf_hex(buf, buflen, hapd->last_gtk, + hapd->last_gtk_len); +} + + +static int hostapd_ctrl_get_igtk(struct hostapd_data *hapd, char *buf, + size_t buflen) +{ + if (hapd->last_igtk_alg == WPA_ALG_NONE) + return -1; + + return wpa_snprintf_hex(buf, buflen, hapd->last_igtk, + hapd->last_igtk_len); +} + + +static int hostapd_ctrl_get_bigtk(struct hostapd_data *hapd, char *buf, + size_t buflen) +{ + if (hapd->last_bigtk_alg == WPA_ALG_NONE) + return -1; + + return wpa_snprintf_hex(buf, buflen, hapd->last_bigtk, + hapd->last_bigtk_len); +} + + static int hostapd_ctrl_register_frame(struct hostapd_data *hapd, const char *cmd) { @@ -4486,6 +4519,12 @@ static int hostapd_ctrl_iface_receive_process(struct hostapd_data *hapd, } else if (os_strncmp(buf, "GET_PMK ", 8) == 0) { reply_len = hostapd_ctrl_get_pmk(hapd, buf + 8, reply, reply_size); + } else if (os_strcmp(buf, "GET_GTK") == 0) { + reply_len = hostapd_ctrl_get_gtk(hapd, reply, reply_size); + } else if (os_strcmp(buf, "GET_IGTK") == 0) { + reply_len = hostapd_ctrl_get_igtk(hapd, reply, reply_size); + } else if (os_strcmp(buf, "GET_BIGTK") == 0) { + reply_len = hostapd_ctrl_get_bigtk(hapd, reply, reply_size); } else if (os_strncmp(buf, "REGISTER_FRAME ", 15) == 0) { if (hostapd_ctrl_register_frame(hapd, buf + 16) < 0) reply_len = -1; From patchwork Fri Sep 11 04:21:57 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Johannes Berg X-Patchwork-Id: 2302838 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@legolas.ozlabs.org Authentication-Results: legolas.ozlabs.org; dkim=pass (2048-bit key; secure) header.d=lists.infradead.org header.i=@lists.infradead.org header.a=rsa-sha256 header.s=bombadil.20210309 header.b=ImbHzGK3; dkim=fail reason="signature verification failed" (2048-bit key; secure) header.d=sipsolutions.net header.i=@sipsolutions.net header.a=rsa-sha256 header.s=mail header.b=vDuBNImP; dkim-atps=neutral Authentication-Results: legolas.ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.infradead.org (client-ip=2607:7c80:54:3::133; helo=bombadil.infradead.org; envelope-from=hostap-bounces+incoming=patchwork.ozlabs.org@lists.infradead.org; receiver=patchwork.ozlabs.org) Received: from bombadil.infradead.org (bombadil.infradead.org [IPv6:2607:7c80:54:3::133]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange x25519 server-signature ECDSA (secp384r1) server-digest SHA384) (No client certificate requested) by legolas.ozlabs.org (Postfix) with ESMTPS id 4hhGxQ4HtHz1y0L for ; Sat, 12 Sep 2026 00:23:38 +1000 (AEST) DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=lists.infradead.org; s=bombadil.20210309; h=Sender: Content-Transfer-Encoding:Content-Type:List-Subscribe:List-Help:List-Post: List-Archive:List-Unsubscribe:List-Id:MIME-Version:References:In-Reply-To: Message-ID:Date:Subject:Cc:To:From:Reply-To:Content-ID:Content-Description: Resent-Date:Resent-From:Resent-Sender:Resent-To:Resent-Cc:Resent-Message-ID: List-Owner; bh=Oe3m7inuiEJUhOjd+rIWsJNapK5jCMtAFXnXpG4N/QI=; b=ImbHzGK3ER2suo BEWAwV4Yhibx6NKThyVIrhZGbhL8OiCp19IgJGX7iEkNJykaZe/zKVqNBf2n/o3Nsz95ZUKWFNiyQ 8Qp0ZUyb/H34bPnJfQhxkDmS7/kVi8hDdoP5A9Ma08CsCfZGC7SknDQ1MN5x+OLgz7C/EWT489DUZ 151SChyJMhhVoVJC4px+3KfS94TcmIPq94O9LKjdmeRA+ESLcXz+HSj+DYKC64pN09XdPGq4IKCeR h5NTw5skX+Mh/ZELP7xZ9NgNErWCyN1AqtH51OqCladyXIo9MuV1TCPbwiZTR/zm0/jo0NL/LbuBO Wg1wZqhQ4pDOCIblpMbQ==; Received: from localhost ([::1] helo=bombadil.infradead.org) by bombadil.infradead.org with esmtp (Exim 4.99.1 #2 (Red Hat Linux)) id 1x528o-0000000Gtdk-1BHr; Fri, 11 Sep 2026 14:22:10 +0000 Received: from s3.sipsolutions.net ([2a01:4f8:242:246e::2] helo=sipsolutions.net) by bombadil.infradead.org with esmtps (Exim 4.99.1 #2 (Red Hat Linux)) id 1x528j-0000000Gtbg-0jrX for hostap@lists.infradead.org; Fri, 11 Sep 2026 14:22:07 +0000 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=sipsolutions.net; s=mail; h=Content-Transfer-Encoding:MIME-Version: References:In-Reply-To:Message-ID:Date:Subject:Cc:To:From:Content-Type:Sender :Reply-To:Content-ID:Content-Description:Resent-Date:Resent-From:Resent-To: Resent-Cc:Resent-Message-ID; bh=nvv5jHQQldXp4C0Tknt4fC6SzrVYwMot4UkyabKWNe8=; t=1789136525; x=1790346125; b=vDuBNImPStpKaaQ/L5DZAvTnynOdvFv7OThLluv04Niy16b FQG5Xmr776D6KEuyfFVhLZQtPX9jKh9HQLlKbydkyE/pXtGCiHJzSB2fotIj3hcqQDhSVTkTyQmRD hBHnAjewtkoIANlwpapnWvhO7WH/YKyln54aacSKfWW9L4kwjuU7xGbChsHR6Xy8QlKmx6+AKKb9q XkNAKaJ8BtnqwgXbuvlVBaqxW4LPtDK1TrzUVPbZ4RnFAlfjqrctN+xJX4751jOc9MtZgmWaqTx/W HlyS//bZvqfUtswh/IAp59zSZ9ZXHGF+zhSs6obmnYYiDydNVzOgxLlKlezeTSWg==; Received: by sipsolutions.net with esmtpsa (TLS1.3:ECDHE_X25519__ECDSA_SECP256R1_SHA256__AES_256_GCM:256) (Exim 4.98.2) (envelope-from ) id 1x528c-0000000C3Fz-3DME; Fri, 11 Sep 2026 16:21:58 +0200 From: Johannes Berg To: hostap@lists.infradead.org Cc: Johannes Berg Subject: [PATCH 2/3] hostapd: ctrl_iface: add LINK_STA command Date: Fri, 11 Sep 2026 16:21:57 +0200 Message-ID: <20260911162155.2027f5ce665b.Ic8a6681ef4102a46e0d61cfb0ebdcdb311985d8e@changeid> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20260911162155.a68a3333d735.I91a1d4893862b7f2e04707626ba62c2216e835c9@changeid> References: <20260911162155.a68a3333d735.I91a1d4893862b7f2e04707626ba62c2216e835c9@changeid> MIME-Version: 1.0 X-CRM114-Version: 20100106-BlameMichelson ( TRE 0.9.0 (BSD) ) MR-646709E3 X-CRM114-CacheID: sfid-20260911_072205_217164_1C54EAE4 X-CRM114-Status: GOOD ( 12.00 ) X-Spam-Score: -2.1 (--) X-Spam-Report: Spam detection software, running on the system "bombadil.infradead.org", has NOT identified this incoming email as spam. The original message has been attached to this so you can view it or label similar future email. If you have any questions, see the administrator of that system for details. Content preview: From: Johannes Berg This can be used to look up a station by link address. Signed-off-by: Johannes Berg --- hostapd/ctrl_iface.c | 5 +++++ src/ap/ctrl_iface_ap.c | 19 +++++++++++++++++++ src/ap/ctrl_iface_ap.h | 4 ++++ 3 files changed, 28 insertions [...] Content analysis details: (-2.1 points, 5.0 required) pts rule name description ---- ---------------------- -------------------------------------------------- -0.0 SPF_HELO_PASS SPF: HELO matches SPF record -0.0 SPF_PASS SPF: sender matches SPF record -0.1 DKIM_VALID_EF Message has a valid DKIM or DK signature from envelope-from domain -0.1 DKIM_VALID Message has at least one valid DKIM or DK signature -0.1 DKIM_VALID_AU Message has a valid DKIM or DK signature from author's domain 0.1 DKIM_SIGNED Message has a DKIM or DK signature, not necessarily valid -1.9 BAYES_00 BODY: Bayes spam probability is 0 to 1% [score: 0.0000] 0.0 DMARC_MISSING Missing DMARC policy X-BeenThere: hostap@lists.infradead.org X-Mailman-Version: 2.1.34 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Sender: "Hostap" Errors-To: hostap-bounces+incoming=patchwork.ozlabs.org@lists.infradead.org From: Johannes Berg This can be used to look up a station by link address. Signed-off-by: Johannes Berg --- hostapd/ctrl_iface.c | 5 +++++ src/ap/ctrl_iface_ap.c | 19 +++++++++++++++++++ src/ap/ctrl_iface_ap.h | 4 ++++ 3 files changed, 28 insertions(+) diff --git a/hostapd/ctrl_iface.c b/hostapd/ctrl_iface.c index dc36b302de57..49b163aaf4a5 100644 --- a/hostapd/ctrl_iface.c +++ b/hostapd/ctrl_iface.c @@ -4310,6 +4310,11 @@ static int hostapd_ctrl_iface_receive_process(struct hostapd_data *hapd, } else if (os_strncmp(buf, "STA ", 4) == 0) { reply_len = hostapd_ctrl_iface_sta(hapd, buf + 4, reply, reply_size); +#ifdef CONFIG_IEEE80211BE + } else if (os_strncmp(buf, "LINK_STA ", 9) == 0) { + reply_len = hostapd_ctrl_iface_link_sta(hapd, buf + 9, reply, + reply_size); +#endif /* CONFIG_IEEE80211BE */ } else if (os_strncmp(buf, "STA-NEXT ", 9) == 0) { reply_len = hostapd_ctrl_iface_sta_next(hapd, buf + 9, reply, reply_size); diff --git a/src/ap/ctrl_iface_ap.c b/src/ap/ctrl_iface_ap.c index 57ec4f6ec12d..223f9601623a 100644 --- a/src/ap/ctrl_iface_ap.c +++ b/src/ap/ctrl_iface_ap.c @@ -587,6 +587,25 @@ int hostapd_ctrl_iface_sta_next(struct hostapd_data *hapd, const char *txtaddr, } +#ifdef CONFIG_IEEE80211BE +int hostapd_ctrl_iface_link_sta(struct hostapd_data *hapd, + const char *txtaddr, char *buf, size_t buflen) +{ + u8 addr[ETH_ALEN]; + struct sta_info *sta; + + if (hwaddr_aton(txtaddr, addr)) + return -1; + + sta = ap_get_link_sta(hapd, addr); + if (!sta) + return -1; + + return hostapd_ctrl_iface_sta_mib(hapd, sta, buf, buflen); +} +#endif /* CONFIG_IEEE80211BE */ + + #ifdef CONFIG_P2P_MANAGER static int p2p_manager_disconnect(struct hostapd_data *hapd, u16 stype, u8 minor_reason_code, const u8 *addr) diff --git a/src/ap/ctrl_iface_ap.h b/src/ap/ctrl_iface_ap.h index 4de140844f0b..e2add32570c6 100644 --- a/src/ap/ctrl_iface_ap.h +++ b/src/ap/ctrl_iface_ap.h @@ -15,6 +15,10 @@ int hostapd_ctrl_iface_sta(struct hostapd_data *hapd, const char *txtaddr, char *buf, size_t buflen); int hostapd_ctrl_iface_sta_next(struct hostapd_data *hapd, const char *txtaddr, char *buf, size_t buflen); +#ifdef CONFIG_IEEE80211BE +int hostapd_ctrl_iface_link_sta(struct hostapd_data *hapd, + const char *txtaddr, char *buf, size_t buflen); +#endif /* CONFIG_IEEE80211BE */ int hostapd_ctrl_iface_deauthenticate(struct hostapd_data *hapd, const char *txtaddr); int hostapd_ctrl_iface_disassociate(struct hostapd_data *hapd, From patchwork Fri Sep 11 04:21:58 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Johannes Berg X-Patchwork-Id: 2302839 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@legolas.ozlabs.org Authentication-Results: legolas.ozlabs.org; dkim=pass (2048-bit key; secure) header.d=lists.infradead.org header.i=@lists.infradead.org header.a=rsa-sha256 header.s=bombadil.20210309 header.b=ALqAaeWW; dkim=fail reason="signature verification failed" (2048-bit key; secure) header.d=sipsolutions.net header.i=@sipsolutions.net header.a=rsa-sha256 header.s=mail header.b=u3F2ptzU; dkim-atps=neutral Authentication-Results: legolas.ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.infradead.org (client-ip=2607:7c80:54:3::133; helo=bombadil.infradead.org; envelope-from=hostap-bounces+incoming=patchwork.ozlabs.org@lists.infradead.org; receiver=patchwork.ozlabs.org) Received: from bombadil.infradead.org (bombadil.infradead.org [IPv6:2607:7c80:54:3::133]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange x25519 server-signature ECDSA (secp384r1) server-digest SHA384) (No client certificate requested) by legolas.ozlabs.org (Postfix) with ESMTPS id 4hhGxV2XVVz1xxw for ; Sat, 12 Sep 2026 00:23:42 +1000 (AEST) DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=lists.infradead.org; s=bombadil.20210309; h=Sender: Content-Transfer-Encoding:Content-Type:List-Subscribe:List-Help:List-Post: List-Archive:List-Unsubscribe:List-Id:MIME-Version:References:In-Reply-To: Message-ID:Date:Subject:Cc:To:From:Reply-To:Content-ID:Content-Description: Resent-Date:Resent-From:Resent-Sender:Resent-To:Resent-Cc:Resent-Message-ID: List-Owner; bh=FpHJzqnyydwP3TmL7N6huq3XjUGXY3gndncEdS1oJ4w=; b=ALqAaeWW+1nrkt ffVn8z/ZPZUK/27UXWProZLa8jURuDHYrA2jJ++dM/Hhc+oAiAYC2HEE0NpPnK2ptCIfewpeoJLdi r1/JtY/XmMhoC3RuZRUEGnodZTb8EcnVXOJOpFfjfP6jW4b5DfHe2nk5LvjnQmt7t/TAd80J0xgyO 6NvSuwAWg8J0OiT1n5NQSiExWvjgSpvMrGr/1htJqgf1kdij6P4wFHodcopb/qVTdxOUBqqFsXl0Q yWhpdJvtCYdLIbzudjTkb3sI5wFwqpJsRGWXIP1Wd93ynUsjI0PXVTX3qqXwIdap8QHvZ2o0gBF3L w1Tob39XlL4CNfBoUI4g==; Received: from localhost ([::1] helo=bombadil.infradead.org) by bombadil.infradead.org with esmtp (Exim 4.99.1 #2 (Red Hat Linux)) id 1x528o-0000000Gtdt-1mFf; Fri, 11 Sep 2026 14:22:10 +0000 Received: from s3.sipsolutions.net ([2a01:4f8:242:246e::2] helo=sipsolutions.net) by bombadil.infradead.org with esmtps (Exim 4.99.1 #2 (Red Hat Linux)) id 1x528j-0000000Gtbf-0gEr for hostap@lists.infradead.org; Fri, 11 Sep 2026 14:22:08 +0000 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=sipsolutions.net; s=mail; h=Content-Transfer-Encoding:MIME-Version: References:In-Reply-To:Message-ID:Date:Subject:Cc:To:From:Content-Type:Sender :Reply-To:Content-ID:Content-Description:Resent-Date:Resent-From:Resent-To: Resent-Cc:Resent-Message-ID; bh=uRblaZvqMoQZOF7Cj8BUQRf8YABoTGtxT8i87xkX6fc=; t=1789136525; x=1790346125; b=u3F2ptzUUv+Pb/hKP18ldlCmQd/a+riEPDbW0+sqNRmR4UH sSgNog24/y6p1PGlkhtpt+G+xkodSUGR7C2GSzyMTUO3jUNsaqhV76nnNCzt3+TEyI4VU1T4AF5np D2psl+rOAJjk9pQIZe6u929WLue0lwf7cFyqZKAYXI8JDJycIMqxbe5rBXGUKcvIp+zNRagvpBt4+ RJwwkgiPm7z1sJF9HhkxHdNCyPOZwYnrsUXTcIscio2fbXmyAAsOc7ryOpXI9jyl+FhUCq9zGM63W hRtC3+1B4xmKnwjtexj1QzNT6X4iDcfyQTTfGG2vNWTEs5eEAyRaSxW9bdqkDaRw==; Received: by sipsolutions.net with esmtpsa (TLS1.3:ECDHE_X25519__ECDSA_SECP256R1_SHA256__AES_256_GCM:256) (Exim 4.98.2) (envelope-from ) id 1x528d-0000000C3Fz-1Ir5; Fri, 11 Sep 2026 16:21:59 +0200 From: Johannes Berg To: hostap@lists.infradead.org Cc: Johannes Berg Subject: [PATCH 3/3] tests: hwsim: add hwsim relay code Date: Fri, 11 Sep 2026 16:21:58 +0200 Message-ID: <20260911162155.f5b8580c732e.I4a5b2e8479865b86b1c66fdc92288f92570a68f1@changeid> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20260911162155.a68a3333d735.I91a1d4893862b7f2e04707626ba62c2216e835c9@changeid> References: <20260911162155.a68a3333d735.I91a1d4893862b7f2e04707626ba62c2216e835c9@changeid> MIME-Version: 1.0 X-CRM114-Version: 20100106-BlameMichelson ( TRE 0.9.0 (BSD) ) MR-646709E3 X-CRM114-CacheID: sfid-20260911_072205_517629_120EFFD3 X-CRM114-Status: GOOD ( 25.20 ) X-Spam-Score: -2.1 (--) X-Spam-Report: Spam detection software, running on the system "bombadil.infradead.org", has NOT identified this incoming email as spam. The original message has been attached to this so you can view it or label similar future email. If you have any questions, see the administrator of that system for details. Content preview: From: Johannes Berg For a lot of tests that we don't have now, it'd be useful to be able to modify or drop arbitrary frames going across the medium, such as beacons to test various CSA/critical update scenarios, missed b [...] Content analysis details: (-2.1 points, 5.0 required) pts rule name description ---- ---------------------- -------------------------------------------------- -0.0 SPF_HELO_PASS SPF: HELO matches SPF record -0.0 SPF_PASS SPF: sender matches SPF record -0.1 DKIM_VALID_EF Message has a valid DKIM or DK signature from envelope-from domain -0.1 DKIM_VALID Message has at least one valid DKIM or DK signature -0.1 DKIM_VALID_AU Message has a valid DKIM or DK signature from author's domain 0.1 DKIM_SIGNED Message has a DKIM or DK signature, not necessarily valid -1.9 BAYES_00 BODY: Bayes spam probability is 0 to 1% [score: 0.0000] 0.0 DMARC_MISSING Missing DMARC policy X-BeenThere: hostap@lists.infradead.org X-Mailman-Version: 2.1.34 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Sender: "Hostap" Errors-To: hostap-bounces+incoming=patchwork.ozlabs.org@lists.infradead.org From: Johannes Berg For a lot of tests that we don't have now, it'd be useful to be able to modify or drop arbitrary frames going across the medium, such as beacons to test various CSA/critical update scenarios, missed beacons overlapping with CSA to force mac80211 to detect it from another link, etc. Even where it's not error conditions hostapd doesn't necessarily support all features we want to test. Add a hwsim relay module that registers with the wmediumd APIs and can be used by tests to intercept frames. By default it'll relay all frames unmodified, but frame handling layers can be stacked on top of it as in the example test. Right now the code has one to wait for frames (relay.WaitFrame), recalculate BIP for protected group management frames and beacons after they've been modified by further layers (bip.GroupMgmtSigner) and one to decrypt management frames before passing to the next layer and re-encrypt them if they were changed (ccmp.ProtectedMgmtCrypto). The choice for CCMP is because that's simpler with python. All of this will likely only work right with UML's time-travel, but that's not really that much of an issue, and it allows us to write a large number of tests that'd otherwise be impossible. Note that the involvement of a background thread which is doing control interface commands now requires a lock in wpaspy. Signed-off-by: Johannes Berg --- tests/hwsim/hostapd.py | 7 + tests/hwsim/relay/__init__.py | 309 ++++++++++++++++++++++++++++++++ tests/hwsim/relay/bip.py | 86 +++++++++ tests/hwsim/relay/ccmp.py | 97 ++++++++++ tests/hwsim/relay/frame.py | 118 ++++++++++++ tests/hwsim/test_hwsim_relay.py | 110 ++++++++++++ wpaspy/wpaspy.py | 29 +-- 7 files changed, 743 insertions(+), 13 deletions(-) create mode 100644 tests/hwsim/relay/__init__.py create mode 100644 tests/hwsim/relay/bip.py create mode 100644 tests/hwsim/relay/ccmp.py create mode 100644 tests/hwsim/relay/frame.py create mode 100644 tests/hwsim/test_hwsim_relay.py diff --git a/tests/hwsim/hostapd.py b/tests/hwsim/hostapd.py index 9cfe5a2b61d0..41f7c7db96f6 100644 --- a/tests/hwsim/hostapd.py +++ b/tests/hwsim/hostapd.py @@ -443,6 +443,13 @@ class Hostapd: res = self.request(cmd + addr + " " + info) else: res = self.request(cmd + addr) + return self._parse_sta_mib(res) + + def get_link_sta(self, addr): + return self._parse_sta_mib(self.request("LINK_STA " + addr)) + + @staticmethod + def _parse_sta_mib(res): lines = res.splitlines() vals = dict() first = True diff --git a/tests/hwsim/relay/__init__.py b/tests/hwsim/relay/__init__.py new file mode 100644 index 000000000000..3d970d369829 --- /dev/null +++ b/tests/hwsim/relay/__init__.py @@ -0,0 +1,309 @@ +# +# hwsim relay - interceptor for hwsim using wmediumd API +# +# Copyright (C) 2026 Intel Corporation +# +# This software may be distributed under the terms of the BSD license. +# See README for more details. +# +# +# This code allows intercepting and manipulating/dropping frames that +# are being transmitted over the hwsim medium simulation, for testing +# purposes. +# +# Note that it will only really work in UML's time-travel. +# + +import threading +import queue +import os +import errno +import logging + +import netlink + +logger = logging.getLogger() + +HWSIM_CMD_REGISTER = 1 +HWSIM_CMD_FRAME = 2 +HWSIM_CMD_TX_INFO_FRAME = 3 + +HWSIM_ATTR_ADDR_RECEIVER = 1 +HWSIM_ATTR_ADDR_TRANSMITTER = 2 +HWSIM_ATTR_FRAME = 3 +HWSIM_ATTR_FLAGS = 4 +HWSIM_ATTR_RX_RATE = 5 +HWSIM_ATTR_SIGNAL = 6 +HWSIM_ATTR_TX_INFO = 7 +HWSIM_ATTR_COOKIE = 8 +HWSIM_ATTR_FREQ = 19 +HWSIM_ATTR_NO_MONITOR = 32 + +HWSIM_TX_CTL_REQ_TX_STATUS = 1 << 0 +HWSIM_TX_CTL_NO_ACK = 1 << 1 +HWSIM_TX_STAT_ACK = 1 << 2 + +IEEE80211_TX_MAX_RATES = 4 + + +def _tx_info_all_invalid(): + # struct hwsim_tx_rate { idx = -1, count = 0 } + return b'\xff\x00' * IEEE80211_TX_MAX_RATES + + +def radio_addr_for_iface(ifname): + phy = os.path.basename(os.readlink( + '/sys/class/net/%s/phy80211' % ifname)) + with open('/sys/class/ieee80211/%s/addresses' % phy) as f: + addrs = f.read().split() + return bytes.fromhex(addrs[1].replace(':', '')) + + +class RelayLayer: + """ + Base layer for frame interception - each layer has its own + .intercept() like the HwsimRelay() itself. + + Note: the intercept is run on a background thread + """ + + def __init__(self, upstream): + self._upstream = upstream + self._downstream = self._default + + def __enter__(self): + self._prev = self._upstream.intercept + self._upstream.intercept = self._run + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._upstream.intercept = self._prev + + @property + def intercept(self): + return self._downstream + + @intercept.setter + def intercept(self, fn): + self._downstream = fn + + def _default(self, src, freq, frame): + return frame + + def _run(self, src, freq, frame): + raise NotImplementedError + + +class WaitFrame(RelayLayer): + def __init__(self, upstream, matchers): + super().__init__(upstream) + self._matchers = list(matchers) + self._results = queue.Queue() + + def _run(self, src, freq, frame): + for matcher in self._matchers: + result = matcher.match(src, freq, frame) + if result is not None: + self._results.put(result) + break + return self.intercept(src, freq, frame) + + def wait_for_frame(self, timeout=5): + try: + return self._results.get(timeout=timeout) + except queue.Empty: + return None + + +_MGMT_SUBTYPES = { + 0: 'AssocReq', + 1: 'AssocResp', + 2: 'ReassocReq', + 3: 'ReassocResp', + 4: 'ProbeReq', + 5: 'ProbeResp', + 6: 'TimingAdv', + 8: 'Beacon', + 9: 'ATIM', + 10: 'Disassoc', + 11: 'Auth', + 12: 'Deauth', + 13: 'Action', + 14: 'ActionNoAck', +} + + +def _frame_type_str(frame): + if len(frame) < 2: + return '?' + + fc = frame[0] + ftype = (fc >> 2) & 0x3 + subtype = (fc >> 4) & 0xf + if ftype == 0: + return _MGMT_SUBTYPES.get(subtype, 'Mgmt(%d)' % subtype) + + return { + 1: 'Ctrl', + 2: 'Data', + 3: 'Ext' + }[ftype] + '(%d)' % subtype + + +class HwsimRelay: + def __init__(self, intercept=None, rx_rate=1, signal=-30, radios=None): + """ + By default every frame is passed through unmodified to every + radio other than the sender, but the intercept call can override + that. + + intercept(src_addr: bytes, freq: int|None, frame: bytes) -> frame: bytes | None + + The returned frame (or None to drop it) is sent to every radio + other than the sender - all receivers always see the same frame, + as they would over the air. + + Note: intercept calls are on a background thread + """ + self._conn = netlink.Connection(netlink.NETLINK_GENERIC) + self._fid = netlink.genl_controller.get_family_id(b'MAC80211_HWSIM') + self._radios = set() + for addr in (radios or []): + self.add_radio(addr) + self._intercept_fn = intercept or self._default_intercept + self._rx_rate = rx_rate + self._signal = signal + self._running = False + self._thread = None + self._exc = None + + @property + def intercept(self): + return self._intercept_fn + + @intercept.setter + def intercept(self, fn): + self._intercept_fn = fn or self._default_intercept + + def add_radio(self, addr): + if isinstance(addr, str): + addr = bytes.fromhex(addr.replace(':', '')) + self._radios.add(addr) + + def add_radio_for_iface(self, ifname): + self.add_radio(radio_addr_for_iface(ifname)) + + def _default_intercept(self, src, freq, frame): + return frame + + def register(self): + msg = netlink.GenlMessage(self._fid, HWSIM_CMD_REGISTER, + flags=netlink.NLM_F_REQUEST | + netlink.NLM_F_ACK) + msg.send_and_recv(self._conn) + + def start(self): + self.register() + self._running = True + self._thread = threading.Thread(target=self._loop, daemon=True) + self._thread.start() + + def stop(self): + self._running = False + self._conn.descriptor.close() + if self._thread: + self._thread.join(timeout=5) + self._thread = None + + def __enter__(self): + self.start() + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.stop() + # raise thread exceptions into the test + if self._exc is not None: + exc, self._exc = self._exc, None + raise exc + + def _loop(self): + while self._running: + try: + msg = self._conn.recv() + if msg.type != self._fid or len(msg.payload) < 4: + continue + cmd = msg.payload[0] + if cmd != HWSIM_CMD_FRAME: + logger.debug("hwsim_relay: non-FRAME cmd=%d" % (cmd,)) + continue + attrs = netlink.parse_attributes(msg.payload[4:]) + self._handle_frame(attrs) + except OSError as e: + # stop() closes the fd to stop the thread, ignore errors + if not self._running: + break + # hwsim rejects frames for radios not started with EINVAL + if e.errno != errno.EINVAL: + logger.warning("hwsim_relay: dropping failed op: %r" % (e,)) + except Exception as e: + logger.error("hwsim_relay: exception in thread: %s" % (e,)) + # record exception for __exit__ + self._exc = e + break + + def _handle_frame(self, attrs): + if HWSIM_ATTR_ADDR_TRANSMITTER not in attrs or \ + HWSIM_ATTR_FRAME not in attrs or \ + HWSIM_ATTR_COOKIE not in attrs: + return + + src = attrs[HWSIM_ATTR_ADDR_TRANSMITTER].str() + frame = attrs[HWSIM_ATTR_FRAME].str() + freq = attrs[HWSIM_ATTR_FREQ].u32() if HWSIM_ATTR_FREQ in attrs else None + flags = attrs[HWSIM_ATTR_FLAGS].u32() if HWSIM_ATTR_FLAGS in attrs else 0 + cookie = attrs[HWSIM_ATTR_COOKIE].str() + + self._radios.add(src) + out_frame = self._intercept_fn(src, freq, frame) + logger.debug("hwsim_relay: %s src=%s len=%d freq=%s flags=0x%x" % + (_frame_type_str(frame), src.hex(), len(frame), freq, flags)) + + delivered = False + if out_frame is not None: + for dst in tuple(self._radios): + if dst != src: + self._deliver(src, dst, out_frame, freq, cookie) + delivered = True + + self._ack(src, flags, cookie, delivered) + + def _deliver(self, src, dst, frame, freq, cookie): + attrs = [ + netlink.StrAttr(HWSIM_ATTR_ADDR_TRANSMITTER, src), + netlink.StrAttr(HWSIM_ATTR_ADDR_RECEIVER, dst), + netlink.StrAttr(HWSIM_ATTR_FRAME, frame), + netlink.U32Attr(HWSIM_ATTR_RX_RATE, self._rx_rate), + netlink.U32Attr(HWSIM_ATTR_SIGNAL, self._signal & 0xffffffff), + netlink.Attr(HWSIM_ATTR_COOKIE, cookie), + ] + if freq is not None: + attrs.append(netlink.U32Attr(HWSIM_ATTR_FREQ, freq)) + msg = netlink.GenlMessage(self._fid, HWSIM_CMD_FRAME, attrs=attrs, + flags=netlink.NLM_F_REQUEST) + msg.send(self._conn) + + def _ack(self, src, flags, cookie, delivered): + tx_flags = HWSIM_TX_STAT_ACK if delivered and \ + not (flags & HWSIM_TX_CTL_NO_ACK) else 0 + attrs = [ + netlink.StrAttr(HWSIM_ATTR_ADDR_TRANSMITTER, src), + netlink.U32Attr(HWSIM_ATTR_FLAGS, tx_flags), + netlink.Attr(HWSIM_ATTR_COOKIE, cookie), + netlink.U32Attr(HWSIM_ATTR_SIGNAL, self._signal & 0xffffffff), + netlink.StrAttr(HWSIM_ATTR_TX_INFO, _tx_info_all_invalid()), + ] + if not delivered: + attrs.append(netlink.FlagAttr(HWSIM_ATTR_NO_MONITOR)) + msg = netlink.GenlMessage(self._fid, HWSIM_CMD_TX_INFO_FRAME, + attrs=attrs, flags=netlink.NLM_F_REQUEST) + msg.send(self._conn) diff --git a/tests/hwsim/relay/bip.py b/tests/hwsim/relay/bip.py new file mode 100644 index 000000000000..0e1395c01506 --- /dev/null +++ b/tests/hwsim/relay/bip.py @@ -0,0 +1,86 @@ +# +# Copyright (C) 2026 Intel Corporation +# +# This software may be distributed under the terms of the BSD license. +# See README for more details. + +try: + from Cryptodome.Cipher import AES + from Cryptodome.Hash import CMAC +except ImportError: + from Crypto.Cipher import AES + from Crypto.Hash import CMAC + +from . import RelayLayer +from .frame import MGMT_HDR_LEN, is_beacon, masked_fc_aad + +WLAN_EID_MMIE = 76 + + +def find_mmie(frame, mic_len=8): + mmie_len = 2 + 2 + 6 + mic_len + if len(frame) < MGMT_HDR_LEN + mmie_len: + return None + mmie = frame[-mmie_len:] + if mmie[0] != WLAN_EID_MMIE or mmie[1] != mmie_len - 2: + return None + return mmie + +def bip_aad(frame): + return masked_fc_aad(frame) + +def bip_cmac_mic(key, frame, mic_len=8): + aad = bip_aad(frame) + body = bytearray(frame[MGMT_HDR_LEN:]) + if is_beacon(frame): + body[0:8] = b'\x00' * 8 + body[-mic_len:] = b'\x00' * mic_len + + c = CMAC.new(key, ciphermod=AES) + c.update(aad + bytes(body)) + return c.digest()[:mic_len] + + +def resign_frame(frame, key): + mmie = find_mmie(frame) + if mmie is None: + return frame + mic_len = len(mmie) - (2 + 2 + 6) + mic = bip_cmac_mic(key, frame, mic_len) + return frame[:-mic_len] + mic + + +def group_key_getter(hapd): + def get_key(frame): + cmd = "GET_BIGTK" if is_beacon(frame) else "GET_IGTK" + res = hapd.request(cmd) + if res is None or "FAIL" in res: + return None + return bytes.fromhex(res.strip()) + return get_key + + +class GroupMgmtSigner(RelayLayer): + """ + Recalculate the MIC for a group-addressed frame after the inner + layers have changed it. + + get_key: callable get_key(frame) or hostapd instance + """ + + def __init__(self, upstream, get_key): + super().__init__(upstream) + self._get_key = get_key if callable(get_key) else \ + group_key_getter(get_key) + + def _run(self, src, freq, frame): + out_frame = self.intercept(src, freq, frame) + if out_frame is None or find_mmie(out_frame) is None: + return out_frame + return self._resign(frame, out_frame) + + def _resign(self, old, frame): + if frame == old: + return frame + key = self._get_key(frame) + return resign_frame(frame, key) if key is not None else frame diff --git a/tests/hwsim/relay/ccmp.py b/tests/hwsim/relay/ccmp.py new file mode 100644 index 000000000000..3f666178291d --- /dev/null +++ b/tests/hwsim/relay/ccmp.py @@ -0,0 +1,97 @@ +# +# Copyright (C) 2026 Intel Corporation +# +# This software may be distributed under the terms of the BSD license. +# See README for more details. +# + +try: + from Cryptodome.Cipher import AES +except ImportError: + from Crypto.Cipher import AES + +from . import RelayLayer +from .frame import (IEEE80211_FCTL_PROTECTED, MGMT_HDR_LEN, is_protected_mgmt, + masked_fc_aad, client_addr) + +CCMP_HDR_LEN = 8 + + +def _mgmt_aad_nonce(frame): + aad = masked_fc_aad(frame, extra_mask=IEEE80211_FCTL_PROTECTED) + aad += bytes([frame[22] & 0x0f, 0]) + + ccmp_hdr = frame[MGMT_HDR_LEN:MGMT_HDR_LEN + CCMP_HDR_LEN] + pn = bytes([ccmp_hdr[7], ccmp_hdr[6], ccmp_hdr[5], ccmp_hdr[4], + ccmp_hdr[1], ccmp_hdr[0]]) + nonce = bytes([0x10]) + frame[10:16] + pn + return aad, nonce + + +def ccmp_decrypt_mgmt(frame, tk, mic_len=8): + aad, nonce = _mgmt_aad_nonce(frame) + + body_start = MGMT_HDR_LEN + CCMP_HDR_LEN + ciphertext = frame[body_start:len(frame) - mic_len] + mic = frame[len(frame) - mic_len:] + + cipher = AES.new(tk, AES.MODE_CCM, nonce=nonce, mac_len=mic_len) + cipher.update(aad) + return cipher.decrypt_and_verify(ciphertext, mic) + + +def ccmp_encrypt_mgmt(frame, tk, body, mic_len=8): + aad, nonce = _mgmt_aad_nonce(frame) + + cipher = AES.new(tk, AES.MODE_CCM, nonce=nonce, mac_len=mic_len) + cipher.update(aad) + ciphertext, mic = cipher.encrypt_and_digest(body) + + body_start = MGMT_HDR_LEN + CCMP_HDR_LEN + return frame[:body_start] + ciphertext + mic + + +def sta_tk_getter(hapd, cipher="CCMP"): + def get_tk(addr): + addr_str = addr.hex(':') + + # might be a link address, try to resolve it + sta = hapd.get_link_sta(addr_str) + resolved = sta.get('addr') + if resolved and resolved != 'FAIL': + addr_str = resolved + + ptksa = hapd.get_ptksa(addr_str, cipher) + if ptksa is None: + return None + return bytes.fromhex(ptksa['tk']) + return get_tk + + +class ProtectedMgmtCrypto(RelayLayer): + """ + Decrypt CCMP-protected management frames and pass them to + the next layer unencrypted (but protected bit still set) + + get_tk: callable get_tk(client_addr) or hostapd instance + """ + def __init__(self, upstream, get_tk): + super().__init__(upstream) + self._get_tk = get_tk if callable(get_tk) else sta_tk_getter(get_tk) + + def _run(self, src, freq, frame): + if is_protected_mgmt(frame): + tk = self._get_tk(client_addr(frame)) + if tk is not None: + try: + body = ccmp_decrypt_mgmt(frame, tk) + except ValueError: + body = None + if body is not None: + clear_frame = frame[:MGMT_HDR_LEN] + body + out_frame = self.intercept(src, freq, clear_frame) + if out_frame is not None and is_protected_mgmt(out_frame): + return ccmp_encrypt_mgmt(frame, tk, + out_frame[MGMT_HDR_LEN:]) + return out_frame + return self.intercept(src, freq, frame) diff --git a/tests/hwsim/relay/frame.py b/tests/hwsim/relay/frame.py new file mode 100644 index 000000000000..27d9a81ff254 --- /dev/null +++ b/tests/hwsim/relay/frame.py @@ -0,0 +1,118 @@ +# +# 802.11 frame helpers for frame relay handling +# +# Copyright (C) 2026 Intel Corporation +# +# This software may be distributed under the terms of the BSD license. +# See README for more details. +# + +import struct + +IEEE80211_FCTL_RETRY = 0x0800 +IEEE80211_FCTL_PM = 0x1000 +IEEE80211_FCTL_MOREDATA = 0x2000 +IEEE80211_FCTL_PROTECTED = 0x4000 +IEEE80211_FCTL_FTYPE = 0x000c +IEEE80211_FTYPE_MGMT = 0x0000 + +STYPE_ASSOC_RESP = 1 +STYPE_REASSOC_RESP = 3 +STYPE_PROBE_RESP = 5 +STYPE_BEACON = 8 +STYPE_DEAUTH = 12 + +MGMT_HDR_LEN = 24 + +WLAN_EID_EXTENSION = 255 + + +def frame_fc(frame): + return struct.unpack_from('> 4) & 0xf + + +def is_mgmt_subtype(frame, stype): + return is_ftype_mgmt(frame) and mgmt_subtype(frame) == stype + + +def is_beacon(frame): + return is_mgmt_subtype(frame, STYPE_BEACON) + + +def is_protected_mgmt(frame): + if len(frame) < MGMT_HDR_LEN: + return False + return is_ftype_mgmt(frame) and bool(frame_fc(frame) & IEEE80211_FCTL_PROTECTED) + + +def is_protected_deauth(frame): + return is_protected_mgmt(frame) and is_mgmt_subtype(frame, STYPE_DEAUTH) + + +def ies_start_offset(frame): + """Byte offset of the IE section for beacon/probe-resp/assoc-resp.""" + stype = mgmt_subtype(frame) + if stype in (STYPE_BEACON, STYPE_PROBE_RESP): + return 24 + 12 # timestamp(8) + beacon_interval(2) + capab(2) + if stype in (STYPE_ASSOC_RESP, STYPE_REASSOC_RESP): + return 24 + 6 # capab(2) + status(2) + aid(2) + raise ValueError("unsupported mgmt subtype %d for IE parsing" % stype) + + +def iter_elements(buf, start=0): + """Yield (eid, ext_id_or_None, elem_start, payload_off, payload_len).""" + i = start + while i + 2 <= len(buf): + eid = buf[i] + elen = buf[i + 1] + if i + 2 + elen > len(buf): + break + payload_off = i + 2 + payload_len = elen + ext_id = None + if eid == WLAN_EID_EXTENSION and elen >= 1: + ext_id = buf[payload_off] + payload_off += 1 + payload_len -= 1 + yield eid, ext_id, i, payload_off, payload_len + i += 2 + elen + + +def find_element(buf, start, eid, ext_id=None): + for e, x, elem_start, payload_off, payload_len in iter_elements(buf, start): + if e == eid and x == ext_id: + elem_total_len = (payload_off + payload_len) - elem_start + return elem_start, elem_total_len, payload_off, payload_len + return None + + +def build_element(payload, eid=None, ext_id=None): + if ext_id is None: + return struct.pack('BB', eid, len(payload)) + payload + return struct.pack('BBB', WLAN_EID_EXTENSION, 1 + len(payload), ext_id) + payload + + +def client_addr(frame): + addr1, addr2, bssid = frame[4:10], frame[10:16], frame[16:22] + return addr1 if addr2 == bssid else addr2 + + +def masked_fc_aad(frame, extra_mask=0): + fc = frame_fc(frame) + masked_fc = (fc & ~(IEEE80211_FCTL_RETRY | IEEE80211_FCTL_PM | + IEEE80211_FCTL_MOREDATA)) | extra_mask + return struct.pack('