wpasupplicant.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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):
  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. go_neg_res = ev
  458. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  459. if ev is None:
  460. if expect_failure:
  461. return None
  462. raise Exception("Group formation timed out")
  463. self.dump_monitor()
  464. return self.group_form_result(ev, expect_failure, go_neg_res)
  465. raise Exception("P2P_CONNECT failed")
  466. def wait_event(self, events, timeout=10):
  467. start = os.times()[4]
  468. while True:
  469. while self.mon.pending():
  470. ev = self.mon.recv()
  471. logger.debug(self.ifname + ": " + ev)
  472. for event in events:
  473. if event in ev:
  474. return ev
  475. now = os.times()[4]
  476. remaining = start + timeout - now
  477. if remaining <= 0:
  478. break
  479. if not self.mon.pending(timeout=remaining):
  480. break
  481. return None
  482. def wait_global_event(self, events, timeout):
  483. if self.global_iface is None:
  484. self.wait_event(events, timeout)
  485. else:
  486. start = os.times()[4]
  487. while True:
  488. while self.global_mon.pending():
  489. ev = self.global_mon.recv()
  490. logger.debug(self.ifname + "(global): " + ev)
  491. for event in events:
  492. if event in ev:
  493. return ev
  494. now = os.times()[4]
  495. remaining = start + timeout - now
  496. if remaining <= 0:
  497. break
  498. if not self.global_mon.pending(timeout=remaining):
  499. break
  500. return None
  501. def wait_go_ending_session(self):
  502. ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
  503. if ev is None:
  504. raise Exception("Group removal event timed out")
  505. if "reason=GO_ENDING_SESSION" not in ev:
  506. raise Exception("Unexpected group removal reason")
  507. def dump_monitor(self):
  508. while self.mon.pending():
  509. ev = self.mon.recv()
  510. logger.debug(self.ifname + ": " + ev)
  511. while self.global_mon.pending():
  512. ev = self.global_mon.recv()
  513. logger.debug(self.ifname + "(global): " + ev)
  514. def remove_group(self, ifname=None):
  515. if ifname is None:
  516. ifname = self.group_ifname if self.group_ifname else self.ifname
  517. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  518. raise Exception("Group could not be removed")
  519. self.group_ifname = None
  520. def p2p_start_go(self, persistent=None, freq=None):
  521. self.dump_monitor()
  522. cmd = "P2P_GROUP_ADD"
  523. if persistent is None:
  524. pass
  525. elif persistent is True:
  526. cmd = cmd + " persistent"
  527. else:
  528. cmd = cmd + " persistent=" + str(persistent)
  529. if freq:
  530. cmd = cmd + " freq=" + str(freq)
  531. if "OK" in self.global_request(cmd):
  532. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  533. if ev is None:
  534. raise Exception("GO start up timed out")
  535. self.dump_monitor()
  536. return self.group_form_result(ev)
  537. raise Exception("P2P_GROUP_ADD failed")
  538. def p2p_go_authorize_client(self, pin):
  539. cmd = "WPS_PIN any " + pin
  540. if "FAIL" in self.group_request(cmd):
  541. raise Exception("Failed to authorize client connection on GO")
  542. return None
  543. def p2p_go_authorize_client_pbc(self):
  544. cmd = "WPS_PBC"
  545. if "FAIL" in self.group_request(cmd):
  546. raise Exception("Failed to authorize client connection on GO")
  547. return None
  548. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False):
  549. self.dump_monitor()
  550. if not self.discover_peer(go_addr, social=social):
  551. if social or not self.discover_peer(go_addr, social=social):
  552. raise Exception("GO " + go_addr + " not found")
  553. self.dump_monitor()
  554. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  555. if "OK" in self.global_request(cmd):
  556. if timeout == 0:
  557. self.dump_monitor()
  558. return None
  559. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  560. if ev is None:
  561. raise Exception("Joining the group timed out")
  562. self.dump_monitor()
  563. return self.group_form_result(ev)
  564. raise Exception("P2P_CONNECT(join) failed")
  565. def tdls_setup(self, peer):
  566. cmd = "TDLS_SETUP " + peer
  567. if "FAIL" in self.group_request(cmd):
  568. raise Exception("Failed to request TDLS setup")
  569. return None
  570. def tdls_teardown(self, peer):
  571. cmd = "TDLS_TEARDOWN " + peer
  572. if "FAIL" in self.group_request(cmd):
  573. raise Exception("Failed to request TDLS teardown")
  574. return None
  575. def connect(self, ssid=None, ssid2=None, **kwargs):
  576. logger.info("Connect STA " + self.ifname + " to AP")
  577. id = self.add_network()
  578. if ssid:
  579. self.set_network_quoted(id, "ssid", ssid)
  580. elif ssid2:
  581. self.set_network(id, "ssid", ssid2)
  582. quoted = [ "psk", "identity", "anonymous_identity", "password",
  583. "ca_cert", "client_cert", "private_key",
  584. "private_key_passwd", "ca_cert2", "client_cert2",
  585. "private_key2", "phase1", "phase2", "domain_suffix_match",
  586. "altsubject_match", "subject_match", "pac_file", "dh_file",
  587. "bgscan", "ht_mcs", "id_str" ]
  588. for field in quoted:
  589. if field in kwargs and kwargs[field]:
  590. self.set_network_quoted(id, field, kwargs[field])
  591. not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
  592. "group", "wep_key0", "scan_freq", "eap",
  593. "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
  594. "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
  595. "disable_max_amsdu", "ampdu_factor", "ampdu_density",
  596. "disable_ht40", "disable_sgi", "disable_ldpc",
  597. "ht40_intolerant" ]
  598. for field in not_quoted:
  599. if field in kwargs and kwargs[field]:
  600. self.set_network(id, field, kwargs[field])
  601. if "raw_psk" in kwargs and kwargs['raw_psk']:
  602. self.set_network(id, "psk", kwargs['raw_psk'])
  603. if "password_hex" in kwargs and kwargs['password_hex']:
  604. self.set_network(id, "password", kwargs['password_hex'])
  605. if "peerkey" in kwargs and kwargs['peerkey']:
  606. self.set_network(id, "peerkey", "1")
  607. if "okc" in kwargs and kwargs['okc']:
  608. self.set_network(id, "proactive_key_caching", "1")
  609. if "ocsp" in kwargs and kwargs['ocsp']:
  610. self.set_network(id, "ocsp", str(kwargs['ocsp']))
  611. if "only_add_network" in kwargs and kwargs['only_add_network']:
  612. return id
  613. if "wait_connect" not in kwargs or kwargs['wait_connect']:
  614. if "eap" in kwargs:
  615. self.connect_network(id, timeout=20)
  616. else:
  617. self.connect_network(id)
  618. else:
  619. self.dump_monitor()
  620. self.select_network(id)
  621. return id
  622. def scan(self, type=None, freq=None, no_wait=False, only_new=False):
  623. if type:
  624. cmd = "SCAN TYPE=" + type
  625. else:
  626. cmd = "SCAN"
  627. if freq:
  628. cmd = cmd + " freq=" + freq
  629. if only_new:
  630. cmd += " only_new=1"
  631. if not no_wait:
  632. self.dump_monitor()
  633. if not "OK" in self.request(cmd):
  634. raise Exception("Failed to trigger scan")
  635. if no_wait:
  636. return
  637. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  638. if ev is None:
  639. raise Exception("Scan timed out")
  640. def scan_for_bss(self, bssid, freq=None, force_scan=False):
  641. if not force_scan and self.get_bss(bssid) is not None:
  642. return
  643. for i in range(0, 10):
  644. self.scan(freq=freq)
  645. if self.get_bss(bssid) is not None:
  646. return
  647. raise Exception("Could not find BSS " + bssid + " in scan")
  648. def roam(self, bssid, fail_test=False):
  649. self.dump_monitor()
  650. if "OK" not in self.request("ROAM " + bssid):
  651. raise Exception("ROAM failed")
  652. if fail_test:
  653. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  654. if ev is not None:
  655. raise Exception("Unexpected connection")
  656. self.dump_monitor()
  657. return
  658. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  659. if ev is None:
  660. raise Exception("Roaming with the AP timed out")
  661. self.dump_monitor()
  662. def roam_over_ds(self, bssid, fail_test=False):
  663. self.dump_monitor()
  664. if "OK" not in self.request("FT_DS " + bssid):
  665. raise Exception("FT_DS failed")
  666. if fail_test:
  667. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  668. if ev is not None:
  669. raise Exception("Unexpected connection")
  670. self.dump_monitor()
  671. return
  672. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  673. if ev is None:
  674. raise Exception("Roaming with the AP timed out")
  675. self.dump_monitor()
  676. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  677. new_passphrase=None, no_wait=False):
  678. self.dump_monitor()
  679. if new_ssid:
  680. self.request("WPS_REG " + bssid + " " + pin + " " +
  681. new_ssid.encode("hex") + " " + key_mgmt + " " +
  682. cipher + " " + new_passphrase.encode("hex"))
  683. if no_wait:
  684. return
  685. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  686. else:
  687. self.request("WPS_REG " + bssid + " " + pin)
  688. if no_wait:
  689. return
  690. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  691. if ev is None:
  692. raise Exception("WPS cred timed out")
  693. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  694. if ev is None:
  695. raise Exception("WPS timed out")
  696. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  697. if ev is None:
  698. raise Exception("Association with the AP timed out")
  699. def relog(self):
  700. self.request("RELOG")
  701. def wait_completed(self, timeout=10):
  702. for i in range(0, timeout * 2):
  703. if self.get_status_field("wpa_state") == "COMPLETED":
  704. return
  705. time.sleep(0.5)
  706. raise Exception("Timeout while waiting for COMPLETED state")
  707. def get_capability(self, field):
  708. res = self.request("GET_CAPABILITY " + field)
  709. if "FAIL" in res:
  710. return None
  711. return res.split(' ')
  712. def get_bss(self, bssid):
  713. res = self.request("BSS " + bssid)
  714. if "FAIL" in res:
  715. return None
  716. lines = res.splitlines()
  717. vals = dict()
  718. for l in lines:
  719. [name,value] = l.split('=', 1)
  720. vals[name] = value
  721. if len(vals) == 0:
  722. return None
  723. return vals
  724. def get_pmksa(self, bssid):
  725. res = self.request("PMKSA")
  726. lines = res.splitlines()
  727. for l in lines:
  728. if bssid not in l:
  729. continue
  730. vals = dict()
  731. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  732. vals['index'] = index
  733. vals['pmkid'] = pmkid
  734. vals['expiration'] = expiration
  735. vals['opportunistic'] = opportunistic
  736. return vals
  737. return None
  738. def get_sta(self, addr, info=None, next=False):
  739. cmd = "STA-NEXT " if next else "STA "
  740. if addr is None:
  741. res = self.request("STA-FIRST")
  742. elif info:
  743. res = self.request(cmd + addr + " " + info)
  744. else:
  745. res = self.request(cmd + addr)
  746. lines = res.splitlines()
  747. vals = dict()
  748. first = True
  749. for l in lines:
  750. if first:
  751. vals['addr'] = l
  752. first = False
  753. else:
  754. [name,value] = l.split('=', 1)
  755. vals[name] = value
  756. return vals
  757. def mgmt_rx(self, timeout=5):
  758. ev = self.wait_event(["MGMT-RX"], timeout=timeout)
  759. if ev is None:
  760. return None
  761. msg = {}
  762. items = ev.split(' ')
  763. field,val = items[1].split('=')
  764. if field != "freq":
  765. raise Exception("Unexpected MGMT-RX event format: " + ev)
  766. msg['freq'] = val
  767. frame = binascii.unhexlify(items[4])
  768. msg['frame'] = frame
  769. hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
  770. msg['fc'] = hdr[0]
  771. msg['subtype'] = (hdr[0] >> 4) & 0xf
  772. hdr = hdr[1:]
  773. msg['duration'] = hdr[0]
  774. hdr = hdr[1:]
  775. msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  776. hdr = hdr[6:]
  777. msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  778. hdr = hdr[6:]
  779. msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  780. hdr = hdr[6:]
  781. msg['seq_ctrl'] = hdr[0]
  782. msg['payload'] = frame[24:]
  783. return msg