wpasupplicant.py 38 KB

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