wpasupplicant.py 14 KB

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