wpasupplicant.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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 hessid 00:00:00:00:00:00")
  83. self.request("SET access_network_type 15")
  84. self.request("SET p2p_add_cli_chan 0")
  85. self.request("SET p2p_no_go_freq ")
  86. self.request("SET p2p_pref_chan ")
  87. self.request("SET p2p_no_group_iface 1")
  88. self.request("SET p2p_go_intent 7")
  89. self.request("SET ignore_old_scan_res 0")
  90. if self.gctrl_mon:
  91. try:
  92. self.gctrl_mon.detach()
  93. except:
  94. pass
  95. self.gctrl_mon = None
  96. self.group_ifname = None
  97. self.dump_monitor()
  98. iter = 0
  99. while iter < 60:
  100. state = self.get_driver_status_field("scan_state")
  101. if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
  102. logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
  103. time.sleep(1)
  104. else:
  105. break
  106. iter = iter + 1
  107. if iter == 60:
  108. logger.error(self.ifname + ": Driver scan state did not clear")
  109. print "Trying to clear cfg80211/mac80211 scan state"
  110. try:
  111. cmd = ["sudo", "ifconfig", self.ifname, "down"]
  112. subprocess.call(cmd)
  113. except subprocess.CalledProcessError, e:
  114. logger.info("ifconfig failed: " + str(e.returncode))
  115. logger.info(e.output)
  116. try:
  117. cmd = ["sudo", "ifconfig", self.ifname, "up"]
  118. subprocess.call(cmd)
  119. except subprocess.CalledProcessError, e:
  120. logger.info("ifconfig failed: " + str(e.returncode))
  121. logger.info(e.output)
  122. if iter > 0:
  123. # The ongoing scan could have discovered BSSes or P2P peers
  124. logger.info("Run FLUSH again since scan was in progress")
  125. self.request("FLUSH")
  126. self.dump_monitor()
  127. if not self.ping():
  128. logger.info("No PING response from " + self.ifname + " after reset")
  129. def add_network(self):
  130. id = self.request("ADD_NETWORK")
  131. if "FAIL" in id:
  132. raise Exception("ADD_NETWORK failed")
  133. return int(id)
  134. def remove_network(self, id):
  135. id = self.request("REMOVE_NETWORK " + str(id))
  136. if "FAIL" in id:
  137. raise Exception("REMOVE_NETWORK failed")
  138. return None
  139. def get_network(self, id, field):
  140. res = self.request("GET_NETWORK " + str(id) + " " + field)
  141. if res == "FAIL\n":
  142. return None
  143. return res
  144. def set_network(self, id, field, value):
  145. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  146. if "FAIL" in res:
  147. raise Exception("SET_NETWORK failed")
  148. return None
  149. def set_network_quoted(self, id, field, value):
  150. res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  151. if "FAIL" in res:
  152. raise Exception("SET_NETWORK failed")
  153. return None
  154. def list_networks(self):
  155. res = self.request("LIST_NETWORKS")
  156. lines = res.splitlines()
  157. networks = []
  158. for l in lines:
  159. if "network id" in l:
  160. continue
  161. [id,ssid,bssid,flags] = l.split('\t')
  162. network = {}
  163. network['id'] = id
  164. network['ssid'] = ssid
  165. network['bssid'] = bssid
  166. network['flags'] = flags
  167. networks.append(network)
  168. return networks
  169. def hs20_enable(self, auto_interworking=False):
  170. self.request("SET interworking 1")
  171. self.request("SET hs20 1")
  172. if auto_interworking:
  173. self.request("SET auto_interworking 1")
  174. else:
  175. self.request("SET auto_interworking 0")
  176. def add_cred(self):
  177. id = self.request("ADD_CRED")
  178. if "FAIL" in id:
  179. raise Exception("ADD_CRED failed")
  180. return int(id)
  181. def remove_cred(self, id):
  182. id = self.request("REMOVE_CRED " + str(id))
  183. if "FAIL" in id:
  184. raise Exception("REMOVE_CRED failed")
  185. return None
  186. def set_cred(self, id, field, value):
  187. res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
  188. if "FAIL" in res:
  189. raise Exception("SET_CRED failed")
  190. return None
  191. def set_cred_quoted(self, id, field, value):
  192. res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
  193. if "FAIL" in res:
  194. raise Exception("SET_CRED failed")
  195. return None
  196. def get_cred(self, id, field):
  197. return self.request("GET_CRED " + str(id) + " " + field)
  198. def add_cred_values(self, params):
  199. id = self.add_cred()
  200. quoted = [ "realm", "username", "password", "domain", "imsi",
  201. "excluded_ssid", "milenage", "ca_cert", "client_cert",
  202. "private_key", "domain_suffix_match", "provisioning_sp",
  203. "roaming_partner", "phase1", "phase2" ]
  204. for field in quoted:
  205. if field in params:
  206. self.set_cred_quoted(id, field, params[field])
  207. not_quoted = [ "eap", "roaming_consortium", "priority",
  208. "required_roaming_consortium", "sp_priority",
  209. "max_bss_load", "update_identifier", "req_conn_capab",
  210. "min_dl_bandwidth_home", "min_ul_bandwidth_home",
  211. "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
  212. for field in not_quoted:
  213. if field in params:
  214. self.set_cred(id, field, params[field])
  215. return id;
  216. def select_network(self, id, freq=None):
  217. if freq:
  218. extra = " freq=" + freq
  219. else:
  220. extra = ""
  221. id = self.request("SELECT_NETWORK " + str(id) + extra)
  222. if "FAIL" in id:
  223. raise Exception("SELECT_NETWORK failed")
  224. return None
  225. def mesh_group_add(self, id):
  226. id = self.request("MESH_GROUP_ADD " + str(id))
  227. if "FAIL" in id:
  228. raise Exception("MESH_GROUP_ADD failed")
  229. return None
  230. def mesh_group_remove(self):
  231. id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
  232. if "FAIL" in id:
  233. raise Exception("MESH_GROUP_REMOVE failed")
  234. return None
  235. def connect_network(self, id, timeout=10):
  236. self.dump_monitor()
  237. self.select_network(id)
  238. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
  239. if ev is None:
  240. raise Exception("Association with the AP timed out")
  241. self.dump_monitor()
  242. def get_status(self, extra=None):
  243. if extra:
  244. extra = "-" + extra
  245. else:
  246. extra = ""
  247. res = self.request("STATUS" + extra)
  248. lines = res.splitlines()
  249. vals = dict()
  250. for l in lines:
  251. try:
  252. [name,value] = l.split('=', 1)
  253. vals[name] = value
  254. except ValueError, e:
  255. logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
  256. return vals
  257. def get_status_field(self, field, extra=None):
  258. vals = self.get_status(extra)
  259. if field in vals:
  260. return vals[field]
  261. return None
  262. def get_group_status(self, extra=None):
  263. if extra:
  264. extra = "-" + extra
  265. else:
  266. extra = ""
  267. res = self.group_request("STATUS" + extra)
  268. lines = res.splitlines()
  269. vals = dict()
  270. for l in lines:
  271. try:
  272. [name,value] = l.split('=', 1)
  273. except ValueError:
  274. logger.info(self.ifname + ": Ignore unexpected status line: " + l)
  275. continue
  276. vals[name] = value
  277. return vals
  278. def get_group_status_field(self, field, extra=None):
  279. vals = self.get_group_status(extra)
  280. if field in vals:
  281. return vals[field]
  282. return None
  283. def get_driver_status(self):
  284. res = self.request("STATUS-DRIVER")
  285. lines = res.splitlines()
  286. vals = dict()
  287. for l in lines:
  288. try:
  289. [name,value] = l.split('=', 1)
  290. except ValueError:
  291. logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
  292. continue
  293. vals[name] = value
  294. return vals
  295. def get_driver_status_field(self, field):
  296. vals = self.get_driver_status()
  297. if field in vals:
  298. return vals[field]
  299. return None
  300. def get_mcc(self):
  301. mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
  302. return 1 if mcc < 2 else mcc
  303. def get_mib(self):
  304. res = self.request("MIB")
  305. lines = res.splitlines()
  306. vals = dict()
  307. for l in lines:
  308. try:
  309. [name,value] = l.split('=', 1)
  310. vals[name] = value
  311. except ValueError, e:
  312. logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
  313. return vals
  314. def p2p_dev_addr(self):
  315. return self.get_status_field("p2p_device_address")
  316. def p2p_interface_addr(self):
  317. return self.get_group_status_field("address")
  318. def own_addr(self):
  319. try:
  320. res = self.p2p_interface_addr()
  321. except:
  322. res = self.p2p_dev_addr()
  323. return res
  324. def p2p_listen(self):
  325. return self.global_request("P2P_LISTEN")
  326. def p2p_find(self, social=False, progressive=False, dev_id=None, dev_type=None):
  327. cmd = "P2P_FIND"
  328. if social:
  329. cmd = cmd + " type=social"
  330. elif progressive:
  331. cmd = cmd + " type=progressive"
  332. if dev_id:
  333. cmd = cmd + " dev_id=" + dev_id
  334. if dev_type:
  335. cmd = cmd + " dev_type=" + dev_type
  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:
  358. time.sleep(1)
  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):
  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. self.dump_monitor()
  607. return self.group_form_result(ev)
  608. raise Exception("P2P_GROUP_ADD failed")
  609. def p2p_go_authorize_client(self, pin):
  610. cmd = "WPS_PIN any " + pin
  611. if "FAIL" in self.group_request(cmd):
  612. raise Exception("Failed to authorize client connection on GO")
  613. return None
  614. def p2p_go_authorize_client_pbc(self):
  615. cmd = "WPS_PBC"
  616. if "FAIL" in self.group_request(cmd):
  617. raise Exception("Failed to authorize client connection on GO")
  618. return None
  619. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False):
  620. self.dump_monitor()
  621. if not self.discover_peer(go_addr, social=social):
  622. if social or not self.discover_peer(go_addr, social=social):
  623. raise Exception("GO " + go_addr + " not found")
  624. self.dump_monitor()
  625. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  626. if "OK" in self.global_request(cmd):
  627. if timeout == 0:
  628. self.dump_monitor()
  629. return None
  630. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  631. if ev is None:
  632. raise Exception("Joining the group timed out")
  633. self.dump_monitor()
  634. return self.group_form_result(ev)
  635. raise Exception("P2P_CONNECT(join) failed")
  636. def tdls_setup(self, peer):
  637. cmd = "TDLS_SETUP " + peer
  638. if "FAIL" in self.group_request(cmd):
  639. raise Exception("Failed to request TDLS setup")
  640. return None
  641. def tdls_teardown(self, peer):
  642. cmd = "TDLS_TEARDOWN " + peer
  643. if "FAIL" in self.group_request(cmd):
  644. raise Exception("Failed to request TDLS teardown")
  645. return None
  646. def add_ts(self, tsid, up):
  647. params = {
  648. "sba": 9000,
  649. "nominal_msdu_size": 1500,
  650. "min_phy_rate": 6000000,
  651. "mean_data_rate": 1500,
  652. }
  653. cmd = "WMM_AC_ADDTS downlink tsid=%d up=%d" % (tsid, up)
  654. for (key, value) in params.iteritems():
  655. cmd += " %s=%d" % (key, value)
  656. if self.request(cmd).strip() != "OK":
  657. raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
  658. ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
  659. if ev is None:
  660. raise Exception("ADDTS failed (time out)")
  661. if "tsid=%d" % (tsid) not in ev:
  662. raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
  663. def del_ts(self, tsid):
  664. if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
  665. raise Exception("DELTS failed")
  666. ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
  667. if ev is None:
  668. raise Exception("DELTS failed (time out)")
  669. if "tsid=%d" % (tsid) not in ev:
  670. raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
  671. def connect(self, ssid=None, ssid2=None, **kwargs):
  672. logger.info("Connect STA " + self.ifname + " to AP")
  673. id = self.add_network()
  674. if ssid:
  675. self.set_network_quoted(id, "ssid", ssid)
  676. elif ssid2:
  677. self.set_network(id, "ssid", ssid2)
  678. quoted = [ "psk", "identity", "anonymous_identity", "password",
  679. "ca_cert", "client_cert", "private_key",
  680. "private_key_passwd", "ca_cert2", "client_cert2",
  681. "private_key2", "phase1", "phase2", "domain_suffix_match",
  682. "altsubject_match", "subject_match", "pac_file", "dh_file",
  683. "bgscan", "ht_mcs", "id_str", "openssl_ciphers" ]
  684. for field in quoted:
  685. if field in kwargs and kwargs[field]:
  686. self.set_network_quoted(id, field, kwargs[field])
  687. not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
  688. "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
  689. "wep_tx_keyidx", "scan_freq", "eap",
  690. "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
  691. "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
  692. "disable_max_amsdu", "ampdu_factor", "ampdu_density",
  693. "disable_ht40", "disable_sgi", "disable_ldpc",
  694. "ht40_intolerant", "update_identifier", "mac_addr" ]
  695. for field in not_quoted:
  696. if field in kwargs and kwargs[field]:
  697. self.set_network(id, field, kwargs[field])
  698. if "raw_psk" in kwargs and kwargs['raw_psk']:
  699. self.set_network(id, "psk", kwargs['raw_psk'])
  700. if "password_hex" in kwargs and kwargs['password_hex']:
  701. self.set_network(id, "password", kwargs['password_hex'])
  702. if "peerkey" in kwargs and kwargs['peerkey']:
  703. self.set_network(id, "peerkey", "1")
  704. if "okc" in kwargs and kwargs['okc']:
  705. self.set_network(id, "proactive_key_caching", "1")
  706. if "ocsp" in kwargs and kwargs['ocsp']:
  707. self.set_network(id, "ocsp", str(kwargs['ocsp']))
  708. if "only_add_network" in kwargs and kwargs['only_add_network']:
  709. return id
  710. if "wait_connect" not in kwargs or kwargs['wait_connect']:
  711. if "eap" in kwargs:
  712. self.connect_network(id, timeout=20)
  713. else:
  714. self.connect_network(id)
  715. else:
  716. self.dump_monitor()
  717. self.select_network(id)
  718. return id
  719. def scan(self, type=None, freq=None, no_wait=False, only_new=False):
  720. if type:
  721. cmd = "SCAN TYPE=" + type
  722. else:
  723. cmd = "SCAN"
  724. if freq:
  725. cmd = cmd + " freq=" + freq
  726. if only_new:
  727. cmd += " only_new=1"
  728. if not no_wait:
  729. self.dump_monitor()
  730. if not "OK" in self.request(cmd):
  731. raise Exception("Failed to trigger scan")
  732. if no_wait:
  733. return
  734. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  735. if ev is None:
  736. raise Exception("Scan timed out")
  737. def scan_for_bss(self, bssid, freq=None, force_scan=False):
  738. if not force_scan and self.get_bss(bssid) is not None:
  739. return
  740. for i in range(0, 10):
  741. self.scan(freq=freq, type="ONLY")
  742. if self.get_bss(bssid) is not None:
  743. return
  744. raise Exception("Could not find BSS " + bssid + " in scan")
  745. def roam(self, bssid, fail_test=False):
  746. self.dump_monitor()
  747. if "OK" not in self.request("ROAM " + bssid):
  748. raise Exception("ROAM failed")
  749. if fail_test:
  750. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  751. if ev is not None:
  752. raise Exception("Unexpected connection")
  753. self.dump_monitor()
  754. return
  755. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  756. if ev is None:
  757. raise Exception("Roaming with the AP timed out")
  758. self.dump_monitor()
  759. def roam_over_ds(self, bssid, fail_test=False):
  760. self.dump_monitor()
  761. if "OK" not in self.request("FT_DS " + bssid):
  762. raise Exception("FT_DS failed")
  763. if fail_test:
  764. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  765. if ev is not None:
  766. raise Exception("Unexpected connection")
  767. self.dump_monitor()
  768. return
  769. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  770. if ev is None:
  771. raise Exception("Roaming with the AP timed out")
  772. self.dump_monitor()
  773. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  774. new_passphrase=None, no_wait=False):
  775. self.dump_monitor()
  776. if new_ssid:
  777. self.request("WPS_REG " + bssid + " " + pin + " " +
  778. new_ssid.encode("hex") + " " + key_mgmt + " " +
  779. cipher + " " + new_passphrase.encode("hex"))
  780. if no_wait:
  781. return
  782. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  783. else:
  784. self.request("WPS_REG " + bssid + " " + pin)
  785. if no_wait:
  786. return
  787. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  788. if ev is None:
  789. raise Exception("WPS cred timed out")
  790. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  791. if ev is None:
  792. raise Exception("WPS timed out")
  793. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  794. if ev is None:
  795. raise Exception("Association with the AP timed out")
  796. def relog(self):
  797. self.global_request("RELOG")
  798. def wait_completed(self, timeout=10):
  799. for i in range(0, timeout * 2):
  800. if self.get_status_field("wpa_state") == "COMPLETED":
  801. return
  802. time.sleep(0.5)
  803. raise Exception("Timeout while waiting for COMPLETED state")
  804. def get_capability(self, field):
  805. res = self.request("GET_CAPABILITY " + field)
  806. if "FAIL" in res:
  807. return None
  808. return res.split(' ')
  809. def get_bss(self, bssid):
  810. res = self.request("BSS " + bssid)
  811. if "FAIL" in res:
  812. return None
  813. lines = res.splitlines()
  814. vals = dict()
  815. for l in lines:
  816. [name,value] = l.split('=', 1)
  817. vals[name] = value
  818. if len(vals) == 0:
  819. return None
  820. return vals
  821. def get_pmksa(self, bssid):
  822. res = self.request("PMKSA")
  823. lines = res.splitlines()
  824. for l in lines:
  825. if bssid not in l:
  826. continue
  827. vals = dict()
  828. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  829. vals['index'] = index
  830. vals['pmkid'] = pmkid
  831. vals['expiration'] = expiration
  832. vals['opportunistic'] = opportunistic
  833. return vals
  834. return None
  835. def get_sta(self, addr, info=None, next=False):
  836. cmd = "STA-NEXT " if next else "STA "
  837. if addr is None:
  838. res = self.request("STA-FIRST")
  839. elif info:
  840. res = self.request(cmd + addr + " " + info)
  841. else:
  842. res = self.request(cmd + addr)
  843. lines = res.splitlines()
  844. vals = dict()
  845. first = True
  846. for l in lines:
  847. if first:
  848. vals['addr'] = l
  849. first = False
  850. else:
  851. [name,value] = l.split('=', 1)
  852. vals[name] = value
  853. return vals
  854. def mgmt_rx(self, timeout=5):
  855. ev = self.wait_event(["MGMT-RX"], timeout=timeout)
  856. if ev is None:
  857. return None
  858. msg = {}
  859. items = ev.split(' ')
  860. field,val = items[1].split('=')
  861. if field != "freq":
  862. raise Exception("Unexpected MGMT-RX event format: " + ev)
  863. msg['freq'] = val
  864. frame = binascii.unhexlify(items[4])
  865. msg['frame'] = frame
  866. hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
  867. msg['fc'] = hdr[0]
  868. msg['subtype'] = (hdr[0] >> 4) & 0xf
  869. hdr = hdr[1:]
  870. msg['duration'] = hdr[0]
  871. hdr = hdr[1:]
  872. msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  873. hdr = hdr[6:]
  874. msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  875. hdr = hdr[6:]
  876. msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  877. hdr = hdr[6:]
  878. msg['seq_ctrl'] = hdr[0]
  879. msg['payload'] = frame[24:]
  880. return msg