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_no_group_iface 1")
  111. self.global_request("P2P_FLUSH")
  112. if self.gctrl_mon:
  113. try:
  114. self.gctrl_mon.detach()
  115. except:
  116. pass
  117. self.gctrl_mon = None
  118. self.group_ifname = None
  119. self.dump_monitor()
  120. iter = 0
  121. while iter < 60:
  122. state1 = self.get_driver_status_field("scan_state")
  123. p2pdev = "p2p-dev-" + self.ifname
  124. state2 = self.get_driver_status_field("scan_state", ifname=p2pdev)
  125. states = str(state1) + " " + str(state2)
  126. if "SCAN_STARTED" in states or "SCAN_REQUESTED" in states:
  127. logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
  128. time.sleep(1)
  129. else:
  130. break
  131. iter = iter + 1
  132. if iter == 60:
  133. logger.error(self.ifname + ": Driver scan state did not clear")
  134. print "Trying to clear cfg80211/mac80211 scan state"
  135. try:
  136. cmd = ["ifconfig", self.ifname, "down"]
  137. subprocess.call(cmd)
  138. except subprocess.CalledProcessError, e:
  139. logger.info("ifconfig failed: " + str(e.returncode))
  140. logger.info(e.output)
  141. try:
  142. cmd = ["ifconfig", self.ifname, "up"]
  143. subprocess.call(cmd)
  144. except subprocess.CalledProcessError, e:
  145. logger.info("ifconfig failed: " + str(e.returncode))
  146. logger.info(e.output)
  147. if iter > 0:
  148. # The ongoing scan could have discovered BSSes or P2P peers
  149. logger.info("Run FLUSH again since scan was in progress")
  150. self.request("FLUSH")
  151. self.dump_monitor()
  152. if not self.ping():
  153. logger.info("No PING response from " + self.ifname + " after reset")
  154. def add_network(self):
  155. id = self.request("ADD_NETWORK")
  156. if "FAIL" in id:
  157. raise Exception("ADD_NETWORK failed")
  158. return int(id)
  159. def remove_network(self, id):
  160. id = self.request("REMOVE_NETWORK " + str(id))
  161. if "FAIL" in id:
  162. raise Exception("REMOVE_NETWORK failed")
  163. return None
  164. def get_network(self, id, field):
  165. res = self.request("GET_NETWORK " + str(id) + " " + field)
  166. if res == "FAIL\n":
  167. return None
  168. return res
  169. def set_network(self, id, field, value):
  170. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  171. if "FAIL" in res:
  172. raise Exception("SET_NETWORK failed")
  173. return None
  174. def set_network_quoted(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 list_networks(self, p2p=False):
  180. if p2p:
  181. res = self.global_request("LIST_NETWORKS")
  182. else:
  183. res = self.request("LIST_NETWORKS")
  184. lines = res.splitlines()
  185. networks = []
  186. for l in lines:
  187. if "network id" in l:
  188. continue
  189. [id,ssid,bssid,flags] = l.split('\t')
  190. network = {}
  191. network['id'] = id
  192. network['ssid'] = ssid
  193. network['bssid'] = bssid
  194. network['flags'] = flags
  195. networks.append(network)
  196. return networks
  197. def hs20_enable(self, auto_interworking=False):
  198. self.request("SET interworking 1")
  199. self.request("SET hs20 1")
  200. if auto_interworking:
  201. self.request("SET auto_interworking 1")
  202. else:
  203. self.request("SET auto_interworking 0")
  204. def interworking_add_network(self, bssid):
  205. id = self.request("INTERWORKING_ADD_NETWORK " + bssid)
  206. if "FAIL" in id or "OK" in id:
  207. raise Exception("INTERWORKING_ADD_NETWORK failed")
  208. return int(id)
  209. def add_cred(self):
  210. id = self.request("ADD_CRED")
  211. if "FAIL" in id:
  212. raise Exception("ADD_CRED failed")
  213. return int(id)
  214. def remove_cred(self, id):
  215. id = self.request("REMOVE_CRED " + str(id))
  216. if "FAIL" in id:
  217. raise Exception("REMOVE_CRED failed")
  218. return None
  219. def set_cred(self, id, field, value):
  220. res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
  221. if "FAIL" in res:
  222. raise Exception("SET_CRED failed")
  223. return None
  224. def set_cred_quoted(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 get_cred(self, id, field):
  230. return self.request("GET_CRED " + str(id) + " " + field)
  231. def add_cred_values(self, params):
  232. id = self.add_cred()
  233. quoted = [ "realm", "username", "password", "domain", "imsi",
  234. "excluded_ssid", "milenage", "ca_cert", "client_cert",
  235. "private_key", "domain_suffix_match", "provisioning_sp",
  236. "roaming_partner", "phase1", "phase2" ]
  237. for field in quoted:
  238. if field in params:
  239. self.set_cred_quoted(id, field, params[field])
  240. not_quoted = [ "eap", "roaming_consortium", "priority",
  241. "required_roaming_consortium", "sp_priority",
  242. "max_bss_load", "update_identifier", "req_conn_capab",
  243. "min_dl_bandwidth_home", "min_ul_bandwidth_home",
  244. "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
  245. for field in not_quoted:
  246. if field in params:
  247. self.set_cred(id, field, params[field])
  248. return id;
  249. def select_network(self, id, freq=None):
  250. if freq:
  251. extra = " freq=" + str(freq)
  252. else:
  253. extra = ""
  254. id = self.request("SELECT_NETWORK " + str(id) + extra)
  255. if "FAIL" in id:
  256. raise Exception("SELECT_NETWORK failed")
  257. return None
  258. def mesh_group_add(self, id):
  259. id = self.request("MESH_GROUP_ADD " + str(id))
  260. if "FAIL" in id:
  261. raise Exception("MESH_GROUP_ADD failed")
  262. return None
  263. def mesh_group_remove(self):
  264. id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
  265. if "FAIL" in id:
  266. raise Exception("MESH_GROUP_REMOVE failed")
  267. return None
  268. def connect_network(self, id, timeout=10):
  269. self.dump_monitor()
  270. self.select_network(id)
  271. self.wait_connected(timeout=timeout)
  272. self.dump_monitor()
  273. def get_status(self, extra=None):
  274. if extra:
  275. extra = "-" + extra
  276. else:
  277. extra = ""
  278. res = self.request("STATUS" + extra)
  279. lines = res.splitlines()
  280. vals = dict()
  281. for l in lines:
  282. try:
  283. [name,value] = l.split('=', 1)
  284. vals[name] = value
  285. except ValueError, e:
  286. logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
  287. return vals
  288. def get_status_field(self, field, extra=None):
  289. vals = self.get_status(extra)
  290. if field in vals:
  291. return vals[field]
  292. return None
  293. def get_group_status(self, extra=None):
  294. if extra:
  295. extra = "-" + extra
  296. else:
  297. extra = ""
  298. res = self.group_request("STATUS" + extra)
  299. lines = res.splitlines()
  300. vals = dict()
  301. for l in lines:
  302. try:
  303. [name,value] = l.split('=', 1)
  304. except ValueError:
  305. logger.info(self.ifname + ": Ignore unexpected status line: " + l)
  306. continue
  307. vals[name] = value
  308. return vals
  309. def get_group_status_field(self, field, extra=None):
  310. vals = self.get_group_status(extra)
  311. if field in vals:
  312. return vals[field]
  313. return None
  314. def get_driver_status(self, ifname=None):
  315. if ifname is None:
  316. res = self.request("STATUS-DRIVER")
  317. else:
  318. res = self.global_request("IFNAME=%s STATUS-DRIVER" % ifname)
  319. if res.startswith("FAIL"):
  320. return dict()
  321. lines = res.splitlines()
  322. vals = dict()
  323. for l in lines:
  324. try:
  325. [name,value] = l.split('=', 1)
  326. except ValueError:
  327. logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
  328. continue
  329. vals[name] = value
  330. return vals
  331. def get_driver_status_field(self, field, ifname=None):
  332. vals = self.get_driver_status(ifname)
  333. if field in vals:
  334. return vals[field]
  335. return None
  336. def get_mcc(self):
  337. mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
  338. return 1 if mcc < 2 else mcc
  339. def get_mib(self):
  340. res = self.request("MIB")
  341. lines = res.splitlines()
  342. vals = dict()
  343. for l in lines:
  344. try:
  345. [name,value] = l.split('=', 1)
  346. vals[name] = value
  347. except ValueError, e:
  348. logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
  349. return vals
  350. def p2p_dev_addr(self):
  351. return self.get_status_field("p2p_device_address")
  352. def p2p_interface_addr(self):
  353. return self.get_group_status_field("address")
  354. def own_addr(self):
  355. try:
  356. res = self.p2p_interface_addr()
  357. except:
  358. res = self.p2p_dev_addr()
  359. return res
  360. def p2p_listen(self):
  361. return self.global_request("P2P_LISTEN")
  362. def p2p_ext_listen(self, period, interval):
  363. return self.global_request("P2P_EXT_LISTEN %d %d" % (period, interval))
  364. def p2p_cancel_ext_listen(self):
  365. return self.global_request("P2P_EXT_LISTEN")
  366. def p2p_find(self, social=False, progressive=False, dev_id=None,
  367. dev_type=None, delay=None, freq=None):
  368. cmd = "P2P_FIND"
  369. if social:
  370. cmd = cmd + " type=social"
  371. elif progressive:
  372. cmd = cmd + " type=progressive"
  373. if dev_id:
  374. cmd = cmd + " dev_id=" + dev_id
  375. if dev_type:
  376. cmd = cmd + " dev_type=" + dev_type
  377. if delay:
  378. cmd = cmd + " delay=" + str(delay)
  379. if freq:
  380. cmd = cmd + " freq=" + str(freq)
  381. return self.global_request(cmd)
  382. def p2p_stop_find(self):
  383. return self.global_request("P2P_STOP_FIND")
  384. def wps_read_pin(self):
  385. self.pin = self.request("WPS_PIN get").rstrip("\n")
  386. if "FAIL" in self.pin:
  387. raise Exception("Could not generate PIN")
  388. return self.pin
  389. def peer_known(self, peer, full=True):
  390. res = self.global_request("P2P_PEER " + peer)
  391. if peer.lower() not in res.lower():
  392. return False
  393. if not full:
  394. return True
  395. return "[PROBE_REQ_ONLY]" not in res
  396. def discover_peer(self, peer, full=True, timeout=15, social=True,
  397. force_find=False, freq=None):
  398. logger.info(self.ifname + ": Trying to discover peer " + peer)
  399. if not force_find and self.peer_known(peer, full):
  400. return True
  401. self.p2p_find(social, freq=freq)
  402. count = 0
  403. while count < timeout * 4:
  404. time.sleep(0.25)
  405. count = count + 1
  406. if self.peer_known(peer, full):
  407. return True
  408. return False
  409. def get_peer(self, peer):
  410. res = self.global_request("P2P_PEER " + peer)
  411. if peer.lower() not in res.lower():
  412. raise Exception("Peer information not available")
  413. lines = res.splitlines()
  414. vals = dict()
  415. for l in lines:
  416. if '=' in l:
  417. [name,value] = l.split('=', 1)
  418. vals[name] = value
  419. return vals
  420. def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
  421. if expect_failure:
  422. if "P2P-GROUP-STARTED" in ev:
  423. raise Exception("Group formation succeeded when expecting failure")
  424. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  425. s = re.split(exp, ev)
  426. if len(s) < 3:
  427. return None
  428. res = {}
  429. res['result'] = 'go-neg-failed'
  430. res['status'] = int(s[2])
  431. return res
  432. if "P2P-GROUP-STARTED" not in ev:
  433. raise Exception("No P2P-GROUP-STARTED event seen")
  434. 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.]*)'
  435. s = re.split(exp, ev)
  436. if len(s) < 11:
  437. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  438. s = re.split(exp, ev)
  439. if len(s) < 8:
  440. raise Exception("Could not parse P2P-GROUP-STARTED")
  441. res = {}
  442. res['result'] = 'success'
  443. res['ifname'] = s[2]
  444. self.group_ifname = s[2]
  445. try:
  446. self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  447. self.gctrl_mon.attach()
  448. except:
  449. logger.debug("Could not open monitor socket for group interface")
  450. self.gctrl_mon = None
  451. res['role'] = s[3]
  452. res['ssid'] = s[4]
  453. res['freq'] = s[5]
  454. if "[PERSISTENT]" in ev:
  455. res['persistent'] = True
  456. else:
  457. res['persistent'] = False
  458. p = re.match(r'psk=([0-9a-f]*)', s[6])
  459. if p:
  460. res['psk'] = p.group(1)
  461. p = re.match(r'passphrase="(.*)"', s[6])
  462. if p:
  463. res['passphrase'] = p.group(1)
  464. res['go_dev_addr'] = s[7]
  465. if len(s) > 8 and len(s[8]) > 0:
  466. res['ip_addr'] = s[8]
  467. if len(s) > 9:
  468. res['ip_mask'] = s[9]
  469. if len(s) > 10:
  470. res['go_ip_addr'] = s[10]
  471. if go_neg_res:
  472. exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
  473. s = re.split(exp, go_neg_res)
  474. if len(s) < 4:
  475. raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
  476. res['go_neg_role'] = s[2]
  477. res['go_neg_freq'] = s[3]
  478. return res
  479. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None,
  480. persistent=False, freq=None, freq2=None,
  481. max_oper_chwidth=None, ht40=False, vht=False):
  482. if not self.discover_peer(peer):
  483. raise Exception("Peer " + peer + " not found")
  484. self.dump_monitor()
  485. if pin:
  486. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  487. else:
  488. cmd = "P2P_CONNECT " + peer + " " + method + " auth"
  489. if go_intent:
  490. cmd = cmd + ' go_intent=' + str(go_intent)
  491. if freq:
  492. cmd = cmd + ' freq=' + str(freq)
  493. if freq2:
  494. cmd = cmd + ' freq2=' + str(freq2)
  495. if max_oper_chwidth:
  496. cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
  497. if ht40:
  498. cmd = cmd + ' ht40'
  499. if vht:
  500. cmd = cmd + ' vht'
  501. if persistent:
  502. cmd = cmd + " persistent"
  503. if "OK" in self.global_request(cmd):
  504. return None
  505. raise Exception("P2P_CONNECT (auth) failed")
  506. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  507. go_neg_res = None
  508. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  509. "P2P-GO-NEG-FAILURE"], timeout);
  510. if ev is None:
  511. if expect_failure:
  512. return None
  513. raise Exception("Group formation timed out")
  514. if "P2P-GO-NEG-SUCCESS" in ev:
  515. go_neg_res = ev
  516. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
  517. if ev is None:
  518. if expect_failure:
  519. return None
  520. raise Exception("Group formation timed out")
  521. self.dump_monitor()
  522. return self.group_form_result(ev, expect_failure, go_neg_res)
  523. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None,
  524. expect_failure=False, persistent=False,
  525. persistent_id=None, freq=None, provdisc=False,
  526. wait_group=True, freq2=None, max_oper_chwidth=None,
  527. ht40=False, vht=False):
  528. if not self.discover_peer(peer):
  529. raise Exception("Peer " + peer + " not found")
  530. self.dump_monitor()
  531. if pin:
  532. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  533. else:
  534. cmd = "P2P_CONNECT " + peer + " " + method
  535. if go_intent:
  536. cmd = cmd + ' go_intent=' + str(go_intent)
  537. if freq:
  538. cmd = cmd + ' freq=' + str(freq)
  539. if freq2:
  540. cmd = cmd + ' freq2=' + str(freq2)
  541. if max_oper_chwidth:
  542. cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
  543. if ht40:
  544. cmd = cmd + ' ht40'
  545. if vht:
  546. cmd = cmd + ' vht'
  547. if persistent:
  548. cmd = cmd + " persistent"
  549. elif persistent_id:
  550. cmd = cmd + " persistent=" + persistent_id
  551. if provdisc:
  552. cmd = cmd + " provdisc"
  553. if "OK" in self.global_request(cmd):
  554. if timeout == 0:
  555. return None
  556. go_neg_res = None
  557. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  558. "P2P-GO-NEG-FAILURE"], timeout)
  559. if ev is None:
  560. if expect_failure:
  561. return None
  562. raise Exception("Group formation timed out")
  563. if "P2P-GO-NEG-SUCCESS" in ev:
  564. if not wait_group:
  565. return ev
  566. go_neg_res = ev
  567. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  568. if ev is None:
  569. if expect_failure:
  570. return None
  571. raise Exception("Group formation timed out")
  572. self.dump_monitor()
  573. return self.group_form_result(ev, expect_failure, go_neg_res)
  574. raise Exception("P2P_CONNECT failed")
  575. def wait_event(self, events, timeout=10):
  576. start = os.times()[4]
  577. while True:
  578. while self.mon.pending():
  579. ev = self.mon.recv()
  580. logger.debug(self.ifname + ": " + ev)
  581. for event in events:
  582. if event in ev:
  583. return ev
  584. now = os.times()[4]
  585. remaining = start + timeout - now
  586. if remaining <= 0:
  587. break
  588. if not self.mon.pending(timeout=remaining):
  589. break
  590. return None
  591. def wait_global_event(self, events, timeout):
  592. if self.global_iface is None:
  593. self.wait_event(events, timeout)
  594. else:
  595. start = os.times()[4]
  596. while True:
  597. while self.global_mon.pending():
  598. ev = self.global_mon.recv()
  599. logger.debug(self.ifname + "(global): " + ev)
  600. for event in events:
  601. if event in ev:
  602. return ev
  603. now = os.times()[4]
  604. remaining = start + timeout - now
  605. if remaining <= 0:
  606. break
  607. if not self.global_mon.pending(timeout=remaining):
  608. break
  609. return None
  610. def wait_group_event(self, events, timeout=10):
  611. if self.group_ifname and self.group_ifname != self.ifname:
  612. if self.gctrl_mon is None:
  613. return None
  614. start = os.times()[4]
  615. while True:
  616. while self.gctrl_mon.pending():
  617. ev = self.gctrl_mon.recv()
  618. logger.debug(self.group_ifname + ": " + ev)
  619. for event in events:
  620. if event in ev:
  621. return ev
  622. now = os.times()[4]
  623. remaining = start + timeout - now
  624. if remaining <= 0:
  625. break
  626. if not self.gctrl_mon.pending(timeout=remaining):
  627. break
  628. return None
  629. return self.wait_event(events, timeout)
  630. def wait_go_ending_session(self):
  631. if self.gctrl_mon:
  632. try:
  633. self.gctrl_mon.detach()
  634. except:
  635. pass
  636. self.gctrl_mon = None
  637. ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=3)
  638. if ev is None:
  639. raise Exception("Group removal event timed out")
  640. if "reason=GO_ENDING_SESSION" not in ev:
  641. raise Exception("Unexpected group removal reason")
  642. def dump_monitor(self):
  643. count_iface = 0
  644. count_global = 0
  645. while self.mon.pending():
  646. ev = self.mon.recv()
  647. logger.debug(self.ifname + ": " + ev)
  648. count_iface += 1
  649. while self.global_mon and self.global_mon.pending():
  650. ev = self.global_mon.recv()
  651. logger.debug(self.ifname + "(global): " + ev)
  652. count_global += 1
  653. return (count_iface, count_global)
  654. def remove_group(self, ifname=None):
  655. if self.gctrl_mon:
  656. try:
  657. self.gctrl_mon.detach()
  658. except:
  659. pass
  660. self.gctrl_mon = None
  661. if ifname is None:
  662. ifname = self.group_ifname if self.group_ifname else self.ifname
  663. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  664. raise Exception("Group could not be removed")
  665. self.group_ifname = None
  666. def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
  667. self.dump_monitor()
  668. cmd = "P2P_GROUP_ADD"
  669. if persistent is None:
  670. pass
  671. elif persistent is True:
  672. cmd = cmd + " persistent"
  673. else:
  674. cmd = cmd + " persistent=" + str(persistent)
  675. if freq:
  676. cmd = cmd + " freq=" + str(freq)
  677. if "OK" in self.global_request(cmd):
  678. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  679. if ev is None:
  680. raise Exception("GO start up timed out")
  681. if not no_event_clear:
  682. self.dump_monitor()
  683. return self.group_form_result(ev)
  684. raise Exception("P2P_GROUP_ADD failed")
  685. def p2p_go_authorize_client(self, pin):
  686. cmd = "WPS_PIN any " + pin
  687. if "FAIL" in self.group_request(cmd):
  688. raise Exception("Failed to authorize client connection on GO")
  689. return None
  690. def p2p_go_authorize_client_pbc(self):
  691. cmd = "WPS_PBC"
  692. if "FAIL" in self.group_request(cmd):
  693. raise Exception("Failed to authorize client connection on GO")
  694. return None
  695. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
  696. freq=None):
  697. self.dump_monitor()
  698. if not self.discover_peer(go_addr, social=social, freq=freq):
  699. if social or not self.discover_peer(go_addr, social=social):
  700. raise Exception("GO " + go_addr + " not found")
  701. self.p2p_stop_find()
  702. self.dump_monitor()
  703. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  704. if freq:
  705. cmd += " freq=" + str(freq)
  706. if "OK" in self.global_request(cmd):
  707. if timeout == 0:
  708. self.dump_monitor()
  709. return None
  710. ev = self.wait_global_event(["P2P-GROUP-STARTED",
  711. "P2P-GROUP-FORMATION-FAILURE"],
  712. timeout)
  713. if ev is None:
  714. raise Exception("Joining the group timed out")
  715. if "P2P-GROUP-STARTED" not in ev:
  716. raise Exception("Failed to join the group")
  717. self.dump_monitor()
  718. return self.group_form_result(ev)
  719. raise Exception("P2P_CONNECT(join) failed")
  720. def tdls_setup(self, peer):
  721. cmd = "TDLS_SETUP " + peer
  722. if "FAIL" in self.group_request(cmd):
  723. raise Exception("Failed to request TDLS setup")
  724. return None
  725. def tdls_teardown(self, peer):
  726. cmd = "TDLS_TEARDOWN " + peer
  727. if "FAIL" in self.group_request(cmd):
  728. raise Exception("Failed to request TDLS teardown")
  729. return None
  730. def tdls_link_status(self, peer):
  731. cmd = "TDLS_LINK_STATUS " + peer
  732. ret = self.group_request(cmd)
  733. if "FAIL" in ret:
  734. raise Exception("Failed to request TDLS link status")
  735. return ret
  736. def tspecs(self):
  737. """Return (tsid, up) tuples representing current tspecs"""
  738. res = self.request("WMM_AC_STATUS")
  739. tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
  740. tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
  741. logger.debug("tspecs: " + str(tspecs))
  742. return tspecs
  743. def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
  744. extra=None):
  745. params = {
  746. "sba": 9000,
  747. "nominal_msdu_size": 1500,
  748. "min_phy_rate": 6000000,
  749. "mean_data_rate": 1500,
  750. }
  751. cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
  752. for (key, value) in params.iteritems():
  753. cmd += " %s=%d" % (key, value)
  754. if extra:
  755. cmd += " " + extra
  756. if self.request(cmd).strip() != "OK":
  757. raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
  758. if expect_failure:
  759. ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
  760. if ev is None:
  761. raise Exception("ADDTS failed (time out while waiting failure)")
  762. if "tsid=%d" % (tsid) not in ev:
  763. raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
  764. return
  765. ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
  766. if ev is None:
  767. raise Exception("ADDTS failed (time out)")
  768. if "tsid=%d" % (tsid) not in ev:
  769. raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
  770. if not (tsid, up) in self.tspecs():
  771. raise Exception("ADDTS failed (tsid not in tspec list)")
  772. def del_ts(self, tsid):
  773. if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
  774. raise Exception("DELTS failed")
  775. ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
  776. if ev is None:
  777. raise Exception("DELTS failed (time out)")
  778. if "tsid=%d" % (tsid) not in ev:
  779. raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
  780. tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
  781. if tspecs:
  782. raise Exception("DELTS failed (still in tspec list)")
  783. def connect(self, ssid=None, ssid2=None, **kwargs):
  784. logger.info("Connect STA " + self.ifname + " to AP")
  785. id = self.add_network()
  786. if ssid:
  787. self.set_network_quoted(id, "ssid", ssid)
  788. elif ssid2:
  789. self.set_network(id, "ssid", ssid2)
  790. quoted = [ "psk", "identity", "anonymous_identity", "password",
  791. "ca_cert", "client_cert", "private_key",
  792. "private_key_passwd", "ca_cert2", "client_cert2",
  793. "private_key2", "phase1", "phase2", "domain_suffix_match",
  794. "altsubject_match", "subject_match", "pac_file", "dh_file",
  795. "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
  796. "domain_match" ]
  797. for field in quoted:
  798. if field in kwargs and kwargs[field]:
  799. self.set_network_quoted(id, field, kwargs[field])
  800. not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
  801. "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
  802. "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
  803. "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
  804. "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
  805. "disable_max_amsdu", "ampdu_factor", "ampdu_density",
  806. "disable_ht40", "disable_sgi", "disable_ldpc",
  807. "ht40_intolerant", "update_identifier", "mac_addr",
  808. "erp", "bg_scan_period", "bssid_blacklist",
  809. "bssid_whitelist", "mem_only_psk", "eap_workaround",
  810. "engine" ]
  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)