wpasupplicant.py 43 KB

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