wpasupplicant.py 41 KB

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