wpasupplicant.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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, field):
  75. res = self.request("STATUS")
  76. lines = res.splitlines()
  77. for l in lines:
  78. [name,value] = l.split('=', 1)
  79. if name == field:
  80. return value
  81. return None
  82. def get_group_status(self, field):
  83. res = self.group_request("STATUS")
  84. lines = res.splitlines()
  85. for l in lines:
  86. [name,value] = l.split('=', 1)
  87. if name == field:
  88. return value
  89. return None
  90. def p2p_dev_addr(self):
  91. return self.get_status("p2p_device_address")
  92. def p2p_interface_addr(self):
  93. return self.get_group_status("address")
  94. def p2p_listen(self):
  95. return self.request("P2P_LISTEN")
  96. def p2p_find(self, social=False):
  97. if social:
  98. return self.request("P2P_FIND type=social")
  99. return self.request("P2P_FIND")
  100. def p2p_stop_find(self):
  101. return self.request("P2P_STOP_FIND")
  102. def wps_read_pin(self):
  103. #TODO: make this random
  104. self.pin = "12345670"
  105. return self.pin
  106. def peer_known(self, peer, full=True):
  107. res = self.request("P2P_PEER " + peer)
  108. if peer.lower() not in res.lower():
  109. return False
  110. if not full:
  111. return True
  112. return "[PROBE_REQ_ONLY]" not in res
  113. def discover_peer(self, peer, full=True, timeout=15, social=True):
  114. logger.info(self.ifname + ": Trying to discover peer " + peer)
  115. if self.peer_known(peer, full):
  116. return True
  117. self.p2p_find(social)
  118. count = 0
  119. while count < timeout:
  120. time.sleep(1)
  121. count = count + 1
  122. if self.peer_known(peer, full):
  123. return True
  124. return False
  125. def group_form_result(self, ev, expect_failure=False):
  126. if expect_failure:
  127. if "P2P-GROUP-STARTED" in ev:
  128. raise Exception("Group formation succeeded when expecting failure")
  129. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  130. s = re.split(exp, ev)
  131. if len(s) < 3:
  132. return None
  133. res = {}
  134. res['result'] = 'go-neg-failed'
  135. res['status'] = int(s[2])
  136. return res
  137. if "P2P-GROUP-STARTED" not in ev:
  138. raise Exception("No P2P-GROUP-STARTED event seen")
  139. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  140. s = re.split(exp, ev)
  141. if len(s) < 8:
  142. raise Exception("Could not parse P2P-GROUP-STARTED")
  143. res = {}
  144. res['result'] = 'success'
  145. res['ifname'] = s[2]
  146. self.group_ifname = s[2]
  147. res['role'] = s[3]
  148. res['ssid'] = s[4]
  149. res['freq'] = s[5]
  150. p = re.match(r'psk=([0-9a-f]*)', s[6])
  151. if p:
  152. res['psk'] = p.group(1)
  153. p = re.match(r'passphrase="(.*)"', s[6])
  154. if p:
  155. res['passphrase'] = p.group(1)
  156. res['go_dev_addr'] = s[7]
  157. return res
  158. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None):
  159. if not self.discover_peer(peer):
  160. raise Exception("Peer " + peer + " not found")
  161. self.dump_monitor()
  162. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  163. if go_intent:
  164. cmd = cmd + ' go_intent=' + str(go_intent)
  165. if "OK" in self.request(cmd):
  166. return None
  167. raise Exception("P2P_CONNECT (auth) failed")
  168. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  169. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout);
  170. if ev is None:
  171. if expect_failure:
  172. return None
  173. raise Exception("Group formation timed out")
  174. self.dump_monitor()
  175. return self.group_form_result(ev, expect_failure)
  176. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False):
  177. if not self.discover_peer(peer):
  178. raise Exception("Peer " + peer + " not found")
  179. self.dump_monitor()
  180. if pin:
  181. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  182. else:
  183. cmd = "P2P_CONNECT " + peer + " " + method
  184. if go_intent:
  185. cmd = cmd + ' go_intent=' + str(go_intent)
  186. if "OK" in self.request(cmd):
  187. if timeout == 0:
  188. self.dump_monitor()
  189. return None
  190. ev = self.wait_event(["P2P-GROUP-STARTED","P2P-GO-NEG-FAILURE"], timeout)
  191. if ev is None:
  192. if expect_failure:
  193. return None
  194. raise Exception("Group formation timed out")
  195. self.dump_monitor()
  196. return self.group_form_result(ev, expect_failure)
  197. raise Exception("P2P_CONNECT failed")
  198. def wait_event(self, events, timeout):
  199. count = 0
  200. while count < timeout * 10:
  201. count = count + 1
  202. time.sleep(0.1)
  203. while self.mon.pending():
  204. ev = self.mon.recv()
  205. logger.debug(self.ifname + ": " + ev)
  206. for event in events:
  207. if event in ev:
  208. return ev
  209. return None
  210. def dump_monitor(self):
  211. while self.mon.pending():
  212. ev = self.mon.recv()
  213. logger.debug(self.ifname + ": " + ev)
  214. def remove_group(self, ifname=None):
  215. if ifname is None:
  216. ifname = self.group_ifname if self.group_ifname else self.iname
  217. if "OK" not in self.request("P2P_GROUP_REMOVE " + ifname):
  218. raise Exception("Group could not be removed")
  219. self.group_ifname = None
  220. def p2p_start_go(self, persistent=None):
  221. self.dump_monitor()
  222. cmd = "P2P_GROUP_ADD"
  223. if persistent is None:
  224. pass
  225. elif persistent is True:
  226. cmd = cmd + " persistent"
  227. else:
  228. cmd = cmd + " persistent=" + str(persistent)
  229. if "OK" in self.request(cmd):
  230. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout=5)
  231. if ev is None:
  232. raise Exception("GO start up timed out")
  233. self.dump_monitor()
  234. return self.group_form_result(ev)
  235. raise Exception("P2P_GROUP_ADD failed")
  236. def p2p_go_authorize_client(self, pin):
  237. cmd = "WPS_PIN any " + pin
  238. if "FAIL" in self.group_request(cmd):
  239. raise Exception("Failed to authorize client connection on GO")
  240. return None
  241. def p2p_connect_group(self, go_addr, pin, timeout=0):
  242. self.dump_monitor()
  243. if not self.discover_peer(go_addr, social=False):
  244. raise Exception("GO " + go_addr + " not found")
  245. self.dump_monitor()
  246. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  247. if "OK" in self.request(cmd):
  248. if timeout == 0:
  249. self.dump_monitor()
  250. return None
  251. ev = self.wait_event(["P2P-GROUP-STARTED"], timeout)
  252. if ev is None:
  253. raise Exception("Joining the group timed out")
  254. self.dump_monitor()
  255. return self.group_form_result(ev)
  256. raise Exception("P2P_CONNECT(join) failed")
  257. def tdls_setup(self, peer):
  258. cmd = "TDLS_SETUP " + peer
  259. if "FAIL" in self.group_request(cmd):
  260. raise Exception("Failed to request TDLS setup")
  261. return None
  262. def tdls_teardown(self, peer):
  263. cmd = "TDLS_TEARDOWN " + peer
  264. if "FAIL" in self.group_request(cmd):
  265. raise Exception("Failed to request TDLS teardown")
  266. return None
  267. def connect(self, ssid, psk=None, proto=None, key_mgmt=None, wep_key0=None):
  268. logger.info("Connect STA " + self.ifname + " to AP")
  269. id = self.add_network()
  270. self.set_network_quoted(id, "ssid", ssid)
  271. if psk:
  272. self.set_network_quoted(id, "psk", psk)
  273. if proto:
  274. self.set_network(id, "proto", proto)
  275. if key_mgmt:
  276. self.set_network(id, "key_mgmt", key_mgmt)
  277. if wep_key0:
  278. self.set_network(id, "wep_key0", wep_key0)
  279. self.connect_network(id)