wpasupplicant.py 18 KB

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