wpasupplicant.py 19 KB

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