wpasupplicant.py 27 KB

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