hostapd.py 10 KB

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