wpasupplicant.py 41 KB

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