wpasupplicant.py 31 KB

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