wpasupplicant.py 31 KB

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