wpasupplicant.py 16 KB

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