wpasupplicant.py 33 KB

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