1# cfg80211 test cases
2# Copyright (c) 2014, Jouni Malinen <j@w1.fi>
3#
4# This software may be distributed under the terms of the BSD license.
5# See README for more details.
6
7from remotehost import remote_compatible
8import logging
9logger = logging.getLogger()
10import binascii
11import os
12import time
13
14import hostapd
15import hwsim_utils
16from tshark import run_tshark
17from nl80211 import *
18from wpasupplicant import WpaSupplicant
19from utils import *
20
21def nl80211_command(dev, cmd, attr):
22    res = dev.request("VENDOR ffffffff {} {}".format(nl80211_cmd[cmd],
23                                                     binascii.hexlify(attr).decode()))
24    if "FAIL" in res:
25        raise Exception("nl80211 command failed")
26    return binascii.unhexlify(res)
27
28@remote_compatible
29def test_cfg80211_disassociate(dev, apdev):
30    """cfg80211 disassociation command"""
31    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
32    dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
33    ev = hapd.wait_event(["AP-STA-CONNECTED"], timeout=5)
34    if ev is None:
35        raise Exception("No connection event received from hostapd")
36
37    ifindex = int(dev[0].get_driver_status_field("ifindex"))
38    attrs = build_nl80211_attr_u32('IFINDEX', ifindex)
39    attrs += build_nl80211_attr_u16('REASON_CODE', 1)
40    attrs += build_nl80211_attr_mac('MAC', apdev[0]['bssid'])
41    nl80211_command(dev[0], 'DISASSOCIATE', attrs)
42
43    ev = hapd.wait_event(["AP-STA-DISCONNECTED"], timeout=5)
44    if ev is None:
45        raise Exception("No disconnection event received from hostapd")
46
47def nl80211_frame(dev, ifindex, frame, freq=None, duration=None, offchannel_tx_ok=False):
48    attrs = build_nl80211_attr_u32('IFINDEX', ifindex)
49    if freq is not None:
50        attrs += build_nl80211_attr_u32('WIPHY_FREQ', freq)
51    if duration is not None:
52        attrs += build_nl80211_attr_u32('DURATION', duration)
53    if offchannel_tx_ok:
54        attrs += build_nl80211_attr_flag('OFFCHANNEL_TX_OK')
55    attrs += build_nl80211_attr('FRAME', frame)
56    return parse_nl80211_attrs(nl80211_command(dev, 'FRAME', attrs))
57
58def nl80211_frame_wait_cancel(dev, ifindex, cookie):
59    attrs = build_nl80211_attr_u32('IFINDEX', ifindex)
60    attrs += build_nl80211_attr('COOKIE', cookie)
61    return nl80211_command(dev, 'FRAME_WAIT_CANCEL', attrs)
62
63def nl80211_remain_on_channel(dev, ifindex, freq, duration):
64    attrs = build_nl80211_attr_u32('IFINDEX', ifindex)
65    attrs += build_nl80211_attr_u32('WIPHY_FREQ', freq)
66    attrs += build_nl80211_attr_u32('DURATION', duration)
67    return nl80211_command(dev, 'REMAIN_ON_CHANNEL', attrs)
68
69def test_cfg80211_tx_frame(dev, apdev, params):
70    """cfg80211 offchannel TX frame command"""
71
72    dev[0].p2p_start_go(freq='2412')
73    go = WpaSupplicant(dev[0].group_ifname)
74    addr = go.own_addr()
75    frame = binascii.unhexlify("d0000000020000000100" + addr.replace(':', '') + "02000000010000000409506f9a090001dd5e506f9a0902020025080401001f0502006414060500585804510b0906000200000000000b1000585804510b0102030405060708090a0b0d1d000200000000000108000000000000000000101100084465766963652041110500585804510bdd190050f204104a0001101012000200011049000600372a000120")
76    ifindex = int(go.get_driver_status_field("ifindex"))
77    res = nl80211_frame(go, ifindex, frame, freq=2422, duration=500,
78                        offchannel_tx_ok=True)
79    time.sleep(0.1)
80
81    # note: Uncommenting this seems to remove the incorrect channel issue
82    #nl80211_frame_wait_cancel(dev[0], ifindex, res[nl80211_attr['COOKIE']])
83
84    # note: this Action frame ends up getting sent incorrectly on 2422 MHz
85    nl80211_frame(go, ifindex, frame, freq=2412)
86    time.sleep(1.5)
87    # note: also the Deauthenticate frame sent by the GO going down ends up
88    # being transmitted incorrectly on 2422 MHz.
89
90    del go
91
92    out = run_tshark(os.path.join(params['logdir'], "hwsim0.pcapng"),
93                     "wlan.fc.type_subtype == 13 && wlan.sa == " + addr,
94                     ["radiotap.channel.freq"])
95    if out is not None:
96        freq = out.splitlines()
97        if len(freq) != 2:
98            raise Exception("Unexpected number of Action frames (%d)" % len(freq))
99        if freq[0] != "2422":
100            raise Exception("First Action frame on unexpected channel: %s MHz" % freq[0])
101        if freq[1] != "2412":
102            raise Exception("Second Action frame on unexpected channel: %s MHz" % freq[1])
103
104@remote_compatible
105def test_cfg80211_wep_key_idx_change(dev, apdev):
106    """WEP Shared Key authentication and key index change without deauth"""
107    check_wep_capa(dev[0])
108    hapd = hostapd.add_ap(apdev[0],
109                          {"ssid": "wep-shared-key",
110                           "wep_key0": '"hello12345678"',
111                           "wep_key1": '"other12345678"',
112                           "auth_algs": "2"})
113    id = dev[0].connect("wep-shared-key", key_mgmt="NONE", auth_alg="SHARED",
114                        wep_key0='"hello12345678"',
115                        wep_key1='"other12345678"',
116                        wep_tx_keyidx="0",
117                        scan_freq="2412")
118    hwsim_utils.test_connectivity(dev[0], hapd)
119
120    dev[0].set_network(id, "wep_tx_keyidx", "1")
121
122    # clear cfg80211 auth state to allow new auth without deauth frame
123    ifindex = int(dev[0].get_driver_status_field("ifindex"))
124    attrs = build_nl80211_attr_u32('IFINDEX', ifindex)
125    attrs += build_nl80211_attr_u16('REASON_CODE', 1)
126    attrs += build_nl80211_attr_mac('MAC', apdev[0]['bssid'])
127    attrs += build_nl80211_attr_flag('LOCAL_STATE_CHANGE')
128    nl80211_command(dev[0], 'DEAUTHENTICATE', attrs)
129    dev[0].wait_disconnected(timeout=5, error="Local-deauth timed out")
130
131    # the previous command results in deauth event followed by auto-reconnect
132    dev[0].wait_connected(timeout=10, error="Reassociation timed out")
133    hwsim_utils.test_connectivity(dev[0], hapd)
134
135@remote_compatible
136def test_cfg80211_hostapd_ext_sta_remove(dev, apdev):
137    """cfg80211 DEL_STATION issued externally to hostapd"""
138    hapd = hostapd.add_ap(apdev[0], {"ssid": "open"})
139    id = dev[0].connect("open", key_mgmt="NONE", scan_freq="2412")
140
141    ifindex = int(hapd.get_driver_status_field("ifindex"))
142    attrs = build_nl80211_attr_u32('IFINDEX', ifindex)
143    attrs += build_nl80211_attr_u16('REASON_CODE', 1)
144    attrs += build_nl80211_attr_u8('MGMT_SUBTYPE', 12)
145    attrs += build_nl80211_attr_mac('MAC', dev[0].own_addr())
146    nl80211_command(hapd, 'DEL_STATION', attrs)
147
148    # Currently, hostapd ignores the NL80211_CMD_DEL_STATION event if
149    # drv->device_ap_sme == 0 (which is the case with mac80211_hwsim), so no
150    # further action happens here. If that event were to be used to remove the
151    # STA entry from hostapd even in device_ap_sme == 0 case, this test case
152    # could be extended to cover additional operations.
153