hostapd.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. # Python class for controlling hostapd
  2. # Copyright (c) 2013-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. import os
  7. import time
  8. import logging
  9. import binascii
  10. import struct
  11. import wpaspy
  12. logger = logging.getLogger()
  13. hapd_ctrl = '/var/run/hostapd'
  14. hapd_global = '/var/run/hostapd-global'
  15. def mac2tuple(mac):
  16. return struct.unpack('6B', binascii.unhexlify(mac.replace(':','')))
  17. class HostapdGlobal:
  18. def __init__(self):
  19. self.ctrl = wpaspy.Ctrl(hapd_global)
  20. self.mon = wpaspy.Ctrl(hapd_global)
  21. self.mon.attach()
  22. def request(self, cmd):
  23. return self.ctrl.request(cmd)
  24. def wait_event(self, events, timeout):
  25. start = os.times()[4]
  26. while True:
  27. while self.mon.pending():
  28. ev = self.mon.recv()
  29. logger.debug("(global): " + ev)
  30. for event in events:
  31. if event in ev:
  32. return ev
  33. now = os.times()[4]
  34. remaining = start + timeout - now
  35. if remaining <= 0:
  36. break
  37. if not self.mon.pending(timeout=remaining):
  38. break
  39. return None
  40. def add(self, ifname):
  41. res = self.ctrl.request("ADD " + ifname + " " + hapd_ctrl)
  42. if not "OK" in res:
  43. raise Exception("Could not add hostapd interface " + ifname)
  44. def add_iface(self, ifname, confname):
  45. res = self.ctrl.request("ADD " + ifname + " config=" + confname)
  46. if not "OK" in res:
  47. raise Exception("Could not add hostapd interface")
  48. def add_bss(self, phy, confname, ignore_error=False):
  49. res = self.ctrl.request("ADD bss_config=" + phy + ":" + confname)
  50. if not "OK" in res:
  51. if not ignore_error:
  52. raise Exception("Could not add hostapd BSS")
  53. def remove(self, ifname):
  54. self.ctrl.request("REMOVE " + ifname, timeout=30)
  55. def relog(self):
  56. self.ctrl.request("RELOG")
  57. def flush(self):
  58. self.ctrl.request("FLUSH")
  59. class Hostapd:
  60. def __init__(self, ifname, bssidx=0):
  61. self.ifname = ifname
  62. self.ctrl = wpaspy.Ctrl(os.path.join(hapd_ctrl, ifname))
  63. self.mon = wpaspy.Ctrl(os.path.join(hapd_ctrl, ifname))
  64. self.mon.attach()
  65. self.bssid = None
  66. self.bssidx = bssidx
  67. def own_addr(self):
  68. if self.bssid is None:
  69. self.bssid = self.get_status_field('bssid[%d]' % self.bssidx)
  70. return self.bssid
  71. def request(self, cmd):
  72. logger.debug(self.ifname + ": CTRL: " + cmd)
  73. return self.ctrl.request(cmd)
  74. def ping(self):
  75. return "PONG" in self.request("PING")
  76. def set(self, field, value):
  77. if not "OK" in self.request("SET " + field + " " + value):
  78. raise Exception("Failed to set hostapd parameter " + field)
  79. def set_defaults(self):
  80. self.set("driver", "nl80211")
  81. self.set("hw_mode", "g")
  82. self.set("channel", "1")
  83. self.set("ieee80211n", "1")
  84. self.set("logger_stdout", "-1")
  85. self.set("logger_stdout_level", "0")
  86. def set_open(self, ssid):
  87. self.set_defaults()
  88. self.set("ssid", ssid)
  89. def set_wpa2_psk(self, ssid, passphrase):
  90. self.set_defaults()
  91. self.set("ssid", ssid)
  92. self.set("wpa_passphrase", passphrase)
  93. self.set("wpa", "2")
  94. self.set("wpa_key_mgmt", "WPA-PSK")
  95. self.set("rsn_pairwise", "CCMP")
  96. def set_wpa_psk(self, ssid, passphrase):
  97. self.set_defaults()
  98. self.set("ssid", ssid)
  99. self.set("wpa_passphrase", passphrase)
  100. self.set("wpa", "1")
  101. self.set("wpa_key_mgmt", "WPA-PSK")
  102. self.set("wpa_pairwise", "TKIP")
  103. def set_wpa_psk_mixed(self, ssid, passphrase):
  104. self.set_defaults()
  105. self.set("ssid", ssid)
  106. self.set("wpa_passphrase", passphrase)
  107. self.set("wpa", "3")
  108. self.set("wpa_key_mgmt", "WPA-PSK")
  109. self.set("wpa_pairwise", "TKIP")
  110. self.set("rsn_pairwise", "CCMP")
  111. def set_wep(self, ssid, key):
  112. self.set_defaults()
  113. self.set("ssid", ssid)
  114. self.set("wep_key0", key)
  115. def enable(self):
  116. if not "OK" in self.request("ENABLE"):
  117. raise Exception("Failed to enable hostapd interface " + self.ifname)
  118. def disable(self):
  119. if not "OK" in self.request("DISABLE"):
  120. raise Exception("Failed to disable hostapd interface " + self.ifname)
  121. def dump_monitor(self):
  122. while self.mon.pending():
  123. ev = self.mon.recv()
  124. logger.debug(self.ifname + ": " + ev)
  125. def wait_event(self, events, timeout):
  126. start = os.times()[4]
  127. while True:
  128. while self.mon.pending():
  129. ev = self.mon.recv()
  130. logger.debug(self.ifname + ": " + ev)
  131. for event in events:
  132. if event in ev:
  133. return ev
  134. now = os.times()[4]
  135. remaining = start + timeout - now
  136. if remaining <= 0:
  137. break
  138. if not self.mon.pending(timeout=remaining):
  139. break
  140. return None
  141. def get_status(self):
  142. res = self.request("STATUS")
  143. lines = res.splitlines()
  144. vals = dict()
  145. for l in lines:
  146. [name,value] = l.split('=', 1)
  147. vals[name] = value
  148. return vals
  149. def get_status_field(self, field):
  150. vals = self.get_status()
  151. if field in vals:
  152. return vals[field]
  153. return None
  154. def get_driver_status(self):
  155. res = self.request("STATUS-DRIVER")
  156. lines = res.splitlines()
  157. vals = dict()
  158. for l in lines:
  159. [name,value] = l.split('=', 1)
  160. vals[name] = value
  161. return vals
  162. def get_driver_status_field(self, field):
  163. vals = self.get_driver_status()
  164. if field in vals:
  165. return vals[field]
  166. return None
  167. def get_config(self):
  168. res = self.request("GET_CONFIG")
  169. lines = res.splitlines()
  170. vals = dict()
  171. for l in lines:
  172. [name,value] = l.split('=', 1)
  173. vals[name] = value
  174. return vals
  175. def mgmt_rx(self, timeout=5):
  176. ev = self.wait_event(["MGMT-RX"], timeout=timeout)
  177. if ev is None:
  178. return None
  179. msg = {}
  180. frame = binascii.unhexlify(ev.split(' ')[1])
  181. msg['frame'] = frame
  182. hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
  183. msg['fc'] = hdr[0]
  184. msg['subtype'] = (hdr[0] >> 4) & 0xf
  185. hdr = hdr[1:]
  186. msg['duration'] = hdr[0]
  187. hdr = hdr[1:]
  188. msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  189. hdr = hdr[6:]
  190. msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  191. hdr = hdr[6:]
  192. msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  193. hdr = hdr[6:]
  194. msg['seq_ctrl'] = hdr[0]
  195. msg['payload'] = frame[24:]
  196. return msg
  197. def mgmt_tx(self, msg):
  198. t = (msg['fc'], 0) + mac2tuple(msg['da']) + mac2tuple(msg['sa']) + mac2tuple(msg['bssid']) + (0,)
  199. hdr = struct.pack('<HH6B6B6BH', *t)
  200. self.request("MGMT_TX " + binascii.hexlify(hdr + msg['payload']))
  201. def get_sta(self, addr, info=None, next=False):
  202. cmd = "STA-NEXT " if next else "STA "
  203. if addr is None:
  204. res = self.request("STA-FIRST")
  205. elif info:
  206. res = self.request(cmd + addr + " " + info)
  207. else:
  208. res = self.request(cmd + addr)
  209. lines = res.splitlines()
  210. vals = dict()
  211. first = True
  212. for l in lines:
  213. if first and '=' not in l:
  214. vals['addr'] = l
  215. first = False
  216. else:
  217. [name,value] = l.split('=', 1)
  218. vals[name] = value
  219. return vals
  220. def get_mib(self, param=None):
  221. if param:
  222. res = self.request("MIB " + param)
  223. else:
  224. res = self.request("MIB")
  225. lines = res.splitlines()
  226. vals = dict()
  227. for l in lines:
  228. name_val = l.split('=', 1)
  229. if len(name_val) > 1:
  230. vals[name_val[0]] = name_val[1]
  231. return vals
  232. def add_ap(ifname, params, wait_enabled=True, no_enable=False):
  233. logger.info("Starting AP " + ifname)
  234. hapd_global = HostapdGlobal()
  235. hapd_global.remove(ifname)
  236. hapd_global.add(ifname)
  237. hapd = Hostapd(ifname)
  238. if not hapd.ping():
  239. raise Exception("Could not ping hostapd")
  240. hapd.set_defaults()
  241. fields = [ "ssid", "wpa_passphrase", "nas_identifier", "wpa_key_mgmt",
  242. "wpa",
  243. "wpa_pairwise", "rsn_pairwise", "auth_server_addr",
  244. "acct_server_addr", "osu_server_uri" ]
  245. for field in fields:
  246. if field in params:
  247. hapd.set(field, params[field])
  248. for f,v in params.items():
  249. if f in fields:
  250. continue
  251. if isinstance(v, list):
  252. for val in v:
  253. hapd.set(f, val)
  254. else:
  255. hapd.set(f, v)
  256. if no_enable:
  257. return hapd
  258. hapd.enable()
  259. if wait_enabled:
  260. ev = hapd.wait_event(["AP-ENABLED", "AP-DISABLED"], timeout=30)
  261. if ev is None:
  262. raise Exception("AP startup timed out")
  263. if "AP-ENABLED" not in ev:
  264. raise Exception("AP startup failed")
  265. return hapd
  266. def add_bss(phy, ifname, confname, ignore_error=False):
  267. logger.info("Starting BSS phy=" + phy + " ifname=" + ifname)
  268. hapd_global = HostapdGlobal()
  269. hapd_global.add_bss(phy, confname, ignore_error)
  270. hapd = Hostapd(ifname)
  271. if not hapd.ping():
  272. raise Exception("Could not ping hostapd")
  273. def add_iface(ifname, confname):
  274. logger.info("Starting interface " + ifname)
  275. hapd_global = HostapdGlobal()
  276. hapd_global.add_iface(ifname, confname)
  277. hapd = Hostapd(ifname)
  278. if not hapd.ping():
  279. raise Exception("Could not ping hostapd")
  280. def remove_bss(ifname):
  281. logger.info("Removing BSS " + ifname)
  282. hapd_global = HostapdGlobal()
  283. hapd_global.remove(ifname)
  284. def wpa2_params(ssid=None, passphrase=None):
  285. params = { "wpa": "2",
  286. "wpa_key_mgmt": "WPA-PSK",
  287. "rsn_pairwise": "CCMP" }
  288. if ssid:
  289. params["ssid"] = ssid
  290. if passphrase:
  291. params["wpa_passphrase"] = passphrase
  292. return params
  293. def wpa_params(ssid=None, passphrase=None):
  294. params = { "wpa": "1",
  295. "wpa_key_mgmt": "WPA-PSK",
  296. "wpa_pairwise": "TKIP" }
  297. if ssid:
  298. params["ssid"] = ssid
  299. if passphrase:
  300. params["wpa_passphrase"] = passphrase
  301. return params
  302. def wpa_mixed_params(ssid=None, passphrase=None):
  303. params = { "wpa": "3",
  304. "wpa_key_mgmt": "WPA-PSK",
  305. "wpa_pairwise": "TKIP",
  306. "rsn_pairwise": "CCMP" }
  307. if ssid:
  308. params["ssid"] = ssid
  309. if passphrase:
  310. params["wpa_passphrase"] = passphrase
  311. return params
  312. def radius_params():
  313. params = { "auth_server_addr": "127.0.0.1",
  314. "auth_server_port": "1812",
  315. "auth_server_shared_secret": "radius",
  316. "nas_identifier": "nas.w1.fi" }
  317. return params
  318. def wpa_eap_params(ssid=None):
  319. params = radius_params()
  320. params["wpa"] = "1"
  321. params["wpa_key_mgmt"] = "WPA-EAP"
  322. params["wpa_pairwise"] = "TKIP"
  323. params["ieee8021x"] = "1"
  324. if ssid:
  325. params["ssid"] = ssid
  326. return params
  327. def wpa2_eap_params(ssid=None):
  328. params = radius_params()
  329. params["wpa"] = "2"
  330. params["wpa_key_mgmt"] = "WPA-EAP"
  331. params["rsn_pairwise"] = "CCMP"
  332. params["ieee8021x"] = "1"
  333. if ssid:
  334. params["ssid"] = ssid
  335. return params