wpasupplicant.py 16 KB

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