wpasupplicant.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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):
  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. def request(self, cmd):
  23. logger.debug(self.ifname + ": CTRL: " + cmd)
  24. return self.ctrl.request(cmd)
  25. def group_request(self, cmd):
  26. if self.group_ifname and self.group_ifname != self.ifname:
  27. logger.debug(self.group_ifname + ": CTRL: " + cmd)
  28. gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  29. return gctrl.request(cmd)
  30. return self.request(cmd)
  31. def ping(self):
  32. return "PONG" in self.request("PING")
  33. def reset(self):
  34. self.request("P2P_STOP_FIND")
  35. self.request("P2P_FLUSH")
  36. self.request("P2P_GROUP_REMOVE *")
  37. self.request("REMOVE_NETWORK *")
  38. self.request("REMOVE_CRED *")
  39. self.request("SET tdls_disabled 0")
  40. self.request("SET tdls_testing 0")
  41. self.group_ifname = None
  42. def add_network(self):
  43. id = self.request("ADD_NETWORK")
  44. if "FAIL" in id:
  45. raise Exception("ADD_NETWORK failed")
  46. return int(id)
  47. def remove_network(self, id):
  48. id = self.request("REMOVE_NETWORK " + str(id))
  49. if "FAIL" in id:
  50. raise Exception("REMOVE_NETWORK failed")
  51. return None
  52. def set_network(self, id, field, value):
  53. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  54. if "FAIL" in res:
  55. raise Exception("SET_NETWORK failed")
  56. return None
  57. def set_network_quoted(self, id, field, value):
  58. res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  59. if "FAIL" in res:
  60. raise Exception("SET_NETWORK failed")
  61. return None
  62. def select_network(self, id):
  63. id = self.request("SELECT_NETWORK " + str(id))
  64. if "FAIL" in id:
  65. raise Exception("SELECT_NETWORK failed")
  66. return None
  67. def connect_network(self, id):
  68. self.dump_monitor()
  69. self.select_network(id)
  70. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  71. if ev is None:
  72. raise Exception("Association with the AP timed out")
  73. self.dump_monitor()
  74. def get_status(self):
  75. res = self.request("STATUS")
  76. lines = res.splitlines()
  77. vals = dict()
  78. for l in lines:
  79. [name,value] = l.split('=', 1)
  80. vals[name] = value
  81. return vals
  82. def get_status_field(self, field):
  83. vals = self.get_status()
  84. if field in vals:
  85. return vals[field]
  86. return None
  87. def get_group_status(self):
  88. res = self.group_request("STATUS")
  89. lines = res.splitlines()
  90. vals = dict()
  91. for l in lines:
  92. [name,value] = l.split('=', 1)
  93. vals[name] = value
  94. return vals
  95. def get_group_status_field(self, field):
  96. vals = self.get_group_status()
  97. if field in vals:
  98. return vals[field]
  99. return None
  100. def p2p_dev_addr(self):
  101. return self.get_status_field("p2p_device_address")
  102. def p2p_interface_addr(self):
  103. return self.get_group_status_field("address")
  104. def p2p_listen(self):
  105. return self.request("P2P_LISTEN")
  106. def p2p_find(self, social=False):
  107. if social:
  108. return self.request("P2P_FIND type=social")
  109. return self.request("P2P_FIND")
  110. def p2p_stop_find(self):
  111. return self.request("P2P_STOP_FIND")
  112. def wps_read_pin(self):
  113. #TODO: make this random
  114. self.pin = "12345670"
  115. return self.pin
  116. def peer_known(self, peer, full=True):
  117. res = self.request("P2P_PEER " + peer)
  118. if peer.lower() not in res.lower():
  119. return False
  120. if not full:
  121. return True
  122. return "[PROBE_REQ_ONLY]" not in res
  123. def discover_peer(self, peer, full=True, timeout=15, social=True):
  124. logger.info(self.ifname + ": Trying to discover peer " + peer)
  125. if self.peer_known(peer, full):
  126. return True
  127. self.p2p_find(social)
  128. count = 0
  129. while count < timeout:
  130. time.sleep(1)
  131. count = count + 1
  132. if self.peer_known(peer, full):
  133. return True
  134. return False
  135. def group_form_result(self, ev, expect_failure=False):
  136. if expect_failure:
  137. if "P2P-GROUP-STARTED" in ev:
  138. raise Exception("Group formation succeeded when expecting failure")
  139. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  140. s = re.split(exp, ev)
  141. if len(s) < 3:
  142. return None
  143. res = {}
  144. res['result'] = 'go-neg-failed'
  145. res['status'] = int(s[2])
  146. return res
  147. if "P2P-GROUP-STARTED" not in ev:
  148. raise Exception("No P2P-GROUP-STARTED event seen")
  149. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  150. s = re.split(exp, ev)
  151. if len(s) < 8:
  152. raise Exception("Could not parse P2P-GROUP-STARTED")
  153. res = {}
  154. res['result'] = 'success'
  155. res['ifname'] = s[2]
  156. self.group_ifname = s[2]
  157. res['role'] = s[3]
  158. res['ssid'] = s[4]
  159. res['freq'] = s[5]
  160. p = re.match(r'psk=([0-9a-f]*)', s[6])
  161. if p:
  162. res['psk'] = p.group(1)
  163. p = re.match(r'passphrase="(.*)"', s[6])
  164. if p:
  165. res['passphrase'] = p.group(1)
  166. res['go_dev_addr'] = s[7]
  167. return res
  168. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None):
  169. if not self.discover_peer(peer):
  170. raise Exception("Peer " + peer + " not found")
  171. self.dump_monitor()
  172. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  173. if go_intent:
  174. cmd = cmd + ' go_intent=' + str(go_intent)
  175. if "OK" in self.request(cmd):
  176. return None
  177. raise Exception("P2P_CONNECT (auth) failed")
  178. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  179. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout);
  180. if ev is None:
  181. if expect_failure:
  182. return None
  183. raise Exception("Group formation timed out")
  184. self.dump_monitor()
  185. return self.group_form_result(ev, expect_failure)
  186. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False):
  187. if not self.discover_peer(peer):
  188. raise Exception("Peer " + peer + " not found")
  189. self.dump_monitor()
  190. if pin:
  191. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  192. else:
  193. cmd = "P2P_CONNECT " + peer + " " + method
  194. if go_intent:
  195. cmd = cmd + ' go_intent=' + str(go_intent)
  196. if "OK" in self.request(cmd):
  197. if timeout == 0:
  198. self.dump_monitor()
  199. return None
  200. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout)
  201. if ev is None:
  202. if expect_failure:
  203. return None
  204. raise Exception("Group formation timed out")
  205. self.dump_monitor()
  206. return self.group_form_result(ev, expect_failure)
  207. raise Exception("P2P_CONNECT failed")
  208. def wait_event(self, events, timeout):
  209. count = 0
  210. while count < timeout * 10:
  211. count = count + 1
  212. time.sleep(0.1)
  213. while self.mon.pending():
  214. ev = self.mon.recv()
  215. logger.debug(self.ifname + ": " + ev)
  216. for event in events:
  217. if event in ev:
  218. return ev
  219. return None
  220. def dump_monitor(self):
  221. while self.mon.pending():
  222. ev = self.mon.recv()
  223. logger.debug(self.ifname + ": " + ev)
  224. def remove_group(self, ifname=None):
  225. if ifname is None:
  226. ifname = self.group_ifname if self.group_ifname else self.iname
  227. if "OK" not in self.request("P2P_GROUP_REMOVE " + ifname):
  228. raise Exception("Group could not be removed")
  229. self.group_ifname = None
  230. def p2p_start_go(self, persistent=None, freq=None):
  231. self.dump_monitor()
  232. cmd = "P2P_GROUP_ADD"
  233. if persistent is None:
  234. pass
  235. elif persistent is True:
  236. cmd = cmd + " persistent"
  237. else:
  238. cmd = cmd + " persistent=" + str(persistent)
  239. if freq:
  240. cmd = cmd + " freq=" + freq
  241. if "OK" in self.request(cmd):
  242. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout=5)
  243. if ev is None:
  244. raise Exception("GO start up timed out")
  245. self.dump_monitor()
  246. return self.group_form_result(ev)
  247. raise Exception("P2P_GROUP_ADD failed")
  248. def p2p_go_authorize_client(self, pin):
  249. cmd = "WPS_PIN any " + pin
  250. if "FAIL" in self.group_request(cmd):
  251. raise Exception("Failed to authorize client connection on GO")
  252. return None
  253. def p2p_connect_group(self, go_addr, pin, timeout=0):
  254. self.dump_monitor()
  255. if not self.discover_peer(go_addr, social=False):
  256. raise Exception("GO " + go_addr + " not found")
  257. self.dump_monitor()
  258. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  259. if "OK" in self.request(cmd):
  260. if timeout == 0:
  261. self.dump_monitor()
  262. return None
  263. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout)
  264. if ev is None:
  265. raise Exception("Joining the group timed out")
  266. self.dump_monitor()
  267. return self.group_form_result(ev)
  268. raise Exception("P2P_CONNECT(join) failed")
  269. def tdls_setup(self, peer):
  270. cmd = "TDLS_SETUP " + peer
  271. if "FAIL" in self.group_request(cmd):
  272. raise Exception("Failed to request TDLS setup")
  273. return None
  274. def tdls_teardown(self, peer):
  275. cmd = "TDLS_TEARDOWN " + peer
  276. if "FAIL" in self.group_request(cmd):
  277. raise Exception("Failed to request TDLS teardown")
  278. return None
  279. def connect(self, ssid, psk=None, proto=None, key_mgmt=None, wep_key0=None, ieee80211w=None):
  280. logger.info("Connect STA " + self.ifname + " to AP")
  281. id = self.add_network()
  282. self.set_network_quoted(id, "ssid", ssid)
  283. if psk:
  284. self.set_network_quoted(id, "psk", psk)
  285. if proto:
  286. self.set_network(id, "proto", proto)
  287. if key_mgmt:
  288. self.set_network(id, "key_mgmt", key_mgmt)
  289. if ieee80211w:
  290. self.set_network(id, "ieee80211w", ieee80211w)
  291. if wep_key0:
  292. self.set_network(id, "wep_key0", wep_key0)
  293. self.connect_network(id)
  294. def scan(self, type=None):
  295. if type:
  296. cmd = "SCAN TYPE=" + type
  297. else:
  298. cmd = "SCAN"
  299. self.dump_monitor()
  300. if not "OK" in self.request(cmd):
  301. raise Exception("Failed to trigger scan")
  302. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  303. if ev is None:
  304. raise Exception("Scan timed out")
  305. def roam(self, bssid):
  306. self.dump_monitor()
  307. self.request("ROAM " + bssid)
  308. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  309. if ev is None:
  310. raise Exception("Roaming with the AP timed out")
  311. self.dump_monitor()