1 # Python class for controlling hostapd
2 # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
14 logger = logging.getLogger()
15 hapd_ctrl = '/var/run/hostapd'
16 hapd_global = '/var/run/hostapd-global'
19 return struct.unpack('6B', binascii.unhexlify(mac.replace(':','')))
23 self.ctrl = wpaspy.Ctrl(hapd_global)
24 self.mon = wpaspy.Ctrl(hapd_global)
27 def request(self, cmd):
28 return self.ctrl.request(cmd)
30 def wait_event(self, events, timeout):
33 while self.mon.pending():
35 logger.debug("(global): " + ev)
40 remaining = start + timeout - now
43 if not self.mon.pending(timeout=remaining):
47 def add(self, ifname):
48 res = self.ctrl.request("ADD " + ifname + " " + hapd_ctrl)
50 raise Exception("Could not add hostapd interface " + ifname)
52 def add_iface(self, ifname, confname):
53 res = self.ctrl.request("ADD " + ifname + " config=" + confname)
55 raise Exception("Could not add hostapd interface")
57 def add_bss(self, phy, confname, ignore_error=False):
58 res = self.ctrl.request("ADD bss_config=" + phy + ":" + confname)
61 raise Exception("Could not add hostapd BSS")
63 def remove(self, ifname):
64 self.ctrl.request("REMOVE " + ifname, timeout=30)
67 self.ctrl.request("RELOG")
70 self.ctrl.request("FLUSH")
74 def __init__(self, ifname, bssidx=0):
76 self.ctrl = wpaspy.Ctrl(os.path.join(hapd_ctrl, ifname))
77 self.mon = wpaspy.Ctrl(os.path.join(hapd_ctrl, ifname))
83 if self.bssid is None:
84 self.bssid = self.get_status_field('bssid[%d]' % self.bssidx)
87 def request(self, cmd):
88 logger.debug(self.ifname + ": CTRL: " + cmd)
89 return self.ctrl.request(cmd)
92 return "PONG" in self.request("PING")
94 def set(self, field, value):
95 if not "OK" in self.request("SET " + field + " " + value):
96 raise Exception("Failed to set hostapd parameter " + field)
98 def set_defaults(self):
99 self.set("driver", "nl80211")
100 self.set("hw_mode", "g")
101 self.set("channel", "1")
102 self.set("ieee80211n", "1")
103 self.set("logger_stdout", "-1")
104 self.set("logger_stdout_level", "0")
106 def set_open(self, ssid):
108 self.set("ssid", ssid)
110 def set_wpa2_psk(self, ssid, passphrase):
112 self.set("ssid", ssid)
113 self.set("wpa_passphrase", passphrase)
115 self.set("wpa_key_mgmt", "WPA-PSK")
116 self.set("rsn_pairwise", "CCMP")
118 def set_wpa_psk(self, ssid, passphrase):
120 self.set("ssid", ssid)
121 self.set("wpa_passphrase", passphrase)
123 self.set("wpa_key_mgmt", "WPA-PSK")
124 self.set("wpa_pairwise", "TKIP")
126 def set_wpa_psk_mixed(self, ssid, passphrase):
128 self.set("ssid", ssid)
129 self.set("wpa_passphrase", passphrase)
131 self.set("wpa_key_mgmt", "WPA-PSK")
132 self.set("wpa_pairwise", "TKIP")
133 self.set("rsn_pairwise", "CCMP")
135 def set_wep(self, ssid, key):
137 self.set("ssid", ssid)
138 self.set("wep_key0", key)
141 if not "OK" in self.request("ENABLE"):
142 raise Exception("Failed to enable hostapd interface " + self.ifname)
145 if not "OK" in self.request("DISABLE"):
146 raise Exception("Failed to disable hostapd interface " + self.ifname)
148 def dump_monitor(self):
149 while self.mon.pending():
151 logger.debug(self.ifname + ": " + ev)
153 def wait_event(self, events, timeout):
154 start = os.times()[4]
156 while self.mon.pending():
158 logger.debug(self.ifname + ": " + ev)
163 remaining = start + timeout - now
166 if not self.mon.pending(timeout=remaining):
170 def get_status(self):
171 res = self.request("STATUS")
172 lines = res.splitlines()
175 [name,value] = l.split('=', 1)
179 def get_status_field(self, field):
180 vals = self.get_status()
185 def get_driver_status(self):
186 res = self.request("STATUS-DRIVER")
187 lines = res.splitlines()
190 [name,value] = l.split('=', 1)
194 def get_driver_status_field(self, field):
195 vals = self.get_driver_status()
200 def get_config(self):
201 res = self.request("GET_CONFIG")
202 lines = res.splitlines()
205 [name,value] = l.split('=', 1)
209 def mgmt_rx(self, timeout=5):
210 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
214 frame = binascii.unhexlify(ev.split(' ')[1])
217 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
219 msg['subtype'] = (hdr[0] >> 4) & 0xf
221 msg['duration'] = hdr[0]
223 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
225 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
227 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
229 msg['seq_ctrl'] = hdr[0]
230 msg['payload'] = frame[24:]
234 def mgmt_tx(self, msg):
235 t = (msg['fc'], 0) + mac2tuple(msg['da']) + mac2tuple(msg['sa']) + mac2tuple(msg['bssid']) + (0,)
236 hdr = struct.pack('<HH6B6B6BH', *t)
237 self.request("MGMT_TX " + binascii.hexlify(hdr + msg['payload']))
239 def get_sta(self, addr, info=None, next=False):
240 cmd = "STA-NEXT " if next else "STA "
242 res = self.request("STA-FIRST")
244 res = self.request(cmd + addr + " " + info)
246 res = self.request(cmd + addr)
247 lines = res.splitlines()
251 if first and '=' not in l:
255 [name,value] = l.split('=', 1)
259 def get_mib(self, param=None):
261 res = self.request("MIB " + param)
263 res = self.request("MIB")
264 lines = res.splitlines()
267 name_val = l.split('=', 1)
268 if len(name_val) > 1:
269 vals[name_val[0]] = name_val[1]
272 def add_ap(ifname, params, wait_enabled=True, no_enable=False):
273 logger.info("Starting AP " + ifname)
274 hapd_global = HostapdGlobal()
275 hapd_global.remove(ifname)
276 hapd_global.add(ifname)
277 hapd = Hostapd(ifname)
279 raise Exception("Could not ping hostapd")
281 fields = [ "ssid", "wpa_passphrase", "nas_identifier", "wpa_key_mgmt",
283 "wpa_pairwise", "rsn_pairwise", "auth_server_addr",
284 "acct_server_addr", "osu_server_uri" ]
287 hapd.set(field, params[field])
288 for f,v in params.items():
291 if isinstance(v, list):
300 ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=30)
302 raise Exception("AP startup timed out")
303 if "AP-ENABLED" not in ev:
304 raise Exception("AP startup failed")
307 def add_bss(phy, ifname, confname, ignore_error=False):
308 logger.info("Starting BSS phy=" + phy + " ifname=" + ifname)
309 hapd_global = HostapdGlobal()
310 hapd_global.add_bss(phy, confname, ignore_error)
311 hapd = Hostapd(ifname)
313 raise Exception("Could not ping hostapd")
315 def add_iface(ifname, confname):
316 logger.info("Starting interface " + ifname)
317 hapd_global = HostapdGlobal()
318 hapd_global.add_iface(ifname, confname)
319 hapd = Hostapd(ifname)
321 raise Exception("Could not ping hostapd")
323 def remove_bss(ifname):
324 logger.info("Removing BSS " + ifname)
325 hapd_global = HostapdGlobal()
326 hapd_global.remove(ifname)
328 def wpa2_params(ssid=None, passphrase=None):
329 params = { "wpa": "2",
330 "wpa_key_mgmt": "WPA-PSK",
331 "rsn_pairwise": "CCMP" }
333 params["ssid"] = ssid
335 params["wpa_passphrase"] = passphrase
338 def wpa_params(ssid=None, passphrase=None):
339 params = { "wpa": "1",
340 "wpa_key_mgmt": "WPA-PSK",
341 "wpa_pairwise": "TKIP" }
343 params["ssid"] = ssid
345 params["wpa_passphrase"] = passphrase
348 def wpa_mixed_params(ssid=None, passphrase=None):
349 params = { "wpa": "3",
350 "wpa_key_mgmt": "WPA-PSK",
351 "wpa_pairwise": "TKIP",
352 "rsn_pairwise": "CCMP" }
354 params["ssid"] = ssid
356 params["wpa_passphrase"] = passphrase
360 params = { "auth_server_addr": "127.0.0.1",
361 "auth_server_port": "1812",
362 "auth_server_shared_secret": "radius",
363 "nas_identifier": "nas.w1.fi" }
366 def wpa_eap_params(ssid=None):
367 params = radius_params()
369 params["wpa_key_mgmt"] = "WPA-EAP"
370 params["wpa_pairwise"] = "TKIP"
371 params["ieee8021x"] = "1"
373 params["ssid"] = ssid
376 def wpa2_eap_params(ssid=None):
377 params = radius_params()
379 params["wpa_key_mgmt"] = "WPA-EAP"
380 params["rsn_pairwise"] = "CCMP"
381 params["ieee8021x"] = "1"
383 params["ssid"] = ssid