wpasupplicant.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. #!/usr/bin/python
  2. #
  3. # Python class for controlling wpa_supplicant
  4. # Copyright (c) 2013, 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 re
  12. import wpaspy
  13. logger = logging.getLogger(__name__)
  14. wpas_ctrl = '/var/run/wpa_supplicant'
  15. class WpaSupplicant:
  16. def __init__(self, ifname):
  17. self.ifname = ifname
  18. self.group_ifname = None
  19. self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  20. self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  21. self.mon.attach()
  22. def request(self, cmd):
  23. logger.debug(self.ifname + ": CTRL: " + cmd)
  24. return self.ctrl.request(cmd)
  25. def group_request(self, cmd):
  26. if self.group_ifname and self.group_ifname != self.ifname:
  27. logger.debug(self.group_ifname + ": CTRL: " + cmd)
  28. gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  29. return gctrl.request(cmd)
  30. return self.request(cmd)
  31. def ping(self):
  32. return "PONG" in self.request("PING")
  33. def reset(self):
  34. self.request("FLUSH")
  35. self.request("SET ignore_old_scan_res 0")
  36. self.group_ifname = None
  37. self.dump_monitor()
  38. def add_network(self):
  39. id = self.request("ADD_NETWORK")
  40. if "FAIL" in id:
  41. raise Exception("ADD_NETWORK failed")
  42. return int(id)
  43. def remove_network(self, id):
  44. id = self.request("REMOVE_NETWORK " + str(id))
  45. if "FAIL" in id:
  46. raise Exception("REMOVE_NETWORK failed")
  47. return None
  48. def set_network(self, id, field, value):
  49. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  50. if "FAIL" in res:
  51. raise Exception("SET_NETWORK failed")
  52. return None
  53. def set_network_quoted(self, id, field, value):
  54. res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  55. if "FAIL" in res:
  56. raise Exception("SET_NETWORK failed")
  57. return None
  58. def add_cred(self):
  59. id = self.request("ADD_CRED")
  60. if "FAIL" in id:
  61. raise Exception("ADD_CRED failed")
  62. return int(id)
  63. def remove_cred(self, id):
  64. id = self.request("REMOVE_CRED " + str(id))
  65. if "FAIL" in id:
  66. raise Exception("REMOVE_CRED failed")
  67. return None
  68. def set_cred(self, id, field, value):
  69. res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
  70. if "FAIL" in res:
  71. raise Exception("SET_CRED failed")
  72. return None
  73. def set_cred_quoted(self, id, field, value):
  74. res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
  75. if "FAIL" in res:
  76. raise Exception("SET_CRED failed")
  77. return None
  78. def select_network(self, id):
  79. id = self.request("SELECT_NETWORK " + str(id))
  80. if "FAIL" in id:
  81. raise Exception("SELECT_NETWORK failed")
  82. return None
  83. def connect_network(self, id):
  84. self.dump_monitor()
  85. self.select_network(id)
  86. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  87. if ev is None:
  88. raise Exception("Association with the AP timed out")
  89. self.dump_monitor()
  90. def get_status(self):
  91. res = self.request("STATUS")
  92. lines = res.splitlines()
  93. vals = dict()
  94. for l in lines:
  95. [name,value] = l.split('=', 1)
  96. vals[name] = value
  97. return vals
  98. def get_status_field(self, field):
  99. vals = self.get_status()
  100. if field in vals:
  101. return vals[field]
  102. return None
  103. def get_group_status(self):
  104. res = self.group_request("STATUS")
  105. lines = res.splitlines()
  106. vals = dict()
  107. for l in lines:
  108. [name,value] = l.split('=', 1)
  109. vals[name] = value
  110. return vals
  111. def get_group_status_field(self, field):
  112. vals = self.get_group_status()
  113. if field in vals:
  114. return vals[field]
  115. return None
  116. def p2p_dev_addr(self):
  117. return self.get_status_field("p2p_device_address")
  118. def p2p_interface_addr(self):
  119. return self.get_group_status_field("address")
  120. def p2p_listen(self):
  121. return self.request("P2P_LISTEN")
  122. def p2p_find(self, social=False):
  123. if social:
  124. return self.request("P2P_FIND type=social")
  125. return self.request("P2P_FIND")
  126. def p2p_stop_find(self):
  127. return self.request("P2P_STOP_FIND")
  128. def wps_read_pin(self):
  129. #TODO: make this random
  130. self.pin = "12345670"
  131. return self.pin
  132. def peer_known(self, peer, full=True):
  133. res = self.request("P2P_PEER " + peer)
  134. if peer.lower() not in res.lower():
  135. return False
  136. if not full:
  137. return True
  138. return "[PROBE_REQ_ONLY]" not in res
  139. def discover_peer(self, peer, full=True, timeout=15, social=True):
  140. logger.info(self.ifname + ": Trying to discover peer " + peer)
  141. if self.peer_known(peer, full):
  142. return True
  143. self.p2p_find(social)
  144. count = 0
  145. while count < timeout:
  146. time.sleep(1)
  147. count = count + 1
  148. if self.peer_known(peer, full):
  149. return True
  150. return False
  151. def group_form_result(self, ev, expect_failure=False):
  152. if expect_failure:
  153. if "P2P-GROUP-STARTED" in ev:
  154. raise Exception("Group formation succeeded when expecting failure")
  155. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  156. s = re.split(exp, ev)
  157. if len(s) < 3:
  158. return None
  159. res = {}
  160. res['result'] = 'go-neg-failed'
  161. res['status'] = int(s[2])
  162. return res
  163. if "P2P-GROUP-STARTED" not in ev:
  164. raise Exception("No P2P-GROUP-STARTED event seen")
  165. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  166. s = re.split(exp, ev)
  167. if len(s) < 8:
  168. raise Exception("Could not parse P2P-GROUP-STARTED")
  169. res = {}
  170. res['result'] = 'success'
  171. res['ifname'] = s[2]
  172. self.group_ifname = s[2]
  173. res['role'] = s[3]
  174. res['ssid'] = s[4]
  175. res['freq'] = s[5]
  176. p = re.match(r'psk=([0-9a-f]*)', s[6])
  177. if p:
  178. res['psk'] = p.group(1)
  179. p = re.match(r'passphrase="(.*)"', s[6])
  180. if p:
  181. res['passphrase'] = p.group(1)
  182. res['go_dev_addr'] = s[7]
  183. return res
  184. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None):
  185. if not self.discover_peer(peer):
  186. raise Exception("Peer " + peer + " not found")
  187. self.dump_monitor()
  188. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  189. if go_intent:
  190. cmd = cmd + ' go_intent=' + str(go_intent)
  191. if "OK" in self.request(cmd):
  192. return None
  193. raise Exception("P2P_CONNECT (auth) failed")
  194. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  195. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout);
  196. if ev is None:
  197. if expect_failure:
  198. return None
  199. raise Exception("Group formation timed out")
  200. self.dump_monitor()
  201. return self.group_form_result(ev, expect_failure)
  202. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False):
  203. if not self.discover_peer(peer):
  204. raise Exception("Peer " + peer + " not found")
  205. self.dump_monitor()
  206. if pin:
  207. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  208. else:
  209. cmd = "P2P_CONNECT " + peer + " " + method
  210. if go_intent:
  211. cmd = cmd + ' go_intent=' + str(go_intent)
  212. if "OK" in self.request(cmd):
  213. if timeout == 0:
  214. self.dump_monitor()
  215. return None
  216. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout)
  217. if ev is None:
  218. if expect_failure:
  219. return None
  220. raise Exception("Group formation timed out")
  221. self.dump_monitor()
  222. return self.group_form_result(ev, expect_failure)
  223. raise Exception("P2P_CONNECT failed")
  224. def wait_event(self, events, timeout):
  225. count = 0
  226. while count < timeout * 10:
  227. count = count + 1
  228. time.sleep(0.1)
  229. while self.mon.pending():
  230. ev = self.mon.recv()
  231. logger.debug(self.ifname + ": " + ev)
  232. for event in events:
  233. if event in ev:
  234. return ev
  235. return None
  236. def dump_monitor(self):
  237. while self.mon.pending():
  238. ev = self.mon.recv()
  239. logger.debug(self.ifname + ": " + ev)
  240. def remove_group(self, ifname=None):
  241. if ifname is None:
  242. ifname = self.group_ifname if self.group_ifname else self.iname
  243. if "OK" not in self.request("P2P_GROUP_REMOVE " + ifname):
  244. raise Exception("Group could not be removed")
  245. self.group_ifname = None
  246. def p2p_start_go(self, persistent=None, freq=None):
  247. self.dump_monitor()
  248. cmd = "P2P_GROUP_ADD"
  249. if persistent is None:
  250. pass
  251. elif persistent is True:
  252. cmd = cmd + " persistent"
  253. else:
  254. cmd = cmd + " persistent=" + str(persistent)
  255. if freq:
  256. cmd = cmd + " freq=" + freq
  257. if "OK" in self.request(cmd):
  258. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout=5)
  259. if ev is None:
  260. raise Exception("GO start up timed out")
  261. self.dump_monitor()
  262. return self.group_form_result(ev)
  263. raise Exception("P2P_GROUP_ADD failed")
  264. def p2p_go_authorize_client(self, pin):
  265. cmd = "WPS_PIN any " + pin
  266. if "FAIL" in self.group_request(cmd):
  267. raise Exception("Failed to authorize client connection on GO")
  268. return None
  269. def p2p_connect_group(self, go_addr, pin, timeout=0):
  270. self.dump_monitor()
  271. if not self.discover_peer(go_addr, social=False):
  272. raise Exception("GO " + go_addr + " not found")
  273. self.dump_monitor()
  274. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  275. if "OK" in self.request(cmd):
  276. if timeout == 0:
  277. self.dump_monitor()
  278. return None
  279. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout)
  280. if ev is None:
  281. raise Exception("Joining the group timed out")
  282. self.dump_monitor()
  283. return self.group_form_result(ev)
  284. raise Exception("P2P_CONNECT(join) failed")
  285. def tdls_setup(self, peer):
  286. cmd = "TDLS_SETUP " + peer
  287. if "FAIL" in self.group_request(cmd):
  288. raise Exception("Failed to request TDLS setup")
  289. return None
  290. def tdls_teardown(self, peer):
  291. cmd = "TDLS_TEARDOWN " + peer
  292. if "FAIL" in self.group_request(cmd):
  293. raise Exception("Failed to request TDLS teardown")
  294. return None
  295. def connect(self, ssid, psk=None, proto=None, key_mgmt=None, wep_key0=None, ieee80211w=None):
  296. logger.info("Connect STA " + self.ifname + " to AP")
  297. id = self.add_network()
  298. self.set_network_quoted(id, "ssid", ssid)
  299. if psk:
  300. self.set_network_quoted(id, "psk", psk)
  301. if proto:
  302. self.set_network(id, "proto", proto)
  303. if key_mgmt:
  304. self.set_network(id, "key_mgmt", key_mgmt)
  305. if ieee80211w:
  306. self.set_network(id, "ieee80211w", ieee80211w)
  307. if wep_key0:
  308. self.set_network(id, "wep_key0", wep_key0)
  309. self.connect_network(id)
  310. def scan(self, type=None):
  311. if type:
  312. cmd = "SCAN TYPE=" + type
  313. else:
  314. cmd = "SCAN"
  315. self.dump_monitor()
  316. if not "OK" in self.request(cmd):
  317. raise Exception("Failed to trigger scan")
  318. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  319. if ev is None:
  320. raise Exception("Scan timed out")
  321. def roam(self, bssid):
  322. self.dump_monitor()
  323. self.request("ROAM " + bssid)
  324. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  325. if ev is None:
  326. raise Exception("Roaming with the AP timed out")
  327. self.dump_monitor()
  328. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  329. new_passphrase=None):
  330. self.dump_monitor()
  331. if new_ssid:
  332. self.request("WPS_REG " + bssid + " " + pin + " " +
  333. new_ssid.encode("hex") + " " + key_mgmt + " " +
  334. cipher + " " + new_passphrase.encode("hex"))
  335. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  336. else:
  337. self.request("WPS_REG " + bssid + " " + pin)
  338. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  339. if ev is None:
  340. raise Exception("WPS cred timed out")
  341. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  342. if ev is None:
  343. raise Exception("WPS timed out")
  344. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  345. if ev is None:
  346. raise Exception("Association with the AP timed out")