wpasupplicant.py 28 KB

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