wpasupplicant.py 37 KB

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