wpasupplicant.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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=None, global_iface=None):
  18. self.group_ifname = None
  19. if ifname:
  20. self.set_ifname(ifname)
  21. else:
  22. self.ifname = None
  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 set_ifname(self, ifname):
  29. self.ifname = ifname
  30. self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  31. self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  32. self.mon.attach()
  33. def remove_ifname(self):
  34. if self.ifname:
  35. self.mon.detach()
  36. self.mon = None
  37. self.ctrl = None
  38. self.ifname = None
  39. def interface_add(self, ifname, driver="nl80211"):
  40. try:
  41. groups = subprocess.check_output(["id"])
  42. group = "admin" if "(admin)" in groups else "adm"
  43. except Exception, e:
  44. group = "admin"
  45. cmd = "INTERFACE_ADD " + ifname + "\t\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
  46. if "FAIL" in self.global_request(cmd):
  47. raise Exception("Failed to add a dynamic wpa_supplicant interface")
  48. self.set_ifname(ifname)
  49. def interface_remove(self, ifname):
  50. self.remove_ifname()
  51. self.global_request("INTERFACE_REMOVE " + ifname)
  52. def request(self, cmd):
  53. logger.debug(self.ifname + ": CTRL: " + cmd)
  54. return self.ctrl.request(cmd)
  55. def global_request(self, cmd):
  56. if self.global_iface is None:
  57. self.request(cmd)
  58. else:
  59. ifname = self.ifname or self.global_iface
  60. logger.debug(ifname + ": CTRL: " + cmd)
  61. return self.global_ctrl.request(cmd)
  62. def group_request(self, cmd):
  63. if self.group_ifname and self.group_ifname != self.ifname:
  64. logger.debug(self.group_ifname + ": CTRL: " + cmd)
  65. gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  66. return gctrl.request(cmd)
  67. return self.request(cmd)
  68. def ping(self):
  69. return "PONG" in self.request("PING")
  70. def reset(self):
  71. res = self.request("FLUSH")
  72. if not "OK" in res:
  73. logger.info("FLUSH to " + self.ifname + " failed: " + res)
  74. self.request("SET ignore_old_scan_res 0")
  75. self.request("SET external_sim 0")
  76. self.request("SET hessid 00:00:00:00:00:00")
  77. self.request("SET access_network_type 15")
  78. self.request("SET p2p_add_cli_chan 0")
  79. self.request("SET p2p_no_go_freq ")
  80. self.request("SET p2p_pref_chan ")
  81. self.request("SET disallow_aps ")
  82. self.request("SET p2p_no_group_iface 1")
  83. self.request("P2P_SET per_sta_psk 0")
  84. self.request("P2P_SET disabled 0")
  85. self.request("P2P_SERVICE_FLUSH")
  86. self.group_ifname = None
  87. self.dump_monitor()
  88. iter = 0
  89. while iter < 60:
  90. state = self.get_driver_status_field("scan_state")
  91. if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
  92. logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
  93. time.sleep(1)
  94. else:
  95. break
  96. iter = iter + 1
  97. if iter == 60:
  98. logger.error(self.ifname + ": Driver scan state did not clear")
  99. print "Trying to clear cfg80211/mac80211 scan state"
  100. try:
  101. cmd = ["sudo", "ifconfig", self.ifname, "down"]
  102. subprocess.call(cmd)
  103. except subprocess.CalledProcessError, e:
  104. logger.info("ifconfig failed: " + str(e.returncode))
  105. logger.info(e.output)
  106. try:
  107. cmd = ["sudo", "ifconfig", self.ifname, "up"]
  108. subprocess.call(cmd)
  109. except subprocess.CalledProcessError, e:
  110. logger.info("ifconfig failed: " + str(e.returncode))
  111. logger.info(e.output)
  112. if not self.ping():
  113. logger.info("No PING response from " + self.ifname + " after reset")
  114. def add_network(self):
  115. id = self.request("ADD_NETWORK")
  116. if "FAIL" in id:
  117. raise Exception("ADD_NETWORK failed")
  118. return int(id)
  119. def remove_network(self, id):
  120. id = self.request("REMOVE_NETWORK " + str(id))
  121. if "FAIL" in id:
  122. raise Exception("REMOVE_NETWORK failed")
  123. return None
  124. def set_network(self, id, field, value):
  125. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  126. if "FAIL" in res:
  127. raise Exception("SET_NETWORK failed")
  128. return None
  129. def set_network_quoted(self, id, field, value):
  130. res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  131. if "FAIL" in res:
  132. raise Exception("SET_NETWORK failed")
  133. return None
  134. def list_networks(self):
  135. res = self.request("LIST_NETWORKS")
  136. lines = res.splitlines()
  137. networks = []
  138. for l in lines:
  139. if "network id" in l:
  140. continue
  141. [id,ssid,bssid,flags] = l.split('\t')
  142. network = {}
  143. network['id'] = id
  144. network['ssid'] = ssid
  145. network['bssid'] = bssid
  146. network['flags'] = flags
  147. networks.append(network)
  148. return networks
  149. def hs20_enable(self):
  150. self.request("SET interworking 1")
  151. self.request("SET hs20 1")
  152. def add_cred(self):
  153. id = self.request("ADD_CRED")
  154. if "FAIL" in id:
  155. raise Exception("ADD_CRED failed")
  156. return int(id)
  157. def remove_cred(self, id):
  158. id = self.request("REMOVE_CRED " + str(id))
  159. if "FAIL" in id:
  160. raise Exception("REMOVE_CRED failed")
  161. return None
  162. def set_cred(self, id, field, value):
  163. res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
  164. if "FAIL" in res:
  165. raise Exception("SET_CRED failed")
  166. return None
  167. def set_cred_quoted(self, id, field, value):
  168. res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
  169. if "FAIL" in res:
  170. raise Exception("SET_CRED failed")
  171. return None
  172. def add_cred_values(self, params):
  173. id = self.add_cred()
  174. quoted = [ "realm", "username", "password", "domain", "imsi",
  175. "excluded_ssid", "milenage", "ca_cert", "client_cert",
  176. "private_key" ]
  177. for field in quoted:
  178. if field in params:
  179. self.set_cred_quoted(id, field, params[field])
  180. not_quoted = [ "eap", "roaming_consortium",
  181. "required_roaming_consortium" ]
  182. for field in not_quoted:
  183. if field in params:
  184. self.set_cred(id, field, params[field])
  185. return id;
  186. def select_network(self, id):
  187. id = self.request("SELECT_NETWORK " + str(id))
  188. if "FAIL" in id:
  189. raise Exception("SELECT_NETWORK failed")
  190. return None
  191. def connect_network(self, id):
  192. self.dump_monitor()
  193. self.select_network(id)
  194. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  195. if ev is None:
  196. raise Exception("Association with the AP timed out")
  197. self.dump_monitor()
  198. def get_status(self):
  199. res = self.request("STATUS")
  200. lines = res.splitlines()
  201. vals = dict()
  202. for l in lines:
  203. [name,value] = l.split('=', 1)
  204. vals[name] = value
  205. return vals
  206. def get_status_field(self, field):
  207. vals = self.get_status()
  208. if field in vals:
  209. return vals[field]
  210. return None
  211. def get_group_status(self):
  212. res = self.group_request("STATUS")
  213. lines = res.splitlines()
  214. vals = dict()
  215. for l in lines:
  216. [name,value] = l.split('=', 1)
  217. vals[name] = value
  218. return vals
  219. def get_group_status_field(self, field):
  220. vals = self.get_group_status()
  221. if field in vals:
  222. return vals[field]
  223. return None
  224. def get_driver_status(self):
  225. res = self.request("STATUS-DRIVER")
  226. lines = res.splitlines()
  227. vals = dict()
  228. for l in lines:
  229. [name,value] = l.split('=', 1)
  230. vals[name] = value
  231. return vals
  232. def get_driver_status_field(self, field):
  233. vals = self.get_driver_status()
  234. if field in vals:
  235. return vals[field]
  236. return None
  237. def p2p_dev_addr(self):
  238. return self.get_status_field("p2p_device_address")
  239. def p2p_interface_addr(self):
  240. return self.get_group_status_field("address")
  241. def p2p_listen(self):
  242. return self.global_request("P2P_LISTEN")
  243. def p2p_find(self, social=False):
  244. if social:
  245. return self.global_request("P2P_FIND type=social")
  246. return self.global_request("P2P_FIND")
  247. def p2p_stop_find(self):
  248. return self.global_request("P2P_STOP_FIND")
  249. def wps_read_pin(self):
  250. #TODO: make this random
  251. self.pin = "12345670"
  252. return self.pin
  253. def peer_known(self, peer, full=True):
  254. res = self.global_request("P2P_PEER " + peer)
  255. if peer.lower() not in res.lower():
  256. return False
  257. if not full:
  258. return True
  259. return "[PROBE_REQ_ONLY]" not in res
  260. def discover_peer(self, peer, full=True, timeout=15, social=True):
  261. logger.info(self.ifname + ": Trying to discover peer " + peer)
  262. if self.peer_known(peer, full):
  263. return True
  264. self.p2p_find(social)
  265. count = 0
  266. while count < timeout:
  267. time.sleep(1)
  268. count = count + 1
  269. if self.peer_known(peer, full):
  270. return True
  271. return False
  272. def get_peer(self, peer):
  273. res = self.global_request("P2P_PEER " + peer)
  274. if peer.lower() not in res.lower():
  275. raise Exception("Peer information not available")
  276. lines = res.splitlines()
  277. vals = dict()
  278. for l in lines:
  279. if '=' in l:
  280. [name,value] = l.split('=', 1)
  281. vals[name] = value
  282. return vals
  283. def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
  284. if expect_failure:
  285. if "P2P-GROUP-STARTED" in ev:
  286. raise Exception("Group formation succeeded when expecting failure")
  287. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  288. s = re.split(exp, ev)
  289. if len(s) < 3:
  290. return None
  291. res = {}
  292. res['result'] = 'go-neg-failed'
  293. res['status'] = int(s[2])
  294. return res
  295. if "P2P-GROUP-STARTED" not in ev:
  296. raise Exception("No P2P-GROUP-STARTED event seen")
  297. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  298. s = re.split(exp, ev)
  299. if len(s) < 8:
  300. raise Exception("Could not parse P2P-GROUP-STARTED")
  301. res = {}
  302. res['result'] = 'success'
  303. res['ifname'] = s[2]
  304. self.group_ifname = s[2]
  305. res['role'] = s[3]
  306. res['ssid'] = s[4]
  307. res['freq'] = s[5]
  308. if "[PERSISTENT]" in ev:
  309. res['persistent'] = True
  310. else:
  311. res['persistent'] = False
  312. p = re.match(r'psk=([0-9a-f]*)', s[6])
  313. if p:
  314. res['psk'] = p.group(1)
  315. p = re.match(r'passphrase="(.*)"', s[6])
  316. if p:
  317. res['passphrase'] = p.group(1)
  318. res['go_dev_addr'] = s[7]
  319. if go_neg_res:
  320. exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
  321. s = re.split(exp, go_neg_res)
  322. if len(s) < 4:
  323. raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
  324. res['go_neg_role'] = s[2]
  325. res['go_neg_freq'] = s[3]
  326. return res
  327. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
  328. if not self.discover_peer(peer):
  329. raise Exception("Peer " + peer + " not found")
  330. self.dump_monitor()
  331. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  332. if go_intent:
  333. cmd = cmd + ' go_intent=' + str(go_intent)
  334. if freq:
  335. cmd = cmd + ' freq=' + str(freq)
  336. if persistent:
  337. cmd = cmd + " persistent"
  338. if "OK" in self.global_request(cmd):
  339. return None
  340. raise Exception("P2P_CONNECT (auth) failed")
  341. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  342. go_neg_res = None
  343. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  344. "P2P-GO-NEG-FAILURE"], timeout);
  345. if ev is None:
  346. if expect_failure:
  347. return None
  348. raise Exception("Group formation timed out")
  349. if "P2P-GO-NEG-SUCCESS" in ev:
  350. go_neg_res = ev
  351. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
  352. if ev is None:
  353. if expect_failure:
  354. return None
  355. raise Exception("Group formation timed out")
  356. self.dump_monitor()
  357. return self.group_form_result(ev, expect_failure, go_neg_res)
  358. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False, persistent=False, freq=None):
  359. if not self.discover_peer(peer):
  360. raise Exception("Peer " + peer + " not found")
  361. self.dump_monitor()
  362. if pin:
  363. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  364. else:
  365. cmd = "P2P_CONNECT " + peer + " " + method
  366. if go_intent:
  367. cmd = cmd + ' go_intent=' + str(go_intent)
  368. if freq:
  369. cmd = cmd + ' freq=' + str(freq)
  370. if persistent:
  371. cmd = cmd + " persistent"
  372. if "OK" in self.global_request(cmd):
  373. if timeout == 0:
  374. self.dump_monitor()
  375. return None
  376. go_neg_res = None
  377. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  378. "P2P-GO-NEG-FAILURE"], timeout)
  379. if ev is None:
  380. if expect_failure:
  381. return None
  382. raise Exception("Group formation timed out")
  383. if "P2P-GO-NEG-SUCCESS" in ev:
  384. go_neg_res = ev
  385. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  386. if ev is None:
  387. if expect_failure:
  388. return None
  389. raise Exception("Group formation timed out")
  390. self.dump_monitor()
  391. return self.group_form_result(ev, expect_failure, go_neg_res)
  392. raise Exception("P2P_CONNECT failed")
  393. def wait_event(self, events, timeout=10):
  394. count = 0
  395. while count < timeout * 10:
  396. count = count + 1
  397. time.sleep(0.1)
  398. while self.mon.pending():
  399. ev = self.mon.recv()
  400. logger.debug(self.ifname + ": " + ev)
  401. for event in events:
  402. if event in ev:
  403. return ev
  404. return None
  405. def wait_global_event(self, events, timeout):
  406. if self.global_iface is None:
  407. self.wait_event(events, timeout)
  408. else:
  409. count = 0
  410. while count < timeout * 10:
  411. count = count + 1
  412. time.sleep(0.1)
  413. while self.global_mon.pending():
  414. ev = self.global_mon.recv()
  415. logger.debug(self.ifname + "(global): " + ev)
  416. for event in events:
  417. if event in ev:
  418. return ev
  419. return None
  420. def wait_go_ending_session(self):
  421. ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
  422. if ev is None:
  423. raise Exception("Group removal event timed out")
  424. if "reason=GO_ENDING_SESSION" not in ev:
  425. raise Exception("Unexpected group removal reason")
  426. def dump_monitor(self):
  427. while self.mon.pending():
  428. ev = self.mon.recv()
  429. logger.debug(self.ifname + ": " + ev)
  430. while self.global_mon.pending():
  431. ev = self.global_mon.recv()
  432. logger.debug(self.ifname + "(global): " + ev)
  433. def remove_group(self, ifname=None):
  434. if ifname is None:
  435. ifname = self.group_ifname if self.group_ifname else self.ifname
  436. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  437. raise Exception("Group could not be removed")
  438. self.group_ifname = None
  439. def p2p_start_go(self, persistent=None, freq=None):
  440. self.dump_monitor()
  441. cmd = "P2P_GROUP_ADD"
  442. if persistent is None:
  443. pass
  444. elif persistent is True:
  445. cmd = cmd + " persistent"
  446. else:
  447. cmd = cmd + " persistent=" + str(persistent)
  448. if freq:
  449. cmd = cmd + " freq=" + str(freq)
  450. if "OK" in self.global_request(cmd):
  451. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  452. if ev is None:
  453. raise Exception("GO start up timed out")
  454. self.dump_monitor()
  455. return self.group_form_result(ev)
  456. raise Exception("P2P_GROUP_ADD failed")
  457. def p2p_go_authorize_client(self, pin):
  458. cmd = "WPS_PIN any " + pin
  459. if "FAIL" in self.group_request(cmd):
  460. raise Exception("Failed to authorize client connection on GO")
  461. return None
  462. def p2p_go_authorize_client_pbc(self):
  463. cmd = "WPS_PBC"
  464. if "FAIL" in self.group_request(cmd):
  465. raise Exception("Failed to authorize client connection on GO")
  466. return None
  467. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False):
  468. self.dump_monitor()
  469. if not self.discover_peer(go_addr, social=social):
  470. raise Exception("GO " + go_addr + " not found")
  471. self.dump_monitor()
  472. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  473. if "OK" in self.global_request(cmd):
  474. if timeout == 0:
  475. self.dump_monitor()
  476. return None
  477. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  478. if ev is None:
  479. raise Exception("Joining the group timed out")
  480. self.dump_monitor()
  481. return self.group_form_result(ev)
  482. raise Exception("P2P_CONNECT(join) failed")
  483. def tdls_setup(self, peer):
  484. cmd = "TDLS_SETUP " + peer
  485. if "FAIL" in self.group_request(cmd):
  486. raise Exception("Failed to request TDLS setup")
  487. return None
  488. def tdls_teardown(self, peer):
  489. cmd = "TDLS_TEARDOWN " + peer
  490. if "FAIL" in self.group_request(cmd):
  491. raise Exception("Failed to request TDLS teardown")
  492. return None
  493. def connect(self, ssid, psk=None, proto=None, key_mgmt=None, wep_key0=None,
  494. ieee80211w=None, pairwise=None, group=None, scan_freq=None,
  495. eap=None, identity=None, anonymous_identity=None,
  496. password=None, phase1=None, phase2=None, ca_cert=None,
  497. domain_suffix_match=None, password_hex=None,
  498. client_cert=None, private_key=None, peerkey=False, okc=False,
  499. wait_connect=True, only_add_network=False):
  500. logger.info("Connect STA " + self.ifname + " to AP")
  501. id = self.add_network()
  502. self.set_network_quoted(id, "ssid", ssid)
  503. if psk:
  504. self.set_network_quoted(id, "psk", psk)
  505. if proto:
  506. self.set_network(id, "proto", proto)
  507. if key_mgmt:
  508. self.set_network(id, "key_mgmt", key_mgmt)
  509. if ieee80211w:
  510. self.set_network(id, "ieee80211w", ieee80211w)
  511. if pairwise:
  512. self.set_network(id, "pairwise", pairwise)
  513. if group:
  514. self.set_network(id, "group", group)
  515. if wep_key0:
  516. self.set_network(id, "wep_key0", wep_key0)
  517. if scan_freq:
  518. self.set_network(id, "scan_freq", scan_freq)
  519. if eap:
  520. self.set_network(id, "eap", eap)
  521. if identity:
  522. self.set_network_quoted(id, "identity", identity)
  523. if anonymous_identity:
  524. self.set_network_quoted(id, "anonymous_identity",
  525. anonymous_identity)
  526. if password:
  527. self.set_network_quoted(id, "password", password)
  528. if password_hex:
  529. self.set_network(id, "password", password_hex)
  530. if ca_cert:
  531. self.set_network_quoted(id, "ca_cert", ca_cert)
  532. if client_cert:
  533. self.set_network_quoted(id, "client_cert", client_cert)
  534. if private_key:
  535. self.set_network_quoted(id, "private_key", private_key)
  536. if phase1:
  537. self.set_network_quoted(id, "phase1", phase1)
  538. if phase2:
  539. self.set_network_quoted(id, "phase2", phase2)
  540. if domain_suffix_match:
  541. self.set_network_quoted(id, "domain_suffix_match",
  542. domain_suffix_match)
  543. if peerkey:
  544. self.set_network(id, "peerkey", "1")
  545. if okc:
  546. self.set_network(id, "proactive_key_caching", "1")
  547. if only_add_network:
  548. return id
  549. if wait_connect:
  550. self.connect_network(id)
  551. else:
  552. self.dump_monitor()
  553. self.select_network(id)
  554. return id
  555. def scan(self, type=None, freq=None):
  556. if type:
  557. cmd = "SCAN TYPE=" + type
  558. else:
  559. cmd = "SCAN"
  560. if freq:
  561. cmd = cmd + " freq=" + freq
  562. self.dump_monitor()
  563. if not "OK" in self.request(cmd):
  564. raise Exception("Failed to trigger scan")
  565. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  566. if ev is None:
  567. raise Exception("Scan timed out")
  568. def roam(self, bssid):
  569. self.dump_monitor()
  570. self.request("ROAM " + bssid)
  571. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  572. if ev is None:
  573. raise Exception("Roaming with the AP timed out")
  574. self.dump_monitor()
  575. def roam_over_ds(self, bssid):
  576. self.dump_monitor()
  577. self.request("FT_DS " + bssid)
  578. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  579. if ev is None:
  580. raise Exception("Roaming with the AP timed out")
  581. self.dump_monitor()
  582. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  583. new_passphrase=None, no_wait=False):
  584. self.dump_monitor()
  585. if new_ssid:
  586. self.request("WPS_REG " + bssid + " " + pin + " " +
  587. new_ssid.encode("hex") + " " + key_mgmt + " " +
  588. cipher + " " + new_passphrase.encode("hex"))
  589. if no_wait:
  590. return
  591. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  592. else:
  593. self.request("WPS_REG " + bssid + " " + pin)
  594. if no_wait:
  595. return
  596. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  597. if ev is None:
  598. raise Exception("WPS cred timed out")
  599. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  600. if ev is None:
  601. raise Exception("WPS timed out")
  602. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  603. if ev is None:
  604. raise Exception("Association with the AP timed out")
  605. def relog(self):
  606. self.request("RELOG")
  607. def wait_completed(self, timeout=10):
  608. for i in range(0, timeout * 2):
  609. if self.get_status_field("wpa_state") == "COMPLETED":
  610. return
  611. time.sleep(0.5)
  612. raise Exception("Timeout while waiting for COMPLETED state")
  613. def get_capability(self, field):
  614. res = self.request("GET_CAPABILITY " + field)
  615. if "FAIL" in res:
  616. return None
  617. return res.split(' ')
  618. def get_bss(self, bssid):
  619. res = self.request("BSS " + bssid)
  620. lines = res.splitlines()
  621. vals = dict()
  622. for l in lines:
  623. [name,value] = l.split('=', 1)
  624. vals[name] = value
  625. return vals
  626. def get_pmksa(self, bssid):
  627. res = self.request("PMKSA")
  628. lines = res.splitlines()
  629. for l in lines:
  630. if bssid not in l:
  631. continue
  632. vals = dict()
  633. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  634. vals['index'] = index
  635. vals['pmkid'] = pmkid
  636. vals['expiration'] = expiration
  637. vals['opportunistic'] = opportunistic
  638. return vals
  639. return None