wpasupplicant.py 30 KB

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