wpasupplicant.py 31 KB

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