-
Notifications
You must be signed in to change notification settings - Fork 1
/
ipipou
executable file
·1638 lines (1490 loc) · 78.8 KB
/
ipipou
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 python3
'''
Utility to create ipipou tunnels (IPIP over UDP [FOU]).
Optionally remote ip:port authentication can be enabled using supported
authentication modes.
It must be run from root or have the following capabilities:
CAP_NET_ADMIN - to create and configure network interfaces
CAP_NET_RAW - if authentication packets sending required
CAP_SYS_MODULE - if "fou" and "ipip" modules are not loaded yet
In client mode SIGUSR1 signal initiates auth resend to the server (the same way
as --reauth-only option do).
On SIGTERM or SIGINT cleanup (deconfiguration) will be initiated first.
Program exit codes with specific meaning:
0: ok
1: generic
2: argparse
10: modprobe
20: nfq
40: nftables
51: ip_address
52: ip_link
53: ip_fou
100: ipipou_create
101: ipipou_update
120: send_auth
127: not_implemented
200: cleanup
'''
from base64 import b64decode, b64encode
from datetime import datetime, timezone, timedelta
from time import sleep
import fcntl
import gc
import ipaddress
import logging
import os
import signal
import socket
import struct
import subprocess
import sys
import traceback
#import argparse # Will be imported if run as a command
#import netfilterqueue as nfq # Will be imported for server mode only
#from nacl.signing import SigningKey, VerifyKey # Will be imported for AUTH_KEY mode only
#from nacl.exceptions import BadSignatureError # Will be imported for AUTH_KEY mode only
# TODO: Use python native bindings instead of subprocess: libnl, netlink, pyroute2, ...?
# pylint:disable=undefined-variable,used-before-assignment,global-statement,global-variable-undefined,subprocess-run-check,too-many-branches
# Some global defaults/initial values
tunl_ip_base = '172.28.0.0' # Default base TUNL_IP (when N == 0)
fou_ip_alt_base = '172.29.0.0' # Default base FOU_IP_ALT (when N == 0)
fou_port_base = 10000 # Default base FOU_PORT (when N == 0)
nfq_range = None # How many bytes of the packet to get. None to full packet.
fou_ip = None # Current FOU local IP, will be filled with one of FOU_IP_MAIN or FOU_IP_ALT
last_remote_ip = None # Last remembered FOU remote IP (str)
last_remote_port = None # Last remembered FOU remote PORT (int)
last_remote_timestamp = None # The time when last_remote_ip:last_remote_port was remembered
own_fou = None # If FOU listener was created by this script
own_fou_ip_alt = None # If FOU alt IP was added by this script
ip_fou_unsupported_local = None # If `ip fou` supports "local" and "dev" arguments. None to autodetect.
returncode = 0 # Default return code (ok)
def cleanup_and_exit(signalnum=None, frame=None, rcode=0):
'''
Cleanup and exit gracefully.
'''
if signalnum is None:
log.info('Cleanup and exit')
else:
log.info('Cleanup and exit on %s (%s)', signal.Signals(signalnum).name, signalnum) # pylint:disable=no-member
try:
Q.unbind()
except Exception:
pass
if not ipipou_delete() \
and rcode == 0:
rcode = 200 # cleanup error exit code
sys.exit(rcode)
def sigignore(signalnum=None, frame=None):
'''
This function should be called when some signal is ignored explicitly.
'''
log.info('%s: ignored', signal.Signals(signalnum).name) # pylint:disable=no-member
def prerequisites():
'''
General script requirements
'''
# Be sure "fou" kernel module is loaded.
# "ipip" module will be loaded automatically on tunnel creation if supported.
fou_loaded = None
try:
with open('/proc/modules') as fd:
for l in fd.read().splitlines():
if l.startswith('fou '):
log.debug('Already loaded module: fou')
fou_loaded = True
break
except Exception as e:
log.debug('Failed to read /proc/modules: %s', e)
if not fou_loaded:
cmd = ('modprobe', 'fou')
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=5, check=True)
except FileNotFoundError:
log.fatal('Executable not found: modprobe')
sys.exit(10) # modprobe error exit code
except subprocess.CalledProcessError as e:
log.fatal('Failed to load module: fou: %s', e.stderr)
sys.exit(10) # modprobe error exit code
except Exception as e:
log.fatal('Failed to load module: fou: %s', e)
sys.exit(10) # modprobe error exit code
else:
log.debug('Loaded module: fou')
if MODE == 'server':
# Be sure that required nftables base chains exists
# May not be able to add table with chains on single call, so add sequentially.
# Add table
cmd = ('nft', '--', 'add table ip', NFT_TABLE, ';')
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=5, check=True)
except FileNotFoundError:
log.fatal('Executable not found: nft')
sys.exit(40) # nftables error exit code
except subprocess.CalledProcessError as e:
log.fatal('Failed to add nftables table %s: %s', NFT_TABLE, e.stderr)
sys.exit(40) # nftables error exit code
except Exception as e:
log.fatal('Failed to add nftables table %s: %s', NFT_TABLE, e)
sys.exit(40) # nftables error exit code
else:
log.debug('Added nftables table %s', NFT_TABLE)
# Add chains
cmd = ('nft', '--',
# 'add table ip', NFT_TABLE, ';',
'add chain ip', NFT_TABLE, 'nat-prerouting { type nat hook prerouting priority -42 ; } ;',
'add chain ip', NFT_TABLE, 'nfq { type nat hook prerouting priority -41 ; } ;',
'add chain ip', NFT_TABLE, 'nat-postrouting { type nat hook postrouting priority -42 ; } ;',
)
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=5, check=True)
except FileNotFoundError:
log.fatal('Executable not found: nft')
sys.exit(40) # nftables error exit code
except subprocess.CalledProcessError as e:
log.fatal('Failed to add nftables chains to table %s: %s', NFT_TABLE, e.stderr)
sys.exit(40) # nftables error exit code
except Exception as e:
log.fatal('Failed to add nftables chains to table %s: %s', NFT_TABLE, e)
sys.exit(40) # nftables error exit code
else:
log.debug('Added nftables chains to table %s', NFT_TABLE)
def client_init(monitor=False):
'''
Create client tunnel and authenticate it to the server.
Optionally monitor connection and reauthenticate if required.
'''
global fou_ip
fou_ip = FOU_IP_MAIN # Alt IP is not supported in client mode
# Create IPIP over FOU tunnel
cmd = ['ip', 'link', 'add', 'name', TUNL_DEV, 'type', 'ipip',
'remote', str(FOU_REMOTE_IP), 'local', str(fou_ip),
'encap', 'fou', 'encap-sport', str(FOU_PORT), 'encap-dport', str(FOU_REMOTE_PORT),
]
if ENCAP_CSUM is True:
cmd.append('encap-csum')
elif ENCAP_CSUM is False:
cmd.append('noencap-csum')
cmd.extend(('mode', 'ipip'))
if FOU_DEV:
cmd.extend(('dev', FOU_DEV))
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=5, check=True)
except FileNotFoundError:
log.fatal('Executable not found: ip')
cleanup_and_exit(rcode=52) # ip_link error exit code
except subprocess.CalledProcessError as e:
log.error('Failed to create %s: %s', TUNL_DEV, e.stderr)
cleanup_and_exit(rcode=52) # ip_link error exit code
except Exception as e:
log.error('Failed to create %s: %s', TUNL_DEV, e)
cleanup_and_exit(rcode=52) # ip_link error exit code
else:
log.debug('%s created', TUNL_DEV)
if not fou_listener_create():
cleanup_and_exit(rcode=53) # ip_fou error exit code
# Assign IP to TUNL_DEV
cmd = ('ip', 'address', 'add', str(TUNL_IP), 'peer', str(TUNL_PEER_IP), 'dev', TUNL_DEV)
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=5, check=True)
except subprocess.CalledProcessError as e:
log.error('Failed to assign IP to %s: %s', TUNL_DEV, e.stderr)
cleanup_and_exit(rcode=51) # ip_address error exit code
except Exception as e:
log.error('Failed to assign IP to %s: %s', TUNL_DEV, e)
cleanup_and_exit(rcode=51) # ip_address error exit code
else:
log.debug('Assigned IP to %s: %s/%s', TUNL_DEV, TUNL_IP, TUNL_PEER_IP)
# Bring up TUNL_DEV
cmd = ('ip', 'link', 'set', TUNL_DEV, 'up')
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=5, check=True)
except subprocess.CalledProcessError as e:
log.error('Failed to bring up %s: %s', TUNL_DEV, e.stderr)
cleanup_and_exit(rcode=52) # ip_link error exit code
except Exception as e:
log.error('Failed to bring up %s: %s', TUNL_DEV, e)
cleanup_and_exit(rcode=52) # ip_link error exit code
else:
log.debug('%s brought up', TUNL_DEV)
# Authenticate on server, send UDP auth packet.
if not client_auth():
cleanup_and_exit(rcode=120) # send_auth error exit code
log.info('Setup completed for %s%s: %s:%s<->%s:%s', TUNL_DEV, '@'+FOU_DEV if FOU_DEV else '', fou_ip, FOU_PORT, FOU_REMOTE_IP, FOU_REMOTE_PORT)
# Catch some signals for clean exit
signal.signal(signal.SIGTERM, cleanup_and_exit)
signal.signal(signal.SIGALRM, cleanup_and_exit)
signal.signal(signal.SIGINT, cleanup_and_exit)
# Catch SIGUSR1 for auth resend
def sigusr1(signalnum=None, frame=None):
log.info('SIGUSR1: sending auth packet')
client_auth()
signal.signal(signal.SIGUSR1, sigusr1)
# Ignore some signals
signal.signal(signal.SIGUSR2, sigignore)
signal.signal(signal.SIGHUP, sigignore)
if monitor:
# TODO: implement monitoring: check periodically if tunnel is alive (by ping?) and if not resend auth packet.
log.error('Monitor mode is not implemented yet')
cleanup_and_exit(rcode=127) # not_implemented error exit code
if KEEPALIVE_SEC > 0:
# Send auth packets every KEEPALIVE_SEC
while True:
sleep(KEEPALIVE_SEC)
client_auth()
else:
# Sleep until SIGTERM is received
while True: # Loop to allow other signals processing like SIGUSR1
signal.pause()
def client_auth():
'''
Send auth packet to the server
'''
# Set udp_payload depends on auth type
if AUTH_TOKEN:
udp_payload = AUTH_TOKEN
elif AUTH_KEY:
if AUTH_KEY_TYPE == 'ed25519':
timestamp = int.to_bytes(int(datetime.now(tz=timezone.utc).timestamp()), 5, 'big')
salt = os.urandom(4)
# sig = AUTH_KEY.sign(timestamp+salt+AUTH_SECRET) # For deprecated module ed25519
sig = AUTH_KEY.sign(timestamp+salt+AUTH_SECRET).signature
udp_payload = sig+timestamp+salt
else:
log.error('Unsupported AUTH_KEY_TYPE: %s', AUTH_KEY_TYPE)
cleanup_and_exit(rcode=127) # not_implemented error exit code
else:
udp_payload = b''
log.debug('Sending auth packet')
return send_raw_packet(
dst_ip=FOU_REMOTE_IP,
dst_port=FOU_REMOTE_PORT,
src_ip=fou_ip or FOU_IP_MAIN,
src_port=FOU_PORT,
payload=udp_payload,
ttl=AUTH_PACKET_TTL,
)
def queue_init(nft_pre_verdict_statement='', nft_queue_flags=''):
'''
Queue to userspace all packets which initiate new connection to FOU port and assign handler.
If alt FOU local IP in use DNAT-matched packets will not be queued because DNAT rule will have higher priority, it's expected.
For server mode only.
'''
global returncode
cmd = ['nft', '--', 'add', 'rule', 'ip', NFT_TABLE, 'nfq']
if FOU_DEV:
cmd.extend(('iifname', '"%s"' % FOU_DEV))
cmd.extend(('ip', 'daddr', str(FOU_IP_MAIN), 'udp', 'dport', str(FOU_PORT)))
if nft_pre_verdict_statement:
cmd.append(nft_pre_verdict_statement)
if NFT_COUNTER:
cmd.append('counter')
cmd.extend(('queue', 'num', str(NFQ_NUM)))
if nft_queue_flags:
cmd.append(nft_queue_flags)
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=5, check=True)
except subprocess.CalledProcessError as e:
log.fatal('Failed to add nftables queue rule: %s', e.stderr)
cleanup_and_exit(rcode=40) # nftables error exit code
except Exception as e:
log.fatal('Failed to add nftables queue rule: %s', e)
cleanup_and_exit(rcode=40) # nftables error exit code
# Catch some signals for clean exit
signal.signal(signal.SIGTERM, cleanup_and_exit)
signal.signal(signal.SIGALRM, lambda s, f: cleanup_and_exit(s, f, rcode=returncode)) # To exit from queue_handler call with proper returncode
# Ignore some signals
signal.signal(signal.SIGUSR1, sigignore)
signal.signal(signal.SIGUSR2, sigignore)
signal.signal(signal.SIGHUP, sigignore)
Q = nfq.NetfilterQueue()
if nfq_range is None:
Q.bind(NFQ_NUM, queue_handler, NFQ_MAX_LEN, nfq.COPY_PACKET)
else:
Q.bind(NFQ_NUM, queue_handler, NFQ_MAX_LEN, nfq.COPY_PACKET, nfq_range)
# Main run loop
try:
# if KEEPALIVE_SEC > 0:
# # Send keepalive packets every KEEPALIVE_SEC
# # TODO: run in separate thread?
# while True:
# sleep(KEEPALIVE_SEC)
# if FOU_REMOTE_IP:
# send_raw_packet(
# dst_ip=FOU_REMOTE_IP, dst_port=FOU_REMOTE_PORT,
# src_ip=fou_ip or FOU_IP_MAIN, src_port=FOU_PORT,
# payload=b'',
# ttl=AUTH_PACKET_TTL,
# )
log.info('Running netfilter queue %s for %s:%s.udp%s...',
NFQ_NUM, FOU_IP_MAIN, FOU_PORT, '@'+FOU_DEV if FOU_DEV else '',
)
Q.run(block=True)
except KeyboardInterrupt as e:
log.info('Exit netfilter queue %s by %s', NFQ_NUM, e.__class__.__name__)
# except SystemExit as e: # Do not use to avoid double cleanup_and_exit call
# log.info('Exit netfilter queue %s by %s', NFQ_NUM, e.__class__.__name__)
# returncode = int(e.code)
except Exception as e:
log.info('Exit netfilter queue %s by %s', NFQ_NUM, e.__class__.__name__)
log.debug(traceback.format_exc())
returncode = 20 # nfq error exit code
cleanup_and_exit(rcode=returncode)
def queue_handler(pkt):
'''
Netfilter queue packets handler.
It's the only performance critical function, so avoid heavy calculations
here (and in functions called from here) if possible.
It authenticates packet and creates/updates tunnel accordingly.
Supported auth:
- remote IP and/or PORT (if FOU_REMOTE_IP and/or FOU_REMOTE_PORT specified)
- UDP payload
'''
global returncode
global last_remote_ip
global last_remote_port
global last_remote_timestamp
global FOU_REMOTE_IP
global FOU_REMOTE_PORT
payload = pkt.get_payload() # Ethernet frame payload
# src_ip = '.'.join(str(i) for i in payload[12:16])
src_ip = socket.inet_ntoa(payload[12:16])
src_udp_port = int.from_bytes(payload[20:22], 'big')
src_udp_payload = payload[28:]
if log.isEnabledFor(logging.DEBUG):
# dst_ip = '.'.join(str(i) for i in payload[16:20])
dst_ip = socket.inet_ntoa(payload[16:20])
dst_udp_port = int.from_bytes(payload[22:24], 'big')
# udp_len_bytes = payload[24:26]
# udp_csum_bytes = payload[26:28]
# inner_udp_csum_bytes = src_udp_payload[6:8]
log.debug('NFQ %s: got packet: %s:%s->%s:%s\n'
'IP__hdr_hex: %s\n'
'UDP_hdr_hex: %s\n'
'UDP_pl__hex: %s',
NFQ_NUM, src_ip, src_udp_port, dst_ip, dst_udp_port,
payload[:20].hex(), payload[20:28].hex(),
src_udp_payload.hex(),
)
# Accept packet for closest followers of the auth packet
# or if connection is expired but related to the last remembered remote with acceptable lifetime
if last_remote_port == src_udp_port \
and last_remote_ip == src_ip:
if AUTH_LIFETIME_SEC > 0 \
and last_remote_timestamp + timedelta(seconds=AUTH_LIFETIME_SEC) < datetime.now():
log.debug('Auth lifetime is expired for the last remembered remote %s:%s', src_ip, src_udp_port)
else:
pkt.accept()
log.debug('Accept packet: the last remembered remote %s:%s match', src_ip, src_udp_port)
# Update last_remote_timestamp if it's auth packet
if auth_is_valid(src_ip, src_udp_port, src_udp_payload, mute=True):
last_remote_timestamp = datetime.now()
log.debug('Auth: Updated remembered remote timestamp')
return
# Authenticate
if not auth_is_valid(src_ip, src_udp_port, src_udp_payload):
pkt.drop()
log.debug('Drop packet (auth error)')
return
pkt.drop() # The packet achieved its goal, so drop it right now, there is no other destination.
log.info('Drop packet (auth ok)')
if FOU_REMOTE_IP is None \
or FOU_REMOTE_PORT is None:
log.debug('FOU remote set to %s:%s', src_ip, src_udp_port)
else:
log.debug('FOU remote changed from %s:%s to %s:%s', FOU_REMOTE_IP, FOU_REMOTE_PORT, src_ip, src_udp_port)
FOU_REMOTE_IP = ipaddress.IPv4Address(src_ip)
FOU_REMOTE_PORT = src_udp_port
if last_remote_ip is None: # The first auth packet for this tunnel
if ipipou_create(): # Create tunnel and set fou_ip
if fou_ip == FOU_IP_MAIN: # For alt IP it breaks NAT
# Add connection manually, because original packet was dropped, so was not tracked.
# It's optional but helps to avoid next packet to be queued, also increases connection timeout.
cmd = ('conntrack', '--create',
'--timeout', '120',
'--status', 'ASSURED,ASSURED',
'--proto', 'udp',
'--orig-src', src_ip, '--reply-dst', src_ip,
'--orig-port-src', str(FOU_REMOTE_PORT), '--reply-port-dst', str(FOU_REMOTE_PORT),
'--orig-dst', str(FOU_IP_MAIN), '--reply-src', str(fou_ip),
'--orig-port-dst', str(FOU_PORT), '--reply-port-src', str(FOU_PORT),
# '--mark', '0',
)
# if fou_ip == FOU_IP_ALT:
# cmd.append('--dst-nat')
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=2, check=True)
except FileNotFoundError:
log.info('Executable not found: conntrack')
except subprocess.CalledProcessError as e:
log.info('Failed to track outer connection for %s: %s', TUNL_DEV, e.stderr)
except Exception as e:
log.info('Failed to track outer connection for %s: %s', TUNL_DEV, e)
else:
log.debug('Outer connection tracked for %s', TUNL_DEV)
else:
log.error('Failed to create %s for remote %s:%s, signaling for exit.', TUNL_DEV, FOU_REMOTE_IP, FOU_REMOTE_PORT)
# Any exception from this handler will be ignored, so use signals instead of sys.exit
if returncode == 0: # Do not overwrite original returncode if any
returncode = 100 # ipipou_create error exit code
signal.alarm(1)
return
else: # Subsequent auth packet, need to update tunnel FOU_REMOTE_IP:FOU_REMOTE_PORT
if not ipipou_update():
log.error('Failed to update %s for remote %s:%s, signaling for exit.', TUNL_DEV, FOU_REMOTE_IP, FOU_REMOTE_PORT)
# Any exception from this handler will be ignored, so use signals instead of sys.exit
if returncode == 0: # Do not overwrite original returncode if any
returncode = 101 # ipipou_update error exit code
signal.alarm(1)
return
if REPLY_ON_AUTH_OK:
# Send reply packet to notify about successful auth (and to complete reply direction of connection tracking if tracked)
if AUTH_KEY and AUTH_REMOTE_PUBKEY:
if AUTH_KEY_TYPE == 'ed25519':
timestamp = int.to_bytes(int(datetime.now(tz=timezone.utc).timestamp()), 5, 'big')
salt = os.urandom(4)
# sig = AUTH_KEY.sign(timestamp+salt+AUTH_SECRET) # For deprecated module ed25519
sig = AUTH_KEY.sign(timestamp+salt+AUTH_SECRET).signature
udp_payload = sig+timestamp+salt
else:
log.error('Unsupported AUTH_KEY_TYPE: %s', AUTH_KEY_TYPE)
returncode = 127 # not_implemented error exit code
signal.alarm(1)
return
else:
udp_payload = src_udp_payload[::-1] # Original payload reverse
send_raw_packet(
dst_ip=FOU_REMOTE_IP,
dst_port=FOU_REMOTE_PORT,
src_ip=fou_ip or FOU_IP_MAIN,
src_port=FOU_PORT,
payload=udp_payload,
ttl=AUTH_PACKET_TTL,
)
last_remote_ip = src_ip
last_remote_port = src_udp_port
last_remote_timestamp = datetime.now()
log.debug('Remembered remote: %s:%s', last_remote_ip, last_remote_port)
def auth_is_valid(src_ip, src_udp_port, src_udp_payload=b'', mute=False):
'''
Check whether authentication is valid or not for selected auth scheme.
'''
# [Pre]authenticate by remote ip and/or port if specified
if AUTH_BY_REMOTE_IP:
if str(FOU_REMOTE_IP) != src_ip:
if not mute:
log.debug('Auth: src IP %s did not match %s but AUTH_BY_REMOTE_IP set', src_ip, FOU_REMOTE_IP)
return False
if AUTH_BY_REMOTE_PORT:
if FOU_REMOTE_PORT != src_udp_port:
if not mute:
log.debug('Auth: src port %s did not match %s but AUTH_BY_REMOTE_PORT set', src_udp_port, FOU_REMOTE_PORT)
return False
# Then check payload based auth if required
if AUTH_TOKEN:
if AUTH_TOKEN == src_udp_payload:
if not mute:
log.info('Auth: %s:%s authenticated successfully by token for %s', src_ip, src_udp_port, TUNL_DEV)
return True
if not mute:
log.debug('Auth: outer UDP payload did not match AUTH_TOKEN')
elif AUTH_REMOTE_PUBKEY:
# Expected UDP payload format: Signature (64 bytes) + Unix time UTC timestamp (5 bytes) + salt (4 bytes)
# TODO: optionally include client public IP to signed message
if len(src_udp_payload) < 73: # 64+5+4
if not mute:
log.info('Auth: %s:%s invalid UDP payload length for %s', src_ip, src_udp_port, TUNL_DEV)
return False
sig = src_udp_payload[:64] # Signature
msg = src_udp_payload[64:] + AUTH_SECRET # Message. Trailing secret assumed in message.
timestamp = int.from_bytes(msg[:5], 'big')
# salt = msg[5:9]
# secret = msg[9:]
if AUTH_KEY_TYPE == 'ed25519':
# Allow up to AUTH_MAX_TIME_DISCREPANCY_SEC time discrepancy between hosts
if AUTH_MAX_TIME_DISCREPANCY_SEC:
utc_now = int(datetime.now(tz=timezone.utc).timestamp())
abs_timedelta = abs(utc_now-timestamp)
if abs_timedelta > AUTH_MAX_TIME_DISCREPANCY_SEC:
if not mute:
log.info('Auth: %s:%s not an auth packet or too high time discrepancy for %s: %ss', src_ip, src_udp_port, TUNL_DEV, abs_timedelta)
return False
try:
# AUTH_REMOTE_PUBKEY.verify(sig, msg)
AUTH_REMOTE_PUBKEY.verify(msg, sig)
except BadSignatureError:
if not mute:
log.info('Auth: %s:%s invalid signature for %s', src_ip, src_udp_port, TUNL_DEV)
except Exception as e:
if not mute:
log.warning('Auth: %s:%s authentication error for %s: %s', src_ip, src_udp_port, TUNL_DEV, e)
else:
if not mute:
log.info('Auth: %s:%s authenticated successfully by ed25519 pubkey for %s', src_ip, src_udp_port, TUNL_DEV)
return True
# elif AUTH_KEY_TYPE == 'another':
# pass
else:
if not mute:
log.warning('Unsupported AUTH_KEY_TYPE: %s', AUTH_KEY_TYPE)
return False
else:
return True
# Auth failure can happen for clients behind NAT when connection is
# expired and client's public src port changed, then client sends data
# packet using new connection, server treat it as auth attempt. Active
# reply about auth failure may help if client expects such replies (see
# REPLY_ON_AUTH_FAILURE and monitor mode). Or client have to keep
# connection alive and/or monitor disconnections with consequent reauth.
return False
def fou_listener_create():
'''
Create fou listener if does not exist
'''
global ip_fou_unsupported_local
global own_fou
cmd = ['ip', 'fou', 'add', 'port', str(FOU_PORT), 'ipproto', '4', 'local', str(fou_ip)]
# if FOU_REMOTE_IP and FOU_REMOTE_PORT: # Establish connection
# cmd.extend(('peer', FOU_REMOTE_IP, 'peer_port', FOU_REMOTE_PORT))
if FOU_DEV:
cmd.extend(('dev', FOU_DEV))
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=5, check=True)
except subprocess.CalledProcessError as e:
if 'RTNETLINK answers: Address already in use' in e.stderr:
own_fou = False
log.warning('Seems IPIP FOU listener %s:%s%s already exists', fou_ip, FOU_PORT, '@'+FOU_DEV if FOU_DEV else '')
elif 'fou: unknown command ' in e.stderr:
log.warning('Unsupported "ip fou" argument(s), fallback to non-bind fou listener.')
cmd = cmd[:cmd.index('local')]
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=5, check=True)
except subprocess.CalledProcessError as e:
own_fou = False
if 'RTNETLINK answers: Address already in use' in e.stderr:
log.warning('Seems IPIP FOU listener 0.0.0.0:%s already exists', FOU_PORT)
else:
log.error('Failed to create IPIP FOU listener 0.0.0.0:%s: %s', FOU_PORT, e.stderr)
return False
except Exception as e:
log.error('Failed to create IPIP FOU listener 0.0.0.0:%s: %s', FOU_PORT, e)
return False
else:
own_fou = True
ip_fou_unsupported_local = True # Remember support status for next calls
log.debug('Added IPIP FOU listener 0.0.0.0:%s', FOU_PORT)
else:
own_fou = False
log.error('Failed to create IPIP FOU listener %s:%s%s: %s', fou_ip, FOU_PORT, '@'+FOU_DEV if FOU_DEV else '', e.stderr)
return False
except Exception as e:
own_fou = False
log.error('Failed to create IPIP FOU listener %s:%s%s: %s', fou_ip, FOU_PORT, '@'+FOU_DEV if FOU_DEV else '', e)
return False
else:
own_fou = True
ip_fou_unsupported_local = False # Remember support status for next calls
log.debug('Added IPIP FOU listener %s:%s%s', fou_ip, FOU_PORT, '@'+FOU_DEV if FOU_DEV else '')
return True
def send_raw_packet(dst_ip, dst_port, src_ip=None, src_port=0, payload=b'', ttl=64, checksum=False):
'''
Send raw UDP packet to remote host.
'''
# # Deprecated way using "sendip" subprocess
# cmd = ['sendip']
# if payload:
# payload_type = type(payload)
# if payload_type is bytes:
# cmd += ('-d', '0x'+payload.hex())
# elif payload_type is str:
# cmd += ('-d', payload)
# else:
# cmd += ('-d', str(payload))
# cmd += ('-p', 'ipv4', '-p', 'udp')
# if src_ip:
# cmd += ('-is', str(src_ip))
# if src_port:
# cmd += ('-us', str(src_port))
# cmd += ('-ud', str(dst_port), str(dst_ip))
# log.debug('call: %s', cmd)
# try:
# p = subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL)
# if p.returncode:
# log.error('Failed to send packet: %s', p.stderr)
# return False
# log.debug('Auth packet send')
# except FileNotFoundError:
# log.error('Executable not found: sendip')
# return False
# return True
# Use raw sockets instead of binding to avoid conflict with FOU listener
try:
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
except Exception as e:
log.error('Failed to create raw socket for packet: %s', e)
return False
if not isinstance(payload, bytes):
if not payload:
payload = b''
else:
payload = bytes(str(payload), 'utf8')
packet = bytearray()
# IP header
# oct| 0 | 1 | 2 | 3 |
# |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|
# ╔═══════╦═══════╦═══════════╦═══╦═══════════════════════════════╗
# 0 ║Version║ IHL ║ DSCP ║ECN║ Total Length ║
# ╠═══════╩═══════╩═══════════╩═══╬═════╦═════════════════════════╣
# 4 ║ Identification ║Flags║ Fragment Offset ║
# ╠═══════════════╦═══════════════╬═════╩═════════════════════════╣
# 8 ║ Time to Live ║ Protocol ║ Header Checksum ║
# ╠═══════════════╩═══════════════╩═══════════════════════════════╣
# 12 ║ Source Address ║
# ╠═══════════════════════════════════════════════════════════════╣
# 16 ║ Destination Address ║
# ╚═══════════════════════════════════════════════════════════════╝
packet += b'\x45\x00\x00\x00' # Total Length will be filled by kernel
packet += b'\x00\x00\x00\x00' # Identification will be filled by kernel if empty
packet += int.to_bytes(ttl, 1, 'big')
packet += b'\x11' # UDP proto (17)
packet += b'\x00\x00' # Header Checksum will be filled by kernel
try:
src_ip_type = type(src_ip)
if src_ip_type is ipaddress.IPv4Address:
packet += src_ip.packed
elif src_ip_type is bytes:
packet += src_ip
elif src_ip_type is str:
packet += socket.inet_aton(src_ip)
elif not src_ip:
packet += b'\x00\x00\x00\x00'
else:
packet += socket.inet_aton(str(src_ip))
except Exception as e:
log.error('Failed to parse source IP %s: %s', src_ip, e)
return False
try:
dst_ip_type = type(dst_ip)
if dst_ip_type is ipaddress.IPv4Address:
packet += dst_ip.packed
elif dst_ip_type is bytes:
packet += dst_ip
elif dst_ip_type is str:
packet += socket.inet_aton(dst_ip)
else:
packet += socket.inet_aton(str(dst_ip))
except Exception as e:
log.error('Failed to parse destination IP %s: %s', dst_ip, e)
return False
# UDP header
# oct| 0 | 1 | 2 | 3 |
# |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|
# ╔═══════════════════════════════╦═══════════════════════════════╗
# 0 ║ Source Port ║ Destination Port ║
# ╠═══════════════════════════════╬═══════════════════════════════╣
# 4 ║ Length (UDP header + payload) ║ Checksum (UDP header+payload) ║
# ╚═══════════════════════════════╩═══════════════════════════════╝
packet += int.to_bytes(src_port, 2, 'big')
packet += int.to_bytes(dst_port, 2, 'big')
packet += int.to_bytes(8+len(payload), 2, 'big')
if checksum:
# TODO: Implement UDP checksum calculation when required
log.warning('UDP checksum computing is not implemented, fallback to empty.')
packet += b'\x00\x00'
else: # Set empty UDP checksum
packet += b'\x00\x00'
# UDP payload
packet += payload
log.debug('Sending raw UDP packet: %s:%s->%s:%s\n'
'IP__hdr_hex: %s\n'
'UDP_hdr_hex: %s\n'
'UDP_pl__hex: %s',
src_ip, src_port, dst_ip, dst_port,
packet[:20].hex(), packet[20:28].hex(),
packet[28:].hex(),
)
try:
s.sendto(packet, (str(dst_ip), dst_port))
except Exception as e:
log.error('Failed to send raw UDP packet %s:%s->%s:%s: %s', src_ip, src_port, dst_ip, dst_port, e)
log.debug(traceback.format_exc())
return False
return True
def ipipou_create():
'''Create ipipou tunnel'''
global returncode
global fou_ip
global own_fou_ip_alt
log.debug('Creating %s', TUNL_DEV)
if FORCE_FOU_IP_ALT:
fou_ip = FOU_IP_ALT
log.debug('Force current FOU local IP to alt %s', fou_ip)
else:
fou_ip = FOU_IP_MAIN
log.debug('Set current FOU local IP to main %s', fou_ip)
# Create IPIP over FOU tunnel
cmd = ['ip', 'link', 'add', 'name', TUNL_DEV, 'type', 'ipip',
'remote', str(FOU_REMOTE_IP), 'local', str(fou_ip),
'encap', 'fou', 'encap-sport', str(FOU_PORT), 'encap-dport', str(FOU_REMOTE_PORT),
]
if ENCAP_CSUM is True:
cmd.append('encap-csum')
elif ENCAP_CSUM is False:
cmd.append('noencap-csum')
cmd.extend(('mode', 'ipip'))
if FOU_DEV:
cmd.extend(('dev', FOU_DEV))
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=3, check=True)
except subprocess.CalledProcessError as e:
if 'RTNETLINK answers: File exists' in e.stderr \
and fou_ip == FOU_IP_MAIN:
# Failed to create tunnel, most probably because the tunnel with the same
# pair FOU_IP_MAIN,FOU_REMOTE_IP already exists (e.g. if clients behind NAT), so
# using alternate local IP with DNAT.
log.warning('Failed to create %s directly using FOU local IP %s, trying to use alt %s.', TUNL_DEV, fou_ip, FOU_IP_ALT)
fou_ip = FOU_IP_ALT
else:
log.error('Failed to create %s using FOU local IP %s: %s', TUNL_DEV, fou_ip, e.stderr)
returncode = 52 # ip_link error exit code
return False
else:
log.debug('%s created', TUNL_DEV)
if fou_ip == FOU_IP_ALT:
# Change to private mapped IP
cmd[cmd.index(str(FOU_IP_MAIN))] = str(fou_ip)
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=3, check=True)
except subprocess.CalledProcessError as e:
log.error('Failed to create alternate %s using FOU local IP %s: %s', TUNL_DEV, fou_ip, e.stderr)
returncode = 52 # ip_link error exit code
return False
else:
log.debug('%s created', TUNL_DEV)
# DNAT rule for mapping
cmd = ['nft', '--', 'add', 'rule', 'ip', NFT_TABLE, 'nat-prerouting']
if FOU_DEV:
cmd.extend(('iifname', '"%s"' % FOU_DEV))
cmd.extend(('ip', 'daddr', str(FOU_IP_MAIN), 'udp', 'dport', str(FOU_PORT),
# Required for FOU_REMOTE_IP:FOU_REMOTE_PORT update lately
'ip', 'saddr', str(FOU_REMOTE_IP), 'udp', 'sport', str(FOU_REMOTE_PORT),
))
if NFT_COUNTER:
cmd.append('counter')
cmd.extend(('dnat', 'to', str(FOU_IP_ALT)))
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=3, check=True)
except subprocess.CalledProcessError as e:
log.error('Failed to add DNAT rule for alt FOU local IP: %s', e.stderr)
returncode = 40 # nftables error exit code
return False
else:
log.debug('Added DNAT rule for alt FOU local IP')
# SNAT rule for mapping (required if incoming connection expired or conntrack disabled)
cmd = ['nft', '--', 'add', 'rule', 'ip', NFT_TABLE, 'nat-postrouting']
if FOU_DEV:
cmd.extend(('oifname', '"%s"' % FOU_DEV))
cmd.extend(('ip', 'saddr', str(FOU_IP_ALT), 'udp', 'sport', str(FOU_PORT)))
if NFT_COUNTER:
cmd.append('counter')
cmd.extend(('snat', 'to', str(FOU_IP_MAIN)))
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=3, check=True)
except subprocess.CalledProcessError as e:
log.error('Failed to add SNAT rule for alt FOU local IP: %s', e.stderr)
returncode = 40 # nftables error exit code
return False
else:
log.debug('Added SNAT rule for alt FOU local IP')
# Add mapped FOU local IP if not yet present
cmd = ('ip', 'address', 'add', str(FOU_IP_ALT), 'scope', 'global', 'dev', FOU_DEV or fou_dev)
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=3, check=True)
except subprocess.CalledProcessError as e:
own_fou_ip_alt = False
if 'RTNETLINK answers: File exists' in e.stderr:
log.warning('Seems alt IP %s already assigned to %s', FOU_IP_ALT, FOU_DEV or fou_dev)
else:
log.error('Failed to add alt IP %s to %s: %s', FOU_IP_ALT, FOU_DEV or fou_dev, e.stderr)
returncode = 51 # ip_address error exit code
return False
else:
own_fou_ip_alt = True
log.debug('Added alt IP %s to %s', FOU_IP_ALT, FOU_DEV or fou_dev)
# Create fou listener if does not exist
if not fou_listener_create():
returncode = 53 # ip_fou error exit code
return False
# Assign IP to TUNL_DEV
cmd = ('ip', 'address', 'add', str(TUNL_IP), 'peer', str(TUNL_PEER_IP), 'dev', TUNL_DEV)
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=3, check=True)
except subprocess.CalledProcessError as e:
log.error('Failed to assign IP to %s: %s', TUNL_DEV, e.stderr)
returncode = 51 # ip_address error exit code
return False
else:
log.debug('Assigned IP to %s: %s/%s', TUNL_DEV, TUNL_IP, TUNL_PEER_IP)
# Bring up TUNL_DEV
cmd = ('ip', 'link', 'set', TUNL_DEV, 'up')
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=3, check=True)
except subprocess.CalledProcessError as e:
log.error('Failed to bring up %s: %s', TUNL_DEV, e.stderr)
returncode = 52 # ip_link error exit code
return False
else:
log.debug('%s brought up', TUNL_DEV)
log.info('Setup completed for %s%s: %s:%s<->%s:%s', TUNL_DEV, '@'+FOU_DEV if FOU_DEV else '', fou_ip, FOU_PORT, FOU_REMOTE_IP, FOU_REMOTE_PORT)
return True
def ipipou_update():
'''Update ipipou tunnel using new FOU_REMOTE_IP:FOU_REMOTE_PORT'''
global returncode
global fou_ip
global own_fou
# Update IPIP over FOU tunnel
cmd = ['ip', 'link', 'set', TUNL_DEV, 'type', 'ipip',
'remote', str(FOU_REMOTE_IP),
'encap', 'fou', 'encap-sport', str(FOU_PORT), 'encap-dport', str(FOU_REMOTE_PORT),
]
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=3, check=True)
except subprocess.CalledProcessError as e:
if 'RTNETLINK answers: File exists' in e.stderr \
and fou_ip == FOU_IP_MAIN:
# Failed to update tunnel directly, most probably because tunnel with the same new
# pair FOU_IP_MAIN,FOU_REMOTE_IP already exists, so reconfigure to use
# alternate local IP with DNAT.
log.warning('Failed to update %s directly using FOU local IP %s, trying to use alt %s.', TUNL_DEV, fou_ip, FOU_IP_ALT)
fou_ip = FOU_IP_ALT
# Update tunnel using FOU_IP_ALT
cmd.extend(('local', str(fou_ip)))
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=3, check=True)
except subprocess.CalledProcessError as e:
log.error('Failed to update %s%s using alt FOU local IP: %s:%s<->%s:%s : %s',
TUNL_DEV, '@'+FOU_DEV if FOU_DEV else '',
fou_ip, FOU_PORT, FOU_REMOTE_IP, FOU_REMOTE_PORT,
e.stderr,
)
returncode = 52 # ip_link error exit code
return False
else:
log.info('%s%s updated using new remote with alt FOU local IP: %s:%s<->%s:%s',
TUNL_DEV, '@'+FOU_DEV if FOU_DEV else '',
fou_ip, FOU_PORT, FOU_REMOTE_IP, FOU_REMOTE_PORT,
)
# DNAT will be added below
# Create SNAT rule for mapping (required if incoming connection expired or conntrack disabled)
cmd = ['nft', '--', 'add', 'rule', 'ip', NFT_TABLE, 'nat-postrouting']
if FOU_DEV:
cmd.extend(('oifname', '"%s"' % FOU_DEV))
cmd.extend(('ip', 'saddr', str(FOU_IP_ALT), 'udp', 'sport', str(FOU_PORT)))
if NFT_COUNTER:
cmd.append('counter')
cmd.extend(('snat', 'to', str(FOU_IP_MAIN)))
log.debug('call: %s', cmd)
try:
subprocess.run(cmd, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, timeout=3, check=True)