wpasupplicant.py 21 KB

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