wpasupplicant.py 30 KB

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