wpasupplicant.py 38 KB

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