wpasupplicant.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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 subprocess
  13. import wpaspy
  14. logger = logging.getLogger()
  15. wpas_ctrl = '/var/run/wpa_supplicant'
  16. class WpaSupplicant:
  17. def __init__(self, ifname, global_iface=None):
  18. self.ifname = ifname
  19. self.group_ifname = None
  20. self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  21. self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
  22. self.mon.attach()
  23. self.global_iface = global_iface
  24. if global_iface:
  25. self.global_ctrl = wpaspy.Ctrl(global_iface)
  26. self.global_mon = wpaspy.Ctrl(global_iface)
  27. self.global_mon.attach()
  28. def request(self, cmd):
  29. logger.debug(self.ifname + ": CTRL: " + cmd)
  30. return self.ctrl.request(cmd)
  31. def global_request(self, cmd):
  32. if self.global_iface is None:
  33. self.request(cmd)
  34. else:
  35. logger.debug(self.ifname + ": CTRL: " + cmd)
  36. return self.global_ctrl.request(cmd)
  37. def group_request(self, cmd):
  38. if self.group_ifname and self.group_ifname != self.ifname:
  39. logger.debug(self.group_ifname + ": CTRL: " + cmd)
  40. gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
  41. return gctrl.request(cmd)
  42. return self.request(cmd)
  43. def ping(self):
  44. return "PONG" in self.request("PING")
  45. def reset(self):
  46. res = self.request("FLUSH")
  47. if not "OK" in res:
  48. logger.info("FLUSH to " + self.ifname + " failed: " + res)
  49. self.request("SET ignore_old_scan_res 0")
  50. self.request("SET external_sim 0")
  51. self.request("SET p2p_add_cli_chan 0")
  52. self.request("SET p2p_no_go_freq ")
  53. self.request("SET p2p_pref_chan ")
  54. self.request("P2P_SET per_sta_psk 0")
  55. self.request("P2P_SET disabled 0")
  56. self.request("P2P_SERVICE_FLUSH")
  57. self.group_ifname = None
  58. self.dump_monitor()
  59. iter = 0
  60. while iter < 60:
  61. state = self.get_driver_status_field("scan_state")
  62. if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
  63. logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
  64. time.sleep(1)
  65. else:
  66. break
  67. iter = iter + 1
  68. if iter == 60:
  69. logger.error(self.ifname + ": Driver scan state did not clear")
  70. print "Trying to clear cfg80211/mac80211 scan state"
  71. try:
  72. cmd = ["sudo", "ifconfig", self.ifname, "down"]
  73. subprocess.call(cmd)
  74. except subprocess.CalledProcessError, e:
  75. logger.info("ifconfig failed: " + str(e.returncode))
  76. logger.info(e.output)
  77. try:
  78. cmd = ["sudo", "ifconfig", self.ifname, "up"]
  79. subprocess.call(cmd)
  80. except subprocess.CalledProcessError, e:
  81. logger.info("ifconfig failed: " + str(e.returncode))
  82. logger.info(e.output)
  83. if not self.ping():
  84. logger.info("No PING response from " + self.ifname + " after reset")
  85. def add_network(self):
  86. id = self.request("ADD_NETWORK")
  87. if "FAIL" in id:
  88. raise Exception("ADD_NETWORK failed")
  89. return int(id)
  90. def remove_network(self, id):
  91. id = self.request("REMOVE_NETWORK " + str(id))
  92. if "FAIL" in id:
  93. raise Exception("REMOVE_NETWORK failed")
  94. return None
  95. def set_network(self, id, field, value):
  96. res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
  97. if "FAIL" in res:
  98. raise Exception("SET_NETWORK failed")
  99. return None
  100. def set_network_quoted(self, id, field, value):
  101. res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
  102. if "FAIL" in res:
  103. raise Exception("SET_NETWORK failed")
  104. return None
  105. def hs20_enable(self):
  106. self.request("SET interworking 1")
  107. self.request("SET hs20 1")
  108. def add_cred(self):
  109. id = self.request("ADD_CRED")
  110. if "FAIL" in id:
  111. raise Exception("ADD_CRED failed")
  112. return int(id)
  113. def remove_cred(self, id):
  114. id = self.request("REMOVE_CRED " + str(id))
  115. if "FAIL" in id:
  116. raise Exception("REMOVE_CRED failed")
  117. return None
  118. def set_cred(self, id, field, value):
  119. res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
  120. if "FAIL" in res:
  121. raise Exception("SET_CRED failed")
  122. return None
  123. def set_cred_quoted(self, id, field, value):
  124. res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
  125. if "FAIL" in res:
  126. raise Exception("SET_CRED failed")
  127. return None
  128. def add_cred_values(self, params):
  129. id = self.add_cred()
  130. quoted = [ "realm", "username", "password", "domain", "imsi",
  131. "excluded_ssid" ]
  132. for field in quoted:
  133. if field in params:
  134. self.set_cred_quoted(id, field, params[field])
  135. not_quoted = [ "eap", "required_roaming_consortium" ]
  136. for field in not_quoted:
  137. if field in params:
  138. self.set_cred(id, field, params[field])
  139. return id;
  140. def select_network(self, id):
  141. id = self.request("SELECT_NETWORK " + str(id))
  142. if "FAIL" in id:
  143. raise Exception("SELECT_NETWORK failed")
  144. return None
  145. def connect_network(self, id):
  146. self.dump_monitor()
  147. self.select_network(id)
  148. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  149. if ev is None:
  150. raise Exception("Association with the AP timed out")
  151. self.dump_monitor()
  152. def get_status(self):
  153. res = self.request("STATUS")
  154. lines = res.splitlines()
  155. vals = dict()
  156. for l in lines:
  157. [name,value] = l.split('=', 1)
  158. vals[name] = value
  159. return vals
  160. def get_status_field(self, field):
  161. vals = self.get_status()
  162. if field in vals:
  163. return vals[field]
  164. return None
  165. def get_group_status(self):
  166. res = self.group_request("STATUS")
  167. lines = res.splitlines()
  168. vals = dict()
  169. for l in lines:
  170. [name,value] = l.split('=', 1)
  171. vals[name] = value
  172. return vals
  173. def get_group_status_field(self, field):
  174. vals = self.get_group_status()
  175. if field in vals:
  176. return vals[field]
  177. return None
  178. def get_driver_status(self):
  179. res = self.request("STATUS-DRIVER")
  180. lines = res.splitlines()
  181. vals = dict()
  182. for l in lines:
  183. [name,value] = l.split('=', 1)
  184. vals[name] = value
  185. return vals
  186. def get_driver_status_field(self, field):
  187. vals = self.get_driver_status()
  188. if field in vals:
  189. return vals[field]
  190. return None
  191. def p2p_dev_addr(self):
  192. return self.get_status_field("p2p_device_address")
  193. def p2p_interface_addr(self):
  194. return self.get_group_status_field("address")
  195. def p2p_listen(self):
  196. return self.global_request("P2P_LISTEN")
  197. def p2p_find(self, social=False):
  198. if social:
  199. return self.global_request("P2P_FIND type=social")
  200. return self.global_request("P2P_FIND")
  201. def p2p_stop_find(self):
  202. return self.global_request("P2P_STOP_FIND")
  203. def wps_read_pin(self):
  204. #TODO: make this random
  205. self.pin = "12345670"
  206. return self.pin
  207. def peer_known(self, peer, full=True):
  208. res = self.global_request("P2P_PEER " + peer)
  209. if peer.lower() not in res.lower():
  210. return False
  211. if not full:
  212. return True
  213. return "[PROBE_REQ_ONLY]" not in res
  214. def discover_peer(self, peer, full=True, timeout=15, social=True):
  215. logger.info(self.ifname + ": Trying to discover peer " + peer)
  216. if self.peer_known(peer, full):
  217. return True
  218. self.p2p_find(social)
  219. count = 0
  220. while count < timeout:
  221. time.sleep(1)
  222. count = count + 1
  223. if self.peer_known(peer, full):
  224. return True
  225. return False
  226. def get_peer(self, peer):
  227. res = self.global_request("P2P_PEER " + peer)
  228. if peer.lower() not in res.lower():
  229. raise Exception("Peer information not available")
  230. lines = res.splitlines()
  231. vals = dict()
  232. for l in lines:
  233. if '=' in l:
  234. [name,value] = l.split('=', 1)
  235. vals[name] = value
  236. return vals
  237. def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
  238. if expect_failure:
  239. if "P2P-GROUP-STARTED" in ev:
  240. raise Exception("Group formation succeeded when expecting failure")
  241. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  242. s = re.split(exp, ev)
  243. if len(s) < 3:
  244. return None
  245. res = {}
  246. res['result'] = 'go-neg-failed'
  247. res['status'] = int(s[2])
  248. return res
  249. if "P2P-GROUP-STARTED" not in ev:
  250. raise Exception("No P2P-GROUP-STARTED event seen")
  251. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  252. s = re.split(exp, ev)
  253. if len(s) < 8:
  254. raise Exception("Could not parse P2P-GROUP-STARTED")
  255. res = {}
  256. res['result'] = 'success'
  257. res['ifname'] = s[2]
  258. self.group_ifname = s[2]
  259. res['role'] = s[3]
  260. res['ssid'] = s[4]
  261. res['freq'] = s[5]
  262. if "[PERSISTENT]" in ev:
  263. res['persistent'] = True
  264. else:
  265. res['persistent'] = False
  266. p = re.match(r'psk=([0-9a-f]*)', s[6])
  267. if p:
  268. res['psk'] = p.group(1)
  269. p = re.match(r'passphrase="(.*)"', s[6])
  270. if p:
  271. res['passphrase'] = p.group(1)
  272. res['go_dev_addr'] = s[7]
  273. if go_neg_res:
  274. exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
  275. s = re.split(exp, go_neg_res)
  276. if len(s) < 4:
  277. raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
  278. res['go_neg_role'] = s[2]
  279. res['go_neg_freq'] = s[3]
  280. return res
  281. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
  282. if not self.discover_peer(peer):
  283. raise Exception("Peer " + peer + " not found")
  284. self.dump_monitor()
  285. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  286. if go_intent:
  287. cmd = cmd + ' go_intent=' + str(go_intent)
  288. if freq:
  289. cmd = cmd + ' freq=' + str(freq)
  290. if persistent:
  291. cmd = cmd + " persistent"
  292. if "OK" in self.global_request(cmd):
  293. return None
  294. raise Exception("P2P_CONNECT (auth) failed")
  295. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  296. go_neg_res = None
  297. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  298. "P2P-GO-NEG-FAILURE"], timeout);
  299. if ev is None:
  300. if expect_failure:
  301. return None
  302. raise Exception("Group formation timed out")
  303. if "P2P-GO-NEG-SUCCESS" in ev:
  304. go_neg_res = ev
  305. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
  306. if ev is None:
  307. if expect_failure:
  308. return None
  309. raise Exception("Group formation timed out")
  310. self.dump_monitor()
  311. return self.group_form_result(ev, expect_failure, go_neg_res)
  312. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False, persistent=False, freq=None):
  313. if not self.discover_peer(peer):
  314. raise Exception("Peer " + peer + " not found")
  315. self.dump_monitor()
  316. if pin:
  317. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  318. else:
  319. cmd = "P2P_CONNECT " + peer + " " + method
  320. if go_intent:
  321. cmd = cmd + ' go_intent=' + str(go_intent)
  322. if freq:
  323. cmd = cmd + ' freq=' + str(freq)
  324. if persistent:
  325. cmd = cmd + " persistent"
  326. if "OK" in self.global_request(cmd):
  327. if timeout == 0:
  328. self.dump_monitor()
  329. return None
  330. go_neg_res = None
  331. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  332. "P2P-GO-NEG-FAILURE"], timeout)
  333. if ev is None:
  334. if expect_failure:
  335. return None
  336. raise Exception("Group formation timed out")
  337. if "P2P-GO-NEG-SUCCESS" in ev:
  338. go_neg_res = ev
  339. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  340. if ev is None:
  341. if expect_failure:
  342. return None
  343. raise Exception("Group formation timed out")
  344. self.dump_monitor()
  345. return self.group_form_result(ev, expect_failure, go_neg_res)
  346. raise Exception("P2P_CONNECT failed")
  347. def wait_event(self, events, timeout):
  348. count = 0
  349. while count < timeout * 10:
  350. count = count + 1
  351. time.sleep(0.1)
  352. while self.mon.pending():
  353. ev = self.mon.recv()
  354. logger.debug(self.ifname + ": " + ev)
  355. for event in events:
  356. if event in ev:
  357. return ev
  358. return None
  359. def wait_global_event(self, events, timeout):
  360. if self.global_iface is None:
  361. self.wait_event(events, timeout)
  362. else:
  363. count = 0
  364. while count < timeout * 10:
  365. count = count + 1
  366. time.sleep(0.1)
  367. while self.global_mon.pending():
  368. ev = self.global_mon.recv()
  369. logger.debug(self.ifname + "(global): " + ev)
  370. for event in events:
  371. if event in ev:
  372. return ev
  373. return None
  374. def wait_go_ending_session(self):
  375. ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
  376. if ev is None:
  377. raise Exception("Group removal event timed out")
  378. if "reason=GO_ENDING_SESSION" not in ev:
  379. raise Exception("Unexpected group removal reason")
  380. def dump_monitor(self):
  381. while self.mon.pending():
  382. ev = self.mon.recv()
  383. logger.debug(self.ifname + ": " + ev)
  384. while self.global_mon.pending():
  385. ev = self.global_mon.recv()
  386. logger.debug(self.ifname + "(global): " + ev)
  387. def remove_group(self, ifname=None):
  388. if ifname is None:
  389. ifname = self.group_ifname if self.group_ifname else self.ifname
  390. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  391. raise Exception("Group could not be removed")
  392. self.group_ifname = None
  393. def p2p_start_go(self, persistent=None, freq=None):
  394. self.dump_monitor()
  395. cmd = "P2P_GROUP_ADD"
  396. if persistent is None:
  397. pass
  398. elif persistent is True:
  399. cmd = cmd + " persistent"
  400. else:
  401. cmd = cmd + " persistent=" + str(persistent)
  402. if freq:
  403. cmd = cmd + " freq=" + str(freq)
  404. if "OK" in self.global_request(cmd):
  405. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  406. if ev is None:
  407. raise Exception("GO start up timed out")
  408. self.dump_monitor()
  409. return self.group_form_result(ev)
  410. raise Exception("P2P_GROUP_ADD failed")
  411. def p2p_go_authorize_client(self, pin):
  412. cmd = "WPS_PIN any " + pin
  413. if "FAIL" in self.group_request(cmd):
  414. raise Exception("Failed to authorize client connection on GO")
  415. return None
  416. def p2p_go_authorize_client_pbc(self):
  417. cmd = "WPS_PBC"
  418. if "FAIL" in self.group_request(cmd):
  419. raise Exception("Failed to authorize client connection on GO")
  420. return None
  421. def p2p_connect_group(self, go_addr, pin, timeout=0):
  422. self.dump_monitor()
  423. if not self.discover_peer(go_addr, social=False):
  424. raise Exception("GO " + go_addr + " not found")
  425. self.dump_monitor()
  426. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  427. if "OK" in self.global_request(cmd):
  428. if timeout == 0:
  429. self.dump_monitor()
  430. return None
  431. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  432. if ev is None:
  433. raise Exception("Joining the group timed out")
  434. self.dump_monitor()
  435. return self.group_form_result(ev)
  436. raise Exception("P2P_CONNECT(join) failed")
  437. def tdls_setup(self, peer):
  438. cmd = "TDLS_SETUP " + peer
  439. if "FAIL" in self.group_request(cmd):
  440. raise Exception("Failed to request TDLS setup")
  441. return None
  442. def tdls_teardown(self, peer):
  443. cmd = "TDLS_TEARDOWN " + peer
  444. if "FAIL" in self.group_request(cmd):
  445. raise Exception("Failed to request TDLS teardown")
  446. return None
  447. def connect(self, ssid, psk=None, proto=None, key_mgmt=None, wep_key0=None,
  448. ieee80211w=None, pairwise=None, group=None, scan_freq=None,
  449. eap=None, identity=None, anonymous_identity=None,
  450. password=None, phase1=None, phase2=None, ca_cert=None,
  451. domain_suffix_match=None, password_hex=None,
  452. client_cert=None, private_key=None,
  453. wait_connect=True):
  454. logger.info("Connect STA " + self.ifname + " to AP")
  455. id = self.add_network()
  456. self.set_network_quoted(id, "ssid", ssid)
  457. if psk:
  458. self.set_network_quoted(id, "psk", psk)
  459. if proto:
  460. self.set_network(id, "proto", proto)
  461. if key_mgmt:
  462. self.set_network(id, "key_mgmt", key_mgmt)
  463. if ieee80211w:
  464. self.set_network(id, "ieee80211w", ieee80211w)
  465. if pairwise:
  466. self.set_network(id, "pairwise", pairwise)
  467. if group:
  468. self.set_network(id, "group", group)
  469. if wep_key0:
  470. self.set_network(id, "wep_key0", wep_key0)
  471. if scan_freq:
  472. self.set_network(id, "scan_freq", scan_freq)
  473. if eap:
  474. self.set_network(id, "eap", eap)
  475. if identity:
  476. self.set_network_quoted(id, "identity", identity)
  477. if anonymous_identity:
  478. self.set_network_quoted(id, "anonymous_identity",
  479. anonymous_identity)
  480. if password:
  481. self.set_network_quoted(id, "password", password)
  482. if password_hex:
  483. self.set_network(id, "password", password_hex)
  484. if ca_cert:
  485. self.set_network_quoted(id, "ca_cert", ca_cert)
  486. if client_cert:
  487. self.set_network_quoted(id, "client_cert", client_cert)
  488. if private_key:
  489. self.set_network_quoted(id, "private_key", private_key)
  490. if phase1:
  491. self.set_network_quoted(id, "phase1", phase1)
  492. if phase2:
  493. self.set_network_quoted(id, "phase2", phase2)
  494. if domain_suffix_match:
  495. self.set_network_quoted(id, "domain_suffix_match",
  496. domain_suffix_match)
  497. if wait_connect:
  498. self.connect_network(id)
  499. else:
  500. self.dump_monitor()
  501. self.select_network(id)
  502. return id
  503. def scan(self, type=None):
  504. if type:
  505. cmd = "SCAN TYPE=" + type
  506. else:
  507. cmd = "SCAN"
  508. self.dump_monitor()
  509. if not "OK" in self.request(cmd):
  510. raise Exception("Failed to trigger scan")
  511. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  512. if ev is None:
  513. raise Exception("Scan timed out")
  514. def roam(self, bssid):
  515. self.dump_monitor()
  516. self.request("ROAM " + bssid)
  517. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  518. if ev is None:
  519. raise Exception("Roaming with the AP timed out")
  520. self.dump_monitor()
  521. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  522. new_passphrase=None):
  523. self.dump_monitor()
  524. if new_ssid:
  525. self.request("WPS_REG " + bssid + " " + pin + " " +
  526. new_ssid.encode("hex") + " " + key_mgmt + " " +
  527. cipher + " " + new_passphrase.encode("hex"))
  528. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  529. else:
  530. self.request("WPS_REG " + bssid + " " + pin)
  531. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  532. if ev is None:
  533. raise Exception("WPS cred timed out")
  534. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  535. if ev is None:
  536. raise Exception("WPS timed out")
  537. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  538. if ev is None:
  539. raise Exception("Association with the AP timed out")
  540. def relog(self):
  541. self.request("RELOG")