-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathpyw.py
2316 lines (2070 loc) · 88.7 KB
/
pyw.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
""" pyw.py: Linux wireless library for the Python Wireless Developer and Pentester
Copyright (C) 2016 Dale V. Patterson ([email protected])
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
Redistribution and use in source and binary forms, with or without
modifications, are permitted provided that the following conditions are met:
o Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
o Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
o Neither the name of the orginal author Dale V. Patterson nor the names of
any contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
Provides a python version of a subset of the iw command & additionally, a
smaller subset of ifconfig, rfkill and macchanger.
Each command/function (excluding interfaces & isinterface which do not rely on
ioctl/netlink sockets) comes in two flavors - one-time & persistent.
1) one-time: similar to iw. The command, creates the netlink socket
(or ioctl), composes the message, sends the message & receives the
response, parses the results, closes the socket & returns the results to
the caller. At no time does the caller need to be aware of any underlying
netlink processes or structures.
2) persistent: communication & parsing only. The onus of socket creation and
deletion is on the caller which allows them to create one (or more)
socket(s). The pyw functions will only handle message construction, message
sending and receiving & message parsing.
Callers that intend to use pyw functionality often & repeatedly may prefer to
use a persistent netlink/ioctl socket. Socket creation & deletion are
relatively fast however, if a program is repeatedly using pyw function(s)
(such as a scanner that is changing channels mulitple times per second) it
makes sense for the caller to create one socket and use it throughout execution.
However, if the caller is only using pyw periodically and/or does not
want to bother with socket maintenance, the one-time flavor would be better.
for one-time execution, for example use
regset('US')
for persistent execution, use
regset('US',nlsocket)
where nlsocket is created with libnl.nl_socket_alloc()
to create/delete sockets use the libraries alloc functions:
o ioctl: libio.io_socket_alloc() and libio.io_socket_free()
o netlink: libnl.nl_socket_alloc() and libnl.nl_socket_free()
NOTE:
1) All functions (excluding wireless core related) will use a Card object which
collates the physical index, device name and interface index (ifindex) in a
tuple rather than a device name or physical index or ifindex as this will not
require the caller to remember if a dev or a phy or a ifindex is needed. The
Exceptions to this are:
devinfo which will accept a Card or a dev
devadd which will accept a Card or a phy
2) All functions allow pyric errors to pass through. Callers must catch these
if they desire
"""
__name__ = 'pyw'
__license__ = 'GPLv3'
__version__ = '0.2.1'
__date__ = 'December 2016'
__author__ = 'Dale Patterson'
__maintainer__ = 'Dale Patterson'
__email__ = '[email protected]'
__status__ = 'Production'
import struct # ioctl unpacking
import re # check addr validity
import pyric # pyric exception
from pyric.nlhelp.nlsearch import cmdbynum # get command name
import pyric.utils.channels as channels # channel related
import pyric.utils.rfkill as rfkill # block/unblock
import pyric.utils.hardware as hw # device related
import pyric.utils.ouifetch as ouifetch # get oui dict
import pyric.net.netlink_h as nlh # netlink definition
import pyric.net.genetlink_h as genlh # genetlink definition
import pyric.net.wireless.nl80211_h as nl80211h # nl80211 definition
import pyric.lib.libnl as nl # netlink (library) functions
import pyric.net.wireless.wlan as wlan # IEEE 802.11 Std definition
import pyric.net.sockios_h as sioch # sockios constants
import pyric.net.if_h as ifh # ifreq structure
import pyric.lib.libio as io # ioctl (library) functions
import os
_FAM80211ID_ = None
# redefine some nl80211 enum lists for ease of use
IFTYPES = nl80211h.NL80211_IFTYPES
MNTRFLAGS = nl80211h.NL80211_MNTR_FLAGS
TXPWRSETTINGS = nl80211h.NL80211_TX_POWER_SETTINGS
################################################################################
#### WIRELESS CORE ####
################################################################################
def interfaces():
"""
Retrieves all network interfaces (APX ifconfig)
:returns: a list of device names of current network interfaces cards
"""
fin = None
try:
# read in devices from /proc/net/dev. After splitting on newlines, the
# first 2 lines are headers and the last line is empty so we remove them
fin = open(hw.dpath, 'r')
ds = fin.read().split('\n')[2:-1]
except IOError:
return []
finally:
if fin: fin.close()
# the remaining lines are <dev>: p1 p2 ... p3, split on ':' & strip whitespace
return [d.split(':')[0].strip() for d in ds]
def isinterface(dev):
"""
Determines if device name belongs to a network card (APX ifconfig <dev>)
:param dev: device name
:returns: {True if dev is a device|False otherwise}
"""
return dev in interfaces()
def winterfaces(iosock=None):
"""
Retrieve all wireless interfaces (APX iwconfig)
:param iosock: ioctl socket
:returns: list of device names of current wireless NICs
"""
if iosock is None: return _iostub_(winterfaces)
wifaces = []
for dev in interfaces():
if iswireless(dev, iosock): wifaces.append(dev)
return wifaces
def iswireless(dev, iosock=None):
"""
Determines if given device is wireless (APX iwconfig <dev>)
:param dev: device name
:param iosock: ioctl socket
:returns: {True:device is wireless|False:device is not wireless/not present}
"""
if iosock is None: return _iostub_(iswireless, dev)
try:
# if the call succeeds, dev is found to be wireless
_ = io.io_transfer(iosock, sioch.SIOCGIWNAME, ifh.ifreq(dev))
return True
except AttributeError as e:
raise pyric.error(pyric.EINVAL, e)
except io.error:
return False
def phylist():
"""
Use rfkill to return all phys of wireless devices
:returns: a list of tuples t = (physical index, physical name)
"""
# these are stroed in /sys/class/ieee80211 but we let rfkill do it (just in
# case the above path differs across distros or in future upgrades). However,
# in some cases like OpenWRT which does not support rfkill we have to walk the
# directory
phys = []
try:
rfdevs = rfkill.rfkill_list()
for rfk in rfdevs:
if rfdevs[rfk]['type'] == 'wlan':
phys.append((int(rfk.split('phy')[1]),rfk))
except IOError as e:
#catch 'No such file or directory' errors when rfkill is not supported
if e.errno == pyric.ENOENT:
try:
rfdevs = os.listdir(rfkill.ipath)
except OSError:
emsg = "{} is not a directory & rfkill is not supported".format(rfkill.ipath)
raise pyric.error(pyric.ENOTDIR,emsg)
else:
for rfk in rfdevs: phys.append((int(rfk.split('phy')[1]),rfk))
else:
raise pyric.error(pyric.EUNDEF,
"PHY listing failed: {}-{}".format(e.errno,e.strerror))
return phys
def regget(nlsock=None):
"""
Get the current regulatory domain (iw reg get)
:param nlsock: netlink socket
:returns: the two charactor regulatory domain
"""
if nlsock is None: return _nlstub_(regget)
try:
msg = nl.nlmsg_new(nltype=_familyid_(nlsock),
cmd=nl80211h.NL80211_CMD_GET_REG,
flags=nlh.NLM_F_REQUEST | nlh.NLM_F_ACK)
nl.nl_sendmsg(nlsock, msg)
rmsg = nl.nl_recvmsg(nlsock)
except nl.error as e:
raise pyric.error(e.errno, e.strerror)
return nl.nla_find(rmsg, nl80211h.NL80211_ATTR_REG_ALPHA2)
def regset(rd, nlsock=None):
"""
Sets the current regulatory domain (iw reg set <rd>)
:param rd: regulatory domain code
:param nlsock: netlink socket
.. warning:: Requires root privileges
"""
if len(rd) != 2: raise pyric.error(pyric.EINVAL, "Invalid reg. domain")
if nlsock is None: return _nlstub_(regset, rd)
try:
msg = nl.nlmsg_new(nltype=_familyid_(nlsock),
cmd=nl80211h.NL80211_CMD_REQ_SET_REG,
flags=nlh.NLM_F_REQUEST | nlh.NLM_F_ACK)
nl.nla_put_string(msg, rd.upper(), nl80211h.NL80211_ATTR_REG_ALPHA2)
nl.nl_sendmsg(nlsock, msg)
_ = nl.nl_recvmsg(nlsock)
except nl.error as e:
raise pyric.error(e.errno, e.strerror)
################################################################################
#### CARD RELATED ####
################################################################################
class Card(tuple):
"""
A wireless network interface controller - Wrapper around a tuple
t = (physical index,device name, interface index)
Exposes the following properties: (callable by '.'):
phy: physical index
dev: device name
idx: interface index (ifindex)
"""
# noinspection PyInitNewSignature
def __new__(cls, p, d, i):
return super(Card, cls).__new__(cls, tuple((p, d, i)))
def __repr__(self):
return "Card(phy={0},dev={1},ifindex={2})".format(self.phy,self.dev,self.idx)
@property
def phy(self): return self[0]
@property
def dev(self): return self[1]
@property
def idx(self): return self[2]
def getcard(dev, nlsock=None):
"""
Get the Card object from device name
:param dev: device name
:param nlsock: netlink socket
:returns: a Card with device name dev
"""
if nlsock is None: return _nlstub_(getcard, dev)
return devinfo(dev, nlsock)['card']
def validcard(card, nlsock=None):
"""
Determines if card is still valid i.e. another program has not changed it
:param card: Card object
:param nlsock: netlink socket
:returns: True if card is still valid, False otherwise
"""
if nlsock is None: return _nlstub_(validcard, card)
try:
return card == devinfo(card.dev, nlsock)['card']
except pyric.error as e:
if e.errno == pyric.ENODEV: return False
else: raise
################################################################################
#### ADDRESS RELATED ####
################################################################################
def macget(card, iosock=None):
"""
Gets the interface's hw address (APX ifconfig <card.dev> | grep HWaddr)
:param card: Card object
:param iosock: ioctl socket
:returns: device mac after operation
"""
if iosock is None: return _iostub_(macget, card)
try:
flag = sioch.SIOCGIFHWADDR
ret = io.io_transfer(iosock, flag, ifh.ifreq(card.dev, flag))
fam = struct.unpack_from(ifh.sa_addr, ret, ifh.IFNAMELEN)[0]
if fam in [ifh.ARPHRD_ETHER, ifh.AF_UNSPEC,ifh.ARPHRD_IEEE80211_RADIOTAP]:
return _hex2mac_(ret[18:24])
else:
raise pyric.error(pyric.EAFNOSUPPORT, "Invalid return hwaddr family")
except AttributeError as e:
raise pyric.error(pyric.EINVAL, e)
except struct.error as e:
raise pyric.error(pyric.EUNDEF, "Error parsing results: {0}".format(e))
except io.error as e:
raise pyric.error(e.errno, e.strerror)
def macset(card, mac, iosock=None):
"""
Set nic's hwaddr (ifconfig <card.dev> hw ether <mac>)
:param card: Card object
:param mac: macaddr to set
:param iosock: ioctl socket
:returns True on success, False otherwise
.. warning:: Requires root privileges
"""
if not _validmac_(mac): raise pyric.error(pyric.EINVAL, "Invalid mac address")
if iosock is None: return _iostub_(macset, card, mac)
try:
flag = sioch.SIOCSIFHWADDR
ret = io.io_transfer(iosock, flag, ifh.ifreq(card.dev, flag, [mac]))
fam = struct.unpack_from(ifh.sa_addr, ret, ifh.IFNAMELEN)[0]
if fam in [ifh.ARPHRD_ETHER, ifh.AF_UNSPEC, ifh.ARPHRD_IEEE80211_RADIOTAP]:
return _hex2mac_(ret[18:24]) == mac
else:
raise pyric.error(pyric.EAFNOSUPPORT, "Invalid return hwaddr family")
except AttributeError as e:
raise pyric.error(pyric.EINVAL, e)
except struct.error as e:
raise pyric.error(pyric.EUNDEF, "Error parsing results: {0}".format(e))
except io.error as e:
raise pyric.error(e.errno, e.strerror)
def ifaddrget(card, iosock=None):
"""
Get nic's ip, netmask and broadcast addresses
:param card: Card object
:param iosock: ioctl socket
:returns: the tuple t = (inet,mask,bcast)
"""
if iosock is None: return _iostub_(ifaddrget, card)
try:
# ip
flag = sioch.SIOCGIFADDR
ret = io.io_transfer(iosock, flag, ifh.ifreq(card.dev, flag))
fam = struct.unpack_from(ifh.sa_addr, ret, ifh.IFNAMELEN)[0]
if fam == ifh.AF_INET:
inet = _hex2ip4_(ret[20:24])
else:
raise pyric.error(pyric.EAFNOSUPPORT, "Invalid return ip family")
# netmask
flag = sioch.SIOCGIFNETMASK
ret = io.io_transfer(iosock, flag, ifh.ifreq(card.dev, flag))
fam = struct.unpack_from(ifh.sa_addr, ret, ifh.IFNAMELEN)[0]
if fam == ifh.AF_INET:
mask = _hex2ip4_(ret[20:24])
else:
raise pyric.error(pyric.EAFNOSUPPORT, "Invalid return netmask family")
# broadcast
flag = sioch.SIOCGIFBRDADDR
ret = io.io_transfer(iosock, flag, ifh.ifreq(card.dev, flag))
fam = struct.unpack_from(ifh.sa_addr, ret, ifh.IFNAMELEN)[0]
if fam == ifh.AF_INET:
bcast = _hex2ip4_(ret[20:24])
else:
raise pyric.error(pyric.EAFNOSUPPORT, "Invalid return broadcast family")
except AttributeError as e:
raise pyric.error(pyric.EINVAL, e)
except struct.error as e:
raise pyric.error(pyric.EUNDEF, "Error parsing results: {0}".format(e))
except io.error as e:
# catch address not available, which means the card currently does not
# have any addresses set - raise others
if e.errno == pyric.EADDRNOTAVAIL: return None, None, None
raise pyric.error(e.errno, e.strerror)
return inet, mask, bcast
def ifaddrset(card, inet=None, mask=None, bcast=None, iosock=None):
"""
Set nic's ip4 addr, netmask and/or broadcast
(ifconfig <card.dev> <inet> netmask <mask> broadcast <bcast>)
can set ipaddr,netmask and/or broadcast to None but one or more of ipaddr,
netmask, broadcast must be set
:param card: Card object
:param inet: ip address to set
:param mask: netmask to set
:param bcast: broadcast to set
:param iosock: ioctl socket
:returns: True on success, False otherwise
.. note:
1) throws error if setting netmask or broadcast and card does not have
an ip assigned
2) if setting only the ip address, netmask and broadcast will be set
accordingly by the kernel.
3) If setting multiple or setting the netmask and/or broadcast after the ip
is assigned, one can set them to erroneous values i.e. ip = 192.168.1.2
and broadcast = 10.0.0.31.
.. warning:: Requires root privileges
"""
# ensure one of params is set & that all set params are valid ip address
if not inet and not mask and not bcast:
raise pyric.error(pyric.EINVAL, "No parameters specified")
if inet and not _validip4_(inet):
raise pyric.error(pyric.EINVAL, "Invalid IP address")
if mask and not _validip4_(mask):
raise pyric.error(pyric.EINVAL, "Invalid netmask")
if bcast and not _validip4_(bcast):
raise pyric.error(pyric.EINVAL, "Invalid broadcast")
if iosock is None: return _iostub_(ifaddrset, card, inet, mask, bcast)
try:
success = True
# we have to do one at a time
if inet: success &= inetset(card, inet, iosock)
if mask: success &= maskset(card, mask, iosock)
if bcast: success &= bcastset(card, bcast, iosock)
return success
except pyric.error as e:
# an ambiguous error is thrown if attempting to set netmask or broadcast
# without an ip address already set on the card
if e.errno == pyric.EADDRNOTAVAIL and inet is None:
raise pyric.error(pyric.EINVAL, "Set ip4 addr first")
else:
raise
except AttributeError as e:
raise pyric.error(pyric.EINVAL, e)
except struct.error as e:
raise pyric.error(pyric.EUNDEF, "Error parsing results: {0}".format(e))
def inetset(card, inet, iosock=None):
"""
Set nic's ip4 addr (ifconfig <card.dev> <inet>
:param card: Card object
:param inet: ip address to set
:param iosock: ioctl socket
:returns: True on success, False otherwise
.. note: setting the ip will set netmask and broadcast accordingly
.. warning:: Requires root privileges
"""
if not _validip4_(inet): raise pyric.error(pyric.EINVAL, "Invalid IP")
if iosock is None: return _iostub_(inetset, card, inet)
try:
flag = sioch.SIOCSIFADDR
ret = io.io_transfer(iosock, flag, ifh.ifreq(card.dev, flag, [inet]))
fam = struct.unpack_from(ifh.sa_addr, ret, ifh.IFNAMELEN)[0]
if fam == ifh.AF_INET:
return _hex2ip4_(ret[20:24]) == inet
else:
raise pyric.error(pyric.EAFNOSUPPORT, "Invalid return ip family")
except AttributeError as e:
raise pyric.error(pyric.EINVAL, e)
except struct.error as e:
raise pyric.error(pyric.EUNDEF, "Error parsing results: {0}".format(e))
except io.error as e:
raise pyric.error(e.errno, e.strerror)
def maskset(card, mask, iosock=None):
"""
Set nic's ip4 netmask (ifconfig <card.dev> netmask <netmask>
:param card: Card object
:param mask: netmask to set
:param iosock: ioctl socket
:returns: True on success, False otherwise
.. note:
throws error if netmask is set and card does not have an ip assigned
.. warning:: Requires root privileges
"""
if not _validip4_(mask): raise pyric.error(pyric.EINVAL, "Invalid netmask")
if iosock is None: return _iostub_(maskset, card, mask)
try:
flag = sioch.SIOCSIFNETMASK
ret = io.io_transfer(iosock, flag, ifh.ifreq(card.dev, flag, [mask]))
fam = struct.unpack_from(ifh.sa_addr, ret, ifh.IFNAMELEN)[0]
if fam == ifh.AF_INET:
return _hex2ip4_(ret[20:24]) == mask
else:
raise pyric.error(pyric.EAFNOSUPPORT, "Invalid return netmask family")
except AttributeError as e:
raise pyric.error(pyric.EINVAL, e)
except struct.error as e:
raise pyric.error(pyric.EUNDEF, "Error parsing results: {0}".format(e))
except io.error as e:
# an ambiguous error is thrown if attempting to set netmask or broadcast
# without an ip address already set on the card
if e.errno == pyric.EADDRNOTAVAIL:
raise pyric.error(pyric.EINVAL, "Cannot set netmask. Set ip first")
else:
raise pyric.error(e, e.strerror)
def bcastset(card, bcast, iosock=None):
"""
Set nic's ip4 netmask (ifconfig <card.dev> broadcast <broadcast>
:param card: Card object
:param bcast: netmask to set
:param iosock: ioctl socket
:returns: True on success, False otherwise
.. note:
1) throws error if netmask is set and card does not have an ip assigned
2) can set broadcast to erroneous values i.e. ipaddr = 192.168.1.2 and
broadcast = 10.0.0.31.
.. warning:: Requires root privileges
"""
if not _validip4_(bcast): raise pyric.error(pyric.EINVAL, "Invalid bcast")
if iosock is None: return _iostub_(bcastset, card, bcast)
# we have to do one at a time
try:
flag = sioch.SIOCSIFBRDADDR
ret = io.io_transfer(iosock, flag, ifh.ifreq(card.dev, flag, [bcast]))
fam = struct.unpack_from(ifh.sa_addr, ret, ifh.IFNAMELEN)[0]
if fam == ifh.AF_INET:
return _hex2ip4_(ret[20:24]) == bcast
else:
raise pyric.error(pyric.EAFNOSUPPORT, "Invalid return broadcast family")
except pyric.error as e:
# an ambiguous error is thrown if attempting to set netmask or broadcast
# without an ip address already set on the card
if e.errno == pyric.EADDRNOTAVAIL:
raise pyric.error(pyric.EINVAL, "Cannot set broadcast. Set ip first")
else:
raise
except AttributeError as e:
raise pyric.error(pyric.EINVAL, e)
except struct.error as e:
raise pyric.error(pyric.EUNDEF, "Error parsing results: {0}".format(e))
except io.error as e:
# an ambiguous error is thrown if attempting to set netmask or broadcast
# without an ip address already set on the card
if e.errno == pyric.EADDRNOTAVAIL:
raise pyric.error(pyric.EINVAL, "Cannot set broadcast. Set ip first")
else:
raise pyric.error(e, e.strerror)
################################################################################
#### HARDWARE ON/OFF ####
################################################################################
def isup(card, iosock=None):
"""
Determine on/off state of card
:param card: Card object
:param iosock: ioctl socket
:returns: True if card is up, False otherwise
"""
if iosock is None: return _iostub_(isup, card)
try:
return _issetf_(_flagsget_(card.dev, iosock), ifh.IFF_UP)
except AttributeError:
raise pyric.error(pyric.EINVAL, "Invalid Card")
def up(card, iosock=None):
"""
Turns dev on (ifconfig <card.dev> up)
:param card: Card object
:param iosock: ioctl socket
.. warning:: Requires root privileges
"""
if iosock is None: return _iostub_(up, card)
try:
flags = _flagsget_(card.dev, iosock)
if not _issetf_(flags, ifh.IFF_UP):
_flagsset_(card.dev, _setf_(flags, ifh.IFF_UP), iosock)
except AttributeError:
raise pyric.error(pyric.EINVAL, "Invalid Card")
def down(card, iosock=None):
"""
Turns def off (ifconfig <card.dev> down)
:param card: Card object
:param iosock: ioctl socket
.. warning:: Requires root privileges
"""
if iosock is None: return _iostub_(down, card)
try:
flags = _flagsget_(card.dev, iosock)
if _issetf_(flags, ifh.IFF_UP):
_flagsset_(card.dev, _unsetf_(flags, ifh.IFF_UP), iosock)
except AttributeError:
raise pyric.error(pyric.EINVAL, "Invalid Card")
def isblocked(card):
"""
Determines blocked state of Card
:param card: Card object
:returns: tuple (Soft={True if soft blocked|False otherwise},
Hard={True if hard blocked|False otherwise})
"""
try:
idx = rfkill.getidx(card.phy)
return rfkill.soft_blocked(idx), rfkill.hard_blocked(idx)
except AttributeError:
raise pyric.error(pyric.ENODEV, "Card is no longer registered")
def block(card):
"""
Soft blocks card
:param card: Card object
"""
try:
idx = rfkill.getidx(card.phy)
rfkill.rfkill_block(idx)
except AttributeError:
raise pyric.error(pyric.ENODEV, "Card is no longer registered")
def unblock(card):
"""
Turns off soft block
:param card:
"""
try:
idx = rfkill.getidx(card.phy)
rfkill.rfkill_unblock(idx)
except AttributeError:
raise pyric.error(pyric.ENODEV, "Card is no longer registered")
################################################################################
#### RADIO PROPERTIES ####
################################################################################
def pwrsaveget(card, nlsock=None):
"""
Returns card's power save state
:param card: Card object
:param nlsock: netlink socket
:returns: True if power save is on, False otherwise
"""
if nlsock is None: return _nlstub_(pwrsaveget, card)
try:
msg = nl.nlmsg_new(nltype=_familyid_(nlsock),
cmd=nl80211h.NL80211_CMD_GET_POWER_SAVE,
flags=nlh.NLM_F_REQUEST | nlh.NLM_F_ACK)
nl.nla_put_u32(msg, card.idx, nl80211h.NL80211_ATTR_IFINDEX)
nl.nl_sendmsg(nlsock, msg)
rmsg = nl.nl_recvmsg(nlsock)
except AttributeError:
raise pyric.error(pyric.EINVAL, "Invalid Card")
except nl.error as e:
raise pyric.error(e.errno, e.strerror)
return nl.nla_find(rmsg, nl80211h.NL80211_ATTR_PS_STATE) == 1
def pwrsaveset(card, on, nlsock=None):
"""
Sets card's power save state
:param card: Card object
:param on: {True = on|False = off}
:param nlsock: netlink socket
.. warning:: Requires root privileges
"""
if nlsock is None: return _nlstub_(pwrsaveset, card, on)
try:
msg = nl.nlmsg_new(nltype=_familyid_(nlsock),
cmd=nl80211h.NL80211_CMD_SET_POWER_SAVE,
flags=nlh.NLM_F_REQUEST | nlh.NLM_F_ACK)
nl.nla_put_u32(msg, card.idx, nl80211h.NL80211_ATTR_IFINDEX)
nl.nla_put_u32(msg, int(on), nl80211h.NL80211_ATTR_PS_STATE)
nl.nl_sendmsg(nlsock, msg)
_ = nl.nl_recvmsg(nlsock)
except AttributeError:
raise pyric.error(pyric.EINVAL, "Invalid Card")
except ValueError:
raise pyric.error(pyric.EINVAL, "Invalid parameter {0} for on".format(on))
except nl.error as e:
raise pyric.error(e.errno, e.strerror)
def covclassget(card, nlsock=None):
"""
Gets the coverage class value
:param card: Card object
:param nlsock: netlink socket
:returns: coverage class value
"""
if nlsock is None: return _nlstub_(covclassget, card)
return phyinfo(card, nlsock)['cov_class']
def covclassset(card, cc, nlsock=None):
"""
Sets the coverage class. The coverage class IAW IEEE Std 802.11-2012 is
defined as the Air propagation time & together with max tx power control
the BSS diamter
:param card: Card object
:param cc: coverage class 0 to 31 IAW IEEE Std 802.11-2012 Table 8-56
:param nlsock: netlink socket
.. warning:: Requires root privileges. Also this might not work on all
systems.
"""
if cc < wlan.COV_CLASS_MIN or cc > wlan.COV_CLASS_MAX:
# this can work 'incorrectly' on non-int values but these will
# be caught later during conversion
emsg = "Cov class must be integer {0}-{1}".format(wlan.COV_CLASS_MIN,
wlan.COV_CLASS_MAX)
raise pyric.error(pyric.EINVAL, emsg)
if nlsock is None: return _nlstub_(covclassset, card, cc)
try:
msg = nl.nlmsg_new(nltype=_familyid_(nlsock),
cmd=nl80211h.NL80211_CMD_SET_WIPHY,
flags=nlh.NLM_F_REQUEST | nlh.NLM_F_ACK)
nl.nla_put_u32(msg, card.phy, nl80211h.NL80211_ATTR_WIPHY)
nl.nla_put_u8(msg, int(cc), nl80211h.NL80211_ATTR_WIPHY_COVERAGE_CLASS)
nl.nl_sendmsg(nlsock, msg)
_ = nl.nl_recvmsg(nlsock)
except AttributeError:
raise pyric.error(pyric.EINVAL, "Invalid Card")
except ValueError:
raise pyric.error(pyric.EINVAL, "Invalid value {0} for Cov. Class".format(cc))
except nl.error as e:
raise pyric.error(e.errno, e.strerror)
def retryshortget(card, nlsock=None):
"""
Gets the short retry limit.
:param card: Card object
:param nlsock: netlink socket
"""
if nlsock is None: return _nlstub_(retryshortget, card)
return phyinfo(card, nlsock)['retry_short']
def retryshortset(card, lim, nlsock=None):
"""
Sets the short retry limit.
:param card: Card object
:param lim: max # of short retries 1 - 255
:param nlsock: netlink socket
.. note: with kernel 4, the kernel does not allow setting up to the max
.. warning:: Requires root privileges
"""
if lim < wlan.RETRY_MIN or lim > wlan.RETRY_MAX:
# this can work 'incorrectly' on non-int values but these will
# be caught later during conversion
emsg = "Retry short must be integer {0}-{1}".format(wlan.RETRY_MIN,
wlan.RETRY_MAX)
raise pyric.error(pyric.EINVAL, emsg)
if nlsock is None: return _nlstub_(retryshortset, card, lim)
try:
msg = nl.nlmsg_new(nltype=_familyid_(nlsock),
cmd=nl80211h.NL80211_CMD_SET_WIPHY,
flags=nlh.NLM_F_REQUEST | nlh.NLM_F_ACK)
nl.nla_put_u32(msg, card.phy, nl80211h.NL80211_ATTR_WIPHY)
nl.nla_put_u8(msg, int(lim), nl80211h.NL80211_ATTR_WIPHY_RETRY_SHORT)
nl.nl_sendmsg(nlsock, msg)
_ = nl.nl_recvmsg(nlsock)
except AttributeError:
raise pyric.error(pyric.EINVAL, "Invalid Card")
except ValueError:
raise pyric.error(pyric.EINVAL, "Invalid value {0} for lim".format(lim))
except nl.error as e:
raise pyric.error(e.errno, e.strerror)
def retrylongget(card, nlsock=None):
"""
Gets the long retry limit.
:param card: Card object
:param nlsock: netlink socket
:returns: card's long retry
"""
if nlsock is None: return _nlstub_(retrylongget, card)
return phyinfo(card, nlsock)['retry_long']
def retrylongset(card, lim, nlsock=None):
"""
Sets the long retry limit.
:param card: Card object
:param lim: max # of short retries 1 - 255
:param nlsock: netlink socket
.. note: after moving to kernel 4, the kernel does not allow setting up to
the max
.. warning:: Requires root privileges
"""
if lim < wlan.RETRY_MIN or lim > wlan.RETRY_MAX:
# this can work 'incorrectly' on non-int values but these will
# be caught later during conversion
emsg = "Retry long must be integer {0}-{1}".format(wlan.RETRY_MIN,
wlan.RETRY_MAX)
raise pyric.error(pyric.EINVAL, emsg)
if nlsock is None: return _nlstub_(retrylongset, card, lim)
try:
msg = nl.nlmsg_new(nltype=_familyid_(nlsock),
cmd=nl80211h.NL80211_CMD_SET_WIPHY,
flags=nlh.NLM_F_REQUEST | nlh.NLM_F_ACK)
nl.nla_put_u32(msg, card.phy, nl80211h.NL80211_ATTR_WIPHY)
nl.nla_put_u8(msg, int(lim), nl80211h.NL80211_ATTR_WIPHY_RETRY_LONG)
nl.nl_sendmsg(nlsock, msg)
_ = nl.nl_recvmsg(nlsock)
except AttributeError:
raise pyric.error(pyric.EINVAL, "Invalid Card")
except ValueError:
raise pyric.error(pyric.EINVAL, "Invalid value {0} for lim".format(lim))
except nl.error as e:
raise pyric.error(e.errno, e.strerror)
def rtsthreshget(card, nlsock=None):
"""
Gets RTS Threshold
:param card: Card Object
:param nlsock: netlink socket
:returns: RTS threshold
"""
if nlsock is None: return _nlstub_(rtsthreshget, card)
return phyinfo(card, nlsock)['rts_thresh']
def rtsthreshset(card, thresh, nlsock=None):
"""
Sets the RTS threshold. If off, RTS is disabled. If an integer, sets the
smallest packet for which card will send an RTS prior to each transmission
:param card: Card object
:param thresh: rts threshold limit
:param nlsock: netlink socket
.. warning:: Requires root privileges
"""
if thresh == 'off': thresh = wlan.RTS_THRESH_OFF
elif thresh == wlan.RTS_THRESH_OFF: pass
elif thresh < wlan.RTS_THRESH_MIN or thresh > wlan.RTS_THRESH_MAX:
emsg = "Thresh must be 'off' or integer {0}-{1}".format(wlan.RTS_THRESH_MIN,
wlan.RTS_THRESH_MAX)
raise pyric.error(pyric.EINVAL, emsg)
if nlsock is None: return _nlstub_(rtsthreshset, card, thresh)
try:
msg = nl.nlmsg_new(nltype=_familyid_(nlsock),
cmd=nl80211h.NL80211_CMD_SET_WIPHY,
flags=nlh.NLM_F_REQUEST | nlh.NLM_F_ACK)
nl.nla_put_u32(msg, card.phy, nl80211h.NL80211_ATTR_WIPHY)
nl.nla_put_u32(msg, thresh, nl80211h.NL80211_ATTR_WIPHY_RTS_THRESHOLD)
nl.nl_sendmsg(nlsock, msg)
_ = nl.nl_recvmsg(nlsock)
except AttributeError:
raise pyric.error(pyric.EINVAL, "Invalid Card")
except ValueError:
raise pyric.error(pyric.EINVAL, "Invalid value {0} for thresh".format(thresh))
except nl.error as e:
raise pyric.error(e.errno, e.strerror)
def fragthreshget(card, nlsock=None):
"""
Gets Fragmentation Threshold
:param card: Card Object
:param nlsock: netlink socket
:returns: RTS threshold
"""
if nlsock is None: return _nlstub_(fragthreshget, card)
return phyinfo(card, nlsock)['frag_thresh']
def fragthreshset(card, thresh, nlsock=None):
"""
Sets the Frag threshold. If off, fragmentation is disabled. If an integer,
sets the largest packet before the card will enable fragmentation
:param card: Card object
:param thresh: frag threshold limit in octets
:param nlsock: netlink socket
.. warning:: Requires root privileges
"""
if thresh == 'off': thresh = wlan.FRAG_THRESH_OFF
elif thresh == wlan.FRAG_THRESH_OFF: pass
elif thresh < wlan.FRAG_THRESH_MIN or thresh > wlan.FRAG_THRESH_MAX:
emsg = "Thresh must be 'off' or integer {0}-{1}".format(wlan.FRAG_THRESH_MIN,
wlan.FRAG_THRESH_MAX)
raise pyric.error(pyric.EINVAL, emsg)
if nlsock is None: return _nlstub_(fragthreshset, card, thresh)
try:
msg = nl.nlmsg_new(nltype=_familyid_(nlsock),
cmd=nl80211h.NL80211_CMD_SET_WIPHY,
flags=nlh.NLM_F_REQUEST | nlh.NLM_F_ACK)
nl.nla_put_u32(msg, card.phy, nl80211h.NL80211_ATTR_WIPHY)
nl.nla_put_u32(msg, thresh, nl80211h.NL80211_ATTR_WIPHY_FRAG_THRESHOLD)
nl.nl_sendmsg(nlsock, msg)
_ = nl.nl_recvmsg(nlsock)
except AttributeError:
raise pyric.error(pyric.EINVAL, "Invalid Card")
except nl.error as e:
raise pyric.error(e.errno, e.strerror)
################################################################################
#### INFO RELATED ####
################################################################################
def devfreqs(card, nlsock=None):
"""
Returns card's supported frequencies
:param card: Card object
:param nlsock: netlink socket
:returns: list of supported frequencies
"""
if nlsock is None: return _nlstub_(devfreqs, card)
rfs = []
pinfo = phyinfo(card, nlsock)
for band in pinfo['bands']:
rfs.extend(pinfo['bands'][band]['rfs'])
rfs = sorted(rfs)
return rfs
def devchs(card, nlsock=None):
"""
Returns card's supported channels
:param card: Card object
:param nlsock: netlink socket
:returns: list of supported channels
"""
if nlsock is None: return _nlstub_(devchs, card)
return [channels.rf2ch(rf) for rf in devfreqs(card,nlsock)]
def devstds(card, nlsock=None):
"""
Gets card's wireless standards (iwconfig <card.dev> | grep IEEE
:param card: Card object
:param nlsock: netlink socket
:returns: list of standards (letter designators)
"""
if nlsock is None: return _nlstub_(devstds, card)
stds = []
bands = phyinfo(card,nlsock)['bands']
if '5GHz' in bands: stds.append('a')
if '2GHz' in bands: stds.extend(['b','g']) # assume backward compat with b
HT = VHT = True
for band in bands:
HT &= bands[band]['HT']
VHT &= bands[band]['VHT']
if HT: stds.append('n')
if VHT: stds.append('ac')
return stds
def devmodes(card, nlsock=None):
"""
Gets supported modes card can operate in
:param card: Card object
:param nlsock: netlink socket
:returns: list of card's supported modes
"""
if nlsock is None: return _nlstub_(devmodes, card)
return phyinfo(card, nlsock)['modes']
def devcmds(card, nlsock=None):
"""
Get supported commands card can execute
:param card: Card object
:param nlsock: netlink socket
:returns: supported commands
"""
if nlsock is None: return _nlstub_(devcmds, card)
return phyinfo(card, nlsock)['commands']