wpasupplicant.py 35 KB

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