wpasupplicant.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 group_form_result(self, ev, expect_failure=False):
  164. if expect_failure:
  165. if "P2P-GROUP-STARTED" in ev:
  166. raise Exception("Group formation succeeded when expecting failure")
  167. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  168. s = re.split(exp, ev)
  169. if len(s) < 3:
  170. return None
  171. res = {}
  172. res['result'] = 'go-neg-failed'
  173. res['status'] = int(s[2])
  174. return res
  175. if "P2P-GROUP-STARTED" not in ev:
  176. raise Exception("No P2P-GROUP-STARTED event seen")
  177. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  178. s = re.split(exp, ev)
  179. if len(s) < 8:
  180. raise Exception("Could not parse P2P-GROUP-STARTED")
  181. res = {}
  182. res['result'] = 'success'
  183. res['ifname'] = s[2]
  184. self.group_ifname = s[2]
  185. res['role'] = s[3]
  186. res['ssid'] = s[4]
  187. res['freq'] = s[5]
  188. p = re.match(r'psk=([0-9a-f]*)', s[6])
  189. if p:
  190. res['psk'] = p.group(1)
  191. p = re.match(r'passphrase="(.*)"', s[6])
  192. if p:
  193. res['passphrase'] = p.group(1)
  194. res['go_dev_addr'] = s[7]
  195. return res
  196. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None):
  197. if not self.discover_peer(peer):
  198. raise Exception("Peer " + peer + " not found")
  199. self.dump_monitor()
  200. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  201. if go_intent:
  202. cmd = cmd + ' go_intent=' + str(go_intent)
  203. if "OK" in self.global_request(cmd):
  204. return None
  205. raise Exception("P2P_CONNECT (auth) failed")
  206. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  207. ev = self.wait_global_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout);
  208. if ev is None:
  209. if expect_failure:
  210. return None
  211. raise Exception("Group formation timed out")
  212. self.dump_monitor()
  213. return self.group_form_result(ev, expect_failure)
  214. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False):
  215. if not self.discover_peer(peer):
  216. raise Exception("Peer " + peer + " not found")
  217. self.dump_monitor()
  218. if pin:
  219. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  220. else:
  221. cmd = "P2P_CONNECT " + peer + " " + method
  222. if go_intent:
  223. cmd = cmd + ' go_intent=' + str(go_intent)
  224. if "OK" in self.global_request(cmd):
  225. if timeout == 0:
  226. self.dump_monitor()
  227. return None
  228. ev = self.wait_global_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout)
  229. if ev is None:
  230. if expect_failure:
  231. return None
  232. raise Exception("Group formation timed out")
  233. self.dump_monitor()
  234. return self.group_form_result(ev, expect_failure)
  235. raise Exception("P2P_CONNECT failed")
  236. def wait_event(self, events, timeout):
  237. count = 0
  238. while count < timeout * 10:
  239. count = count + 1
  240. time.sleep(0.1)
  241. while self.mon.pending():
  242. ev = self.mon.recv()
  243. logger.debug(self.ifname + ": " + ev)
  244. for event in events:
  245. if event in ev:
  246. return ev
  247. return None
  248. def wait_global_event(self, events, timeout):
  249. if self.global_iface is None:
  250. self.wait_event(events, timeout)
  251. else:
  252. count = 0
  253. while count < timeout * 10:
  254. count = count + 1
  255. time.sleep(0.1)
  256. while self.global_mon.pending():
  257. ev = self.global_mon.recv()
  258. logger.debug(self.ifname + ": " + ev)
  259. for event in events:
  260. if event in ev:
  261. return ev
  262. return None
  263. def dump_monitor(self):
  264. while self.mon.pending():
  265. ev = self.mon.recv()
  266. logger.debug(self.ifname + ": " + ev)
  267. def remove_group(self, ifname=None):
  268. if ifname is None:
  269. ifname = self.group_ifname if self.group_ifname else self.iname
  270. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  271. raise Exception("Group could not be removed")
  272. self.group_ifname = None
  273. def p2p_start_go(self, persistent=None, freq=None):
  274. self.dump_monitor()
  275. cmd = "P2P_GROUP_ADD"
  276. if persistent is None:
  277. pass
  278. elif persistent is True:
  279. cmd = cmd + " persistent"
  280. else:
  281. cmd = cmd + " persistent=" + str(persistent)
  282. if freq:
  283. cmd = cmd + " freq=" + freq
  284. if "OK" in self.global_request(cmd):
  285. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  286. if ev is None:
  287. raise Exception("GO start up timed out")
  288. self.dump_monitor()
  289. return self.group_form_result(ev)
  290. raise Exception("P2P_GROUP_ADD failed")
  291. def p2p_go_authorize_client(self, pin):
  292. cmd = "WPS_PIN any " + pin
  293. if "FAIL" in self.group_request(cmd):
  294. raise Exception("Failed to authorize client connection on GO")
  295. return None
  296. def p2p_go_authorize_client_pbc(self):
  297. cmd = "WPS_PBC"
  298. if "FAIL" in self.group_request(cmd):
  299. raise Exception("Failed to authorize client connection on GO")
  300. return None
  301. def p2p_connect_group(self, go_addr, pin, timeout=0):
  302. self.dump_monitor()
  303. if not self.discover_peer(go_addr, social=False):
  304. raise Exception("GO " + go_addr + " not found")
  305. self.dump_monitor()
  306. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  307. if "OK" in self.global_request(cmd):
  308. if timeout == 0:
  309. self.dump_monitor()
  310. return None
  311. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  312. if ev is None:
  313. raise Exception("Joining the group timed out")
  314. self.dump_monitor()
  315. return self.group_form_result(ev)
  316. raise Exception("P2P_CONNECT(join) failed")
  317. def tdls_setup(self, peer):
  318. cmd = "TDLS_SETUP " + peer
  319. if "FAIL" in self.group_request(cmd):
  320. raise Exception("Failed to request TDLS setup")
  321. return None
  322. def tdls_teardown(self, peer):
  323. cmd = "TDLS_TEARDOWN " + peer
  324. if "FAIL" in self.group_request(cmd):
  325. raise Exception("Failed to request TDLS teardown")
  326. return None
  327. def connect(self, ssid, psk=None, proto=None, key_mgmt=None, wep_key0=None, ieee80211w=None):
  328. logger.info("Connect STA " + self.ifname + " to AP")
  329. id = self.add_network()
  330. self.set_network_quoted(id, "ssid", ssid)
  331. if psk:
  332. self.set_network_quoted(id, "psk", psk)
  333. if proto:
  334. self.set_network(id, "proto", proto)
  335. if key_mgmt:
  336. self.set_network(id, "key_mgmt", key_mgmt)
  337. if ieee80211w:
  338. self.set_network(id, "ieee80211w", ieee80211w)
  339. if wep_key0:
  340. self.set_network(id, "wep_key0", wep_key0)
  341. self.connect_network(id)
  342. def scan(self, type=None):
  343. if type:
  344. cmd = "SCAN TYPE=" + type
  345. else:
  346. cmd = "SCAN"
  347. self.dump_monitor()
  348. if not "OK" in self.request(cmd):
  349. raise Exception("Failed to trigger scan")
  350. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  351. if ev is None:
  352. raise Exception("Scan timed out")
  353. def roam(self, bssid):
  354. self.dump_monitor()
  355. self.request("ROAM " + bssid)
  356. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  357. if ev is None:
  358. raise Exception("Roaming with the AP timed out")
  359. self.dump_monitor()
  360. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  361. new_passphrase=None):
  362. self.dump_monitor()
  363. if new_ssid:
  364. self.request("WPS_REG " + bssid + " " + pin + " " +
  365. new_ssid.encode("hex") + " " + key_mgmt + " " +
  366. cipher + " " + new_passphrase.encode("hex"))
  367. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  368. else:
  369. self.request("WPS_REG " + bssid + " " + pin)
  370. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  371. if ev is None:
  372. raise Exception("WPS cred timed out")
  373. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  374. if ev is None:
  375. raise Exception("WPS timed out")
  376. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  377. if ev is None:
  378. raise Exception("Association with the AP timed out")