wpasupplicant.py 33 KB

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