wpasupplicant.py 28 KB

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