wpasupplicant.py 41 KB

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