wpasupplicant.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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 binascii
  10. import re
  11. import struct
  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. self.gctrl_mon = None
  20. if ifname:
  21. self.set_ifname(ifname)
  22. else:
  23. self.ifname = None
  24. self.global_iface = global_iface
  25. if global_iface:
  26. self.global_ctrl = wpaspy.Ctrl(global_iface)
  27. self.global_mon = wpaspy.Ctrl(global_iface)
  28. self.global_mon.attach()
  29. def set_ifname(self, ifname):
  30. self.ifname = ifname
  31. self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  32. self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  33. self.mon.attach()
  34. def remove_ifname(self):
  35. if self.ifname:
  36. self.mon.detach()
  37. self.mon = None
  38. self.ctrl = None
  39. self.ifname = None
  40. def interface_add(self, ifname, config="", driver="nl80211", drv_params=None):
  41. try:
  42. groups = subprocess.check_output(["id"])
  43. group = "admin" if "(admin)" in groups else "adm"
  44. except Exception, e:
  45. group = "admin"
  46. cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
  47. if drv_params:
  48. cmd = cmd + '\t' + drv_params
  49. if "FAIL" in self.global_request(cmd):
  50. raise Exception("Failed to add a dynamic wpa_supplicant interface")
  51. self.set_ifname(ifname)
  52. def interface_remove(self, ifname):
  53. self.remove_ifname()
  54. self.global_request("INTERFACE_REMOVE " + ifname)
  55. def request(self, cmd):
  56. logger.debug(self.ifname + ": CTRL: " + cmd)
  57. return self.ctrl.request(cmd)
  58. def global_request(self, cmd):
  59. if self.global_iface is None:
  60. self.request(cmd)
  61. else:
  62. ifname = self.ifname or self.global_iface
  63. logger.debug(ifname + ": CTRL(global): " + cmd)
  64. return self.global_ctrl.request(cmd)
  65. def group_request(self, cmd):
  66. if self.group_ifname and self.group_ifname != self.ifname:
  67. logger.debug(self.group_ifname + ": CTRL: " + cmd)
  68. gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  69. return gctrl.request(cmd)
  70. return self.request(cmd)
  71. def ping(self):
  72. return "PONG" in self.request("PING")
  73. def global_ping(self):
  74. return "PONG" in self.global_request("PING")
  75. def reset(self):
  76. self.dump_monitor()
  77. res = self.request("FLUSH")
  78. if not "OK" in res:
  79. logger.info("FLUSH to " + self.ifname + " failed: " + res)
  80. self.request("WPS_ER_STOP")
  81. self.request("SET pmf 0")
  82. self.request("SET p2p_add_cli_chan 0")
  83. self.request("SET p2p_no_go_freq ")
  84. self.request("SET p2p_pref_chan ")
  85. self.request("SET p2p_no_group_iface 1")
  86. self.request("SET p2p_go_intent 7")
  87. self.request("SET ignore_old_scan_res 0")
  88. if self.gctrl_mon:
  89. try:
  90. self.gctrl_mon.detach()
  91. except:
  92. pass
  93. self.gctrl_mon = None
  94. self.group_ifname = None
  95. self.dump_monitor()
  96. iter = 0
  97. while iter < 60:
  98. state = self.get_driver_status_field("scan_state")
  99. if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
  100. logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
  101. time.sleep(1)
  102. else:
  103. break
  104. iter = iter + 1
  105. if iter == 60:
  106. logger.error(self.ifname + ": Driver scan state did not clear")
  107. print "Trying to clear cfg80211/mac80211 scan state"
  108. try:
  109. cmd = ["sudo", "ifconfig", self.ifname, "down"]
  110. subprocess.call(cmd)
  111. except subprocess.CalledProcessError, e:
  112. logger.info("ifconfig failed: " + str(e.returncode))
  113. logger.info(e.output)
  114. try:
  115. cmd = ["sudo", "ifconfig", self.ifname, "up"]
  116. subprocess.call(cmd)
  117. except subprocess.CalledProcessError, e:
  118. logger.info("ifconfig failed: " + str(e.returncode))
  119. logger.info(e.output)
  120. if iter > 0:
  121. # The ongoing scan could have discovered BSSes or P2P peers
  122. logger.info("Run FLUSH again since scan was in progress")
  123. self.request("FLUSH")
  124. self.dump_monitor()
  125. if not self.ping():
  126. logger.info("No PING response from " + self.ifname + " after reset")
  127. def add_network(self):
  128. id = self.request("ADD_NETWORK")
  129. if "FAIL" in id:
  130. raise Exception("ADD_NETWORK failed")
  131. return int(id)
  132. def remove_network(self, id):
  133. id = self.request("REMOVE_NETWORK " + str(id))
  134. if "FAIL" in id:
  135. raise Exception("REMOVE_NETWORK failed")
  136. return None
  137. def get_network(self, id, field):
  138. res = self.request("GET_NETWORK " + str(id) + " " + field)
  139. if res == "FAIL\n":
  140. return None
  141. return res
  142. def set_network(self, id, field, value):
  143. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  144. if "FAIL" in res:
  145. raise Exception("SET_NETWORK failed")
  146. return None
  147. def set_network_quoted(self, id, field, value):
  148. res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  149. if "FAIL" in res:
  150. raise Exception("SET_NETWORK failed")
  151. return None
  152. def list_networks(self):
  153. res = self.request("LIST_NETWORKS")
  154. lines = res.splitlines()
  155. networks = []
  156. for l in lines:
  157. if "network id" in l:
  158. continue
  159. [id,ssid,bssid,flags] = l.split('\t')
  160. network = {}
  161. network['id'] = id
  162. network['ssid'] = ssid
  163. network['bssid'] = bssid
  164. network['flags'] = flags
  165. networks.append(network)
  166. return networks
  167. def hs20_enable(self, auto_interworking=False):
  168. self.request("SET interworking 1")
  169. self.request("SET hs20 1")
  170. if auto_interworking:
  171. self.request("SET auto_interworking 1")
  172. else:
  173. self.request("SET auto_interworking 0")
  174. def add_cred(self):
  175. id = self.request("ADD_CRED")
  176. if "FAIL" in id:
  177. raise Exception("ADD_CRED failed")
  178. return int(id)
  179. def remove_cred(self, id):
  180. id = self.request("REMOVE_CRED " + str(id))
  181. if "FAIL" in id:
  182. raise Exception("REMOVE_CRED failed")
  183. return None
  184. def set_cred(self, id, field, value):
  185. res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
  186. if "FAIL" in res:
  187. raise Exception("SET_CRED failed")
  188. return None
  189. def set_cred_quoted(self, id, field, value):
  190. res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
  191. if "FAIL" in res:
  192. raise Exception("SET_CRED failed")
  193. return None
  194. def get_cred(self, id, field):
  195. return self.request("GET_CRED " + str(id) + " " + field)
  196. def add_cred_values(self, params):
  197. id = self.add_cred()
  198. quoted = [ "realm", "username", "password", "domain", "imsi",
  199. "excluded_ssid", "milenage", "ca_cert", "client_cert",
  200. "private_key", "domain_suffix_match", "provisioning_sp",
  201. "roaming_partner", "phase1", "phase2" ]
  202. for field in quoted:
  203. if field in params:
  204. self.set_cred_quoted(id, field, params[field])
  205. not_quoted = [ "eap", "roaming_consortium", "priority",
  206. "required_roaming_consortium", "sp_priority",
  207. "max_bss_load", "update_identifier", "req_conn_capab",
  208. "min_dl_bandwidth_home", "min_ul_bandwidth_home",
  209. "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
  210. for field in not_quoted:
  211. if field in params:
  212. self.set_cred(id, field, params[field])
  213. return id;
  214. def select_network(self, id, freq=None):
  215. if freq:
  216. extra = " freq=" + freq
  217. else:
  218. extra = ""
  219. id = self.request("SELECT_NETWORK " + str(id) + extra)
  220. if "FAIL" in id:
  221. raise Exception("SELECT_NETWORK failed")
  222. return None
  223. def mesh_group_add(self, id):
  224. id = self.request("MESH_GROUP_ADD " + str(id))
  225. if "FAIL" in id:
  226. raise Exception("MESH_GROUP_ADD failed")
  227. return None
  228. def mesh_group_remove(self):
  229. id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
  230. if "FAIL" in id:
  231. raise Exception("MESH_GROUP_REMOVE failed")
  232. return None
  233. def connect_network(self, id, timeout=10):
  234. self.dump_monitor()
  235. self.select_network(id)
  236. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
  237. if ev is None:
  238. raise Exception("Association with the AP timed out")
  239. self.dump_monitor()
  240. def get_status(self, extra=None):
  241. if extra:
  242. extra = "-" + extra
  243. else:
  244. extra = ""
  245. res = self.request("STATUS" + extra)
  246. lines = res.splitlines()
  247. vals = dict()
  248. for l in lines:
  249. try:
  250. [name,value] = l.split('=', 1)
  251. vals[name] = value
  252. except ValueError, e:
  253. logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
  254. return vals
  255. def get_status_field(self, field, extra=None):
  256. vals = self.get_status(extra)
  257. if field in vals:
  258. return vals[field]
  259. return None
  260. def get_group_status(self, extra=None):
  261. if extra:
  262. extra = "-" + extra
  263. else:
  264. extra = ""
  265. res = self.group_request("STATUS" + extra)
  266. lines = res.splitlines()
  267. vals = dict()
  268. for l in lines:
  269. try:
  270. [name,value] = l.split('=', 1)
  271. except ValueError:
  272. logger.info(self.ifname + ": Ignore unexpected status line: " + l)
  273. continue
  274. vals[name] = value
  275. return vals
  276. def get_group_status_field(self, field, extra=None):
  277. vals = self.get_group_status(extra)
  278. if field in vals:
  279. return vals[field]
  280. return None
  281. def get_driver_status(self):
  282. res = self.request("STATUS-DRIVER")
  283. lines = res.splitlines()
  284. vals = dict()
  285. for l in lines:
  286. try:
  287. [name,value] = l.split('=', 1)
  288. except ValueError:
  289. logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
  290. continue
  291. vals[name] = value
  292. return vals
  293. def get_driver_status_field(self, field):
  294. vals = self.get_driver_status()
  295. if field in vals:
  296. return vals[field]
  297. return None
  298. def get_mcc(self):
  299. mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
  300. return 1 if mcc < 2 else mcc
  301. def get_mib(self):
  302. res = self.request("MIB")
  303. lines = res.splitlines()
  304. vals = dict()
  305. for l in lines:
  306. try:
  307. [name,value] = l.split('=', 1)
  308. vals[name] = value
  309. except ValueError, e:
  310. logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
  311. return vals
  312. def p2p_dev_addr(self):
  313. return self.get_status_field("p2p_device_address")
  314. def p2p_interface_addr(self):
  315. return self.get_group_status_field("address")
  316. def own_addr(self):
  317. try:
  318. res = self.p2p_interface_addr()
  319. except:
  320. res = self.p2p_dev_addr()
  321. return res
  322. def p2p_listen(self):
  323. return self.global_request("P2P_LISTEN")
  324. def p2p_find(self, social=False, progressive=False, dev_id=None, dev_type=None):
  325. cmd = "P2P_FIND"
  326. if social:
  327. cmd = cmd + " type=social"
  328. elif progressive:
  329. cmd = cmd + " type=progressive"
  330. if dev_id:
  331. cmd = cmd + " dev_id=" + dev_id
  332. if dev_type:
  333. cmd = cmd + " dev_type=" + dev_type
  334. return self.global_request(cmd)
  335. def p2p_stop_find(self):
  336. return self.global_request("P2P_STOP_FIND")
  337. def wps_read_pin(self):
  338. self.pin = self.request("WPS_PIN get").rstrip("\n")
  339. if "FAIL" in self.pin:
  340. raise Exception("Could not generate PIN")
  341. return self.pin
  342. def peer_known(self, peer, full=True):
  343. res = self.global_request("P2P_PEER " + peer)
  344. if peer.lower() not in res.lower():
  345. return False
  346. if not full:
  347. return True
  348. return "[PROBE_REQ_ONLY]" not in res
  349. def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
  350. logger.info(self.ifname + ": Trying to discover peer " + peer)
  351. if not force_find and self.peer_known(peer, full):
  352. return True
  353. self.p2p_find(social)
  354. count = 0
  355. while count < timeout * 4:
  356. time.sleep(0.25)
  357. count = count + 1
  358. if self.peer_known(peer, full):
  359. return True
  360. return False
  361. def get_peer(self, peer):
  362. res = self.global_request("P2P_PEER " + peer)
  363. if peer.lower() not in res.lower():
  364. raise Exception("Peer information not available")
  365. lines = res.splitlines()
  366. vals = dict()
  367. for l in lines:
  368. if '=' in l:
  369. [name,value] = l.split('=', 1)
  370. vals[name] = value
  371. return vals
  372. def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
  373. if expect_failure:
  374. if "P2P-GROUP-STARTED" in ev:
  375. raise Exception("Group formation succeeded when expecting failure")
  376. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  377. s = re.split(exp, ev)
  378. if len(s) < 3:
  379. return None
  380. res = {}
  381. res['result'] = 'go-neg-failed'
  382. res['status'] = int(s[2])
  383. return res
  384. if "P2P-GROUP-STARTED" not in ev:
  385. raise Exception("No P2P-GROUP-STARTED event seen")
  386. 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.]*)'
  387. s = re.split(exp, ev)
  388. if len(s) < 11:
  389. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  390. s = re.split(exp, ev)
  391. if len(s) < 8:
  392. raise Exception("Could not parse P2P-GROUP-STARTED")
  393. res = {}
  394. res['result'] = 'success'
  395. res['ifname'] = s[2]
  396. self.group_ifname = s[2]
  397. try:
  398. self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  399. self.gctrl_mon.attach()
  400. except:
  401. logger.debug("Could not open monitor socket for group interface")
  402. self.gctrl_mon = None
  403. res['role'] = s[3]
  404. res['ssid'] = s[4]
  405. res['freq'] = s[5]
  406. if "[PERSISTENT]" in ev:
  407. res['persistent'] = True
  408. else:
  409. res['persistent'] = False
  410. p = re.match(r'psk=([0-9a-f]*)', s[6])
  411. if p:
  412. res['psk'] = p.group(1)
  413. p = re.match(r'passphrase="(.*)"', s[6])
  414. if p:
  415. res['passphrase'] = p.group(1)
  416. res['go_dev_addr'] = s[7]
  417. if len(s) > 8 and len(s[8]) > 0:
  418. res['ip_addr'] = s[8]
  419. if len(s) > 9:
  420. res['ip_mask'] = s[9]
  421. if len(s) > 10:
  422. res['go_ip_addr'] = s[10]
  423. if go_neg_res:
  424. exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
  425. s = re.split(exp, go_neg_res)
  426. if len(s) < 4:
  427. raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
  428. res['go_neg_role'] = s[2]
  429. res['go_neg_freq'] = s[3]
  430. return res
  431. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
  432. if not self.discover_peer(peer):
  433. raise Exception("Peer " + peer + " not found")
  434. self.dump_monitor()
  435. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  436. if go_intent:
  437. cmd = cmd + ' go_intent=' + str(go_intent)
  438. if freq:
  439. cmd = cmd + ' freq=' + str(freq)
  440. if persistent:
  441. cmd = cmd + " persistent"
  442. if "OK" in self.global_request(cmd):
  443. return None
  444. raise Exception("P2P_CONNECT (auth) failed")
  445. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  446. go_neg_res = None
  447. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  448. "P2P-GO-NEG-FAILURE"], timeout);
  449. if ev is None:
  450. if expect_failure:
  451. return None
  452. raise Exception("Group formation timed out")
  453. if "P2P-GO-NEG-SUCCESS" in ev:
  454. go_neg_res = ev
  455. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
  456. if ev is None:
  457. if expect_failure:
  458. return None
  459. raise Exception("Group formation timed out")
  460. self.dump_monitor()
  461. return self.group_form_result(ev, expect_failure, go_neg_res)
  462. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False, persistent=False, persistent_id=None, freq=None, provdisc=False, wait_group=True):
  463. if not self.discover_peer(peer):
  464. raise Exception("Peer " + peer + " not found")
  465. self.dump_monitor()
  466. if pin:
  467. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  468. else:
  469. cmd = "P2P_CONNECT " + peer + " " + method
  470. if go_intent:
  471. cmd = cmd + ' go_intent=' + str(go_intent)
  472. if freq:
  473. cmd = cmd + ' freq=' + str(freq)
  474. if persistent:
  475. cmd = cmd + " persistent"
  476. elif persistent_id:
  477. cmd = cmd + " persistent=" + persistent_id
  478. if provdisc:
  479. cmd = cmd + " provdisc"
  480. if "OK" in self.global_request(cmd):
  481. if timeout == 0:
  482. self.dump_monitor()
  483. return None
  484. go_neg_res = None
  485. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  486. "P2P-GO-NEG-FAILURE"], timeout)
  487. if ev is None:
  488. if expect_failure:
  489. return None
  490. raise Exception("Group formation timed out")
  491. if "P2P-GO-NEG-SUCCESS" in ev:
  492. if not wait_group:
  493. return ev
  494. go_neg_res = ev
  495. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  496. if ev is None:
  497. if expect_failure:
  498. return None
  499. raise Exception("Group formation timed out")
  500. self.dump_monitor()
  501. return self.group_form_result(ev, expect_failure, go_neg_res)
  502. raise Exception("P2P_CONNECT failed")
  503. def wait_event(self, events, timeout=10):
  504. start = os.times()[4]
  505. while True:
  506. while self.mon.pending():
  507. ev = self.mon.recv()
  508. logger.debug(self.ifname + ": " + ev)
  509. for event in events:
  510. if event in ev:
  511. return ev
  512. now = os.times()[4]
  513. remaining = start + timeout - now
  514. if remaining <= 0:
  515. break
  516. if not self.mon.pending(timeout=remaining):
  517. break
  518. return None
  519. def wait_global_event(self, events, timeout):
  520. if self.global_iface is None:
  521. self.wait_event(events, timeout)
  522. else:
  523. start = os.times()[4]
  524. while True:
  525. while self.global_mon.pending():
  526. ev = self.global_mon.recv()
  527. logger.debug(self.ifname + "(global): " + ev)
  528. for event in events:
  529. if event in ev:
  530. return ev
  531. now = os.times()[4]
  532. remaining = start + timeout - now
  533. if remaining <= 0:
  534. break
  535. if not self.global_mon.pending(timeout=remaining):
  536. break
  537. return None
  538. def wait_group_event(self, events, timeout=10):
  539. if self.group_ifname and self.group_ifname != self.ifname:
  540. if self.gctrl_mon is None:
  541. return None
  542. start = os.times()[4]
  543. while True:
  544. while self.gctrl_mon.pending():
  545. ev = self.gctrl_mon.recv()
  546. logger.debug(self.group_ifname + ": " + ev)
  547. for event in events:
  548. if event in ev:
  549. return ev
  550. now = os.times()[4]
  551. remaining = start + timeout - now
  552. if remaining <= 0:
  553. break
  554. if not self.gctrl_mon.pending(timeout=remaining):
  555. break
  556. return None
  557. return self.wait_event(events, timeout)
  558. def wait_go_ending_session(self):
  559. if self.gctrl_mon:
  560. try:
  561. self.gctrl_mon.detach()
  562. except:
  563. pass
  564. self.gctrl_mon = None
  565. ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
  566. if ev is None:
  567. raise Exception("Group removal event timed out")
  568. if "reason=GO_ENDING_SESSION" not in ev:
  569. raise Exception("Unexpected group removal reason")
  570. def dump_monitor(self):
  571. while self.mon.pending():
  572. ev = self.mon.recv()
  573. logger.debug(self.ifname + ": " + ev)
  574. while self.global_mon.pending():
  575. ev = self.global_mon.recv()
  576. logger.debug(self.ifname + "(global): " + ev)
  577. def remove_group(self, ifname=None):
  578. if self.gctrl_mon:
  579. try:
  580. self.gctrl_mon.detach()
  581. except:
  582. pass
  583. self.gctrl_mon = None
  584. if ifname is None:
  585. ifname = self.group_ifname if self.group_ifname else self.ifname
  586. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  587. raise Exception("Group could not be removed")
  588. self.group_ifname = None
  589. def p2p_start_go(self, persistent=None, freq=None):
  590. self.dump_monitor()
  591. cmd = "P2P_GROUP_ADD"
  592. if persistent is None:
  593. pass
  594. elif persistent is True:
  595. cmd = cmd + " persistent"
  596. else:
  597. cmd = cmd + " persistent=" + str(persistent)
  598. if freq:
  599. cmd = cmd + " freq=" + str(freq)
  600. if "OK" in self.global_request(cmd):
  601. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  602. if ev is None:
  603. raise Exception("GO start up timed out")
  604. self.dump_monitor()
  605. return self.group_form_result(ev)
  606. raise Exception("P2P_GROUP_ADD failed")
  607. def p2p_go_authorize_client(self, pin):
  608. cmd = "WPS_PIN any " + pin
  609. if "FAIL" in self.group_request(cmd):
  610. raise Exception("Failed to authorize client connection on GO")
  611. return None
  612. def p2p_go_authorize_client_pbc(self):
  613. cmd = "WPS_PBC"
  614. if "FAIL" in self.group_request(cmd):
  615. raise Exception("Failed to authorize client connection on GO")
  616. return None
  617. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
  618. freq=None):
  619. self.dump_monitor()
  620. if not self.discover_peer(go_addr, social=social):
  621. if social or not self.discover_peer(go_addr, social=social):
  622. raise Exception("GO " + go_addr + " not found")
  623. self.dump_monitor()
  624. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  625. if freq:
  626. cmd += " freq=" + str(freq)
  627. if "OK" in self.global_request(cmd):
  628. if timeout == 0:
  629. self.dump_monitor()
  630. return None
  631. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  632. if ev is None:
  633. raise Exception("Joining the group timed out")
  634. self.dump_monitor()
  635. return self.group_form_result(ev)
  636. raise Exception("P2P_CONNECT(join) failed")
  637. def tdls_setup(self, peer):
  638. cmd = "TDLS_SETUP " + peer
  639. if "FAIL" in self.group_request(cmd):
  640. raise Exception("Failed to request TDLS setup")
  641. return None
  642. def tdls_teardown(self, peer):
  643. cmd = "TDLS_TEARDOWN " + peer
  644. if "FAIL" in self.group_request(cmd):
  645. raise Exception("Failed to request TDLS teardown")
  646. return None
  647. def add_ts(self, tsid, up):
  648. params = {
  649. "sba": 9000,
  650. "nominal_msdu_size": 1500,
  651. "min_phy_rate": 6000000,
  652. "mean_data_rate": 1500,
  653. }
  654. cmd = "WMM_AC_ADDTS downlink tsid=%d up=%d" % (tsid, up)
  655. for (key, value) in params.iteritems():
  656. cmd += " %s=%d" % (key, value)
  657. if self.request(cmd).strip() != "OK":
  658. raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
  659. ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
  660. if ev is None:
  661. raise Exception("ADDTS failed (time out)")
  662. if "tsid=%d" % (tsid) not in ev:
  663. raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
  664. def del_ts(self, tsid):
  665. if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
  666. raise Exception("DELTS failed")
  667. ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
  668. if ev is None:
  669. raise Exception("DELTS failed (time out)")
  670. if "tsid=%d" % (tsid) not in ev:
  671. raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
  672. def connect(self, ssid=None, ssid2=None, **kwargs):
  673. logger.info("Connect STA " + self.ifname + " to AP")
  674. id = self.add_network()
  675. if ssid:
  676. self.set_network_quoted(id, "ssid", ssid)
  677. elif ssid2:
  678. self.set_network(id, "ssid", ssid2)
  679. quoted = [ "psk", "identity", "anonymous_identity", "password",
  680. "ca_cert", "client_cert", "private_key",
  681. "private_key_passwd", "ca_cert2", "client_cert2",
  682. "private_key2", "phase1", "phase2", "domain_suffix_match",
  683. "altsubject_match", "subject_match", "pac_file", "dh_file",
  684. "bgscan", "ht_mcs", "id_str", "openssl_ciphers" ]
  685. for field in quoted:
  686. if field in kwargs and kwargs[field]:
  687. self.set_network_quoted(id, field, kwargs[field])
  688. not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
  689. "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
  690. "wep_tx_keyidx", "scan_freq", "eap",
  691. "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
  692. "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
  693. "disable_max_amsdu", "ampdu_factor", "ampdu_density",
  694. "disable_ht40", "disable_sgi", "disable_ldpc",
  695. "ht40_intolerant", "update_identifier", "mac_addr",
  696. "erp" ]
  697. for field in not_quoted:
  698. if field in kwargs and kwargs[field]:
  699. self.set_network(id, field, kwargs[field])
  700. if "raw_psk" in kwargs and kwargs['raw_psk']:
  701. self.set_network(id, "psk", kwargs['raw_psk'])
  702. if "password_hex" in kwargs and kwargs['password_hex']:
  703. self.set_network(id, "password", kwargs['password_hex'])
  704. if "peerkey" in kwargs and kwargs['peerkey']:
  705. self.set_network(id, "peerkey", "1")
  706. if "okc" in kwargs and kwargs['okc']:
  707. self.set_network(id, "proactive_key_caching", "1")
  708. if "ocsp" in kwargs and kwargs['ocsp']:
  709. self.set_network(id, "ocsp", str(kwargs['ocsp']))
  710. if "only_add_network" in kwargs and kwargs['only_add_network']:
  711. return id
  712. if "wait_connect" not in kwargs or kwargs['wait_connect']:
  713. if "eap" in kwargs:
  714. self.connect_network(id, timeout=20)
  715. else:
  716. self.connect_network(id)
  717. else:
  718. self.dump_monitor()
  719. self.select_network(id)
  720. return id
  721. def scan(self, type=None, freq=None, no_wait=False, only_new=False):
  722. if type:
  723. cmd = "SCAN TYPE=" + type
  724. else:
  725. cmd = "SCAN"
  726. if freq:
  727. cmd = cmd + " freq=" + str(freq)
  728. if only_new:
  729. cmd += " only_new=1"
  730. if not no_wait:
  731. self.dump_monitor()
  732. if not "OK" in self.request(cmd):
  733. raise Exception("Failed to trigger scan")
  734. if no_wait:
  735. return
  736. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  737. if ev is None:
  738. raise Exception("Scan timed out")
  739. def scan_for_bss(self, bssid, freq=None, force_scan=False):
  740. if not force_scan and self.get_bss(bssid) is not None:
  741. return
  742. for i in range(0, 10):
  743. self.scan(freq=freq, type="ONLY")
  744. if self.get_bss(bssid) is not None:
  745. return
  746. raise Exception("Could not find BSS " + bssid + " in scan")
  747. def flush_scan_cache(self):
  748. self.request("BSS_FLUSH 0")
  749. self.scan(freq=2412, only_new=True)
  750. def roam(self, bssid, fail_test=False):
  751. self.dump_monitor()
  752. if "OK" not in self.request("ROAM " + bssid):
  753. raise Exception("ROAM failed")
  754. if fail_test:
  755. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  756. if ev is not None:
  757. raise Exception("Unexpected connection")
  758. self.dump_monitor()
  759. return
  760. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  761. if ev is None:
  762. raise Exception("Roaming with the AP timed out")
  763. self.dump_monitor()
  764. def roam_over_ds(self, bssid, fail_test=False):
  765. self.dump_monitor()
  766. if "OK" not in self.request("FT_DS " + bssid):
  767. raise Exception("FT_DS failed")
  768. if fail_test:
  769. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  770. if ev is not None:
  771. raise Exception("Unexpected connection")
  772. self.dump_monitor()
  773. return
  774. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  775. if ev is None:
  776. raise Exception("Roaming with the AP timed out")
  777. self.dump_monitor()
  778. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  779. new_passphrase=None, no_wait=False):
  780. self.dump_monitor()
  781. if new_ssid:
  782. self.request("WPS_REG " + bssid + " " + pin + " " +
  783. new_ssid.encode("hex") + " " + key_mgmt + " " +
  784. cipher + " " + new_passphrase.encode("hex"))
  785. if no_wait:
  786. return
  787. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  788. else:
  789. self.request("WPS_REG " + bssid + " " + pin)
  790. if no_wait:
  791. return
  792. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  793. if ev is None:
  794. raise Exception("WPS cred timed out")
  795. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  796. if ev is None:
  797. raise Exception("WPS timed out")
  798. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  799. if ev is None:
  800. raise Exception("Association with the AP timed out")
  801. def relog(self):
  802. self.global_request("RELOG")
  803. def wait_completed(self, timeout=10):
  804. for i in range(0, timeout * 2):
  805. if self.get_status_field("wpa_state") == "COMPLETED":
  806. return
  807. time.sleep(0.5)
  808. raise Exception("Timeout while waiting for COMPLETED state")
  809. def get_capability(self, field):
  810. res = self.request("GET_CAPABILITY " + field)
  811. if "FAIL" in res:
  812. return None
  813. return res.split(' ')
  814. def get_bss(self, bssid):
  815. res = self.request("BSS " + bssid)
  816. if "FAIL" in res:
  817. return None
  818. lines = res.splitlines()
  819. vals = dict()
  820. for l in lines:
  821. [name,value] = l.split('=', 1)
  822. vals[name] = value
  823. if len(vals) == 0:
  824. return None
  825. return vals
  826. def get_pmksa(self, bssid):
  827. res = self.request("PMKSA")
  828. lines = res.splitlines()
  829. for l in lines:
  830. if bssid not in l:
  831. continue
  832. vals = dict()
  833. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  834. vals['index'] = index
  835. vals['pmkid'] = pmkid
  836. vals['expiration'] = expiration
  837. vals['opportunistic'] = opportunistic
  838. return vals
  839. return None
  840. def get_sta(self, addr, info=None, next=False):
  841. cmd = "STA-NEXT " if next else "STA "
  842. if addr is None:
  843. res = self.request("STA-FIRST")
  844. elif info:
  845. res = self.request(cmd + addr + " " + info)
  846. else:
  847. res = self.request(cmd + addr)
  848. lines = res.splitlines()
  849. vals = dict()
  850. first = True
  851. for l in lines:
  852. if first:
  853. vals['addr'] = l
  854. first = False
  855. else:
  856. [name,value] = l.split('=', 1)
  857. vals[name] = value
  858. return vals
  859. def mgmt_rx(self, timeout=5):
  860. ev = self.wait_event(["MGMT-RX"], timeout=timeout)
  861. if ev is None:
  862. return None
  863. msg = {}
  864. items = ev.split(' ')
  865. field,val = items[1].split('=')
  866. if field != "freq":
  867. raise Exception("Unexpected MGMT-RX event format: " + ev)
  868. msg['freq'] = val
  869. frame = binascii.unhexlify(items[4])
  870. msg['frame'] = frame
  871. hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
  872. msg['fc'] = hdr[0]
  873. msg['subtype'] = (hdr[0] >> 4) & 0xf
  874. hdr = hdr[1:]
  875. msg['duration'] = hdr[0]
  876. hdr = hdr[1:]
  877. msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  878. hdr = hdr[6:]
  879. msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  880. hdr = hdr[6:]
  881. msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  882. hdr = hdr[6:]
  883. msg['seq_ctrl'] = hdr[0]
  884. msg['payload'] = frame[24:]
  885. return msg