hostapd.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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, param=None):
  189. if param:
  190. res = self.request("MIB " + param)
  191. else:
  192. res = self.request("MIB")
  193. lines = res.splitlines()
  194. vals = dict()
  195. for l in lines:
  196. name_val = l.split('=', 1)
  197. if len(name_val) > 1:
  198. vals[name_val[0]] = name_val[1]
  199. return vals
  200. def add_ap(ifname, params, wait_enabled=True):
  201. logger.info("Starting AP " + ifname)
  202. hapd_global = HostapdGlobal()
  203. hapd_global.remove(ifname)
  204. hapd_global.add(ifname)
  205. hapd = Hostapd(ifname)
  206. if not hapd.ping():
  207. raise Exception("Could not ping hostapd")
  208. hapd.set_defaults()
  209. fields = [ "ssid", "wpa_passphrase", "nas_identifier", "wpa_key_mgmt",
  210. "wpa",
  211. "wpa_pairwise", "rsn_pairwise", "auth_server_addr",
  212. "acct_server_addr" ]
  213. for field in fields:
  214. if field in params:
  215. hapd.set(field, params[field])
  216. for f,v in params.items():
  217. if f in fields:
  218. continue
  219. if isinstance(v, list):
  220. for val in v:
  221. hapd.set(f, val)
  222. else:
  223. hapd.set(f, v)
  224. hapd.enable()
  225. if wait_enabled:
  226. ev = hapd.wait_event(["AP-ENABLED"], timeout=30)
  227. if ev is None:
  228. raise Exception("AP startup timed out")
  229. return hapd
  230. def add_bss(phy, ifname, confname, ignore_error=False):
  231. logger.info("Starting BSS phy=" + phy + " ifname=" + ifname)
  232. hapd_global = HostapdGlobal()
  233. hapd_global.add_bss(phy, confname, ignore_error)
  234. hapd = Hostapd(ifname)
  235. if not hapd.ping():
  236. raise Exception("Could not ping hostapd")
  237. def add_iface(ifname, confname):
  238. logger.info("Starting interface " + ifname)
  239. hapd_global = HostapdGlobal()
  240. hapd_global.add_iface(ifname, confname)
  241. hapd = Hostapd(ifname)
  242. if not hapd.ping():
  243. raise Exception("Could not ping hostapd")
  244. def remove_bss(ifname):
  245. logger.info("Removing BSS " + ifname)
  246. hapd_global = HostapdGlobal()
  247. hapd_global.remove(ifname)
  248. def wpa2_params(ssid=None, passphrase=None):
  249. params = { "wpa": "2",
  250. "wpa_key_mgmt": "WPA-PSK",
  251. "rsn_pairwise": "CCMP" }
  252. if ssid:
  253. params["ssid"] = ssid
  254. if passphrase:
  255. params["wpa_passphrase"] = passphrase
  256. return params
  257. def wpa_params(ssid=None, passphrase=None):
  258. params = { "wpa": "1",
  259. "wpa_key_mgmt": "WPA-PSK",
  260. "wpa_pairwise": "TKIP" }
  261. if ssid:
  262. params["ssid"] = ssid
  263. if passphrase:
  264. params["wpa_passphrase"] = passphrase
  265. return params
  266. def wpa_mixed_params(ssid=None, passphrase=None):
  267. params = { "wpa": "3",
  268. "wpa_key_mgmt": "WPA-PSK",
  269. "wpa_pairwise": "TKIP",
  270. "rsn_pairwise": "CCMP" }
  271. if ssid:
  272. params["ssid"] = ssid
  273. if passphrase:
  274. params["wpa_passphrase"] = passphrase
  275. return params
  276. def radius_params():
  277. params = { "auth_server_addr": "127.0.0.1",
  278. "auth_server_port": "1812",
  279. "auth_server_shared_secret": "radius",
  280. "nas_identifier": "nas.w1.fi" }
  281. return params
  282. def wpa_eap_params(ssid=None):
  283. params = radius_params()
  284. params["wpa"] = "1"
  285. params["wpa_key_mgmt"] = "WPA-EAP"
  286. params["wpa_pairwise"] = "TKIP"
  287. params["ieee8021x"] = "1"
  288. if ssid:
  289. params["ssid"] = ssid
  290. return params
  291. def wpa2_eap_params(ssid=None):
  292. params = radius_params()
  293. params["wpa"] = "2"
  294. params["wpa_key_mgmt"] = "WPA-EAP"
  295. params["rsn_pairwise"] = "CCMP"
  296. params["ieee8021x"] = "1"
  297. if ssid:
  298. params["ssid"] = ssid
  299. return params