wpasupplicant.py 25 KB

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