wpasupplicant.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. #!/usr/bin/python
  2. #
  3. # Python class for controlling wpa_supplicant
  4. # Copyright (c) 2013, Jouni Malinen <j@w1.fi>
  5. #
  6. # This software may be distributed under the terms of the BSD license.
  7. # See README for more details.
  8. import os
  9. import time
  10. import logging
  11. import re
  12. import subprocess
  13. import wpaspy
  14. logger = logging.getLogger(__name__)
  15. wpas_ctrl = '/var/run/wpa_supplicant'
  16. class WpaSupplicant:
  17. def __init__(self, ifname, global_iface=None):
  18. self.ifname = ifname
  19. self.group_ifname = None
  20. self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  21. self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  22. self.mon.attach()
  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 request(self, cmd):
  29. logger.debug(self.ifname + ": CTRL: " + cmd)
  30. return self.ctrl.request(cmd)
  31. def global_request(self, cmd):
  32. if self.global_iface is None:
  33. self.request(cmd)
  34. else:
  35. logger.debug(self.ifname + ": CTRL: " + cmd)
  36. return self.global_ctrl.request(cmd)
  37. def group_request(self, cmd):
  38. if self.group_ifname and self.group_ifname != self.ifname:
  39. logger.debug(self.group_ifname + ": CTRL: " + cmd)
  40. gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  41. return gctrl.request(cmd)
  42. return self.request(cmd)
  43. def ping(self):
  44. return "PONG" in self.request("PING")
  45. def reset(self):
  46. res = self.request("FLUSH")
  47. if not "OK" in res:
  48. logger.info("FLUSH to " + self.ifname + " failed: " + res)
  49. self.request("SET ignore_old_scan_res 0")
  50. self.request("P2P_SET per_sta_psk 0")
  51. self.request("P2P_SET disabled 0")
  52. self.group_ifname = None
  53. self.dump_monitor()
  54. iter = 0
  55. while iter < 60:
  56. state = self.get_driver_status_field("scan_state")
  57. if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
  58. logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
  59. time.sleep(1)
  60. else:
  61. break
  62. iter = iter + 1
  63. if iter == 60:
  64. logger.error(self.ifname + ": Driver scan state did not clear")
  65. print "Trying to clear cfg80211/mac80211 scan state"
  66. try:
  67. cmd = ["sudo", "ifconfig", self.ifname, "down"]
  68. subprocess.call(cmd)
  69. except subprocess.CalledProcessError, e:
  70. logger.info("ifconfig failed: " + str(e.returncode))
  71. logger.info(e.output)
  72. try:
  73. cmd = ["sudo", "ifconfig", self.ifname, "up"]
  74. subprocess.call(cmd)
  75. except subprocess.CalledProcessError, e:
  76. logger.info("ifconfig failed: " + str(e.returncode))
  77. logger.info(e.output)
  78. if not self.ping():
  79. logger.info("No PING response from " + self.ifname + " after reset")
  80. def add_network(self):
  81. id = self.request("ADD_NETWORK")
  82. if "FAIL" in id:
  83. raise Exception("ADD_NETWORK failed")
  84. return int(id)
  85. def remove_network(self, id):
  86. id = self.request("REMOVE_NETWORK " + str(id))
  87. if "FAIL" in id:
  88. raise Exception("REMOVE_NETWORK failed")
  89. return None
  90. def set_network(self, id, field, value):
  91. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  92. if "FAIL" in res:
  93. raise Exception("SET_NETWORK failed")
  94. return None
  95. def set_network_quoted(self, id, field, value):
  96. res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  97. if "FAIL" in res:
  98. raise Exception("SET_NETWORK failed")
  99. return None
  100. def add_cred(self):
  101. id = self.request("ADD_CRED")
  102. if "FAIL" in id:
  103. raise Exception("ADD_CRED failed")
  104. return int(id)
  105. def remove_cred(self, id):
  106. id = self.request("REMOVE_CRED " + str(id))
  107. if "FAIL" in id:
  108. raise Exception("REMOVE_CRED failed")
  109. return None
  110. def set_cred(self, id, field, value):
  111. res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
  112. if "FAIL" in res:
  113. raise Exception("SET_CRED failed")
  114. return None
  115. def set_cred_quoted(self, id, field, value):
  116. res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
  117. if "FAIL" in res:
  118. raise Exception("SET_CRED failed")
  119. return None
  120. def select_network(self, id):
  121. id = self.request("SELECT_NETWORK " + str(id))
  122. if "FAIL" in id:
  123. raise Exception("SELECT_NETWORK failed")
  124. return None
  125. def connect_network(self, id):
  126. self.dump_monitor()
  127. self.select_network(id)
  128. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  129. if ev is None:
  130. raise Exception("Association with the AP timed out")
  131. self.dump_monitor()
  132. def get_status(self):
  133. res = self.request("STATUS")
  134. lines = res.splitlines()
  135. vals = dict()
  136. for l in lines:
  137. [name,value] = l.split('=', 1)
  138. vals[name] = value
  139. return vals
  140. def get_status_field(self, field):
  141. vals = self.get_status()
  142. if field in vals:
  143. return vals[field]
  144. return None
  145. def get_group_status(self):
  146. res = self.group_request("STATUS")
  147. lines = res.splitlines()
  148. vals = dict()
  149. for l in lines:
  150. [name,value] = l.split('=', 1)
  151. vals[name] = value
  152. return vals
  153. def get_group_status_field(self, field):
  154. vals = self.get_group_status()
  155. if field in vals:
  156. return vals[field]
  157. return None
  158. def get_driver_status(self):
  159. res = self.request("STATUS-DRIVER")
  160. lines = res.splitlines()
  161. vals = dict()
  162. for l in lines:
  163. [name,value] = l.split('=', 1)
  164. vals[name] = value
  165. return vals
  166. def get_driver_status_field(self, field):
  167. vals = self.get_driver_status()
  168. if field in vals:
  169. return vals[field]
  170. return None
  171. def p2p_dev_addr(self):
  172. return self.get_status_field("p2p_device_address")
  173. def p2p_interface_addr(self):
  174. return self.get_group_status_field("address")
  175. def p2p_listen(self):
  176. return self.global_request("P2P_LISTEN")
  177. def p2p_find(self, social=False):
  178. if social:
  179. return self.global_request("P2P_FIND type=social")
  180. return self.global_request("P2P_FIND")
  181. def p2p_stop_find(self):
  182. return self.global_request("P2P_STOP_FIND")
  183. def wps_read_pin(self):
  184. #TODO: make this random
  185. self.pin = "12345670"
  186. return self.pin
  187. def peer_known(self, peer, full=True):
  188. res = self.global_request("P2P_PEER " + peer)
  189. if peer.lower() not in res.lower():
  190. return False
  191. if not full:
  192. return True
  193. return "[PROBE_REQ_ONLY]" not in res
  194. def discover_peer(self, peer, full=True, timeout=15, social=True):
  195. logger.info(self.ifname + ": Trying to discover peer " + peer)
  196. if self.peer_known(peer, full):
  197. return True
  198. self.p2p_find(social)
  199. count = 0
  200. while count < timeout:
  201. time.sleep(1)
  202. count = count + 1
  203. if self.peer_known(peer, full):
  204. return True
  205. return False
  206. def get_peer(self, peer):
  207. res = self.global_request("P2P_PEER " + peer)
  208. if peer.lower() not in res.lower():
  209. raise Exception("Peer information not available")
  210. lines = res.splitlines()
  211. vals = dict()
  212. for l in lines:
  213. if '=' in l:
  214. [name,value] = l.split('=', 1)
  215. vals[name] = value
  216. return vals
  217. def group_form_result(self, ev, expect_failure=False):
  218. if expect_failure:
  219. if "P2P-GROUP-STARTED" in ev:
  220. raise Exception("Group formation succeeded when expecting failure")
  221. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  222. s = re.split(exp, ev)
  223. if len(s) < 3:
  224. return None
  225. res = {}
  226. res['result'] = 'go-neg-failed'
  227. res['status'] = int(s[2])
  228. return res
  229. if "P2P-GROUP-STARTED" not in ev:
  230. raise Exception("No P2P-GROUP-STARTED event seen")
  231. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  232. s = re.split(exp, ev)
  233. if len(s) < 8:
  234. raise Exception("Could not parse P2P-GROUP-STARTED")
  235. res = {}
  236. res['result'] = 'success'
  237. res['ifname'] = s[2]
  238. self.group_ifname = s[2]
  239. res['role'] = s[3]
  240. res['ssid'] = s[4]
  241. res['freq'] = s[5]
  242. if "[PERSISTENT]" in ev:
  243. res['persistent'] = True
  244. else:
  245. res['persistent'] = False
  246. p = re.match(r'psk=([0-9a-f]*)', s[6])
  247. if p:
  248. res['psk'] = p.group(1)
  249. p = re.match(r'passphrase="(.*)"', s[6])
  250. if p:
  251. res['passphrase'] = p.group(1)
  252. res['go_dev_addr'] = s[7]
  253. return res
  254. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False):
  255. if not self.discover_peer(peer):
  256. raise Exception("Peer " + peer + " not found")
  257. self.dump_monitor()
  258. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  259. if go_intent:
  260. cmd = cmd + ' go_intent=' + str(go_intent)
  261. if persistent:
  262. cmd = cmd + " persistent"
  263. if "OK" in self.global_request(cmd):
  264. return None
  265. raise Exception("P2P_CONNECT (auth) failed")
  266. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  267. ev = self.wait_global_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout);
  268. if ev is None:
  269. if expect_failure:
  270. return None
  271. raise Exception("Group formation timed out")
  272. self.dump_monitor()
  273. return self.group_form_result(ev, expect_failure)
  274. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False, persistent=False, freq=None):
  275. if not self.discover_peer(peer):
  276. raise Exception("Peer " + peer + " not found")
  277. self.dump_monitor()
  278. if pin:
  279. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  280. else:
  281. cmd = "P2P_CONNECT " + peer + " " + method
  282. if go_intent:
  283. cmd = cmd + ' go_intent=' + str(go_intent)
  284. if freq:
  285. cmd = cmd + ' freq=' + str(freq)
  286. if persistent:
  287. cmd = cmd + " persistent"
  288. if "OK" in self.global_request(cmd):
  289. if timeout == 0:
  290. self.dump_monitor()
  291. return None
  292. ev = self.wait_global_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout)
  293. if ev is None:
  294. if expect_failure:
  295. return None
  296. raise Exception("Group formation timed out")
  297. self.dump_monitor()
  298. return self.group_form_result(ev, expect_failure)
  299. raise Exception("P2P_CONNECT failed")
  300. def wait_event(self, events, timeout):
  301. count = 0
  302. while count < timeout * 10:
  303. count = count + 1
  304. time.sleep(0.1)
  305. while self.mon.pending():
  306. ev = self.mon.recv()
  307. logger.debug(self.ifname + ": " + ev)
  308. for event in events:
  309. if event in ev:
  310. return ev
  311. return None
  312. def wait_global_event(self, events, timeout):
  313. if self.global_iface is None:
  314. self.wait_event(events, timeout)
  315. else:
  316. count = 0
  317. while count < timeout * 10:
  318. count = count + 1
  319. time.sleep(0.1)
  320. while self.global_mon.pending():
  321. ev = self.global_mon.recv()
  322. logger.debug(self.ifname + "(global): " + ev)
  323. for event in events:
  324. if event in ev:
  325. return ev
  326. return None
  327. def wait_go_ending_session(self):
  328. ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
  329. if ev is None:
  330. raise Exception("Group removal event timed out")
  331. if "reason=GO_ENDING_SESSION" not in ev:
  332. raise Exception("Unexpected group removal reason")
  333. def dump_monitor(self):
  334. while self.mon.pending():
  335. ev = self.mon.recv()
  336. logger.debug(self.ifname + ": " + ev)
  337. while self.global_mon.pending():
  338. ev = self.global_mon.recv()
  339. logger.debug(self.ifname + "(global): " + ev)
  340. def remove_group(self, ifname=None):
  341. if ifname is None:
  342. ifname = self.group_ifname if self.group_ifname else self.ifname
  343. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  344. raise Exception("Group could not be removed")
  345. self.group_ifname = None
  346. def p2p_start_go(self, persistent=None, freq=None):
  347. self.dump_monitor()
  348. cmd = "P2P_GROUP_ADD"
  349. if persistent is None:
  350. pass
  351. elif persistent is True:
  352. cmd = cmd + " persistent"
  353. else:
  354. cmd = cmd + " persistent=" + str(persistent)
  355. if freq:
  356. cmd = cmd + " freq=" + str(freq)
  357. if "OK" in self.global_request(cmd):
  358. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  359. if ev is None:
  360. raise Exception("GO start up timed out")
  361. self.dump_monitor()
  362. return self.group_form_result(ev)
  363. raise Exception("P2P_GROUP_ADD failed")
  364. def p2p_go_authorize_client(self, pin):
  365. cmd = "WPS_PIN any " + pin
  366. if "FAIL" in self.group_request(cmd):
  367. raise Exception("Failed to authorize client connection on GO")
  368. return None
  369. def p2p_go_authorize_client_pbc(self):
  370. cmd = "WPS_PBC"
  371. if "FAIL" in self.group_request(cmd):
  372. raise Exception("Failed to authorize client connection on GO")
  373. return None
  374. def p2p_connect_group(self, go_addr, pin, timeout=0):
  375. self.dump_monitor()
  376. if not self.discover_peer(go_addr, social=False):
  377. raise Exception("GO " + go_addr + " not found")
  378. self.dump_monitor()
  379. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  380. if "OK" in self.global_request(cmd):
  381. if timeout == 0:
  382. self.dump_monitor()
  383. return None
  384. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  385. if ev is None:
  386. raise Exception("Joining the group timed out")
  387. self.dump_monitor()
  388. return self.group_form_result(ev)
  389. raise Exception("P2P_CONNECT(join) failed")
  390. def tdls_setup(self, peer):
  391. cmd = "TDLS_SETUP " + peer
  392. if "FAIL" in self.group_request(cmd):
  393. raise Exception("Failed to request TDLS setup")
  394. return None
  395. def tdls_teardown(self, peer):
  396. cmd = "TDLS_TEARDOWN " + peer
  397. if "FAIL" in self.group_request(cmd):
  398. raise Exception("Failed to request TDLS teardown")
  399. return None
  400. def connect(self, ssid, psk=None, proto=None, key_mgmt=None, wep_key0=None, ieee80211w=None, pairwise=None, group=None, scan_freq=None):
  401. logger.info("Connect STA " + self.ifname + " to AP")
  402. id = self.add_network()
  403. self.set_network_quoted(id, "ssid", ssid)
  404. if psk:
  405. self.set_network_quoted(id, "psk", psk)
  406. if proto:
  407. self.set_network(id, "proto", proto)
  408. if key_mgmt:
  409. self.set_network(id, "key_mgmt", key_mgmt)
  410. if ieee80211w:
  411. self.set_network(id, "ieee80211w", ieee80211w)
  412. if pairwise:
  413. self.set_network(id, "pairwise", pairwise)
  414. if group:
  415. self.set_network(id, "group", group)
  416. if wep_key0:
  417. self.set_network(id, "wep_key0", wep_key0)
  418. if scan_freq:
  419. self.set_network(id, "scan_freq", scan_freq)
  420. self.connect_network(id)
  421. def scan(self, type=None):
  422. if type:
  423. cmd = "SCAN TYPE=" + type
  424. else:
  425. cmd = "SCAN"
  426. self.dump_monitor()
  427. if not "OK" in self.request(cmd):
  428. raise Exception("Failed to trigger scan")
  429. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  430. if ev is None:
  431. raise Exception("Scan timed out")
  432. def roam(self, bssid):
  433. self.dump_monitor()
  434. self.request("ROAM " + bssid)
  435. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  436. if ev is None:
  437. raise Exception("Roaming with the AP timed out")
  438. self.dump_monitor()
  439. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  440. new_passphrase=None):
  441. self.dump_monitor()
  442. if new_ssid:
  443. self.request("WPS_REG " + bssid + " " + pin + " " +
  444. new_ssid.encode("hex") + " " + key_mgmt + " " +
  445. cipher + " " + new_passphrase.encode("hex"))
  446. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  447. else:
  448. self.request("WPS_REG " + bssid + " " + pin)
  449. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  450. if ev is None:
  451. raise Exception("WPS cred timed out")
  452. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  453. if ev is None:
  454. raise Exception("WPS timed out")
  455. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  456. if ev is None:
  457. raise Exception("Association with the AP timed out")