wpasupplicant.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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 p2p_no_group_iface 1")
  83. self.group_ifname = None
  84. self.dump_monitor()
  85. iter = 0
  86. while iter < 60:
  87. state = self.get_driver_status_field("scan_state")
  88. if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
  89. logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
  90. time.sleep(1)
  91. else:
  92. break
  93. iter = iter + 1
  94. if iter == 60:
  95. logger.error(self.ifname + ": Driver scan state did not clear")
  96. print "Trying to clear cfg80211/mac80211 scan state"
  97. try:
  98. cmd = ["sudo", "ifconfig", self.ifname, "down"]
  99. subprocess.call(cmd)
  100. except subprocess.CalledProcessError, e:
  101. logger.info("ifconfig failed: " + str(e.returncode))
  102. logger.info(e.output)
  103. try:
  104. cmd = ["sudo", "ifconfig", self.ifname, "up"]
  105. subprocess.call(cmd)
  106. except subprocess.CalledProcessError, e:
  107. logger.info("ifconfig failed: " + str(e.returncode))
  108. logger.info(e.output)
  109. if iter > 0:
  110. # The ongoing scan could have discovered BSSes or P2P peers
  111. logger.info("Run FLUSH again since scan was in progress")
  112. self.request("FLUSH")
  113. self.dump_monitor()
  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, timeout=10):
  194. self.dump_monitor()
  195. self.select_network(id)
  196. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
  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, dev_id=None, dev_type=None):
  246. cmd = "P2P_FIND"
  247. if social:
  248. cmd = cmd + " type=social"
  249. if dev_id:
  250. cmd = cmd + " dev_id=" + dev_id
  251. if dev_type:
  252. cmd = cmd + " dev_type=" + dev_type
  253. return self.global_request(cmd)
  254. def p2p_stop_find(self):
  255. return self.global_request("P2P_STOP_FIND")
  256. def wps_read_pin(self):
  257. #TODO: make this random
  258. self.pin = "12345670"
  259. return self.pin
  260. def peer_known(self, peer, full=True):
  261. res = self.global_request("P2P_PEER " + peer)
  262. if peer.lower() not in res.lower():
  263. return False
  264. if not full:
  265. return True
  266. return "[PROBE_REQ_ONLY]" not in res
  267. def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
  268. logger.info(self.ifname + ": Trying to discover peer " + peer)
  269. if not force_find and self.peer_known(peer, full):
  270. return True
  271. self.p2p_find(social)
  272. count = 0
  273. while count < timeout:
  274. time.sleep(1)
  275. count = count + 1
  276. if self.peer_known(peer, full):
  277. return True
  278. return False
  279. def get_peer(self, peer):
  280. res = self.global_request("P2P_PEER " + peer)
  281. if peer.lower() not in res.lower():
  282. raise Exception("Peer information not available")
  283. lines = res.splitlines()
  284. vals = dict()
  285. for l in lines:
  286. if '=' in l:
  287. [name,value] = l.split('=', 1)
  288. vals[name] = value
  289. return vals
  290. def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
  291. if expect_failure:
  292. if "P2P-GROUP-STARTED" in ev:
  293. raise Exception("Group formation succeeded when expecting failure")
  294. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  295. s = re.split(exp, ev)
  296. if len(s) < 3:
  297. return None
  298. res = {}
  299. res['result'] = 'go-neg-failed'
  300. res['status'] = int(s[2])
  301. return res
  302. if "P2P-GROUP-STARTED" not in ev:
  303. raise Exception("No P2P-GROUP-STARTED event seen")
  304. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  305. s = re.split(exp, ev)
  306. if len(s) < 8:
  307. raise Exception("Could not parse P2P-GROUP-STARTED")
  308. res = {}
  309. res['result'] = 'success'
  310. res['ifname'] = s[2]
  311. self.group_ifname = s[2]
  312. res['role'] = s[3]
  313. res['ssid'] = s[4]
  314. res['freq'] = s[5]
  315. if "[PERSISTENT]" in ev:
  316. res['persistent'] = True
  317. else:
  318. res['persistent'] = False
  319. p = re.match(r'psk=([0-9a-f]*)', s[6])
  320. if p:
  321. res['psk'] = p.group(1)
  322. p = re.match(r'passphrase="(.*)"', s[6])
  323. if p:
  324. res['passphrase'] = p.group(1)
  325. res['go_dev_addr'] = s[7]
  326. if go_neg_res:
  327. exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
  328. s = re.split(exp, go_neg_res)
  329. if len(s) < 4:
  330. raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
  331. res['go_neg_role'] = s[2]
  332. res['go_neg_freq'] = s[3]
  333. return res
  334. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
  335. if not self.discover_peer(peer):
  336. raise Exception("Peer " + peer + " not found")
  337. self.dump_monitor()
  338. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  339. if go_intent:
  340. cmd = cmd + ' go_intent=' + str(go_intent)
  341. if freq:
  342. cmd = cmd + ' freq=' + str(freq)
  343. if persistent:
  344. cmd = cmd + " persistent"
  345. if "OK" in self.global_request(cmd):
  346. return None
  347. raise Exception("P2P_CONNECT (auth) failed")
  348. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  349. go_neg_res = None
  350. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  351. "P2P-GO-NEG-FAILURE"], timeout);
  352. if ev is None:
  353. if expect_failure:
  354. return None
  355. raise Exception("Group formation timed out")
  356. if "P2P-GO-NEG-SUCCESS" in ev:
  357. go_neg_res = ev
  358. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
  359. if ev is None:
  360. if expect_failure:
  361. return None
  362. raise Exception("Group formation timed out")
  363. self.dump_monitor()
  364. return self.group_form_result(ev, expect_failure, go_neg_res)
  365. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False, persistent=False, freq=None):
  366. if not self.discover_peer(peer):
  367. raise Exception("Peer " + peer + " not found")
  368. self.dump_monitor()
  369. if pin:
  370. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  371. else:
  372. cmd = "P2P_CONNECT " + peer + " " + method
  373. if go_intent:
  374. cmd = cmd + ' go_intent=' + str(go_intent)
  375. if freq:
  376. cmd = cmd + ' freq=' + str(freq)
  377. if persistent:
  378. cmd = cmd + " persistent"
  379. if "OK" in self.global_request(cmd):
  380. if timeout == 0:
  381. self.dump_monitor()
  382. return None
  383. go_neg_res = None
  384. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  385. "P2P-GO-NEG-FAILURE"], timeout)
  386. if ev is None:
  387. if expect_failure:
  388. return None
  389. raise Exception("Group formation timed out")
  390. if "P2P-GO-NEG-SUCCESS" in ev:
  391. go_neg_res = ev
  392. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  393. if ev is None:
  394. if expect_failure:
  395. return None
  396. raise Exception("Group formation timed out")
  397. self.dump_monitor()
  398. return self.group_form_result(ev, expect_failure, go_neg_res)
  399. raise Exception("P2P_CONNECT failed")
  400. def wait_event(self, events, timeout=10):
  401. start = os.times()[4]
  402. while True:
  403. while self.mon.pending():
  404. ev = self.mon.recv()
  405. logger.debug(self.ifname + ": " + ev)
  406. for event in events:
  407. if event in ev:
  408. return ev
  409. now = os.times()[4]
  410. remaining = start + timeout - now
  411. if remaining <= 0:
  412. break
  413. if not self.mon.pending(timeout=remaining):
  414. break
  415. return None
  416. def wait_global_event(self, events, timeout):
  417. if self.global_iface is None:
  418. self.wait_event(events, timeout)
  419. else:
  420. start = os.times()[4]
  421. while True:
  422. while self.global_mon.pending():
  423. ev = self.global_mon.recv()
  424. logger.debug(self.ifname + "(global): " + ev)
  425. for event in events:
  426. if event in ev:
  427. return ev
  428. now = os.times()[4]
  429. remaining = start + timeout - now
  430. if remaining <= 0:
  431. break
  432. if not self.global_mon.pending(timeout=remaining):
  433. break
  434. return None
  435. def wait_go_ending_session(self):
  436. ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
  437. if ev is None:
  438. raise Exception("Group removal event timed out")
  439. if "reason=GO_ENDING_SESSION" not in ev:
  440. raise Exception("Unexpected group removal reason")
  441. def dump_monitor(self):
  442. while self.mon.pending():
  443. ev = self.mon.recv()
  444. logger.debug(self.ifname + ": " + ev)
  445. while self.global_mon.pending():
  446. ev = self.global_mon.recv()
  447. logger.debug(self.ifname + "(global): " + ev)
  448. def remove_group(self, ifname=None):
  449. if ifname is None:
  450. ifname = self.group_ifname if self.group_ifname else self.ifname
  451. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  452. raise Exception("Group could not be removed")
  453. self.group_ifname = None
  454. def p2p_start_go(self, persistent=None, freq=None):
  455. self.dump_monitor()
  456. cmd = "P2P_GROUP_ADD"
  457. if persistent is None:
  458. pass
  459. elif persistent is True:
  460. cmd = cmd + " persistent"
  461. else:
  462. cmd = cmd + " persistent=" + str(persistent)
  463. if freq:
  464. cmd = cmd + " freq=" + str(freq)
  465. if "OK" in self.global_request(cmd):
  466. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  467. if ev is None:
  468. raise Exception("GO start up timed out")
  469. self.dump_monitor()
  470. return self.group_form_result(ev)
  471. raise Exception("P2P_GROUP_ADD failed")
  472. def p2p_go_authorize_client(self, pin):
  473. cmd = "WPS_PIN any " + pin
  474. if "FAIL" in self.group_request(cmd):
  475. raise Exception("Failed to authorize client connection on GO")
  476. return None
  477. def p2p_go_authorize_client_pbc(self):
  478. cmd = "WPS_PBC"
  479. if "FAIL" in self.group_request(cmd):
  480. raise Exception("Failed to authorize client connection on GO")
  481. return None
  482. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False):
  483. self.dump_monitor()
  484. if not self.discover_peer(go_addr, social=social):
  485. raise Exception("GO " + go_addr + " not found")
  486. self.dump_monitor()
  487. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  488. if "OK" in self.global_request(cmd):
  489. if timeout == 0:
  490. self.dump_monitor()
  491. return None
  492. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  493. if ev is None:
  494. raise Exception("Joining the group timed out")
  495. self.dump_monitor()
  496. return self.group_form_result(ev)
  497. raise Exception("P2P_CONNECT(join) failed")
  498. def tdls_setup(self, peer):
  499. cmd = "TDLS_SETUP " + peer
  500. if "FAIL" in self.group_request(cmd):
  501. raise Exception("Failed to request TDLS setup")
  502. return None
  503. def tdls_teardown(self, peer):
  504. cmd = "TDLS_TEARDOWN " + peer
  505. if "FAIL" in self.group_request(cmd):
  506. raise Exception("Failed to request TDLS teardown")
  507. return None
  508. def connect(self, ssid=None, ssid2=None, psk=None, proto=None,
  509. key_mgmt=None, wep_key0=None,
  510. ieee80211w=None, pairwise=None, group=None, scan_freq=None,
  511. eap=None, identity=None, anonymous_identity=None,
  512. password=None, phase1=None, phase2=None, ca_cert=None,
  513. domain_suffix_match=None, password_hex=None,
  514. client_cert=None, private_key=None, peerkey=False, okc=False,
  515. eapol_flags=None, fragment_size=None,
  516. wait_connect=True, only_add_network=False,
  517. ca_cert2=None, client_cert2=None, private_key2=None,
  518. scan_ssid=None, raw_psk=None, pac_file=None,
  519. subject_match=None, altsubject_match=None,
  520. private_key_passwd=None, ocsp=None):
  521. logger.info("Connect STA " + self.ifname + " to AP")
  522. id = self.add_network()
  523. if ssid:
  524. self.set_network_quoted(id, "ssid", ssid)
  525. elif ssid2:
  526. self.set_network(id, "ssid", ssid2)
  527. if psk:
  528. self.set_network_quoted(id, "psk", psk)
  529. if raw_psk:
  530. self.set_network(id, "psk", raw_psk)
  531. if proto:
  532. self.set_network(id, "proto", proto)
  533. if key_mgmt:
  534. self.set_network(id, "key_mgmt", key_mgmt)
  535. if ieee80211w:
  536. self.set_network(id, "ieee80211w", ieee80211w)
  537. if pairwise:
  538. self.set_network(id, "pairwise", pairwise)
  539. if group:
  540. self.set_network(id, "group", group)
  541. if wep_key0:
  542. self.set_network(id, "wep_key0", wep_key0)
  543. if scan_freq:
  544. self.set_network(id, "scan_freq", scan_freq)
  545. if eap:
  546. self.set_network(id, "eap", eap)
  547. if identity:
  548. self.set_network_quoted(id, "identity", identity)
  549. if anonymous_identity:
  550. self.set_network_quoted(id, "anonymous_identity",
  551. anonymous_identity)
  552. if password:
  553. self.set_network_quoted(id, "password", password)
  554. if password_hex:
  555. self.set_network(id, "password", password_hex)
  556. if ca_cert:
  557. self.set_network_quoted(id, "ca_cert", ca_cert)
  558. if client_cert:
  559. self.set_network_quoted(id, "client_cert", client_cert)
  560. if private_key:
  561. self.set_network_quoted(id, "private_key", private_key)
  562. if private_key_passwd:
  563. self.set_network_quoted(id, "private_key_passwd",
  564. private_key_passwd)
  565. if ca_cert2:
  566. self.set_network_quoted(id, "ca_cert2", ca_cert2)
  567. if client_cert2:
  568. self.set_network_quoted(id, "client_cert2", client_cert2)
  569. if private_key2:
  570. self.set_network_quoted(id, "private_key2", private_key2)
  571. if phase1:
  572. self.set_network_quoted(id, "phase1", phase1)
  573. if phase2:
  574. self.set_network_quoted(id, "phase2", phase2)
  575. if domain_suffix_match:
  576. self.set_network_quoted(id, "domain_suffix_match",
  577. domain_suffix_match)
  578. if altsubject_match:
  579. self.set_network_quoted(id, "altsubject_match",
  580. altsubject_match)
  581. if subject_match:
  582. self.set_network_quoted(id, "subject_match",
  583. subject_match)
  584. if peerkey:
  585. self.set_network(id, "peerkey", "1")
  586. if okc:
  587. self.set_network(id, "proactive_key_caching", "1")
  588. if eapol_flags:
  589. self.set_network(id, "eapol_flags", eapol_flags)
  590. if fragment_size:
  591. self.set_network(id, "fragment_size", fragment_size)
  592. if scan_ssid:
  593. self.set_network(id, "scan_ssid", scan_ssid)
  594. if pac_file:
  595. self.set_network_quoted(id, "pac_file", pac_file)
  596. if ocsp:
  597. self.set_network(id, "ocsp", str(ocsp))
  598. if only_add_network:
  599. return id
  600. if wait_connect:
  601. if eap:
  602. self.connect_network(id, timeout=20)
  603. else:
  604. self.connect_network(id)
  605. else:
  606. self.dump_monitor()
  607. self.select_network(id)
  608. return id
  609. def scan(self, type=None, freq=None, no_wait=False):
  610. if type:
  611. cmd = "SCAN TYPE=" + type
  612. else:
  613. cmd = "SCAN"
  614. if freq:
  615. cmd = cmd + " freq=" + freq
  616. if not no_wait:
  617. self.dump_monitor()
  618. if not "OK" in self.request(cmd):
  619. raise Exception("Failed to trigger scan")
  620. if no_wait:
  621. return
  622. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  623. if ev is None:
  624. raise Exception("Scan timed out")
  625. def roam(self, bssid):
  626. self.dump_monitor()
  627. self.request("ROAM " + bssid)
  628. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  629. if ev is None:
  630. raise Exception("Roaming with the AP timed out")
  631. self.dump_monitor()
  632. def roam_over_ds(self, bssid):
  633. self.dump_monitor()
  634. self.request("FT_DS " + bssid)
  635. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  636. if ev is None:
  637. raise Exception("Roaming with the AP timed out")
  638. self.dump_monitor()
  639. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  640. new_passphrase=None, no_wait=False):
  641. self.dump_monitor()
  642. if new_ssid:
  643. self.request("WPS_REG " + bssid + " " + pin + " " +
  644. new_ssid.encode("hex") + " " + key_mgmt + " " +
  645. cipher + " " + new_passphrase.encode("hex"))
  646. if no_wait:
  647. return
  648. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  649. else:
  650. self.request("WPS_REG " + bssid + " " + pin)
  651. if no_wait:
  652. return
  653. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  654. if ev is None:
  655. raise Exception("WPS cred timed out")
  656. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  657. if ev is None:
  658. raise Exception("WPS timed out")
  659. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  660. if ev is None:
  661. raise Exception("Association with the AP timed out")
  662. def relog(self):
  663. self.request("RELOG")
  664. def wait_completed(self, timeout=10):
  665. for i in range(0, timeout * 2):
  666. if self.get_status_field("wpa_state") == "COMPLETED":
  667. return
  668. time.sleep(0.5)
  669. raise Exception("Timeout while waiting for COMPLETED state")
  670. def get_capability(self, field):
  671. res = self.request("GET_CAPABILITY " + field)
  672. if "FAIL" in res:
  673. return None
  674. return res.split(' ')
  675. def get_bss(self, bssid):
  676. res = self.request("BSS " + bssid)
  677. lines = res.splitlines()
  678. vals = dict()
  679. for l in lines:
  680. [name,value] = l.split('=', 1)
  681. vals[name] = value
  682. return vals
  683. def get_pmksa(self, bssid):
  684. res = self.request("PMKSA")
  685. lines = res.splitlines()
  686. for l in lines:
  687. if bssid not in l:
  688. continue
  689. vals = dict()
  690. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  691. vals['index'] = index
  692. vals['pmkid'] = pmkid
  693. vals['expiration'] = expiration
  694. vals['opportunistic'] = opportunistic
  695. return vals
  696. return None