wpasupplicant.py 26 KB

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