wpasupplicant.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. for field in quoted:
  132. if field in params:
  133. self.set_cred_quoted(id, field, params[field])
  134. not_quoted = [ "eap" ]
  135. for field in not_quoted:
  136. if field in params:
  137. self.set_cred(id, field, params[field])
  138. return id;
  139. def select_network(self, id):
  140. id = self.request("SELECT_NETWORK " + str(id))
  141. if "FAIL" in id:
  142. raise Exception("SELECT_NETWORK failed")
  143. return None
  144. def connect_network(self, id):
  145. self.dump_monitor()
  146. self.select_network(id)
  147. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  148. if ev is None:
  149. raise Exception("Association with the AP timed out")
  150. self.dump_monitor()
  151. def get_status(self):
  152. res = self.request("STATUS")
  153. lines = res.splitlines()
  154. vals = dict()
  155. for l in lines:
  156. [name,value] = l.split('=', 1)
  157. vals[name] = value
  158. return vals
  159. def get_status_field(self, field):
  160. vals = self.get_status()
  161. if field in vals:
  162. return vals[field]
  163. return None
  164. def get_group_status(self):
  165. res = self.group_request("STATUS")
  166. lines = res.splitlines()
  167. vals = dict()
  168. for l in lines:
  169. [name,value] = l.split('=', 1)
  170. vals[name] = value
  171. return vals
  172. def get_group_status_field(self, field):
  173. vals = self.get_group_status()
  174. if field in vals:
  175. return vals[field]
  176. return None
  177. def get_driver_status(self):
  178. res = self.request("STATUS-DRIVER")
  179. lines = res.splitlines()
  180. vals = dict()
  181. for l in lines:
  182. [name,value] = l.split('=', 1)
  183. vals[name] = value
  184. return vals
  185. def get_driver_status_field(self, field):
  186. vals = self.get_driver_status()
  187. if field in vals:
  188. return vals[field]
  189. return None
  190. def p2p_dev_addr(self):
  191. return self.get_status_field("p2p_device_address")
  192. def p2p_interface_addr(self):
  193. return self.get_group_status_field("address")
  194. def p2p_listen(self):
  195. return self.global_request("P2P_LISTEN")
  196. def p2p_find(self, social=False):
  197. if social:
  198. return self.global_request("P2P_FIND type=social")
  199. return self.global_request("P2P_FIND")
  200. def p2p_stop_find(self):
  201. return self.global_request("P2P_STOP_FIND")
  202. def wps_read_pin(self):
  203. #TODO: make this random
  204. self.pin = "12345670"
  205. return self.pin
  206. def peer_known(self, peer, full=True):
  207. res = self.global_request("P2P_PEER " + peer)
  208. if peer.lower() not in res.lower():
  209. return False
  210. if not full:
  211. return True
  212. return "[PROBE_REQ_ONLY]" not in res
  213. def discover_peer(self, peer, full=True, timeout=15, social=True):
  214. logger.info(self.ifname + ": Trying to discover peer " + peer)
  215. if self.peer_known(peer, full):
  216. return True
  217. self.p2p_find(social)
  218. count = 0
  219. while count < timeout:
  220. time.sleep(1)
  221. count = count + 1
  222. if self.peer_known(peer, full):
  223. return True
  224. return False
  225. def get_peer(self, peer):
  226. res = self.global_request("P2P_PEER " + peer)
  227. if peer.lower() not in res.lower():
  228. raise Exception("Peer information not available")
  229. lines = res.splitlines()
  230. vals = dict()
  231. for l in lines:
  232. if '=' in l:
  233. [name,value] = l.split('=', 1)
  234. vals[name] = value
  235. return vals
  236. def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
  237. if expect_failure:
  238. if "P2P-GROUP-STARTED" in ev:
  239. raise Exception("Group formation succeeded when expecting failure")
  240. exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
  241. s = re.split(exp, ev)
  242. if len(s) < 3:
  243. return None
  244. res = {}
  245. res['result'] = 'go-neg-failed'
  246. res['status'] = int(s[2])
  247. return res
  248. if "P2P-GROUP-STARTED" not in ev:
  249. raise Exception("No P2P-GROUP-STARTED event seen")
  250. exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
  251. s = re.split(exp, ev)
  252. if len(s) < 8:
  253. raise Exception("Could not parse P2P-GROUP-STARTED")
  254. res = {}
  255. res['result'] = 'success'
  256. res['ifname'] = s[2]
  257. self.group_ifname = s[2]
  258. res['role'] = s[3]
  259. res['ssid'] = s[4]
  260. res['freq'] = s[5]
  261. if "[PERSISTENT]" in ev:
  262. res['persistent'] = True
  263. else:
  264. res['persistent'] = False
  265. p = re.match(r'psk=([0-9a-f]*)', s[6])
  266. if p:
  267. res['psk'] = p.group(1)
  268. p = re.match(r'passphrase="(.*)"', s[6])
  269. if p:
  270. res['passphrase'] = p.group(1)
  271. res['go_dev_addr'] = s[7]
  272. if go_neg_res:
  273. exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
  274. s = re.split(exp, go_neg_res)
  275. if len(s) < 4:
  276. raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
  277. res['go_neg_role'] = s[2]
  278. res['go_neg_freq'] = s[3]
  279. return res
  280. def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
  281. if not self.discover_peer(peer):
  282. raise Exception("Peer " + peer + " not found")
  283. self.dump_monitor()
  284. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
  285. if go_intent:
  286. cmd = cmd + ' go_intent=' + str(go_intent)
  287. if freq:
  288. cmd = cmd + ' freq=' + str(freq)
  289. if persistent:
  290. cmd = cmd + " persistent"
  291. if "OK" in self.global_request(cmd):
  292. return None
  293. raise Exception("P2P_CONNECT (auth) failed")
  294. def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
  295. go_neg_res = None
  296. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  297. "P2P-GO-NEG-FAILURE"], timeout);
  298. if ev is None:
  299. if expect_failure:
  300. return None
  301. raise Exception("Group formation timed out")
  302. if "P2P-GO-NEG-SUCCESS" in ev:
  303. go_neg_res = ev
  304. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
  305. if ev is None:
  306. if expect_failure:
  307. return None
  308. raise Exception("Group formation timed out")
  309. self.dump_monitor()
  310. return self.group_form_result(ev, expect_failure, go_neg_res)
  311. def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False, persistent=False, freq=None):
  312. if not self.discover_peer(peer):
  313. raise Exception("Peer " + peer + " not found")
  314. self.dump_monitor()
  315. if pin:
  316. cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
  317. else:
  318. cmd = "P2P_CONNECT " + peer + " " + method
  319. if go_intent:
  320. cmd = cmd + ' go_intent=' + str(go_intent)
  321. if freq:
  322. cmd = cmd + ' freq=' + str(freq)
  323. if persistent:
  324. cmd = cmd + " persistent"
  325. if "OK" in self.global_request(cmd):
  326. if timeout == 0:
  327. self.dump_monitor()
  328. return None
  329. go_neg_res = None
  330. ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
  331. "P2P-GO-NEG-FAILURE"], timeout)
  332. if ev is None:
  333. if expect_failure:
  334. return None
  335. raise Exception("Group formation timed out")
  336. if "P2P-GO-NEG-SUCCESS" in ev:
  337. go_neg_res = ev
  338. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  339. if ev is None:
  340. if expect_failure:
  341. return None
  342. raise Exception("Group formation timed out")
  343. self.dump_monitor()
  344. return self.group_form_result(ev, expect_failure, go_neg_res)
  345. raise Exception("P2P_CONNECT failed")
  346. def wait_event(self, events, timeout):
  347. count = 0
  348. while count < timeout * 10:
  349. count = count + 1
  350. time.sleep(0.1)
  351. while self.mon.pending():
  352. ev = self.mon.recv()
  353. logger.debug(self.ifname + ": " + ev)
  354. for event in events:
  355. if event in ev:
  356. return ev
  357. return None
  358. def wait_global_event(self, events, timeout):
  359. if self.global_iface is None:
  360. self.wait_event(events, timeout)
  361. else:
  362. count = 0
  363. while count < timeout * 10:
  364. count = count + 1
  365. time.sleep(0.1)
  366. while self.global_mon.pending():
  367. ev = self.global_mon.recv()
  368. logger.debug(self.ifname + "(global): " + ev)
  369. for event in events:
  370. if event in ev:
  371. return ev
  372. return None
  373. def wait_go_ending_session(self):
  374. ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
  375. if ev is None:
  376. raise Exception("Group removal event timed out")
  377. if "reason=GO_ENDING_SESSION" not in ev:
  378. raise Exception("Unexpected group removal reason")
  379. def dump_monitor(self):
  380. while self.mon.pending():
  381. ev = self.mon.recv()
  382. logger.debug(self.ifname + ": " + ev)
  383. while self.global_mon.pending():
  384. ev = self.global_mon.recv()
  385. logger.debug(self.ifname + "(global): " + ev)
  386. def remove_group(self, ifname=None):
  387. if ifname is None:
  388. ifname = self.group_ifname if self.group_ifname else self.ifname
  389. if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
  390. raise Exception("Group could not be removed")
  391. self.group_ifname = None
  392. def p2p_start_go(self, persistent=None, freq=None):
  393. self.dump_monitor()
  394. cmd = "P2P_GROUP_ADD"
  395. if persistent is None:
  396. pass
  397. elif persistent is True:
  398. cmd = cmd + " persistent"
  399. else:
  400. cmd = cmd + " persistent=" + str(persistent)
  401. if freq:
  402. cmd = cmd + " freq=" + str(freq)
  403. if "OK" in self.global_request(cmd):
  404. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
  405. if ev is None:
  406. raise Exception("GO start up timed out")
  407. self.dump_monitor()
  408. return self.group_form_result(ev)
  409. raise Exception("P2P_GROUP_ADD failed")
  410. def p2p_go_authorize_client(self, pin):
  411. cmd = "WPS_PIN any " + pin
  412. if "FAIL" in self.group_request(cmd):
  413. raise Exception("Failed to authorize client connection on GO")
  414. return None
  415. def p2p_go_authorize_client_pbc(self):
  416. cmd = "WPS_PBC"
  417. if "FAIL" in self.group_request(cmd):
  418. raise Exception("Failed to authorize client connection on GO")
  419. return None
  420. def p2p_connect_group(self, go_addr, pin, timeout=0):
  421. self.dump_monitor()
  422. if not self.discover_peer(go_addr, social=False):
  423. raise Exception("GO " + go_addr + " not found")
  424. self.dump_monitor()
  425. cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
  426. if "OK" in self.global_request(cmd):
  427. if timeout == 0:
  428. self.dump_monitor()
  429. return None
  430. ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
  431. if ev is None:
  432. raise Exception("Joining the group timed out")
  433. self.dump_monitor()
  434. return self.group_form_result(ev)
  435. raise Exception("P2P_CONNECT(join) failed")
  436. def tdls_setup(self, peer):
  437. cmd = "TDLS_SETUP " + peer
  438. if "FAIL" in self.group_request(cmd):
  439. raise Exception("Failed to request TDLS setup")
  440. return None
  441. def tdls_teardown(self, peer):
  442. cmd = "TDLS_TEARDOWN " + peer
  443. if "FAIL" in self.group_request(cmd):
  444. raise Exception("Failed to request TDLS teardown")
  445. return None
  446. def connect(self, ssid, psk=None, proto=None, key_mgmt=None, wep_key0=None,
  447. ieee80211w=None, pairwise=None, group=None, scan_freq=None,
  448. eap=None, identity=None, anonymous_identity=None,
  449. password=None, phase1=None, phase2=None, ca_cert=None,
  450. domain_suffix_match=None, password_hex=None,
  451. client_cert=None, private_key=None,
  452. wait_connect=True):
  453. logger.info("Connect STA " + self.ifname + " to AP")
  454. id = self.add_network()
  455. self.set_network_quoted(id, "ssid", ssid)
  456. if psk:
  457. self.set_network_quoted(id, "psk", psk)
  458. if proto:
  459. self.set_network(id, "proto", proto)
  460. if key_mgmt:
  461. self.set_network(id, "key_mgmt", key_mgmt)
  462. if ieee80211w:
  463. self.set_network(id, "ieee80211w", ieee80211w)
  464. if pairwise:
  465. self.set_network(id, "pairwise", pairwise)
  466. if group:
  467. self.set_network(id, "group", group)
  468. if wep_key0:
  469. self.set_network(id, "wep_key0", wep_key0)
  470. if scan_freq:
  471. self.set_network(id, "scan_freq", scan_freq)
  472. if eap:
  473. self.set_network(id, "eap", eap)
  474. if identity:
  475. self.set_network_quoted(id, "identity", identity)
  476. if anonymous_identity:
  477. self.set_network_quoted(id, "anonymous_identity",
  478. anonymous_identity)
  479. if password:
  480. self.set_network_quoted(id, "password", password)
  481. if password_hex:
  482. self.set_network(id, "password", password_hex)
  483. if ca_cert:
  484. self.set_network_quoted(id, "ca_cert", ca_cert)
  485. if client_cert:
  486. self.set_network_quoted(id, "client_cert", client_cert)
  487. if private_key:
  488. self.set_network_quoted(id, "private_key", private_key)
  489. if phase1:
  490. self.set_network_quoted(id, "phase1", phase1)
  491. if phase2:
  492. self.set_network_quoted(id, "phase2", phase2)
  493. if domain_suffix_match:
  494. self.set_network_quoted(id, "domain_suffix_match",
  495. domain_suffix_match)
  496. if wait_connect:
  497. self.connect_network(id)
  498. else:
  499. self.dump_monitor()
  500. self.select_network(id)
  501. return id
  502. def scan(self, type=None):
  503. if type:
  504. cmd = "SCAN TYPE=" + type
  505. else:
  506. cmd = "SCAN"
  507. self.dump_monitor()
  508. if not "OK" in self.request(cmd):
  509. raise Exception("Failed to trigger scan")
  510. ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  511. if ev is None:
  512. raise Exception("Scan timed out")
  513. def roam(self, bssid):
  514. self.dump_monitor()
  515. self.request("ROAM " + bssid)
  516. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
  517. if ev is None:
  518. raise Exception("Roaming with the AP timed out")
  519. self.dump_monitor()
  520. def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
  521. new_passphrase=None):
  522. self.dump_monitor()
  523. if new_ssid:
  524. self.request("WPS_REG " + bssid + " " + pin + " " +
  525. new_ssid.encode("hex") + " " + key_mgmt + " " +
  526. cipher + " " + new_passphrase.encode("hex"))
  527. ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
  528. else:
  529. self.request("WPS_REG " + bssid + " " + pin)
  530. ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
  531. if ev is None:
  532. raise Exception("WPS cred timed out")
  533. ev = self.wait_event(["WPS-FAIL"], timeout=15)
  534. if ev is None:
  535. raise Exception("WPS timed out")
  536. ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
  537. if ev is None:
  538. raise Exception("Association with the AP timed out")
  539. def relog(self):
  540. self.request("RELOG")