wpasupplicant.py 27 KB

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