wpasupplicant.py 22 KB

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