wpasupplicant.py 34 KB

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