wpasupplicant.py 36 KB

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