wpasupplicant.py 20 KB

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