wpasupplicant.py 41 KB

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