wpasupplicant.py 27 KB

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