hostapd.py 13 KB

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