wpasupplicant.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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, hostname=None,
  18. port=9877, global_port=9878):
  19. self.hostname = hostname
  20. self.group_ifname = None
  21. self.gctrl_mon = None
  22. if ifname:
  23. self.set_ifname(ifname, hostname, port)
  24. else:
  25. self.ifname = None
  26. self.global_iface = global_iface
  27. if global_iface:
  28. if hostname != None:
  29. self.global_ctrl = wpaspy.Ctrl(hostname, global_port)
  30. self.global_mon = wpaspy.Ctrl(hostname, global_port)
  31. else:
  32. self.global_ctrl = wpaspy.Ctrl(global_iface)
  33. self.global_mon = wpaspy.Ctrl(global_iface)
  34. self.global_mon.attach()
  35. else:
  36. self.global_mon = None
  37. def close_ctrl(self):
  38. if self.global_mon:
  39. self.global_mon.detach()
  40. self.global_mon = None
  41. self.global_ctrl = None
  42. self.remove_ifname()
  43. def set_ifname(self, ifname, hostname=None, port=9877):
  44. self.ifname = ifname
  45. if hostname != None:
  46. self.ctrl = wpaspy.Ctrl(hostname, port)
  47. self.mon = wpaspy.Ctrl(hostname, port)
  48. else:
  49. self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  50. self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  51. self.mon.attach()
  52. def remove_ifname(self):
  53. if self.ifname:
  54. self.mon.detach()
  55. self.mon = None
  56. self.ctrl = None
  57. self.ifname = None
  58. def get_ctrl_iface_port(self, ifname):
  59. if self.hostname is None:
  60. return None
  61. res = self.global_request("INTERFACES ctrl")
  62. lines = res.splitlines()
  63. found = False
  64. for line in lines:
  65. words = line.split()
  66. if words[0] == ifname:
  67. found = True
  68. break
  69. if not found:
  70. raise Exception("Could not find UDP port for " + ifname)
  71. res = line.find("ctrl_iface=udp:")
  72. if res == -1:
  73. raise Exception("Wrong ctrl_interface format")
  74. words = line.split(":")
  75. return int(words[1])
  76. def interface_add(self, ifname, config="", driver="nl80211",
  77. drv_params=None, br_ifname=None, create=False,
  78. set_ifname=True, all_params=False, if_type=None):
  79. try:
  80. groups = subprocess.check_output(["id"])
  81. group = "admin" if "(admin)" in groups else "adm"
  82. except Exception, e:
  83. group = "admin"
  84. cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
  85. if drv_params:
  86. cmd = cmd + '\t' + drv_params
  87. if br_ifname:
  88. if not drv_params:
  89. cmd += '\t'
  90. cmd += '\t' + br_ifname
  91. if create:
  92. if not br_ifname:
  93. cmd += '\t'
  94. if not drv_params:
  95. cmd += '\t'
  96. cmd += '\tcreate'
  97. if if_type:
  98. cmd += '\t' + if_type
  99. if all_params and not create:
  100. if not br_ifname:
  101. cmd += '\t'
  102. if not drv_params:
  103. cmd += '\t'
  104. cmd += '\t'
  105. if "FAIL" in self.global_request(cmd):
  106. raise Exception("Failed to add a dynamic wpa_supplicant interface")
  107. if not create and set_ifname:
  108. port = self.get_ctrl_iface_port(ifname)
  109. self.set_ifname(ifname, self.hostname, port)
  110. def interface_remove(self, ifname):
  111. self.remove_ifname()
  112. self.global_request("INTERFACE_REMOVE " + ifname)
  113. def request(self, cmd, timeout=10):
  114. logger.debug(self.ifname + ": CTRL: " + cmd)
  115. return self.ctrl.request(cmd, timeout=timeout)
  116. def global_request(self, cmd):
  117. if self.global_iface is None:
  118. self.request(cmd)
  119. else:
  120. ifname = self.ifname or self.global_iface
  121. logger.debug(ifname + ": CTRL(global): " + cmd)
  122. return self.global_ctrl.request(cmd)
  123. def group_request(self, cmd):
  124. if self.group_ifname and self.group_ifname != self.ifname:
  125. logger.debug(self.group_ifname + ": CTRL: " + cmd)
  126. gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  127. return gctrl.request(cmd)
  128. return self.request(cmd)
  129. def ping(self):
  130. return "PONG" in self.request("PING")
  131. def global_ping(self):
  132. return "PONG" in self.global_request("PING")
  133. def reset(self):
  134. self.dump_monitor()
  135. res = self.request("FLUSH")
  136. if not "OK" in res:
  137. logger.info("FLUSH to " + self.ifname + " failed: " + res)
  138. self.global_request("REMOVE_NETWORK all")
  139. self.global_request("SET p2p_no_group_iface 1")
  140. self.global_request("P2P_FLUSH")
  141. if self.gctrl_mon:
  142. try:
  143. self.gctrl_mon.detach()
  144. except:
  145. pass
  146. self.gctrl_mon = None
  147. self.group_ifname = None
  148. self.dump_monitor()
  149. iter = 0
  150. while iter < 60:
  151. state1 = self.get_driver_status_field("scan_state")
  152. p2pdev = "p2p-dev-" + self.ifname
  153. state2 = self.get_driver_status_field("scan_state", ifname=p2pdev)
  154. states = str(state1) + " " + str(state2)
  155. if "SCAN_STARTED" in states or "SCAN_REQUESTED" in states:
  156. logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
  157. time.sleep(1)
  158. else:
  159. break
  160. iter = iter + 1
  161. if iter == 60:
  162. logger.error(self.ifname + ": Driver scan state did not clear")
  163. print "Trying to clear cfg80211/mac80211 scan state"
  164. try:
  165. cmd = ["ifconfig", self.ifname, "down"]
  166. subprocess.call(cmd)
  167. except subprocess.CalledProcessError, e:
  168. logger.info("ifconfig failed: " + str(e.returncode))
  169. logger.info(e.output)
  170. try:
  171. cmd = ["ifconfig", self.ifname, "up"]
  172. subprocess.call(cmd)
  173. except subprocess.CalledProcessError, e:
  174. logger.info("ifconfig failed: " + str(e.returncode))
  175. logger.info(e.output)
  176. if iter > 0:
  177. # The ongoing scan could have discovered BSSes or P2P peers
  178. logger.info("Run FLUSH again since scan was in progress")
  179. self.request("FLUSH")
  180. self.dump_monitor()
  181. if not self.ping():
  182. logger.info("No PING response from " + self.ifname + " after reset")
  183. def add_network(self):
  184. id = self.request("ADD_NETWORK")
  185. if "FAIL" in id:
  186. raise Exception("ADD_NETWORK failed")
  187. return int(id)
  188. def remove_network(self, id):
  189. id = self.request("REMOVE_NETWORK " + str(id))
  190. if "FAIL" in id:
  191. raise Exception("REMOVE_NETWORK failed")
  192. return None
  193. def get_network(self, id, field):
  194. res = self.request("GET_NETWORK " + str(id) + " " + field)
  195. if res == "FAIL\n":
  196. return None
  197. return res
  198. def set_network(self, id, field, value):
  199. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  200. if "FAIL" in res:
  201. raise Exception("SET_NETWORK failed")
  202. return None
  203. def set_network_quoted(self, id, field, value):
  204. res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  205. if "FAIL" in res:
  206. raise Exception("SET_NETWORK failed")
  207. return None
  208. def list_networks(self, p2p=False):
  209. if p2p:
  210. res = self.global_request("LIST_NETWORKS")
  211. else:
  212. res = self.request("LIST_NETWORKS")
  213. lines = res.splitlines()
  214. networks = []
  215. for l in lines:
  216. if "network id" in l:
  217. continue
  218. [id,ssid,bssid,flags] = l.split('\t')
  219. network = {}
  220. network['id'] = id
  221. network['ssid'] = ssid
  222. network['bssid'] = bssid
  223. network['flags'] = flags
  224. networks.append(network)
  225. return networks
  226. def hs20_enable(self, auto_interworking=False):
  227. self.request("SET interworking 1")
  228. self.request("SET hs20 1")
  229. if auto_interworking:
  230. self.request("SET auto_interworking 1")
  231. else:
  232. self.request("SET auto_interworking 0")
  233. def interworking_add_network(self, bssid):
  234. id = self.request("INTERWORKING_ADD_NETWORK " + bssid)
  235. if "FAIL" in id or "OK" in id:
  236. raise Exception("INTERWORKING_ADD_NETWORK failed")
  237. return int(id)
  238. def add_cred(self):
  239. id = self.request("ADD_CRED")
  240. if "FAIL" in id:
  241. raise Exception("ADD_CRED failed")
  242. return int(id)
  243. def remove_cred(self, id):
  244. id = self.request("REMOVE_CRED " + str(id))
  245. if "FAIL" in id:
  246. raise Exception("REMOVE_CRED failed")
  247. return None
  248. def set_cred(self, id, field, value):
  249. res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
  250. if "FAIL" in res:
  251. raise Exception("SET_CRED failed")
  252. return None
  253. def set_cred_quoted(self, id, field, value):
  254. res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
  255. if "FAIL" in res:
  256. raise Exception("SET_CRED failed")
  257. return None
  258. def get_cred(self, id, field):
  259. return self.request("GET_CRED " + str(id) + " " + field)
  260. def add_cred_values(self, params):
  261. id = self.add_cred()
  262. quoted = [ "realm", "username", "password", "domain", "imsi",
  263. "excluded_ssid", "milenage", "ca_cert", "client_cert",
  264. "private_key", "domain_suffix_match", "provisioning_sp",
  265. "roaming_partner", "phase1", "phase2" ]
  266. for field in quoted:
  267. if field in params:
  268. self.set_cred_quoted(id, field, params[field])
  269. not_quoted = [ "eap", "roaming_consortium", "priority",
  270. "required_roaming_consortium", "sp_priority",
  271. "max_bss_load", "update_identifier", "req_conn_capab",
  272. "min_dl_bandwidth_home", "min_ul_bandwidth_home",
  273. "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
  274. for field in not_quoted:
  275. if field in params:
  276. self.set_cred(id, field, params[field])
  277. return id;
  278. def select_network(self, id, freq=None):
  279. if freq:
  280. extra = " freq=" + str(freq)
  281. else:
  282. extra = ""
  283. id = self.request("SELECT_NETWORK " + str(id) + extra)
  284. if "FAIL" in id:
  285. raise Exception("SELECT_NETWORK failed")
  286. return None
  287. def mesh_group_add(self, id):
  288. id = self.request("MESH_GROUP_ADD " + str(id))
  289. if "FAIL" in id:
  290. raise Exception("MESH_GROUP_ADD failed")
  291. return None
  292. def mesh_group_remove(self):
  293. id = self.request("MESH_GROUP_REMOVE " + str(self.ifname))
  294. if "FAIL" in id:
  295. raise Exception("MESH_GROUP_REMOVE failed")
  296. return None
  297. def connect_network(self, id, timeout=10):
  298. self.dump_monitor()
  299. self.select_network(id)
  300. self.wait_connected(timeout=timeout)
  301. self.dump_monitor()
  302. def get_status(self, extra=None):
  303. if extra:
  304. extra = "-" + extra
  305. else:
  306. extra = ""
  307. res = self.request("STATUS" + extra)
  308. lines = res.splitlines()
  309. vals = dict()
  310. for l in lines:
  311. try:
  312. [name,value] = l.split('=', 1)
  313. vals[name] = value
  314. except ValueError, e:
  315. logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
  316. return vals
  317. def get_status_field(self, field, extra=None):
  318. vals = self.get_status(extra)
  319. if field in vals:
  320. return vals[field]
  321. return None
  322. def get_group_status(self, extra=None):
  323. if extra:
  324. extra = "-" + extra
  325. else:
  326. extra = ""
  327. res = self.group_request("STATUS" + extra)
  328. lines = res.splitlines()
  329. vals = dict()
  330. for l in lines:
  331. try:
  332. [name,value] = l.split('=', 1)
  333. except ValueError:
  334. logger.info(self.ifname + ": Ignore unexpected status line: " + l)
  335. continue
  336. vals[name] = value
  337. return vals
  338. def get_group_status_field(self, field, extra=None):
  339. vals = self.get_group_status(extra)
  340. if field in vals:
  341. return vals[field]
  342. return None
  343. def get_driver_status(self, ifname=None):
  344. if ifname is None:
  345. res = self.request("STATUS-DRIVER")
  346. else:
  347. res = self.global_request("IFNAME=%s STATUS-DRIVER" % ifname)
  348. if res.startswith("FAIL"):
  349. return dict()
  350. lines = res.splitlines()
  351. vals = dict()
  352. for l in lines:
  353. try:
  354. [name,value] = l.split('=', 1)
  355. except ValueError:
  356. logger.info(self.ifname + ": Ignore unexpected status-driver line: " + l)
  357. continue
  358. vals[name] = value
  359. return vals
  360. def get_driver_status_field(self, field, ifname=None):
  361. vals = self.get_driver_status(ifname)
  362. if field in vals:
  363. return vals[field]
  364. return None
  365. def get_mcc(self):
  366. mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
  367. return 1 if mcc < 2 else mcc
  368. def get_mib(self):
  369. res = self.request("MIB")
  370. lines = res.splitlines()
  371. vals = dict()
  372. for l in lines:
  373. try:
  374. [name,value] = l.split('=', 1)
  375. vals[name] = value
  376. except ValueError, e:
  377. logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
  378. return vals
  379. def p2p_dev_addr(self):
  380. return self.get_status_field("p2p_device_address")
  381. def p2p_interface_addr(self):
  382. return self.get_group_status_field("address")
  383. def own_addr(self):
  384. try:
  385. res = self.p2p_interface_addr()
  386. except:
  387. res = self.p2p_dev_addr()
  388. return res
  389. def p2p_listen(self):
  390. return self.global_request("P2P_LISTEN")
  391. def p2p_ext_listen(self, period, interval):
  392. return self.global_request("P2P_EXT_LISTEN %d %d" % (period, interval))
  393. def p2p_cancel_ext_listen(self):
  394. return self.global_request("P2P_EXT_LISTEN")
  395. def p2p_find(self, social=False, progressive=False, dev_id=None,
  396. dev_type=None, delay=None, freq=None):
  397. cmd = "P2P_FIND"
  398. if social:
  399. cmd = cmd + " type=social"
  400. elif progressive:
  401. cmd = cmd + " type=progressive"
  402. if dev_id:
  403. cmd = cmd + " dev_id=" + dev_id
  404. if dev_type:
  405. cmd = cmd + " dev_type=" + dev_type
  406. if delay:
  407. cmd = cmd + " delay=" + str(delay)
  408. if freq:
  409. cmd = cmd + " freq=" + str(freq)
  410. return self.global_request(cmd)
  411. def p2p_stop_find(self):
  412. return self.global_request("P2P_STOP_FIND")
  413. def wps_read_pin(self):
  414. self.pin = self.request("WPS_PIN get").rstrip("\n")
  415. if "FAIL" in self.pin:
  416. raise Exception("Could not generate PIN")
  417. return self.pin
  418. def peer_known(self, peer, full=True):
  419. res = self.global_request("P2P_PEER " + peer)
  420. if peer.lower() not in res.lower():
  421. return False
  422. if not full:
  423. return True
  424. return "[PROBE_REQ_ONLY]" not in res
  425. def discover_peer(self, peer, full=True, timeout=15, social=True,
  426. force_find=False, freq=None):
  427. logger.info(self.ifname + ": Trying to discover peer " + peer)
  428. if not force_find and self.peer_known(peer, full):
  429. return True
  430. self.p2p_find(social, freq=freq)
  431. count = 0
  432. while count < timeout * 4:
  433. time.sleep(0.25)
  434. count = count + 1
  435. if self.peer_known(peer, full):
  436. return True
  437. return False
  438. def get_peer(self, peer):
  439. res = self.global_request("P2P_PEER " + peer)
  440. if peer.lower() not in res.lower():
  441. raise Exception("Peer information not available")
  442. lines = res.splitlines()
  443. vals = dict()
  444. for l in lines:
  445. if '=' in l:
  446. [name,value] = l.split('=', 1)
  447. vals[name] = value
  448. return vals
  449. def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
  450. if expect_failure:
  451. if "P2P-GROUP-STARTED" in ev:
  452. raise Exception("Group formation succeeded when expecting failure")
  453. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  454. s = re.split(exp, ev)
  455. if len(s) < 3:
  456. return None
  457. res = {}
  458. res['result'] = 'go-neg-failed'
  459. res['status'] = int(s[2])
  460. return res
  461. if "P2P-GROUP-STARTED" not in ev:
  462. raise Exception("No P2P-GROUP-STARTED event seen")
  463. 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.]*)'
  464. s = re.split(exp, ev)
  465. if len(s) < 11:
  466. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  467. s = re.split(exp, ev)
  468. if len(s) < 8:
  469. raise Exception("Could not parse P2P-GROUP-STARTED")
  470. res = {}
  471. res['result'] = 'success'
  472. res['ifname'] = s[2]
  473. self.group_ifname = s[2]
  474. try:
  475. self.gctrl_mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  476. self.gctrl_mon.attach()
  477. except:
  478. logger.debug("Could not open monitor socket for group interface")
  479. self.gctrl_mon = None
  480. res['role'] = s[3]
  481. res['ssid'] = s[4]
  482. res['freq'] = s[5]
  483. if "[PERSISTENT]" in ev:
  484. res['persistent'] = True
  485. else:
  486. res['persistent'] = False
  487. p = re.match(r'psk=([0-9a-f]*)', s[6])
  488. if p:
  489. res['psk'] = p.group(1)
  490. p = re.match(r'passphrase="(.*)"', s[6])
  491. if p:
  492. res['passphrase'] = p.group(1)
  493. res['go_dev_addr'] = s[7]
  494. if len(s) > 8 and len(s[8]) > 0:
  495. res['ip_addr'] = s[8]
  496. if len(s) > 9:
  497. res['ip_mask'] = s[9]
  498. if len(s) > 10:
  499. res['go_ip_addr'] = s[10]
  500. if go_neg_res:
  501. exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
  502. s = re.split(exp, go_neg_res)
  503. if len(s) < 4:
  504. raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
  505. res['go_neg_role'] = s[2]
  506. res['go_neg_freq'] = s[3]
  507. return res
  508. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None,
  509. persistent=False, freq=None, freq2=None,
  510. max_oper_chwidth=None, ht40=False, vht=False):
  511. if not self.discover_peer(peer):
  512. raise Exception("Peer " + peer + " not found")
  513. self.dump_monitor()
  514. if pin:
  515. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  516. else:
  517. cmd = "P2P_CONNECT " + peer + " " + method + " auth"
  518. if go_intent:
  519. cmd = cmd + ' go_intent=' + str(go_intent)
  520. if freq:
  521. cmd = cmd + ' freq=' + str(freq)
  522. if freq2:
  523. cmd = cmd + ' freq2=' + str(freq2)
  524. if max_oper_chwidth:
  525. cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
  526. if ht40:
  527. cmd = cmd + ' ht40'
  528. if vht:
  529. cmd = cmd + ' vht'
  530. if persistent:
  531. cmd = cmd + " persistent"
  532. if "OK" in self.global_request(cmd):
  533. return None
  534. raise Exception("P2P_CONNECT (auth) failed")
  535. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  536. go_neg_res = None
  537. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  538. "P2P-GO-NEG-FAILURE"], timeout);
  539. if ev is None:
  540. if expect_failure:
  541. return None
  542. raise Exception("Group formation timed out")
  543. if "P2P-GO-NEG-SUCCESS" in ev:
  544. go_neg_res = ev
  545. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
  546. if ev is None:
  547. if expect_failure:
  548. return None
  549. raise Exception("Group formation timed out")
  550. self.dump_monitor()
  551. return self.group_form_result(ev, expect_failure, go_neg_res)
  552. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None,
  553. expect_failure=False, persistent=False,
  554. persistent_id=None, freq=None, provdisc=False,
  555. wait_group=True, freq2=None, max_oper_chwidth=None,
  556. ht40=False, vht=False):
  557. if not self.discover_peer(peer):
  558. raise Exception("Peer " + peer + " not found")
  559. self.dump_monitor()
  560. if pin:
  561. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  562. else:
  563. cmd = "P2P_CONNECT " + peer + " " + method
  564. if go_intent:
  565. cmd = cmd + ' go_intent=' + str(go_intent)
  566. if freq:
  567. cmd = cmd + ' freq=' + str(freq)
  568. if freq2:
  569. cmd = cmd + ' freq2=' + str(freq2)
  570. if max_oper_chwidth:
  571. cmd = cmd + ' max_oper_chwidth=' + str(max_oper_chwidth)
  572. if ht40:
  573. cmd = cmd + ' ht40'
  574. if vht:
  575. cmd = cmd + ' vht'
  576. if persistent:
  577. cmd = cmd + " persistent"
  578. elif persistent_id:
  579. cmd = cmd + " persistent=" + persistent_id
  580. if provdisc:
  581. cmd = cmd + " provdisc"
  582. if "OK" in self.global_request(cmd):
  583. if timeout == 0:
  584. return None
  585. go_neg_res = None
  586. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  587. "P2P-GO-NEG-FAILURE"], timeout)
  588. if ev is None:
  589. if expect_failure:
  590. return None
  591. raise Exception("Group formation timed out")
  592. if "P2P-GO-NEG-SUCCESS" in ev:
  593. if not wait_group:
  594. return ev
  595. go_neg_res = ev
  596. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  597. if ev is None:
  598. if expect_failure:
  599. return None
  600. raise Exception("Group formation timed out")
  601. self.dump_monitor()
  602. return self.group_form_result(ev, expect_failure, go_neg_res)
  603. raise Exception("P2P_CONNECT failed")
  604. def wait_event(self, events, timeout=10):
  605. start = os.times()[4]
  606. while True:
  607. while self.mon.pending():
  608. ev = self.mon.recv()
  609. logger.debug(self.ifname + ": " + ev)
  610. for event in events:
  611. if event in ev:
  612. return ev
  613. now = os.times()[4]
  614. remaining = start + timeout - now
  615. if remaining <= 0:
  616. break
  617. if not self.mon.pending(timeout=remaining):
  618. break
  619. return None
  620. def wait_global_event(self, events, timeout):
  621. if self.global_iface is None:
  622. self.wait_event(events, timeout)
  623. else:
  624. start = os.times()[4]
  625. while True:
  626. while self.global_mon.pending():
  627. ev = self.global_mon.recv()
  628. logger.debug(self.ifname + "(global): " + ev)
  629. for event in events:
  630. if event in ev:
  631. return ev
  632. now = os.times()[4]
  633. remaining = start + timeout - now
  634. if remaining <= 0:
  635. break
  636. if not self.global_mon.pending(timeout=remaining):
  637. break
  638. return None
  639. def wait_group_event(self, events, timeout=10):
  640. if self.group_ifname and self.group_ifname != self.ifname:
  641. if self.gctrl_mon is None:
  642. return None
  643. start = os.times()[4]
  644. while True:
  645. while self.gctrl_mon.pending():
  646. ev = self.gctrl_mon.recv()
  647. logger.debug(self.group_ifname + ": " + ev)
  648. for event in events:
  649. if event in ev:
  650. return ev
  651. now = os.times()[4]
  652. remaining = start + timeout - now
  653. if remaining <= 0:
  654. break
  655. if not self.gctrl_mon.pending(timeout=remaining):
  656. break
  657. return None
  658. return self.wait_event(events, timeout)
  659. def wait_go_ending_session(self):
  660. if self.gctrl_mon:
  661. try:
  662. self.gctrl_mon.detach()
  663. except:
  664. pass
  665. self.gctrl_mon = None
  666. ev = self.wait_global_event(["P2P-GROUP-REMOVED"], timeout=3)
  667. if ev is None:
  668. raise Exception("Group removal event timed out")
  669. if "reason=GO_ENDING_SESSION" not in ev:
  670. raise Exception("Unexpected group removal reason")
  671. def dump_monitor(self):
  672. count_iface = 0
  673. count_global = 0
  674. while self.mon.pending():
  675. ev = self.mon.recv()
  676. logger.debug(self.ifname + ": " + ev)
  677. count_iface += 1
  678. while self.global_mon and self.global_mon.pending():
  679. ev = self.global_mon.recv()
  680. logger.debug(self.ifname + "(global): " + ev)
  681. count_global += 1
  682. return (count_iface, count_global)
  683. def remove_group(self, ifname=None):
  684. if self.gctrl_mon:
  685. try:
  686. self.gctrl_mon.detach()
  687. except:
  688. pass
  689. self.gctrl_mon = None
  690. if ifname is None:
  691. ifname = self.group_ifname if self.group_ifname else self.ifname
  692. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  693. raise Exception("Group could not be removed")
  694. self.group_ifname = None
  695. def p2p_start_go(self, persistent=None, freq=None, no_event_clear=False):
  696. self.dump_monitor()
  697. cmd = "P2P_GROUP_ADD"
  698. if persistent is None:
  699. pass
  700. elif persistent is True:
  701. cmd = cmd + " persistent"
  702. else:
  703. cmd = cmd + " persistent=" + str(persistent)
  704. if freq:
  705. cmd = cmd + " freq=" + str(freq)
  706. if "OK" in self.global_request(cmd):
  707. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  708. if ev is None:
  709. raise Exception("GO start up timed out")
  710. if not no_event_clear:
  711. self.dump_monitor()
  712. return self.group_form_result(ev)
  713. raise Exception("P2P_GROUP_ADD failed")
  714. def p2p_go_authorize_client(self, pin):
  715. cmd = "WPS_PIN any " + pin
  716. if "FAIL" in self.group_request(cmd):
  717. raise Exception("Failed to authorize client connection on GO")
  718. return None
  719. def p2p_go_authorize_client_pbc(self):
  720. cmd = "WPS_PBC"
  721. if "FAIL" in self.group_request(cmd):
  722. raise Exception("Failed to authorize client connection on GO")
  723. return None
  724. def p2p_connect_group(self, go_addr, pin, timeout=0, social=False,
  725. freq=None):
  726. self.dump_monitor()
  727. if not self.discover_peer(go_addr, social=social, freq=freq):
  728. if social or not self.discover_peer(go_addr, social=social):
  729. raise Exception("GO " + go_addr + " not found")
  730. self.p2p_stop_find()
  731. self.dump_monitor()
  732. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  733. if freq:
  734. cmd += " freq=" + str(freq)
  735. if "OK" in self.global_request(cmd):
  736. if timeout == 0:
  737. self.dump_monitor()
  738. return None
  739. ev = self.wait_global_event(["P2P-GROUP-STARTED",
  740. "P2P-GROUP-FORMATION-FAILURE"],
  741. timeout)
  742. if ev is None:
  743. raise Exception("Joining the group timed out")
  744. if "P2P-GROUP-STARTED" not in ev:
  745. raise Exception("Failed to join the group")
  746. self.dump_monitor()
  747. return self.group_form_result(ev)
  748. raise Exception("P2P_CONNECT(join) failed")
  749. def tdls_setup(self, peer):
  750. cmd = "TDLS_SETUP " + peer
  751. if "FAIL" in self.group_request(cmd):
  752. raise Exception("Failed to request TDLS setup")
  753. return None
  754. def tdls_teardown(self, peer):
  755. cmd = "TDLS_TEARDOWN " + peer
  756. if "FAIL" in self.group_request(cmd):
  757. raise Exception("Failed to request TDLS teardown")
  758. return None
  759. def tdls_link_status(self, peer):
  760. cmd = "TDLS_LINK_STATUS " + peer
  761. ret = self.group_request(cmd)
  762. if "FAIL" in ret:
  763. raise Exception("Failed to request TDLS link status")
  764. return ret
  765. def tspecs(self):
  766. """Return (tsid, up) tuples representing current tspecs"""
  767. res = self.request("WMM_AC_STATUS")
  768. tspecs = re.findall(r"TSID=(\d+) UP=(\d+)", res)
  769. tspecs = [tuple(map(int, tspec)) for tspec in tspecs]
  770. logger.debug("tspecs: " + str(tspecs))
  771. return tspecs
  772. def add_ts(self, tsid, up, direction="downlink", expect_failure=False,
  773. extra=None):
  774. params = {
  775. "sba": 9000,
  776. "nominal_msdu_size": 1500,
  777. "min_phy_rate": 6000000,
  778. "mean_data_rate": 1500,
  779. }
  780. cmd = "WMM_AC_ADDTS %s tsid=%d up=%d" % (direction, tsid, up)
  781. for (key, value) in params.iteritems():
  782. cmd += " %s=%d" % (key, value)
  783. if extra:
  784. cmd += " " + extra
  785. if self.request(cmd).strip() != "OK":
  786. raise Exception("ADDTS failed (tsid=%d up=%d)" % (tsid, up))
  787. if expect_failure:
  788. ev = self.wait_event(["TSPEC-REQ-FAILED"], timeout=2)
  789. if ev is None:
  790. raise Exception("ADDTS failed (time out while waiting failure)")
  791. if "tsid=%d" % (tsid) not in ev:
  792. raise Exception("ADDTS failed (invalid tsid in TSPEC-REQ-FAILED")
  793. return
  794. ev = self.wait_event(["TSPEC-ADDED"], timeout=1)
  795. if ev is None:
  796. raise Exception("ADDTS failed (time out)")
  797. if "tsid=%d" % (tsid) not in ev:
  798. raise Exception("ADDTS failed (invalid tsid in TSPEC-ADDED)")
  799. if not (tsid, up) in self.tspecs():
  800. raise Exception("ADDTS failed (tsid not in tspec list)")
  801. def del_ts(self, tsid):
  802. if self.request("WMM_AC_DELTS %d" % (tsid)).strip() != "OK":
  803. raise Exception("DELTS failed")
  804. ev = self.wait_event(["TSPEC-REMOVED"], timeout=1)
  805. if ev is None:
  806. raise Exception("DELTS failed (time out)")
  807. if "tsid=%d" % (tsid) not in ev:
  808. raise Exception("DELTS failed (invalid tsid in TSPEC-REMOVED)")
  809. tspecs = [(t, u) for (t, u) in self.tspecs() if t == tsid]
  810. if tspecs:
  811. raise Exception("DELTS failed (still in tspec list)")
  812. def connect(self, ssid=None, ssid2=None, **kwargs):
  813. logger.info("Connect STA " + self.ifname + " to AP")
  814. id = self.add_network()
  815. if ssid:
  816. self.set_network_quoted(id, "ssid", ssid)
  817. elif ssid2:
  818. self.set_network(id, "ssid", ssid2)
  819. quoted = [ "psk", "identity", "anonymous_identity", "password",
  820. "ca_cert", "client_cert", "private_key",
  821. "private_key_passwd", "ca_cert2", "client_cert2",
  822. "private_key2", "phase1", "phase2", "domain_suffix_match",
  823. "altsubject_match", "subject_match", "pac_file", "dh_file",
  824. "bgscan", "ht_mcs", "id_str", "openssl_ciphers",
  825. "domain_match" ]
  826. for field in quoted:
  827. if field in kwargs and kwargs[field]:
  828. self.set_network_quoted(id, field, kwargs[field])
  829. not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
  830. "group", "wep_key0", "wep_key1", "wep_key2", "wep_key3",
  831. "wep_tx_keyidx", "scan_freq", "freq_list", "eap",
  832. "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
  833. "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
  834. "disable_max_amsdu", "ampdu_factor", "ampdu_density",
  835. "disable_ht40", "disable_sgi", "disable_ldpc",
  836. "ht40_intolerant", "update_identifier", "mac_addr",
  837. "erp", "bg_scan_period", "bssid_blacklist",
  838. "bssid_whitelist", "mem_only_psk", "eap_workaround",
  839. "engine" ]
  840. for field in not_quoted:
  841. if field in kwargs and kwargs[field]:
  842. self.set_network(id, field, kwargs[field])
  843. if "raw_psk" in kwargs and kwargs['raw_psk']:
  844. self.set_network(id, "psk", kwargs['raw_psk'])
  845. if "password_hex" in kwargs and kwargs['password_hex']:
  846. self.set_network(id, "password", kwargs['password_hex'])
  847. if "peerkey" in kwargs and kwargs['peerkey']:
  848. self.set_network(id, "peerkey", "1")
  849. if "okc" in kwargs and kwargs['okc']:
  850. self.set_network(id, "proactive_key_caching", "1")
  851. if "ocsp" in kwargs and kwargs['ocsp']:
  852. self.set_network(id, "ocsp", str(kwargs['ocsp']))
  853. if "only_add_network" in kwargs and kwargs['only_add_network']:
  854. return id
  855. if "wait_connect" not in kwargs or kwargs['wait_connect']:
  856. if "eap" in kwargs:
  857. self.connect_network(id, timeout=20)
  858. else:
  859. self.connect_network(id)
  860. else:
  861. self.dump_monitor()
  862. self.select_network(id)
  863. return id
  864. def scan(self, type=None, freq=None, no_wait=False, only_new=False):
  865. if type:
  866. cmd = "SCAN TYPE=" + type
  867. else:
  868. cmd = "SCAN"
  869. if freq:
  870. cmd = cmd + " freq=" + str(freq)
  871. if only_new:
  872. cmd += " only_new=1"
  873. if not no_wait:
  874. self.dump_monitor()
  875. if not "OK" in self.request(cmd):
  876. raise Exception("Failed to trigger scan")
  877. if no_wait:
  878. return
  879. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  880. if ev is None:
  881. raise Exception("Scan timed out")
  882. def scan_for_bss(self, bssid, freq=None, force_scan=False, only_new=False):
  883. if not force_scan and self.get_bss(bssid) is not None:
  884. return
  885. for i in range(0, 10):
  886. self.scan(freq=freq, type="ONLY", only_new=only_new)
  887. if self.get_bss(bssid) is not None:
  888. return
  889. raise Exception("Could not find BSS " + bssid + " in scan")
  890. def flush_scan_cache(self, freq=2417):
  891. self.request("BSS_FLUSH 0")
  892. self.scan(freq=freq, only_new=True)
  893. res = self.request("SCAN_RESULTS")
  894. if len(res.splitlines()) > 1:
  895. self.request("BSS_FLUSH 0")
  896. self.scan(freq=2422, only_new=True)
  897. res = self.request("SCAN_RESULTS")
  898. if len(res.splitlines()) > 1:
  899. logger.info("flush_scan_cache: Could not clear all BSS entries. These remain:\n" + res)
  900. def roam(self, bssid, fail_test=False):
  901. self.dump_monitor()
  902. if "OK" not in self.request("ROAM " + bssid):
  903. raise Exception("ROAM failed")
  904. if fail_test:
  905. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  906. if ev is not None:
  907. raise Exception("Unexpected connection")
  908. self.dump_monitor()
  909. return
  910. self.wait_connected(timeout=10, error="Roaming with the AP timed out")
  911. self.dump_monitor()
  912. def roam_over_ds(self, bssid, fail_test=False):
  913. self.dump_monitor()
  914. if "OK" not in self.request("FT_DS " + bssid):
  915. raise Exception("FT_DS failed")
  916. if fail_test:
  917. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
  918. if ev is not None:
  919. raise Exception("Unexpected connection")
  920. self.dump_monitor()
  921. return
  922. self.wait_connected(timeout=10, error="Roaming with the AP timed out")
  923. self.dump_monitor()
  924. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  925. new_passphrase=None, no_wait=False):
  926. self.dump_monitor()
  927. if new_ssid:
  928. self.request("WPS_REG " + bssid + " " + pin + " " +
  929. new_ssid.encode("hex") + " " + key_mgmt + " " +
  930. cipher + " " + new_passphrase.encode("hex"))
  931. if no_wait:
  932. return
  933. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  934. else:
  935. self.request("WPS_REG " + bssid + " " + pin)
  936. if no_wait:
  937. return
  938. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  939. if ev is None:
  940. raise Exception("WPS cred timed out")
  941. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  942. if ev is None:
  943. raise Exception("WPS timed out")
  944. self.wait_connected(timeout=15)
  945. def relog(self):
  946. self.global_request("RELOG")
  947. def wait_completed(self, timeout=10):
  948. for i in range(0, timeout * 2):
  949. if self.get_status_field("wpa_state") == "COMPLETED":
  950. return
  951. time.sleep(0.5)
  952. raise Exception("Timeout while waiting for COMPLETED state")
  953. def get_capability(self, field):
  954. res = self.request("GET_CAPABILITY " + field)
  955. if "FAIL" in res:
  956. return None
  957. return res.split(' ')
  958. def get_bss(self, bssid, ifname=None):
  959. if not ifname or ifname == self.ifname:
  960. res = self.request("BSS " + bssid)
  961. elif ifname == self.group_ifname:
  962. res = self.group_request("BSS " + bssid)
  963. else:
  964. return None
  965. if "FAIL" in res:
  966. return None
  967. lines = res.splitlines()
  968. vals = dict()
  969. for l in lines:
  970. [name,value] = l.split('=', 1)
  971. vals[name] = value
  972. if len(vals) == 0:
  973. return None
  974. return vals
  975. def get_pmksa(self, bssid):
  976. res = self.request("PMKSA")
  977. lines = res.splitlines()
  978. for l in lines:
  979. if bssid not in l:
  980. continue
  981. vals = dict()
  982. [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
  983. vals['index'] = index
  984. vals['pmkid'] = pmkid
  985. vals['expiration'] = expiration
  986. vals['opportunistic'] = opportunistic
  987. return vals
  988. return None
  989. def get_sta(self, addr, info=None, next=False):
  990. cmd = "STA-NEXT " if next else "STA "
  991. if addr is None:
  992. res = self.request("STA-FIRST")
  993. elif info:
  994. res = self.request(cmd + addr + " " + info)
  995. else:
  996. res = self.request(cmd + addr)
  997. lines = res.splitlines()
  998. vals = dict()
  999. first = True
  1000. for l in lines:
  1001. if first:
  1002. vals['addr'] = l
  1003. first = False
  1004. else:
  1005. [name,value] = l.split('=', 1)
  1006. vals[name] = value
  1007. return vals
  1008. def mgmt_rx(self, timeout=5):
  1009. ev = self.wait_event(["MGMT-RX"], timeout=timeout)
  1010. if ev is None:
  1011. return None
  1012. msg = {}
  1013. items = ev.split(' ')
  1014. field,val = items[1].split('=')
  1015. if field != "freq":
  1016. raise Exception("Unexpected MGMT-RX event format: " + ev)
  1017. msg['freq'] = val
  1018. frame = binascii.unhexlify(items[4])
  1019. msg['frame'] = frame
  1020. hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
  1021. msg['fc'] = hdr[0]
  1022. msg['subtype'] = (hdr[0] >> 4) & 0xf
  1023. hdr = hdr[1:]
  1024. msg['duration'] = hdr[0]
  1025. hdr = hdr[1:]
  1026. msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1027. hdr = hdr[6:]
  1028. msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1029. hdr = hdr[6:]
  1030. msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
  1031. hdr = hdr[6:]
  1032. msg['seq_ctrl'] = hdr[0]
  1033. msg['payload'] = frame[24:]
  1034. return msg
  1035. def wait_connected(self, timeout=10, error="Connection timed out"):
  1036. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
  1037. if ev is None:
  1038. raise Exception(error)
  1039. return ev
  1040. def wait_disconnected(self, timeout=10, error="Disconnection timed out"):
  1041. ev = self.wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=timeout)
  1042. if ev is None:
  1043. raise Exception(error)
  1044. return ev
  1045. def get_group_ifname(self):
  1046. return self.group_ifname if self.group_ifname else self.ifname
  1047. def get_config(self):
  1048. res = self.request("DUMP")
  1049. if res.startswith("FAIL"):
  1050. raise Exception("DUMP failed")
  1051. lines = res.splitlines()
  1052. vals = dict()
  1053. for l in lines:
  1054. [name,value] = l.split('=', 1)
  1055. vals[name] = value
  1056. return vals
  1057. def asp_provision(self, peer, adv_id, adv_mac, session_id, session_mac,
  1058. method="1000", info="", status=None, cpt=None, role=None):
  1059. if status is None:
  1060. cmd = "P2P_ASP_PROVISION"
  1061. params = "info='%s' method=%s" % (info, method)
  1062. else:
  1063. cmd = "P2P_ASP_PROVISION_RESP"
  1064. params = "status=%d" % status
  1065. if role is not None:
  1066. params += " role=" + role
  1067. if cpt is not None:
  1068. params += " cpt=" + cpt
  1069. if "OK" not in self.global_request("%s %s adv_id=%s adv_mac=%s session=%d session_mac=%s %s" %
  1070. (cmd, peer, adv_id, adv_mac, session_id, session_mac, params)):
  1071. raise Exception("%s request failed" % cmd)