wpasupplicant.py 27 KB

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