wpasupplicant.py 43 KB

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