wpasupplicant.py 27 KB

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