hostapd.py 9.6 KB

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