wpasupplicant.py 18 KB

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