wpasupplicant.py 37 KB

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