wpasupplicant.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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):
  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 "OK" in self.global_request(cmd):
  402. if timeout == 0:
  403. self.dump_monitor()
  404. return None
  405. go_neg_res = None
  406. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  407. "P2P-GO-NEG-FAILURE"], timeout)
  408. if ev is None:
  409. if expect_failure:
  410. return None
  411. raise Exception("Group formation timed out")
  412. if "P2P-GO-NEG-SUCCESS" in ev:
  413. go_neg_res = ev
  414. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  415. if ev is None:
  416. if expect_failure:
  417. return None
  418. raise Exception("Group formation timed out")
  419. self.dump_monitor()
  420. return self.group_form_result(ev, expect_failure, go_neg_res)
  421. raise Exception("P2P_CONNECT failed")
  422. def wait_event(self, events, timeout=10):
  423. start = os.times()[4]
  424. while True:
  425. while self.mon.pending():
  426. ev = self.mon.recv()
  427. logger.debug(self.ifname + ": " + ev)
  428. for event in events:
  429. if event in ev:
  430. return ev
  431. now = os.times()[4]
  432. remaining = start + timeout - now
  433. if remaining <= 0:
  434. break
  435. if not self.mon.pending(timeout=remaining):
  436. break
  437. return None
  438. def wait_global_event(self, events, timeout):
  439. if self.global_iface is None:
  440. self.wait_event(events, timeout)
  441. else:
  442. start = os.times()[4]
  443. while True:
  444. while self.global_mon.pending():
  445. ev = self.global_mon.recv()
  446. logger.debug(self.ifname + "(global): " + ev)
  447. for event in events:
  448. if event in ev:
  449. return ev
  450. now = os.times()[4]
  451. remaining = start + timeout - now
  452. if remaining <= 0:
  453. break
  454. if not self.global_mon.pending(timeout=remaining):
  455. break
  456. return None
  457. def wait_go_ending_session(self):
  458. ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
  459. if ev is None:
  460. raise Exception("Group removal event timed out")
  461. if "reason=GO_ENDING_SESSION" not in ev:
  462. raise Exception("Unexpected group removal reason")
  463. def dump_monitor(self):
  464. while self.mon.pending():
  465. ev = self.mon.recv()
  466. logger.debug(self.ifname + ": " + ev)
  467. while self.global_mon.pending():
  468. ev = self.global_mon.recv()
  469. logger.debug(self.ifname + "(global): " + ev)
  470. def remove_group(self, ifname=None):
  471. if ifname is None:
  472. ifname = self.group_ifname if self.group_ifname else self.ifname
  473. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  474. raise Exception("Group could not be removed")
  475. self.group_ifname = None
  476. def p2p_start_go(self, persistent=None, freq=None):
  477. self.dump_monitor()
  478. cmd = "P2P_GROUP_ADD"
  479. if persistent is None:
  480. pass
  481. elif persistent is True:
  482. cmd = cmd + " persistent"
  483. else:
  484. cmd = cmd + " persistent=" + str(persistent)
  485. if freq:
  486. cmd = cmd + " freq=" + str(freq)
  487. if "OK" in self.global_request(cmd):
  488. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  489. if ev is None:
  490. raise Exception("GO start up timed out")
  491. self.dump_monitor()
  492. return self.group_form_result(ev)
  493. raise Exception("P2P_GROUP_ADD failed")
  494. def p2p_go_authorize_client(self, pin):
  495. cmd = "WPS_PIN any " + pin
  496. if "FAIL" in self.group_request(cmd):
  497. raise Exception("Failed to authorize client connection on GO")
  498. return None
  499. def p2p_go_authorize_client_pbc(self):
  500. cmd = "WPS_PBC"
  501. if "FAIL" in self.group_request(cmd):
  502. raise Exception("Failed to authorize client connection on GO")
  503. return None
  504. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False):
  505. self.dump_monitor()
  506. if not self.discover_peer(go_addr, social=social):
  507. raise Exception("GO " + go_addr + " not found")
  508. self.dump_monitor()
  509. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  510. if "OK" in self.global_request(cmd):
  511. if timeout == 0:
  512. self.dump_monitor()
  513. return None
  514. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  515. if ev is None:
  516. raise Exception("Joining the group timed out")
  517. self.dump_monitor()
  518. return self.group_form_result(ev)
  519. raise Exception("P2P_CONNECT(join) failed")
  520. def tdls_setup(self, peer):
  521. cmd = "TDLS_SETUP " + peer
  522. if "FAIL" in self.group_request(cmd):
  523. raise Exception("Failed to request TDLS setup")
  524. return None
  525. def tdls_teardown(self, peer):
  526. cmd = "TDLS_TEARDOWN " + peer
  527. if "FAIL" in self.group_request(cmd):
  528. raise Exception("Failed to request TDLS teardown")
  529. return None
  530. def connect(self, ssid=None, ssid2=None, **kwargs):
  531. logger.info("Connect STA " + self.ifname + " to AP")
  532. id = self.add_network()
  533. if ssid:
  534. self.set_network_quoted(id, "ssid", ssid)
  535. elif ssid2:
  536. self.set_network(id, "ssid", ssid2)
  537. quoted = [ "psk", "identity", "anonymous_identity", "password",
  538. "ca_cert", "client_cert", "private_key",
  539. "private_key_passwd", "ca_cert2", "client_cert2",
  540. "private_key2", "phase1", "phase2", "domain_suffix_match",
  541. "altsubject_match", "subject_match", "pac_file", "dh_file" ]
  542. for field in quoted:
  543. if field in kwargs and kwargs[field]:
  544. self.set_network_quoted(id, field, kwargs[field])
  545. not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
  546. "group", "wep_key0", "scan_freq", "eap",
  547. "eapol_flags", "fragment_size", "scan_ssid", "auth_alg" ]
  548. for field in not_quoted:
  549. if field in kwargs and kwargs[field]:
  550. self.set_network(id, field, kwargs[field])
  551. if "raw_psk" in kwargs and kwargs['raw_psk']:
  552. self.set_network(id, "psk", kwargs['raw_psk'])
  553. if "password_hex" in kwargs and kwargs['password_hex']:
  554. self.set_network(id, "password", kwargs['password_hex'])
  555. if "peerkey" in kwargs and kwargs['peerkey']:
  556. self.set_network(id, "peerkey", "1")
  557. if "okc" in kwargs and kwargs['okc']:
  558. self.set_network(id, "proactive_key_caching", "1")
  559. if "ocsp" in kwargs and kwargs['ocsp']:
  560. self.set_network(id, "ocsp", str(kwargs['ocsp']))
  561. if "only_add_network" in kwargs and kwargs['only_add_network']:
  562. return id
  563. if "wait_connect" not in kwargs or kwargs['wait_connect']:
  564. if "eap" in kwargs:
  565. self.connect_network(id, timeout=20)
  566. else:
  567. self.connect_network(id)
  568. else:
  569. self.dump_monitor()
  570. self.select_network(id)
  571. return id
  572. def scan(self, type=None, freq=None, no_wait=False):
  573. if type:
  574. cmd = "SCAN TYPE=" + type
  575. else:
  576. cmd = "SCAN"
  577. if freq:
  578. cmd = cmd + " freq=" + freq
  579. if not no_wait:
  580. self.dump_monitor()
  581. if not "OK" in self.request(cmd):
  582. raise Exception("Failed to trigger scan")
  583. if no_wait:
  584. return
  585. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  586. if ev is None:
  587. raise Exception("Scan timed out")
  588. def roam(self, bssid):
  589. self.dump_monitor()
  590. self.request("ROAM " + bssid)
  591. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  592. if ev is None:
  593. raise Exception("Roaming with the AP timed out")
  594. self.dump_monitor()
  595. def roam_over_ds(self, bssid):
  596. self.dump_monitor()
  597. self.request("FT_DS " + bssid)
  598. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  599. if ev is None:
  600. raise Exception("Roaming with the AP timed out")
  601. self.dump_monitor()
  602. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  603. new_passphrase=None, no_wait=False):
  604. self.dump_monitor()
  605. if new_ssid:
  606. self.request("WPS_REG " + bssid + " " + pin + " " +
  607. new_ssid.encode("hex") + " " + key_mgmt + " " +
  608. cipher + " " + new_passphrase.encode("hex"))
  609. if no_wait:
  610. return
  611. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  612. else:
  613. self.request("WPS_REG " + bssid + " " + pin)
  614. if no_wait:
  615. return
  616. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  617. if ev is None:
  618. raise Exception("WPS cred timed out")
  619. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  620. if ev is None:
  621. raise Exception("WPS timed out")
  622. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  623. if ev is None:
  624. raise Exception("Association with the AP timed out")
  625. def relog(self):
  626. self.request("RELOG")
  627. def wait_completed(self, timeout=10):
  628. for i in range(0, timeout * 2):
  629. if self.get_status_field("wpa_state") == "COMPLETED":
  630. return
  631. time.sleep(0.5)
  632. raise Exception("Timeout while waiting for COMPLETED state")
  633. def get_capability(self, field):
  634. res = self.request("GET_CAPABILITY " + field)
  635. if "FAIL" in res:
  636. return None
  637. return res.split(' ')
  638. def get_bss(self, bssid):
  639. res = self.request("BSS " + bssid)
  640. lines = res.splitlines()
  641. vals = dict()
  642. for l in lines:
  643. [name,value] = l.split('=', 1)
  644. vals[name] = value
  645. return vals
  646. def get_pmksa(self, bssid):
  647. res = self.request("PMKSA")
  648. lines = res.splitlines()
  649. for l in lines:
  650. if bssid not in l:
  651. continue
  652. vals = dict()
  653. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  654. vals['index'] = index
  655. vals['pmkid'] = pmkid
  656. vals['expiration'] = expiration
  657. vals['opportunistic'] = opportunistic
  658. return vals
  659. return None
  660. def get_sta(self, addr, info=None, next=False):
  661. cmd = "STA-NEXT " if next else "STA "
  662. if addr is None:
  663. res = self.request("STA-FIRST")
  664. elif info:
  665. res = self.request(cmd + addr + " " + info)
  666. else:
  667. res = self.request(cmd + addr)
  668. lines = res.splitlines()
  669. vals = dict()
  670. first = True
  671. for l in lines:
  672. if first:
  673. vals['addr'] = l
  674. first = False
  675. else:
  676. [name,value] = l.split('=', 1)
  677. vals[name] = value
  678. return vals