forked from br0ns/net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net
executable file
·1480 lines (1277 loc) · 42.3 KB
/
net
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 python2.7
import os, sys, time, subprocess, re, random, yaml, json, resource
# Based on https://git.pwnies.dk/IdolfHatler/vcsh-wifi
DEFAULT_CONFIG_FILE = '~/.net.conf'
CONFIG_FILE = None
CONFIG = None
COMMON = None
IFACE = None
VERBOSE = False
IGNORED_IFACES = set()
IGNORED_SSIDS = set()
VPN_TMPSTOP_DELAY = 60*5
# Valid config file keys:
KNOWN_KEYS = (
'ssid',
'psk',
'mac',
'dns',
'wpa',
'hostname',
'interface',
'addr',
'gateway',
'vpn',
'routes',
'udhcpc-config',
'ap-addr',
)
# Use these if they are not defined in the configuration file
FALLBACK_CONFIG = {
'ignored': {
'interfaces': [
r'docker[0-9]+',
r'br[0-9]+',
r'vboxnet[0-9]+',
r'tap[0-9]+',
r'tun[0-9]+',
r'vmnet[0-9]+',
],
'ssids': [],
},
'wired': {
'dns' : 'dhcp',
'mac' : 'default',
'hostname': None,
},
}
def die(msg='', exitcode=1):
if msg:
print >>sys.stderr, msg
sys.exit(exitcode)
def log(msg):
print >>sys.stderr, msg
def logv(msg):
if VERBOSE:
log(msg)
def usage():
die(\
'''usage: net [<command>] [<args>] [--config=<config>] [--iface=<interface>]
[--no-vpn] [--verbose] [-h] [--help]
Shorthands:
If no positional arguments are given the command is "list".
If one positional argument is given the command is "connect".
Commands:
list:
List available connections.
scan:
Scan for access points.
connect <connection> [<password>]:
If <connection> is present in the configuration file then use that,
otherwise connect to an access point with SSID <connection>, using the
password <password> if specified.
stop [<interface> [<interface> ...]]:
Bring down the connection. Brings down all interfaces if called with no
arguments.
dns [<dns> [<dns> ...]]:
Change DNS server. No argument or "dhcp" requests DNS servers via DHCP.
mac [<mac>]:
Change the MAC address of the interface specified by --iface. If no address
is given, one is chosen at random.
vpn <name> [stop|tmpstop [delay]]:
Connect to, or disconnect (temporarily [default = 5m] in case of tmpstop)
from, VPN.
genkey:
Generate a WireGuard key pair.
show [<connection>]:
Show configuration options. If no connection is specified, all are show.
help:
You're reading it.
Options:
--config=<config>:
Select configurations file. If <config> is "-" no configuration file is
used. Defaults to "~/.net.conf".
--iface=<interface>:
Select networking interface. Overridden by configuration file if specified.
Defaults to first WiFi capable interface found.
--no-vpn:
Don't connect to a VPN. Acts as if the connection configuration did not
have a `vpn` field.
--verbose:
Print every executed command (and the result) to stdout.''')
ANSI_ESC = '\x1b[%dm'
ANSI_RESET = ANSI_ESC % 0
def ansi(s, esc):
s = esc + s
if not s.endswith(ANSI_RESET):
s += ANSI_RESET
return s
def red(s):
return ansi(s, ANSI_ESC % 31)
def green(s):
return ansi(s, ANSI_ESC % 32)
def optlist(s, opts, default = None, abbrevs = None):
# Option list:
# [(key, altkey1, altkey2, ..., value), ...]
# [key, ...]
def conv(opt):
if isinstance(opt, (str, unicode)):
return ((opt,),opt)
return (opt[:-1], opt[-1])
opts = map(conv, opts)
abbrevs = abbrevs or {}
for ks, _ in opts:
k = ks[0]
abbrevs.setdefault(k, k[0])
if len(set(abbrevs.values())) != len(opts):
die('Ambiguous options')
ls = map(len, abbrevs.values())
if max(ls) > 1 or min(ls) < 1:
die('Abbreviation must be exactly one character')
abbrs = []
pabbrs = []
for ks, v in opts:
k = ks[0]
abbr = abbrevs[k]
abbrs.append(abbr)
if default in (k, v):
abbr = green(abbr.upper())
pabbrs.append(abbr)
prompt = '%s [%s]: ' % (s, '/'.join(pabbrs))
while True:
opt = raw_input(prompt).lower()
if opt == '':
return default
for ks, v in opts:
abbr = abbrevs[ks[0]]
if opt == abbr or opt in ks:
return v
print 'Please select one of %s' % ', '.join(abbrs)
def yesno (s, default):
optlist = green('Y') + '/n' if default else 'y/' + green('N')
prompt = '%s [%s]: ' % (s, optlist)
while True:
opt = raw_input(prompt).lower()
if opt == '':
return default
if opt in ('yes', 'y'):
return True
if opt in ('no', 'n'):
return False
print 'Please answer yes or no'
def run(cmd, exit_on_error = False):
if VERBOSE:
print '+', cmd
p = subprocess.Popen(cmd,
stdin = file('/dev/null'),
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True,
)
o, e = p.communicate()
status = p.poll()
if status != 0:
if exit_on_error or VERBOSE:
print 'Failed (status: %d): %s' % (status, cmd)
if exit_on_error:
die(e)
else:
return None
if VERBOSE:
if o:
print o.rstrip()
if e:
print red(e.strip())
return o
def run_or_die(cmd):
return run(cmd, exit_on_error = True)
def daemon():
try:
pid = os.fork()
if pid > 0:
# Return as parent
return False
except OSError, e:
die('fork failed')
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError, e:
die('fork failed')
# Close file descriptors
# sys.stdout.flush()
# sys.stderr.flush()
# for i in range(1024):
# os.close(i)
# Return as daemon
return True
def run_daemon(argv):
if VERBOSE:
print '+ (DAEMON)', ' '.join(argv)
if daemon():
os.execvp(argv[0], argv)
die('exec failed')
def rm(*paths):
for p in paths:
try:
os.unlink(p)
except OSError:
pass
def expand(path):
if path.startswith('~/'):
user = os.environ.get('SUDO_USER', '')
path = '~%s/%s' % (user, path[2:])
return os.path.expanduser(path)
def become_root():
if os.getuid() != 0:
os.execlp('sudo', 'sudo', 'python', *sys.argv)
def write_root_file(path, mode, data):
with open(path, 'w') as fd:
os.fchown(fd.fileno(), 0, 0)
os.fchmod(fd.fileno(), mode)
fd.write(data)
def ignore(iface):
return any(ign.match(iface) for ign in IGNORED_IFACES)
def get_ifaces(only_up = False):
ifaces = []
for iface, parms in re.findall(r'^\d+: (\S+?)(?:@\S+)?: <([^>]*)>',
run_or_die('ip link show'),
re.MULTILINE):
if 'LOOPBACK' in parms:
continue
if only_up and 'UP' not in parms:
continue
if not ignore(iface):
ifaces.append(iface)
return ifaces
def get_ifaces_up():
return get_ifaces(True)
def is_wifi_iface(iface):
return run('iw dev %s info' % iface) != None
def get_wifi_ifaces():
return [iface for iface in
run_or_die('ls -d /sys/class/net/*/wireless 2>/dev/null | cut -d/ -f5').strip().split('\n')
if not ignore(iface)]
def get_wifi_iface_up():
for iface in get_ifaces_up():
if is_wifi_iface(iface):
return iface
def get_default_wifi_iface():
ifaces = get_wifi_ifaces()
if ifaces:
iface = ifaces[0]
if len(ifaces) > 1:
print 'Using interface "%s"' % iface
return iface
die('Could not find any WiFi interfaces')
def get_default_wired_iface():
# This is an ugly hack, but is there any better way? We get the
# non-wireless, non-loopback interfaces and select the first one. Hopefully
# that is good enough.
ifaces = [iface for iface in get_ifaces() if not is_wifi_iface(iface)]
if ifaces:
iface = ifaces[0]
if len(ifaces) > 1:
print 'Using interface "%s"' % iface
return iface
die('Could not find any wired interfaces')
def normalize_net_or_host(sel):
if sel == 'default':
sel = '0.0.0.0/0'
if '/' in sel:
addr, mask = sel.split('/')
mask = int(mask)
else:
addr = sel
mask = 32
return addr, mask
def get_routes():
become_root()
output = run_or_die('ip -4 route')
routes = []
for line in output.splitlines():
fields = line.split()
target = fields[0]
attrs = fields[1:]
target, netmask = normalize_net_or_host(target)
route = {'target': target,
'netmask': netmask,
}
for i in xrange(0, len(attrs), 2):
route[attrs[i]] = attrs[i + 1]
routes.append(route)
return routes
def get_default_route():
for route in get_routes():
if route['netmask'] == 0:
return route
def get_addrs4(iface, with_netmask=False):
output = run_or_die('ip addr show %s' % iface)
addrs = re.findall(r'inet (\d+\.\d+\.\d+\.\d+)(?:/(\d+))?', output)
if not with_netmask:
addrs = [addr[0] for addr in addrs]
return addrs
def get_addr4(iface, with_netmask=False):
addrs = get_addrs4(iface, with_netmask=with_netmask)
if addrs:
return addrs[0]
def get_vpns():
read_config()
return VPN.keys()
def bash_complete(xs):
# XXX: Make this robust
def quote(s):
return s.encode('utf8').replace(' ', r'\\ ')
print '\n'.join(map(quote, xs))
sys.exit(0)
def parse_args():
global CONFIG_FILE, IFACE, VERBOSE, NOVPN
optional = {}
args = sys.argv[1:][::]
i = 0
while i < len(args):
arg = args[i]
if arg.startswith('--'):
if '=' in arg:
key, val = arg.split('=', 1)
else:
key = arg
val = True
optional[key] = val
args.pop(i)
elif arg.startswith('-'):
for key in arg[1:]:
optional['-' + key] = True
args.pop(i)
else:
i += 1
CONFIG_FILE = optional.pop('--config', DEFAULT_CONFIG_FILE)
if CONFIG_FILE == '-':
CONFIG_FILE = None
if '-h' in optional or '--help' in optional or (args and args[0] == 'help'):
usage()
read_config()
if '--internal-list-all' in optional:
bash_complete(CONFIG.keys())
if '--internal-list-up' in optional:
bash_complete(get_ifaces_up())
if '--internal-list-vpn' in optional:
bash_complete(get_vpns())
if '--internal-scan-cache' in optional:
try:
bash_complete(json.load(open('/tmp/.net-scan')))
except:
die('')
IFACE = optional.pop('--iface', None)
VERBOSE = optional.pop('--verbose', False)
NOVPN = optional.pop('--no-vpn', False)
if optional:
die('Unknown argument: %s' % optional.keys()[0])
if len(args) == 0:
return 'list', []
if args[0] in ('list', 'scan', 'connect', 'mac', 'dns', 'stop', 'show', 'vpn', 'genkey'):
cmd = args.pop(0)
else:
cmd = 'connect'
return cmd, args
def parse_wpa_conf(raw_conf):
stack = []
obj = {}
for line in raw_conf.split('\n'):
line = line.strip()
if not line:
continue
if line == '}':
try:
obj = stack.pop()
except IndexError:
die('Unmatched }')
continue
if '=' not in line:
die('Expected = in line: %s' % line)
key, val = line.split('=', 1)
key = key.strip()
val = val.strip()
if val == '{':
child = {}
obj[key] = child
stack.append(obj)
obj = child
else:
obj[key] = val
if len(stack) > 0:
die('Unmatched {')
return obj
def write_wpa_conf(conf):
def loop(obj):
out = []
for k, v in obj.items():
if isinstance(v, str):
out.append('%s=%s' % (k, v))
else:
out.append('%s={' % k)
out += [' ' + line for line in loop(v)]
out.append('}')
return out
return '\n'.join(loop(conf)) + '\n'
def read_config(reraise = False):
global CONFIG, COMMON, IGNORED_IFACES, IGNORED_SSIDS, VPN
if CONFIG is not None:
return
CONFIG = {}
COMMON = {}
if CONFIG_FILE is None:
return
try:
with open(expand(CONFIG_FILE)) as fd:
raw_config = yaml.load(fd)
except Exception as e:
if reraise:
raise
die(e)
if raw_config is None:
if reraise:
raise
die('Empty configuration')
for k, v in FALLBACK_CONFIG.items():
raw_config.setdefault(k, v)
IGN = raw_config.pop('ignored', {})
IGNORED_IFACES = set(re.compile(ign) for ign in IGN.get('interfaces') or [])
IGNORED_SSIDS = set(re.compile(ign) for ign in IGN.get('ssids') or [])
VPN = raw_config.pop('vpn', {})
for name, raw_conn in raw_config.items():
conn = {}
for key, val in (raw_conn or {}).items():
# Assume UTF-8 encoding
if isinstance(val, unicode):
val = val.encode('utf8')
if key == 'wpa':
val = parse_wpa_conf(val)
if key not in KNOWN_KEYS:
die('Unknown key: %s' % key)
if isinstance(val, unicode):
# The yaml decoder will convert
# non-ascii strings into unicode
# This is not what we want. We want
# e.g. '\xc3' in the yaml file to become b'\xc3',
# not u'\xc3'.
# This is an ugly hack to fix it.
val = val.encode('iso-8859-1')
conn[key] = val
if name == 'common':
COMMON = conn
else:
CONFIG[name] = conn
# Set common settings
for name, conn in CONFIG.items():
for key, val in COMMON.items():
conn.setdefault(key, val)
def do_show(k = None):
read_config()
if k:
if k not in CONFIG:
die('No such key: %s' % k)
v = CONFIG[k]
else:
v = CONFIG
die(yaml.dump(v), 0)
def do_list():
read_config()
connections = CONFIG.keys()
c2if = get_connection_to_iface_map()
width = max(len(c) for c in connections)
for conn in sorted(connections):
if conn in c2if:
iface = c2if[conn]
print '%s (%s: %s)' % (conn.ljust(width), iface,
get_addr4(iface) or 'no address')
del c2if[conn]
else:
print conn
if c2if:
print
for c, i in c2if.items():
print '%s: "%s", %s' % (i, c, get_addr4(i) or 'no address')
def unescape_c_str(data):
return re.sub(
r'\\x([0-9a-f]{2})',
lambda x: x.group(1).decode('hex'),
data
)
def escape_c_str(data):
return re.sub(
r'[^a-zA-Z0-9!#$%&()*+,./:;<=>?@\[\]^_`{|}~ -]|(\s*$)|(^\s*)',
lambda x: ''.join(r'\x%02x' % ord(c) for c in x.group(0)),
data
)
def parse_iw_scan_tree(iface):
while True:
data = run_or_die('iw dev %s scan | expand' % iface).strip('\n')
if data:
break
else:
print "Scan failed, re-running"
time.sleep(0.5)
parents = [(-1, {})]
last = None
def popold(curindent):
obj = None
while parents and curindent <= parents[-1][0]:
_, obj = parents.pop()
for key, val in obj.items():
if isinstance(val, dict) and val.keys() == [None]:
obj[key] = val[None]
return obj
for line in data.split('\n'):
curindent = len(line) - len(line.lstrip(' '))
popold(curindent)
line = line.lstrip(' ')
if line.startswith('* '):
line = line[2:].lstrip(' ')
if ': ' in line:
key, value = line.split(': ', 1)
obj = {None: value.lstrip(' ')}
else:
key = line
obj = {}
parents[-1][1][key] = obj
parents.append((curindent, obj))
return popold(-1)
def do_scan():
become_root()
iface = IFACE or get_wifi_iface_up() or get_default_wifi_iface()
# Make sure iface is up
run_or_die('ip link set dev %s up' % iface)
aps = {}
signal_re = re.compile(r'^([0-9.-]*) dBm$')
addr_re = re.compile(r'BSS (([0-9a-f]{2}:?){6})')
for addr, ap in parse_iw_scan_tree(iface).items():
addr = addr_re.match(addr).group(1)
ok = True
for key in ['SSID', 'signal']:
if key not in ap or ap[key] == '':
ok = False
if 'SSID' not in ap:
continue
ap['SSID'] = unescape_c_str(ap['SSID'])
try:
ssid = ap['SSID'].decode('utf8')
except UnicodeDecodeError:
ssid = escape_c_str(ap['SSID'])
quality = float(signal_re.match(ap['signal']).group(1))
crypto = ap.get('RSN', ap.get('WPA', ''))
if crypto:
crypto = crypto.get('Authentication suites', 'UNKNOWN')
if ap['SSID'] == '':
continue
if ssid in aps:
aps[ssid][1].append(quality)
aps[ssid][2].append(addr)
else:
aps[ssid] = [crypto, [quality], [addr]]
if len(aps) == 0:
print 'Found no access points'
return
with open('/tmp/.net-scan', 'w') as fd:
json.dump(aps.keys(), fd)
ssid_align = max(map(len, aps.keys()))
for ssid, (crypto, qualities, addrs) in \
sorted(aps.items(), key=lambda x: -max(x[1][1])):
ssid = ssid.strip('\x00')
print '%s %d dBm %s' % ((ssid or '(hidden)').ljust(ssid_align),
max(qualities),
crypto
)
if len(addrs) > 1 or ssid == '':
for addr, quality in zip(addrs, qualities):
print ' - %s %d dBm' % (addr, quality)
def start_dhcp_cmd(iface, hostname = None, udhcpc_config = None):
cmd = 'udhcpc -R -i %s' % iface
if hostname:
cmd += ' -x hostname:%s' % hostname
if udhcpc_config:
cmd += ' -s %s' % udhcpc_config
return cmd
def stop_dhcp_cmd(iface):
pattern = start_dhcp_cmd(iface)
return 'pkill -f "^%s"' % pattern
def stop_dhcp(iface):
run(stop_dhcp_cmd(iface))
def renew_dhcp_cmd():
# It would be nice only notify the "right one". But what *is* the right one?
# We only call this function in `do_dns', and this function is not aware of
# which interface we are talking about. So: We renew them all and accept the
# race condition.
return 'pkill -SIGUSR1 udhcpc'
def renew_dhcp():
run(renew_dhcp_cmd())
def start_openvpn_cmd(name):
return 'openvpn --config /tmp/%s.ovpn --log /tmp/%s.ovpn.log' % \
(name, name)
def create_wg_iface(iface = 'wg1337', addr = '192.168.255.1/24'):
become_root()
run_or_die('ip link add dev %s type wireguard' % iface)
run_or_die('ip address add dev %s %s' % (iface, addr))
def destroy_wg_iface(iface = 'wg1337'):
become_root()
run('ip link set dev %s down' % iface)
run('ip link del dev %s' % iface)
def wg_setconf(name, iface = 'wg1337'):
become_root()
run_or_die('ip link set dev %s down' % iface)
conf = VPN[name]['config']
path_conf = '/tmp/%s-wg.conf' % name
write_root_file(path_conf, 0o600, conf)
run_or_die('wg setconf %s %s' % (iface, path_conf))
rm(path_conf)
def set_wg_dgw(name):
cfg_ep = [x for x in VPN[name]['config'].split('\n') if 'Endpoint' in x or 'endpoint' in x]
if not cfg_ep:
stop_vpn(name)
die('No endpoint set for VPN: %s' % name)
dgwaddr = [x for x in run_or_die('ip route show').split('\n') if 'default' in x]
endpoint = ''.join(re.findall(r'[0-9]+(?:\.[0-9]+){3}', str(cfg_ep)))
dgwaddress = ''.join(re.findall(r'[0-9]+(?:\.[0-9]+){3}', str(dgwaddr)))
become_root()
run('ip route del 0.0.0.0/1 dev %s' % VPN[name]['interface'])
run('ip route del 128.0.0.0/1 dev %s' % VPN[name]['interface'])
run('ip route del %s/32 via %s' % (endpoint, dgwaddress))
run_or_die('ip route add 0.0.0.0/1 dev %s' % VPN[name]['interface'])
run_or_die('ip route add 128.0.0.0/1 dev %s' % VPN[name]['interface'])
run_or_die('ip route add %s/32 via %s' % (endpoint, dgwaddress))
def start_vpn(name):
print 'Starting VPN (%s)' % name
try:
type = VPN[name]['type']
conf = VPN[name]['config']
except (KeyError, TypeError):
die('%s is misconfigured - check .net.conf.example' % name)
if type == 'openvpn':
path_conf = '/tmp/%s.ovpn' % name
path_log = path_conf + '.log'
write_root_file(path_conf, 0o600, conf)
rm(path_log)
run_daemon(start_openvpn_cmd(name).split())
# Wait for OpenVPN to start
while True:
try:
fd = open(path_log)
break
except IOError:
time.sleep(0.1)
# Now we can remove the config file
rm(path_conf)
# Wait for the connection to be established
line = ''
marker = 'Initialization Sequence Completed'
while True:
s = fd.readline()
line += s
if not s or s[-1] != '\n':
time.sleep(0.05)
continue
line = line.rstrip()
if VERBOSE:
print line
if marker in line:
break
line = ''
elif type == 'wireguard':
internaddr = ''
ifacename = ''
d_gateway = False
try:
internaddr = VPN[name]['address']
ifacename = VPN[name]['interface']
d_gateway = VPN[name]['gateway']
except:
pass
if internaddr and ifacename:
create_wg_iface(iface = ifacename, addr = internaddr)
wg_setconf(name, iface = ifacename)
run_or_die('ip link set dev %s up' % ifacename)
elif internaddr:
create_wg_iface(addr = internaddr)
wg_setconf(name)
run_or_die('ip link set dev wg1337 up')
elif ifacename:
create_wg_iface(iface = ifacename)
wg_setconf(name, iface = ifacename)
run_or_die('ip link set dev %s up' % ifacename)
else:
create_wg_iface()
wg_setconf(name)
run_or_die('ip link set dev wg1337 up')
if d_gateway == True:
set_wg_dgw(name)
else:
die('Unknown VPN type selected for: %s\
\nSupported VPN types: openvpn, wireguard' % name)
def stop_vpn(name):
print 'Stopping VPN (%s)' % name
try:
type = VPN[name]['type']
except (KeyError, TypeError):
die('%s is misconfigured - check .net.conf.example' % name)
if type == 'openvpn':
pattern = start_openvpn_cmd(name)
run('pkill -9 -f "^%s"' % pattern)
elif type == 'wireguard':
try:
if VPN[name]['interface']:
destroy_wg_iface(iface = VPN[name]['interface'])
except KeyError:
destroy_wg_iface()
else:
die('Unknown VPN type selected for: %s\
\nSupported VPN types: openvpn, wireguard' % name)
def tmp_stop_vpn(name, delay):
print 'Temporarily:',
stop_vpn(name)
# Daemonize
if os.fork():
os._exit(0)
# Detach from terminal and create own PG
os.setsid()
# Close FD's
for fd in range(resource.getrlimit(resource.RLIMIT_NOFILE)[0]):
try:
os.close(fd)
except OSError:
pass
# Attach /dev/null to std{in,out,err}
devnull = os.open('/dev/null', os.O_RDWR)
os.dup2(devnull, 0)
os.dup2(devnull, 1)
os.dup2(devnull, 2)
os.close(devnull)
# Wait
time.sleep(delay)
# Restart VPN
start_vpn(name)
def add_route_cmd(route, default_gw=None):
# Format:
# <dst>[/prefix] [-> {<addr>,<interface>,<connection>)]
if not route:
die('no route given')
fields = route.split()
dst = fields[0]
if len(fields) == 1:
gw = default_gw
elif len(fields) == 3:
if fields[1] != '->':
die('Bad route format: %s' % route)
sel = fields[2]
# Determine gateway from (in this order):
# - Concrete address
# - Interface
# - Interface of active connection
# - Configured connection:
# - Gateway
# - Address
# - Interface
def get_gw(sel):
if validate_ipv4(sel):
return sel
def from_addr(addr, netmask):
if not netmask:
logv('(Guessed netmask: 255.255.255.0)')
netmask = '24'
return guess_gateway_ipv4(addr, netmask)
def from_iface(iface):
return from_addr(*get_addr4(sel, with_netmask=True))
ifaces = get_ifaces_up()
if sel in ifaces:
return from_iface(sel)
c2if = get_connection_to_iface_map()
if sel in c2if:
return from_iface(c2if[sel])
read_config()
conf = CONFIG.get(sel)
if conf:
gw = conf.get('gateway')
if gw:
return gw
addr = conf.get('addr')
if addr:
return from_addr(
re.findall(r'inet (\d+\.\d+\.\d+\.\d+)(?:/(\d+))?',
addr)
)
iface = conf.get('interface')
if iface:
return from_iface(iface)
gw = get_gw(sel)
if not gw:
die('No gateway matches "%s"' % sel)
addr, netmask = normalize_net_or_host(dst)
cmd = 'ip route add %s/%d via %s' % (addr, netmask, gw)
return cmd
def finalize_hostname(hostname):
names = ('Jonas', 'Noah', 'Liam', 'Jacob', 'Mason', 'William', 'Ethan',
'Michael', 'Alexander', 'Jayden', 'Daniel', 'Elijah', 'Aiden',
'James', 'Benjamin', 'Matthew', 'Jackson', 'Logan', 'David',
'Anthony', 'Joseph', 'Joshua', 'Andrew', 'Lucas', 'Gabriel',
'Samuel', 'Christopher', 'John', 'Dylan', 'Isaac', 'Ryan',
'Nathan', 'Carter', 'Caleb', 'Luke', 'Christian', 'Hunter',
'Henry', 'Owen', 'Landon', 'Jack', 'Wyatt', 'Jonathan', 'Eli',
'Isaiah', 'Sebastian', 'Jaxon', 'Julian', 'Brayden', 'Gavin',
'Levi', 'Aaron', 'Oliver', 'Jordan', 'Nicholas', 'Evan', 'Connor',
'Charles', 'Jeremiah', 'Cameron', 'Adrian', 'Thomas', 'Robert',
'Tyler', 'Colton', 'Austin', 'Jace', 'Angel', 'Dominic', 'Josiah',
'Brandon', 'Ayden', 'Kevin', 'Zachary', 'Parker', 'Blake', 'Jose',
'Chase', 'Grayson', 'Jason', 'Ian', 'Bentley', 'Adam', 'Xavier',
'Cooper', 'Justin', 'Nolan', 'Hudson', 'Easton', 'Jase', 'Carson',
'Nathaniel', 'Jaxson', 'Kayden', 'Brody', 'Lincoln', 'Luis',
'Tristan', 'Damian', 'Camden', 'Juan', 'Sophia', 'Emma', 'Olivia',
'Isabella', 'Ava', 'Mia', 'Emily', 'Abigail', 'Madison',
'Elizabeth', 'Charlotte', 'Avery', 'Sofia', 'Chloe', 'Ella',
'Harper', 'Amelia', 'Aubrey', 'Addison', 'Evelyn', 'Natalie',
'Grace', 'Hannah', 'Zoey', 'Victoria', 'Lillian', 'Lily',
'Brooklyn', 'Samantha', 'Layla', 'Zoe', 'Audrey', 'Leah',
'Allison', 'Anna', 'Aaliyah', 'Savannah', 'Gabriella', 'Camila',
'Aria', 'Kaylee', 'Scarlett', 'Hailey', 'Arianna', 'Riley',
'Alexis', 'Nevaeh', 'Sarah', 'Claire', 'Sadie', 'Peyton', 'Aubree',
'Serenity', 'Ariana', 'Genesis', 'Penelope', 'Alyssa', 'Bella',
'Taylor', 'Alexa', 'Kylie', 'Mackenzie', 'Caroline', 'Kennedy',
'Autumn', 'Lucy', 'Ashley', 'Madelyn', 'Violet', 'Stella',
'Brianna', 'Maya', 'Skylar', 'Ellie', 'Julia', 'Sophie',
'Katherine', 'Mila', 'Khloe', 'Paisley', 'Annabelle', 'Alexandra',
'Nora', 'Melanie', 'London', 'Gianna', 'Naomi', 'Eva', 'Faith',
'Madeline', 'Lauren', 'Nicole', 'Ruby', 'Makayla', 'Kayla',
'Lydia', 'Piper', 'Sydney', 'Jocelyn', 'Morgan')
while '<name>' in hostname:
hostname = hostname.replace('<name>', random.choice(names), 1)
return hostname
def stop_wpa(iface):
for pattern in ('wpa_supplicant .* -i *%s' % iface,
'wpa_cli .* -i *%s' % iface):
run('pkill -f "^%s"' % pattern)
def stop(iface):
conns = read_connections()
if iface in conns:
conn = conns[iface]
if conn in CONFIG:
vpn = CONFIG[conn].get('vpn')
elif 'vpn' in COMMON:
vpn = COMMON['vpn']
else:
vpn = None
if vpn: