wpasupplicant.py 43 KB

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