]> git.ipfire.org Git - thirdparty/hostap.git/blob - tests/hwsim/wpasupplicant.py
tests: Random MAC address use
[thirdparty/hostap.git] / tests / hwsim / wpasupplicant.py
1 # Python class for controlling wpa_supplicant
2 # Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
3 #
4 # This software may be distributed under the terms of the BSD license.
5 # See README for more details.
6
7 import os
8 import time
9 import logging
10 import binascii
11 import re
12 import struct
13 import subprocess
14 import wpaspy
15
16 logger = logging.getLogger()
17 wpas_ctrl = '/var/run/wpa_supplicant'
18
19 class WpaSupplicant:
20 def __init__(self, ifname=None, global_iface=None):
21 self.group_ifname = None
22 if ifname:
23 self.set_ifname(ifname)
24 else:
25 self.ifname = None
26
27 self.global_iface = global_iface
28 if global_iface:
29 self.global_ctrl = wpaspy.Ctrl(global_iface)
30 self.global_mon = wpaspy.Ctrl(global_iface)
31 self.global_mon.attach()
32
33 def set_ifname(self, ifname):
34 self.ifname = ifname
35 self.ctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
36 self.mon = wpaspy.Ctrl(os.path.join(wpas_ctrl, ifname))
37 self.mon.attach()
38
39 def remove_ifname(self):
40 if self.ifname:
41 self.mon.detach()
42 self.mon = None
43 self.ctrl = None
44 self.ifname = None
45
46 def interface_add(self, ifname, config="", driver="nl80211", drv_params=None):
47 try:
48 groups = subprocess.check_output(["id"])
49 group = "admin" if "(admin)" in groups else "adm"
50 except Exception, e:
51 group = "admin"
52 cmd = "INTERFACE_ADD " + ifname + "\t" + config + "\t" + driver + "\tDIR=/var/run/wpa_supplicant GROUP=" + group
53 if drv_params:
54 cmd = cmd + '\t' + drv_params
55 if "FAIL" in self.global_request(cmd):
56 raise Exception("Failed to add a dynamic wpa_supplicant interface")
57 self.set_ifname(ifname)
58
59 def interface_remove(self, ifname):
60 self.remove_ifname()
61 self.global_request("INTERFACE_REMOVE " + ifname)
62
63 def request(self, cmd):
64 logger.debug(self.ifname + ": CTRL: " + cmd)
65 return self.ctrl.request(cmd)
66
67 def global_request(self, cmd):
68 if self.global_iface is None:
69 self.request(cmd)
70 else:
71 ifname = self.ifname or self.global_iface
72 logger.debug(ifname + ": CTRL(global): " + cmd)
73 return self.global_ctrl.request(cmd)
74
75 def group_request(self, cmd):
76 if self.group_ifname and self.group_ifname != self.ifname:
77 logger.debug(self.group_ifname + ": CTRL: " + cmd)
78 gctrl = wpaspy.Ctrl(os.path.join(wpas_ctrl, self.group_ifname))
79 return gctrl.request(cmd)
80 return self.request(cmd)
81
82 def ping(self):
83 return "PONG" in self.request("PING")
84
85 def global_ping(self):
86 return "PONG" in self.global_request("PING")
87
88 def reset(self):
89 self.dump_monitor()
90 res = self.request("FLUSH")
91 if not "OK" in res:
92 logger.info("FLUSH to " + self.ifname + " failed: " + res)
93 self.request("WPS_ER_STOP")
94 self.request("SET pmf 0")
95 self.request("SET external_sim 0")
96 self.request("SET hessid 00:00:00:00:00:00")
97 self.request("SET access_network_type 15")
98 self.request("SET p2p_add_cli_chan 0")
99 self.request("SET p2p_no_go_freq ")
100 self.request("SET p2p_pref_chan ")
101 self.request("SET p2p_no_group_iface 1")
102 self.request("SET p2p_go_intent 7")
103 self.group_ifname = None
104 self.dump_monitor()
105
106 iter = 0
107 while iter < 60:
108 state = self.get_driver_status_field("scan_state")
109 if "SCAN_STARTED" in state or "SCAN_REQUESTED" in state:
110 logger.info(self.ifname + ": Waiting for scan operation to complete before continuing")
111 time.sleep(1)
112 else:
113 break
114 iter = iter + 1
115 if iter == 60:
116 logger.error(self.ifname + ": Driver scan state did not clear")
117 print "Trying to clear cfg80211/mac80211 scan state"
118 try:
119 cmd = ["sudo", "ifconfig", self.ifname, "down"]
120 subprocess.call(cmd)
121 except subprocess.CalledProcessError, e:
122 logger.info("ifconfig failed: " + str(e.returncode))
123 logger.info(e.output)
124 try:
125 cmd = ["sudo", "ifconfig", self.ifname, "up"]
126 subprocess.call(cmd)
127 except subprocess.CalledProcessError, e:
128 logger.info("ifconfig failed: " + str(e.returncode))
129 logger.info(e.output)
130 if iter > 0:
131 # The ongoing scan could have discovered BSSes or P2P peers
132 logger.info("Run FLUSH again since scan was in progress")
133 self.request("FLUSH")
134 self.dump_monitor()
135
136 if not self.ping():
137 logger.info("No PING response from " + self.ifname + " after reset")
138
139 def add_network(self):
140 id = self.request("ADD_NETWORK")
141 if "FAIL" in id:
142 raise Exception("ADD_NETWORK failed")
143 return int(id)
144
145 def remove_network(self, id):
146 id = self.request("REMOVE_NETWORK " + str(id))
147 if "FAIL" in id:
148 raise Exception("REMOVE_NETWORK failed")
149 return None
150
151 def get_network(self, id, field):
152 res = self.request("GET_NETWORK " + str(id) + " " + field)
153 if res == "FAIL\n":
154 return None
155 return res
156
157 def set_network(self, id, field, value):
158 res = self.request("SET_NETWORK " + str(id) + " " + field + " " + value)
159 if "FAIL" in res:
160 raise Exception("SET_NETWORK failed")
161 return None
162
163 def set_network_quoted(self, id, field, value):
164 res = self.request("SET_NETWORK " + str(id) + " " + field + ' "' + value + '"')
165 if "FAIL" in res:
166 raise Exception("SET_NETWORK failed")
167 return None
168
169 def list_networks(self):
170 res = self.request("LIST_NETWORKS")
171 lines = res.splitlines()
172 networks = []
173 for l in lines:
174 if "network id" in l:
175 continue
176 [id,ssid,bssid,flags] = l.split('\t')
177 network = {}
178 network['id'] = id
179 network['ssid'] = ssid
180 network['bssid'] = bssid
181 network['flags'] = flags
182 networks.append(network)
183 return networks
184
185 def hs20_enable(self, auto_interworking=False):
186 self.request("SET interworking 1")
187 self.request("SET hs20 1")
188 if auto_interworking:
189 self.request("SET auto_interworking 1")
190 else:
191 self.request("SET auto_interworking 0")
192
193 def add_cred(self):
194 id = self.request("ADD_CRED")
195 if "FAIL" in id:
196 raise Exception("ADD_CRED failed")
197 return int(id)
198
199 def remove_cred(self, id):
200 id = self.request("REMOVE_CRED " + str(id))
201 if "FAIL" in id:
202 raise Exception("REMOVE_CRED failed")
203 return None
204
205 def set_cred(self, id, field, value):
206 res = self.request("SET_CRED " + str(id) + " " + field + " " + value)
207 if "FAIL" in res:
208 raise Exception("SET_CRED failed")
209 return None
210
211 def set_cred_quoted(self, id, field, value):
212 res = self.request("SET_CRED " + str(id) + " " + field + ' "' + value + '"')
213 if "FAIL" in res:
214 raise Exception("SET_CRED failed")
215 return None
216
217 def get_cred(self, id, field):
218 return self.request("GET_CRED " + str(id) + " " + field)
219
220 def add_cred_values(self, params):
221 id = self.add_cred()
222
223 quoted = [ "realm", "username", "password", "domain", "imsi",
224 "excluded_ssid", "milenage", "ca_cert", "client_cert",
225 "private_key", "domain_suffix_match", "provisioning_sp",
226 "roaming_partner", "phase1", "phase2" ]
227 for field in quoted:
228 if field in params:
229 self.set_cred_quoted(id, field, params[field])
230
231 not_quoted = [ "eap", "roaming_consortium", "priority",
232 "required_roaming_consortium", "sp_priority",
233 "max_bss_load", "update_identifier", "req_conn_capab",
234 "min_dl_bandwidth_home", "min_ul_bandwidth_home",
235 "min_dl_bandwidth_roaming", "min_ul_bandwidth_roaming" ]
236 for field in not_quoted:
237 if field in params:
238 self.set_cred(id, field, params[field])
239
240 return id;
241
242 def select_network(self, id, freq=None):
243 if freq:
244 extra = " freq=" + freq
245 else:
246 extra = ""
247 id = self.request("SELECT_NETWORK " + str(id) + extra)
248 if "FAIL" in id:
249 raise Exception("SELECT_NETWORK failed")
250 return None
251
252 def connect_network(self, id, timeout=10):
253 self.dump_monitor()
254 self.select_network(id)
255 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=timeout)
256 if ev is None:
257 raise Exception("Association with the AP timed out")
258 self.dump_monitor()
259
260 def get_status(self, extra=None):
261 if extra:
262 extra = "-" + extra
263 else:
264 extra = ""
265 res = self.request("STATUS" + extra)
266 lines = res.splitlines()
267 vals = dict()
268 for l in lines:
269 try:
270 [name,value] = l.split('=', 1)
271 vals[name] = value
272 except ValueError, e:
273 logger.info(self.ifname + ": Ignore unexpected STATUS line: " + l)
274 return vals
275
276 def get_status_field(self, field, extra=None):
277 vals = self.get_status(extra)
278 if field in vals:
279 return vals[field]
280 return None
281
282 def get_group_status(self, extra=None):
283 if extra:
284 extra = "-" + extra
285 else:
286 extra = ""
287 res = self.group_request("STATUS" + extra)
288 lines = res.splitlines()
289 vals = dict()
290 for l in lines:
291 [name,value] = l.split('=', 1)
292 vals[name] = value
293 return vals
294
295 def get_group_status_field(self, field, extra=None):
296 vals = self.get_group_status(extra)
297 if field in vals:
298 return vals[field]
299 return None
300
301 def get_driver_status(self):
302 res = self.request("STATUS-DRIVER")
303 lines = res.splitlines()
304 vals = dict()
305 for l in lines:
306 [name,value] = l.split('=', 1)
307 vals[name] = value
308 return vals
309
310 def get_driver_status_field(self, field):
311 vals = self.get_driver_status()
312 if field in vals:
313 return vals[field]
314 return None
315
316 def get_mcc(self):
317 mcc = int(self.get_driver_status_field('capa.num_multichan_concurrent'))
318 return 1 if mcc < 2 else mcc
319
320 def get_mib(self):
321 res = self.request("MIB")
322 lines = res.splitlines()
323 vals = dict()
324 for l in lines:
325 try:
326 [name,value] = l.split('=', 1)
327 vals[name] = value
328 except ValueError, e:
329 logger.info(self.ifname + ": Ignore unexpected MIB line: " + l)
330 return vals
331
332 def p2p_dev_addr(self):
333 return self.get_status_field("p2p_device_address")
334
335 def p2p_interface_addr(self):
336 return self.get_group_status_field("address")
337
338 def p2p_listen(self):
339 return self.global_request("P2P_LISTEN")
340
341 def p2p_find(self, social=False, progressive=False, dev_id=None, dev_type=None):
342 cmd = "P2P_FIND"
343 if social:
344 cmd = cmd + " type=social"
345 elif progressive:
346 cmd = cmd + " type=progressive"
347 if dev_id:
348 cmd = cmd + " dev_id=" + dev_id
349 if dev_type:
350 cmd = cmd + " dev_type=" + dev_type
351 return self.global_request(cmd)
352
353 def p2p_stop_find(self):
354 return self.global_request("P2P_STOP_FIND")
355
356 def wps_read_pin(self):
357 self.pin = self.request("WPS_PIN get").rstrip("\n")
358 if "FAIL" in self.pin:
359 raise Exception("Could not generate PIN")
360 return self.pin
361
362 def peer_known(self, peer, full=True):
363 res = self.global_request("P2P_PEER " + peer)
364 if peer.lower() not in res.lower():
365 return False
366 if not full:
367 return True
368 return "[PROBE_REQ_ONLY]" not in res
369
370 def discover_peer(self, peer, full=True, timeout=15, social=True, force_find=False):
371 logger.info(self.ifname + ": Trying to discover peer " + peer)
372 if not force_find and self.peer_known(peer, full):
373 return True
374 self.p2p_find(social)
375 count = 0
376 while count < timeout:
377 time.sleep(1)
378 count = count + 1
379 if self.peer_known(peer, full):
380 return True
381 return False
382
383 def get_peer(self, peer):
384 res = self.global_request("P2P_PEER " + peer)
385 if peer.lower() not in res.lower():
386 raise Exception("Peer information not available")
387 lines = res.splitlines()
388 vals = dict()
389 for l in lines:
390 if '=' in l:
391 [name,value] = l.split('=', 1)
392 vals[name] = value
393 return vals
394
395 def group_form_result(self, ev, expect_failure=False, go_neg_res=None):
396 if expect_failure:
397 if "P2P-GROUP-STARTED" in ev:
398 raise Exception("Group formation succeeded when expecting failure")
399 exp = r'<.>(P2P-GO-NEG-FAILURE) status=([0-9]*)'
400 s = re.split(exp, ev)
401 if len(s) < 3:
402 return None
403 res = {}
404 res['result'] = 'go-neg-failed'
405 res['status'] = int(s[2])
406 return res
407
408 if "P2P-GROUP-STARTED" not in ev:
409 raise Exception("No P2P-GROUP-STARTED event seen")
410
411 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*) ip_addr=([0-9.]*) ip_mask=([0-9.]*) go_ip_addr=([0-9.]*)'
412 s = re.split(exp, ev)
413 if len(s) < 11:
414 exp = r'<.>(P2P-GROUP-STARTED) ([^ ]*) ([^ ]*) ssid="(.*)" freq=([0-9]*) ((?:psk=.*)|(?:passphrase=".*")) go_dev_addr=([0-9a-f:]*)'
415 s = re.split(exp, ev)
416 if len(s) < 8:
417 raise Exception("Could not parse P2P-GROUP-STARTED")
418 res = {}
419 res['result'] = 'success'
420 res['ifname'] = s[2]
421 self.group_ifname = s[2]
422 res['role'] = s[3]
423 res['ssid'] = s[4]
424 res['freq'] = s[5]
425 if "[PERSISTENT]" in ev:
426 res['persistent'] = True
427 else:
428 res['persistent'] = False
429 p = re.match(r'psk=([0-9a-f]*)', s[6])
430 if p:
431 res['psk'] = p.group(1)
432 p = re.match(r'passphrase="(.*)"', s[6])
433 if p:
434 res['passphrase'] = p.group(1)
435 res['go_dev_addr'] = s[7]
436
437 if len(s) > 8 and len(s[8]) > 0:
438 res['ip_addr'] = s[8]
439 if len(s) > 9:
440 res['ip_mask'] = s[9]
441 if len(s) > 10:
442 res['go_ip_addr'] = s[10]
443
444 if go_neg_res:
445 exp = r'<.>(P2P-GO-NEG-SUCCESS) role=(GO|client) freq=([0-9]*)'
446 s = re.split(exp, go_neg_res)
447 if len(s) < 4:
448 raise Exception("Could not parse P2P-GO-NEG-SUCCESS")
449 res['go_neg_role'] = s[2]
450 res['go_neg_freq'] = s[3]
451
452 return res
453
454 def p2p_go_neg_auth(self, peer, pin, method, go_intent=None, persistent=False, freq=None):
455 if not self.discover_peer(peer):
456 raise Exception("Peer " + peer + " not found")
457 self.dump_monitor()
458 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method + " auth"
459 if go_intent:
460 cmd = cmd + ' go_intent=' + str(go_intent)
461 if freq:
462 cmd = cmd + ' freq=' + str(freq)
463 if persistent:
464 cmd = cmd + " persistent"
465 if "OK" in self.global_request(cmd):
466 return None
467 raise Exception("P2P_CONNECT (auth) failed")
468
469 def p2p_go_neg_auth_result(self, timeout=1, expect_failure=False):
470 go_neg_res = None
471 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
472 "P2P-GO-NEG-FAILURE"], timeout);
473 if ev is None:
474 if expect_failure:
475 return None
476 raise Exception("Group formation timed out")
477 if "P2P-GO-NEG-SUCCESS" in ev:
478 go_neg_res = ev
479 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout);
480 if ev is None:
481 if expect_failure:
482 return None
483 raise Exception("Group formation timed out")
484 self.dump_monitor()
485 return self.group_form_result(ev, expect_failure, go_neg_res)
486
487 def p2p_go_neg_init(self, peer, pin, method, timeout=0, go_intent=None, expect_failure=False, persistent=False, persistent_id=None, freq=None, provdisc=False):
488 if not self.discover_peer(peer):
489 raise Exception("Peer " + peer + " not found")
490 self.dump_monitor()
491 if pin:
492 cmd = "P2P_CONNECT " + peer + " " + pin + " " + method
493 else:
494 cmd = "P2P_CONNECT " + peer + " " + method
495 if go_intent:
496 cmd = cmd + ' go_intent=' + str(go_intent)
497 if freq:
498 cmd = cmd + ' freq=' + str(freq)
499 if persistent:
500 cmd = cmd + " persistent"
501 elif persistent_id:
502 cmd = cmd + " persistent=" + persistent_id
503 if provdisc:
504 cmd = cmd + " provdisc"
505 if "OK" in self.global_request(cmd):
506 if timeout == 0:
507 self.dump_monitor()
508 return None
509 go_neg_res = None
510 ev = self.wait_global_event(["P2P-GO-NEG-SUCCESS",
511 "P2P-GO-NEG-FAILURE"], timeout)
512 if ev is None:
513 if expect_failure:
514 return None
515 raise Exception("Group formation timed out")
516 if "P2P-GO-NEG-SUCCESS" in ev:
517 go_neg_res = ev
518 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
519 if ev is None:
520 if expect_failure:
521 return None
522 raise Exception("Group formation timed out")
523 self.dump_monitor()
524 return self.group_form_result(ev, expect_failure, go_neg_res)
525 raise Exception("P2P_CONNECT failed")
526
527 def wait_event(self, events, timeout=10):
528 start = os.times()[4]
529 while True:
530 while self.mon.pending():
531 ev = self.mon.recv()
532 logger.debug(self.ifname + ": " + ev)
533 for event in events:
534 if event in ev:
535 return ev
536 now = os.times()[4]
537 remaining = start + timeout - now
538 if remaining <= 0:
539 break
540 if not self.mon.pending(timeout=remaining):
541 break
542 return None
543
544 def wait_global_event(self, events, timeout):
545 if self.global_iface is None:
546 self.wait_event(events, timeout)
547 else:
548 start = os.times()[4]
549 while True:
550 while self.global_mon.pending():
551 ev = self.global_mon.recv()
552 logger.debug(self.ifname + "(global): " + ev)
553 for event in events:
554 if event in ev:
555 return ev
556 now = os.times()[4]
557 remaining = start + timeout - now
558 if remaining <= 0:
559 break
560 if not self.global_mon.pending(timeout=remaining):
561 break
562 return None
563
564 def wait_go_ending_session(self):
565 ev = self.wait_event(["P2P-GROUP-REMOVED"], timeout=3)
566 if ev is None:
567 raise Exception("Group removal event timed out")
568 if "reason=GO_ENDING_SESSION" not in ev:
569 raise Exception("Unexpected group removal reason")
570
571 def dump_monitor(self):
572 while self.mon.pending():
573 ev = self.mon.recv()
574 logger.debug(self.ifname + ": " + ev)
575 while self.global_mon.pending():
576 ev = self.global_mon.recv()
577 logger.debug(self.ifname + "(global): " + ev)
578
579 def remove_group(self, ifname=None):
580 if ifname is None:
581 ifname = self.group_ifname if self.group_ifname else self.ifname
582 if "OK" not in self.global_request("P2P_GROUP_REMOVE " + ifname):
583 raise Exception("Group could not be removed")
584 self.group_ifname = None
585
586 def p2p_start_go(self, persistent=None, freq=None):
587 self.dump_monitor()
588 cmd = "P2P_GROUP_ADD"
589 if persistent is None:
590 pass
591 elif persistent is True:
592 cmd = cmd + " persistent"
593 else:
594 cmd = cmd + " persistent=" + str(persistent)
595 if freq:
596 cmd = cmd + " freq=" + str(freq)
597 if "OK" in self.global_request(cmd):
598 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout=5)
599 if ev is None:
600 raise Exception("GO start up timed out")
601 self.dump_monitor()
602 return self.group_form_result(ev)
603 raise Exception("P2P_GROUP_ADD failed")
604
605 def p2p_go_authorize_client(self, pin):
606 cmd = "WPS_PIN any " + pin
607 if "FAIL" in self.group_request(cmd):
608 raise Exception("Failed to authorize client connection on GO")
609 return None
610
611 def p2p_go_authorize_client_pbc(self):
612 cmd = "WPS_PBC"
613 if "FAIL" in self.group_request(cmd):
614 raise Exception("Failed to authorize client connection on GO")
615 return None
616
617 def p2p_connect_group(self, go_addr, pin, timeout=0, social=False):
618 self.dump_monitor()
619 if not self.discover_peer(go_addr, social=social):
620 if social or not self.discover_peer(go_addr, social=social):
621 raise Exception("GO " + go_addr + " not found")
622 self.dump_monitor()
623 cmd = "P2P_CONNECT " + go_addr + " " + pin + " join"
624 if "OK" in self.global_request(cmd):
625 if timeout == 0:
626 self.dump_monitor()
627 return None
628 ev = self.wait_global_event(["P2P-GROUP-STARTED"], timeout)
629 if ev is None:
630 raise Exception("Joining the group timed out")
631 self.dump_monitor()
632 return self.group_form_result(ev)
633 raise Exception("P2P_CONNECT(join) failed")
634
635 def tdls_setup(self, peer):
636 cmd = "TDLS_SETUP " + peer
637 if "FAIL" in self.group_request(cmd):
638 raise Exception("Failed to request TDLS setup")
639 return None
640
641 def tdls_teardown(self, peer):
642 cmd = "TDLS_TEARDOWN " + peer
643 if "FAIL" in self.group_request(cmd):
644 raise Exception("Failed to request TDLS teardown")
645 return None
646
647 def connect(self, ssid=None, ssid2=None, **kwargs):
648 logger.info("Connect STA " + self.ifname + " to AP")
649 id = self.add_network()
650 if ssid:
651 self.set_network_quoted(id, "ssid", ssid)
652 elif ssid2:
653 self.set_network(id, "ssid", ssid2)
654
655 quoted = [ "psk", "identity", "anonymous_identity", "password",
656 "ca_cert", "client_cert", "private_key",
657 "private_key_passwd", "ca_cert2", "client_cert2",
658 "private_key2", "phase1", "phase2", "domain_suffix_match",
659 "altsubject_match", "subject_match", "pac_file", "dh_file",
660 "bgscan", "ht_mcs", "id_str" ]
661 for field in quoted:
662 if field in kwargs and kwargs[field]:
663 self.set_network_quoted(id, field, kwargs[field])
664
665 not_quoted = [ "proto", "key_mgmt", "ieee80211w", "pairwise",
666 "group", "wep_key0", "scan_freq", "eap",
667 "eapol_flags", "fragment_size", "scan_ssid", "auth_alg",
668 "wpa_ptk_rekey", "disable_ht", "disable_vht", "bssid",
669 "disable_max_amsdu", "ampdu_factor", "ampdu_density",
670 "disable_ht40", "disable_sgi", "disable_ldpc",
671 "ht40_intolerant", "update_identifier", "mac_addr" ]
672 for field in not_quoted:
673 if field in kwargs and kwargs[field]:
674 self.set_network(id, field, kwargs[field])
675
676 if "raw_psk" in kwargs and kwargs['raw_psk']:
677 self.set_network(id, "psk", kwargs['raw_psk'])
678 if "password_hex" in kwargs and kwargs['password_hex']:
679 self.set_network(id, "password", kwargs['password_hex'])
680 if "peerkey" in kwargs and kwargs['peerkey']:
681 self.set_network(id, "peerkey", "1")
682 if "okc" in kwargs and kwargs['okc']:
683 self.set_network(id, "proactive_key_caching", "1")
684 if "ocsp" in kwargs and kwargs['ocsp']:
685 self.set_network(id, "ocsp", str(kwargs['ocsp']))
686 if "only_add_network" in kwargs and kwargs['only_add_network']:
687 return id
688 if "wait_connect" not in kwargs or kwargs['wait_connect']:
689 if "eap" in kwargs:
690 self.connect_network(id, timeout=20)
691 else:
692 self.connect_network(id)
693 else:
694 self.dump_monitor()
695 self.select_network(id)
696 return id
697
698 def scan(self, type=None, freq=None, no_wait=False, only_new=False):
699 if type:
700 cmd = "SCAN TYPE=" + type
701 else:
702 cmd = "SCAN"
703 if freq:
704 cmd = cmd + " freq=" + freq
705 if only_new:
706 cmd += " only_new=1"
707 if not no_wait:
708 self.dump_monitor()
709 if not "OK" in self.request(cmd):
710 raise Exception("Failed to trigger scan")
711 if no_wait:
712 return
713 ev = self.wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
714 if ev is None:
715 raise Exception("Scan timed out")
716
717 def scan_for_bss(self, bssid, freq=None, force_scan=False):
718 if not force_scan and self.get_bss(bssid) is not None:
719 return
720 for i in range(0, 10):
721 self.scan(freq=freq, type="ONLY")
722 if self.get_bss(bssid) is not None:
723 return
724 raise Exception("Could not find BSS " + bssid + " in scan")
725
726 def roam(self, bssid, fail_test=False):
727 self.dump_monitor()
728 if "OK" not in self.request("ROAM " + bssid):
729 raise Exception("ROAM failed")
730 if fail_test:
731 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
732 if ev is not None:
733 raise Exception("Unexpected connection")
734 self.dump_monitor()
735 return
736 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
737 if ev is None:
738 raise Exception("Roaming with the AP timed out")
739 self.dump_monitor()
740
741 def roam_over_ds(self, bssid, fail_test=False):
742 self.dump_monitor()
743 if "OK" not in self.request("FT_DS " + bssid):
744 raise Exception("FT_DS failed")
745 if fail_test:
746 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=1)
747 if ev is not None:
748 raise Exception("Unexpected connection")
749 self.dump_monitor()
750 return
751 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10)
752 if ev is None:
753 raise Exception("Roaming with the AP timed out")
754 self.dump_monitor()
755
756 def wps_reg(self, bssid, pin, new_ssid=None, key_mgmt=None, cipher=None,
757 new_passphrase=None, no_wait=False):
758 self.dump_monitor()
759 if new_ssid:
760 self.request("WPS_REG " + bssid + " " + pin + " " +
761 new_ssid.encode("hex") + " " + key_mgmt + " " +
762 cipher + " " + new_passphrase.encode("hex"))
763 if no_wait:
764 return
765 ev = self.wait_event(["WPS-SUCCESS"], timeout=15)
766 else:
767 self.request("WPS_REG " + bssid + " " + pin)
768 if no_wait:
769 return
770 ev = self.wait_event(["WPS-CRED-RECEIVED"], timeout=15)
771 if ev is None:
772 raise Exception("WPS cred timed out")
773 ev = self.wait_event(["WPS-FAIL"], timeout=15)
774 if ev is None:
775 raise Exception("WPS timed out")
776 ev = self.wait_event(["CTRL-EVENT-CONNECTED"], timeout=15)
777 if ev is None:
778 raise Exception("Association with the AP timed out")
779
780 def relog(self):
781 self.request("RELOG")
782
783 def wait_completed(self, timeout=10):
784 for i in range(0, timeout * 2):
785 if self.get_status_field("wpa_state") == "COMPLETED":
786 return
787 time.sleep(0.5)
788 raise Exception("Timeout while waiting for COMPLETED state")
789
790 def get_capability(self, field):
791 res = self.request("GET_CAPABILITY " + field)
792 if "FAIL" in res:
793 return None
794 return res.split(' ')
795
796 def get_bss(self, bssid):
797 res = self.request("BSS " + bssid)
798 if "FAIL" in res:
799 return None
800 lines = res.splitlines()
801 vals = dict()
802 for l in lines:
803 [name,value] = l.split('=', 1)
804 vals[name] = value
805 if len(vals) == 0:
806 return None
807 return vals
808
809 def get_pmksa(self, bssid):
810 res = self.request("PMKSA")
811 lines = res.splitlines()
812 for l in lines:
813 if bssid not in l:
814 continue
815 vals = dict()
816 [index,aa,pmkid,expiration,opportunistic] = l.split(' ')
817 vals['index'] = index
818 vals['pmkid'] = pmkid
819 vals['expiration'] = expiration
820 vals['opportunistic'] = opportunistic
821 return vals
822 return None
823
824 def get_sta(self, addr, info=None, next=False):
825 cmd = "STA-NEXT " if next else "STA "
826 if addr is None:
827 res = self.request("STA-FIRST")
828 elif info:
829 res = self.request(cmd + addr + " " + info)
830 else:
831 res = self.request(cmd + addr)
832 lines = res.splitlines()
833 vals = dict()
834 first = True
835 for l in lines:
836 if first:
837 vals['addr'] = l
838 first = False
839 else:
840 [name,value] = l.split('=', 1)
841 vals[name] = value
842 return vals
843
844 def mgmt_rx(self, timeout=5):
845 ev = self.wait_event(["MGMT-RX"], timeout=timeout)
846 if ev is None:
847 return None
848 msg = {}
849 items = ev.split(' ')
850 field,val = items[1].split('=')
851 if field != "freq":
852 raise Exception("Unexpected MGMT-RX event format: " + ev)
853 msg['freq'] = val
854 frame = binascii.unhexlify(items[4])
855 msg['frame'] = frame
856
857 hdr = struct.unpack('<HH6B6B6BH', frame[0:24])
858 msg['fc'] = hdr[0]
859 msg['subtype'] = (hdr[0] >> 4) & 0xf
860 hdr = hdr[1:]
861 msg['duration'] = hdr[0]
862 hdr = hdr[1:]
863 msg['da'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
864 hdr = hdr[6:]
865 msg['sa'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
866 hdr = hdr[6:]
867 msg['bssid'] = "%02x:%02x:%02x:%02x:%02x:%02x" % hdr[0:6]
868 hdr = hdr[6:]
869 msg['seq_ctrl'] = hdr[0]
870 msg['payload'] = frame[24:]
871
872 return msg