-
Notifications
You must be signed in to change notification settings - Fork 8
/
ts-warp.c
1470 lines (1236 loc) · 70.2 KB
/
ts-warp.c
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
/* ------------------------------------------------------------------------------------------------------------------ */
/* TS-Warp - Transparent proxy server and traffic wrapper */
/* ------------------------------------------------------------------------------------------------------------------ */
/*
* Copyright (c) 2021-2024, Mikhail Zakharov <[email protected]>
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* -- Main program file --------------------------------------------------------------------------------------------- */
#if defined(linux)
#define _GNU_SOURCE
#include <netinet/in.h>
#include <linux/netfilter_ipv4.h>
#endif
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <time.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <pwd.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#if (WITH_LIBSSH2)
#include <libssh2.h>
#endif
#include "network.h"
#include "utility.h"
#include "socks.h"
#include "http.h"
#include "ssh2.h"
#include "inifile.h"
#include "logfile.h"
#include "pidfile.h"
#include "pidlist.h"
#include "natlook.h"
#include "ts-warp.h"
/* ------------------------------------------------------------------------------------------------------------------ */
int loglevel = LOG_LEVEL_DEFAULT;
FILE *lfile = NULL;
char *ifile_name = INI_FILE_NAME;
char *lfile_name = LOG_FILE_NAME;
char *tfile_name = ACT_FILE_NAME;
char *pfile_name = PID_FILE_NAME;
int cn = 1; /* Active clients number */
pid_t pid, mpid; /* Current and main daemon PID */
struct pid_list *pids = NULL; /* List of active clients with PIDs and Sections */
int Tsock, Ssock, Hsock, isock, csock; /* Sockets for Transparent/Internal-Socks&HTTP/in/clients */
chs ssock; /* Structure for Out socket or SSH2 channel */
ini_section *ini_root; /* Root section of the INI-file */
#if !defined(linux)
int pfd; /* PF device-file on *BSD */
#endif
int msgid; /* Message Queue ID */
int tfd = -1; /* Traffic log file descriptor */
/* ------------------------------------------------------------------------------------------------------------------ */
int main(int argc, char* argv[]) {
/* Usage:
Usage:
ts-warp -T IP:Port -S IP:Port -H IP:Port -c file.ini -l file.log -v 0-4 -t file.act -d -p file.pid -f -u user -D -h
Version:
TS-Warp-X.Y.Z
All parameters are optional:
-T IP:Port Local IP address and port for incoming Transparent requests; set -T 0:0 to disables it
-S IP:Port Local IP address and port for internal Socks5 server; set -S 0:0 to disables it
-H IP:Port Local IP address and port for internal HTTP server; set -H 0:0 to disables it
-l file.log Main log filename
-v 0..4 Log verbosity level: 0 - off, default: 3
-t file.act Active connections and traffic log
-d Daemon mode
-p file.pid PID filename
-f Force start
-u user A user to run ts-warp, default: nobody
-D 0..512 Deep Packet Inspections bypass fragment size. Default: 0 - disabled. Set any value, e.g., 2 to enable
-h This message */
int flg; /* Command-line options flag */
char *taddr = LISTEN_DEFAULT; /* Our address and... */
char *tport = LISTEN_TRANS_PORT; /* ...a port to accept clients */
char *saddr = LISTEN_DEFAULT; /* Internal Socks address and... */
char *sport = LISTEN_SOCKS_PORT; /* ...a port to accept clients */
char *haddr = LISTEN_DEFAULT; /* Internal HTTP address and... */
char *hport = LISTEN_HTTP_PORT; /* ...a port to accept clients */
int l_flg = 0; /* User didn't set the log file */
int d_flg = 0; /* Daemon mode */
int f_flg = 0; /* Force start */
int sdpi = 0; /* Packet fragment size: default 0. Set any
positive value to try tricking DPI */
/* According to https://github.com/xvzc/SpoofDPI?tab=readme-ov-file#https sending the first 1 byte of a request
to the server, and then sending the rest of the data can help to bypass Deep Packet Inspections of HTTPS */
char *runas_user = RUNAS_USER; /* A user to run ts-warp */
struct addrinfo thints, *tres = NULL, *sres = NULL, *hres = NULL; /* TS-Warp incoming addresses info structures */
ini_section *s_ini = NULL; /* Current section of the INI-file */
struct sockaddr_storage caddr; /* Client address */
socklen_t caddrlen; /* Client address len */
struct uvaddr daddr; /* Client destination ip and/or name */
unsigned int daddr_len;
unsigned char auth_method; /* Socks5 accepted auth method */
fd_set sfd; /* Internal servers FDs */
fd_set rfd; /* Connection FDs */
struct timeval tv;
char buf[BUF_SIZE]; /* Multipurpose buffer */
char suf[STR_SIZE]; /* String buffer */
int ret; /* Various function return codes */
int rec = 0, snd = 0; /* received/sent bytes */
pid_t cpid; /* Child PID */
key_t mskey; /* IPC ID */
struct traffic_message tmessage; /* IPC message to pass info about traffic */
struct pid_list *d = NULL, *c = NULL; /* PID list related ... */
struct ini_section *push_ini = NULL; /* variables */
#if (WITH_LIBSSH2)
LIBSSH2_SESSION *ssh2sess = NULL; /* SSH2 Session */
LIBSSH2_CHANNEL *ssh2ch = NULL; /* SSH2 channel */
struct uvaddr p_server;
#endif
while ((flg = getopt(argc, argv, "T:S:H:c:l:v:t:dp:fu:D:h")) != -1)
switch(flg) {
case 'T': /* Internal Transparent server IP/name */
taddr = strsep(&optarg, ":"); /* IP:PORT */
if (optarg) tport = optarg;
break;
case 'S': /* Internal Socks server IP/name */
saddr = strsep(&optarg, ":"); /* IP:PORT */
if (optarg) sport = optarg;
break;
case 'H': /* Internal HTTP server IP/name */
haddr = strsep(&optarg, ":"); /* IP:PORT */
if (optarg) hport = optarg;
break;
case 'c': /* INI-file */
ifile_name = optarg;
break;
case 'l': /* Logfile */
l_flg = 1; lfile_name = optarg;
break;
case 'v': /* Log verbosity */
loglevel = toint(optarg);
if (loglevel < LOG_NONE || loglevel > LOG_VERB) {
fprintf(stderr, "Wrong -v verbosity level value: [%s]\n", optarg);
usage(1);
}
break;
case 't': /* Active connections and traffic log */
tfile_name = optarg;
break;
case 'd': /* Daemon mode */
d_flg = 1;
break;
case 'p':
pfile_name = optarg; /* PID-file */
break;
case 'f': /* Force start */
f_flg = 1;
break;
case 'u':
runas_user = optarg;
#if defined(__APPLE__)
fprintf(stderr, "Note, -u option has no effect on macOS\n");
#endif
break;
case 'D':
sdpi = toint(optarg);
if (sdpi < 0 || sdpi > SDPI_FRAGMENTSZ_MAX) {
fprintf(stderr, "Fatal: wrong -D value:[%s]\n", optarg);
usage(1);
}
break;
case 'h': /* Help */
default:
usage(0);
}
if (!taddr[0]) taddr = LISTEN_DEFAULT;
if (!tport[0]) tport = LISTEN_TRANS_PORT;
if (!saddr[0]) haddr = LISTEN_DEFAULT;
if (!sport[0]) hport = LISTEN_SOCKS_PORT;
if (!haddr[0]) haddr = LISTEN_DEFAULT;
if (!hport[0]) hport = LISTEN_HTTP_PORT;
/* -- Open log-files -------------------------------------------------------------------------------------------- */
if (!d_flg && !l_flg) {
lfile = stdout;
printl(LOG_INFO, "Log file: [STDOUT], verbosity level: [%d]", loglevel);
} else if (!(lfile = fopen(lfile_name, "a"))) {
printl(LOG_WARN, "Unable to open log: [%s], now trying: [%s]", lfile_name, LOG_FILE_NAME);
lfile_name = LOG_FILE_NAME;
if (!(lfile = fopen(lfile_name, "a"))) {
printl(LOG_CRIT, "Unable to open the default log: [%s]", lfile_name);
exit(1);
}
printl(LOG_INFO, "Log file: [%s], verbosity level: [%d]", lfile_name, loglevel);
}
printl(LOG_INFO, "ts-warp incoming Transparent address: [%s:%s]", taddr, tport);
printl(LOG_INFO, "ts-warp Internal Socks address: [%s:%s]", saddr, sport);
printl(LOG_INFO, "ts-warp Internal HTTP address: [%s:%s]", haddr, hport);
struct passwd *pwd = getpwnam(runas_user);
if (mkfifo(tfile_name, S_IFIFO|S_IRWXU|S_IRGRP|S_IROTH) == -1 && errno != EEXIST)
printl(LOG_WARN, "Unable to create active connections and traffic log pipe: [%s]", tfile_name);
else {
if (chown(tfile_name, pwd ? pwd->pw_uid : 0, pwd ? pwd->pw_gid : 0) == -1)
printl(LOG_WARN, "Unable change owner of the ACT log pipe[%s]", tfile_name);
if ((tfd = open(tfile_name, O_RDWR) ) == -1)
printl(LOG_WARN, "Unable to open active connections and traffic log pipe: [%s]", tfile_name);
else
printl(LOG_INFO, "Active connections and traffic log pipe available: [%s]", tfile_name);
}
#if !defined(linux)
pfd = pf_open(); /* Open PF device-file on *BSD */
#endif
#if (WITH_LIBSSH2) /* Init LIBSSH2 */
if ((ret = libssh2_init(0))) {
fprintf (stderr, "libssh2 initialization failed (%d)\n", ret);
return 1;
}
#endif
if (d_flg) {
/* -- Daemonizing ------------------------------------------------------------------------------------------- */
signal(SIGHUP, trap_signal);
signal(SIGINT, trap_signal);
signal(SIGQUIT, trap_signal);
signal(SIGTERM, trap_signal);
signal(SIGCHLD, trap_signal);
signal(SIGUSR1, trap_signal);
signal(SIGUSR2, trap_signal);
signal(SIGPIPE, SIG_IGN); /* Ignore the signal if nobody reads the traffig log pipe! */
if ((pid = fork()) == -1) {
printl(LOG_CRIT, "Daemonizing failed. The 1-st fork() failed");
exit(1);
}
if (pid > 0) exit(0);
if (setsid() < 0) {
printl(LOG_CRIT, "Daemonizing failed. Fatal setsid()");
exit(1);
}
if ((pid = fork()) == -1) {
printl(LOG_CRIT, "Daemonizing failed. The 2-nd fork() failed");
exit(1);
}
if (pid > 0) exit(0);
printl(LOG_CRIT, "%s-%s daemon started", PROG_NAME, PROG_VERSION);
pid = mk_pidfile(pfile_name, f_flg, pwd ? pwd->pw_uid : 0, pwd ? pwd->pw_gid : 0);
}
mpid = pid;
#if !defined(__APPLE__)
/* unfortunately, macOS won't allow reading /dev/pf under non-root user */
if (setuid(pwd->pw_uid) && setgid(pwd->pw_gid)) {
printl(LOG_CRIT, "Failed to set privilege level to UID:GID [%d:%d]", pwd->pw_uid, pwd->pw_gid);
exit(1);
}
#endif
/* -- Try validating our address for incoming connections ------------------------------------------------------- */
memset(&thints, 0, sizeof(thints));
thints.ai_family = PF_UNSPEC;
thints.ai_socktype = SOCK_STREAM;
thints.ai_flags = AI_PASSIVE;
if ((ret = getaddrinfo(taddr, tport, &thints, &tres)) > 0) {
printl(LOG_CRIT, "Error resolving ts-warp Transparent address [%s]: %s", taddr, gai_strerror(ret));
mexit(1, pfile_name, tfile_name);
}
printl(LOG_INFO, "ts-warp Transparent address [%s] successfully resolved to [%s]",
taddr, inet2str((struct sockaddr_storage *)(tres->ai_addr), buf));
if ((ret = getaddrinfo(saddr, sport, &thints, &sres)) > 0) {
printl(LOG_CRIT, "Error resolving ts-warp Socks address [%s]: %s", saddr, gai_strerror(ret));
mexit(1, pfile_name, tfile_name);
}
printl(LOG_INFO, "ts-warp Socks address [%s] successfully resolved to [%s]",
saddr, inet2str((struct sockaddr_storage *)(sres->ai_addr), buf));
if ((ret = getaddrinfo(haddr, hport, &thints, &hres)) > 0) {
printl(LOG_CRIT, "Error resolving ts-warp HTTP address [%s]: %s", haddr, gai_strerror(ret));
mexit(1, pfile_name, tfile_name);
}
printl(LOG_INFO, "ts-warp HTTP address [%s] successfully resolved to [%s]",
haddr, inet2str((struct sockaddr_storage *)(hres->ai_addr), buf));
ini_root = read_ini(ifile_name);
show_ini(ini_root, LOG_VERB);
/* -- Create sockets for incoming connections ------------------------------------------------------------------- */
if (ntohs(SIN_PORT(*(tres->ai_addr)))) {
if ((Tsock = socket(tres->ai_family, tres->ai_socktype, tres->ai_protocol)) == -1) {
printl(LOG_CRIT, "Error creating a socket for Transparent incoming connections");
mexit(1, pfile_name, tfile_name);
}
} else {
Tsock = -1;
printl(LOG_INFO, "Transparent connections is disabled!");
}
if (ntohs(SIN_PORT(*(sres->ai_addr)))) {
if ((Ssock = socket(sres->ai_family, sres->ai_socktype, sres->ai_protocol)) == -1) {
printl(LOG_CRIT, "Error creating a socket for Socks5 incoming connections");
mexit(1, pfile_name, tfile_name);
}
} else {
Ssock = -1;
printl(LOG_INFO, "Socks5 incoming connections is disabled!");
}
if (ntohs(SIN_PORT(*(hres->ai_addr)))) {
if ((Hsock = socket(hres->ai_family, hres->ai_socktype, hres->ai_protocol)) == -1) {
printl(LOG_CRIT, "Error creating a socket for HTTP incoming connections");
mexit(1, pfile_name, tfile_name);
}
} else {
Hsock = -1;
printl(LOG_INFO, "HTTP incoming connections is disabled!");
}
if (Tsock == -1 && Ssock == -1 && Hsock == -1) {
printl(LOG_CRIT, "All incoming connections are disabled! Nothing to do, exitting.");
mexit(0, pfile_name, tfile_name);
}
/* Internal servers to be non-blocking, so we can check which one acceps connection */
if (Tsock != -1) fcntl(Tsock, F_SETFL, O_NONBLOCK);
if (Ssock != -1) fcntl(Ssock, F_SETFL, O_NONBLOCK);
if (Hsock != -1) fcntl(Hsock, F_SETFL, O_NONBLOCK);
printl(LOG_VERB, "Socket(s) for incoming connections created");
/* -- Apply socket options -------------------------------------------------------------------------------------- */
int keepalive_opt = 1;
#if (WITH_TCP_NODELAY)
int tpc_ndelay = 1;
if (Tsock != -1) {
if (setsockopt(Tsock, IPPROTO_TCP, TCP_NODELAY, &tpc_ndelay, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_NODELAY socket option for Transparent connections");
else printl(LOG_INFO, "TCP_NODELAY option for Transparent socket enabled");
if (setsockopt(Tsock, SOL_SOCKET, SO_KEEPALIVE, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting SO_KEEPALIVE socket option for Transparent connections");
}
if (Ssock != -1) {
if (setsockopt(Ssock, IPPROTO_TCP, TCP_NODELAY, &tpc_ndelay, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_NODELAY socket option for Socks5 incoming connections");
else printl(LOG_INFO, "TCP_NODELAY option for Socks socket enabled");
if (setsockopt(Ssock, SOL_SOCKET, SO_KEEPALIVE, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting SO_KEEPALIVE socket option for Socks5 incoming connections");
}
if (Hsock != -1) {
if (setsockopt(Hsock, IPPROTO_TCP, TCP_NODELAY, &tpc_ndelay, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_NODELAY socket option for HTTP incoming connections");
else printl(LOG_INFO, "TCP_NODELAY option for HTTP socket enabled");
if (setsockopt(Hsock, SOL_SOCKET, SO_KEEPALIVE, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting SO_KEEPALIVE socket option for HTTP incoming connections");
}
#endif
#if !defined(__OpenBSD__)
#if !defined(__APPLE__)
keepalive_opt = TCP_KEEPIDLE_S;
if (Tsock != -1)
if (setsockopt(Tsock, IPPROTO_TCP, TCP_KEEPIDLE, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_KEEPIDLE socket option for Transparent connections");
if (Ssock != -1)
if (setsockopt(Ssock, IPPROTO_TCP, TCP_KEEPIDLE, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_KEEPIDLE socket option for Socks5 incoming connections");
if (Hsock != -1)
if (setsockopt(Hsock, IPPROTO_TCP, TCP_KEEPIDLE, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_KEEPIDLE socket option for HTTP incoming connections");
#endif
keepalive_opt = TCP_KEEPCNT_N;
if (Tsock != -1)
if (setsockopt(Tsock, IPPROTO_TCP, TCP_KEEPCNT, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_KEEPCNT socket option for Transparent connections");
if (Ssock != -1)
if (setsockopt(Ssock, IPPROTO_TCP, TCP_KEEPCNT, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_KEEPCNT socket option for Socks5 incoming connections");
if (Hsock != -1)
if (setsockopt(Hsock, IPPROTO_TCP, TCP_KEEPCNT, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_KEEPCNT socket option for HTTP incoming connections");
keepalive_opt = TCP_KEEPINTVL_S;
if (Tsock != -1)
if (setsockopt(Tsock, IPPROTO_TCP, TCP_KEEPINTVL, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_KEEPINTVL socket option for Transparent connections");
if (Ssock != -1)
if (setsockopt(Ssock, IPPROTO_TCP, TCP_KEEPINTVL, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_KEEPINTVL socket option for Socks5 incoming connections");
if (Hsock != -1)
if (setsockopt(Hsock, IPPROTO_TCP, TCP_KEEPINTVL, &keepalive_opt, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting TCP_KEEPINTVL socket option for HTTP incoming connections");
#endif /* __OpenBSD__ */
int raddr = 1;
if (Tsock != -1)
if (setsockopt(Tsock, SOL_SOCKET, SO_REUSEADDR, &raddr, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting Transparent connections socket to be reusable");
if (Ssock != -1)
if (setsockopt(Ssock, SOL_SOCKET, SO_REUSEADDR, &raddr, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting Socks incomming socket to be reusable");
if (Hsock != -1)
if (setsockopt(Hsock, SOL_SOCKET, SO_REUSEADDR, &raddr, sizeof(int)) == -1)
printl(LOG_WARN, "Error setting HTTP incomming socket to be reusable");
/* -- Bind incoming connection sockets & start listening for clients -------------------------------------------- */
if (Tsock != -1) {
if (bind(Tsock, tres->ai_addr, tres->ai_addrlen) < 0) {
printl(LOG_CRIT, "Error binding socket for Transparent incoming connections");
close(Tsock);
mexit(1, pfile_name, tfile_name);
}
printl(LOG_VERB, "The socket for Transparent connections successfully bound");
if (listen(Tsock, SOMAXCONN) == -1) {
printl(LOG_CRIT, "Error listening the socket for Transparent connections");
close(Tsock);
mexit(1, pfile_name, tfile_name);
}
printl(LOG_INFO, "Listening for Transparent connections");
}
if (Ssock != -1) {
if (bind(Ssock, sres->ai_addr, sres->ai_addrlen) < 0) {
printl(LOG_CRIT, "Error binding socket for Socks incoming connections connections");
close(Ssock);
mexit(1, pfile_name, tfile_name);
}
printl(LOG_VERB, "The socket for Socks incoming connections successfully bound");
if (listen(Ssock, SOMAXCONN) == -1) {
printl(LOG_CRIT, "Error listening the socket for Socks incoming connections");
close(Ssock);
mexit(1, pfile_name, tfile_name);
}
printl(LOG_INFO, "Listening for Socks incoming connections");
}
if (Hsock != -1) {
if (bind(Hsock, hres->ai_addr, hres->ai_addrlen) < 0) {
printl(LOG_CRIT, "Error binding socket for HTTP incoming connections");
close(Hsock);
mexit(1, pfile_name, tfile_name);
}
printl(LOG_VERB, "The socket for HTTP incoming connections successfully bound");
if (listen(Hsock, SOMAXCONN) == -1) {
printl(LOG_CRIT, "Error listening the socket for HTTP incoming connections");
close(Hsock);
mexit(1, pfile_name, tfile_name);
}
printl(LOG_INFO, "Listening for HTTP incoming connections");
}
/* -- Set message queue ----------------------------------------------------------------------------------------- */
mskey = ftok("TS-WARP", 10800);
if ((msgid = msgget(mskey, 0600 | IPC_CREAT)) == -1)
printl(LOG_WARN, "Unable to acquire IPC mesage queue ID. No traffic stats will be collected");
/* -- Process clients ------------------------------------------------------------------------------------------- */
while (1) {
FD_ZERO(&sfd);
if (Tsock != -1) FD_SET(Tsock, &sfd);
if (Ssock != -1) FD_SET(Ssock, &sfd);
if (Hsock != -1) FD_SET(Hsock, &sfd);
tv.tv_sec = 0;
tv.tv_usec = 10000;
ret = select(MAX(MAX(Hsock, Ssock), Tsock) + 1, &sfd, NULL, NULL, &tv);
if (ret < 0) continue; /* On an error skip to the next iteration */
if (ret == 0) { /* Timeout - no new connections */
if (msgid != -1 && msgrcv(msgid, &tmessage, sizeof(tmessage), 1, IPC_NOWAIT) != -1)
pidlist_update_traffic(pids, tmessage.mtext);
continue;
}
if (msgid != -1 && msgrcv(msgid, &tmessage, sizeof(tmessage), 1, IPC_NOWAIT) != -1)
pidlist_update_traffic(pids, tmessage.mtext);
/* Check which of the internal servers has a pending connection */
if (Tsock != -1 && FD_ISSET(Tsock, &sfd)) isock = Tsock; else
if (Tsock != -1 && FD_ISSET(Ssock, &sfd)) isock = Ssock; else
isock = Hsock;
caddrlen = sizeof caddr;
memset(&caddr, 0, caddrlen);
if ((csock = accept(isock, (struct sockaddr *)&caddr, &caddrlen)) < 0) {
printl(LOG_CRIT, "Error accepting incoming connection");
return 1;
}
fcntl(csock, F_SETFL, ~O_NONBLOCK); /* Don't block client connections */
printl(LOG_INFO, "Client: [%d], IP: [%s] accepted", cn++, inet2str(&caddr, buf));
/* -- Get the client original destination from NAT ---------------------------------------------------------- */
/* Initialize daddr */
daddr_len = sizeof(daddr.ip_addr);
memset(&daddr.ip_addr, 0, daddr_len);
memset(&daddr.name, 0, sizeof(daddr.name) - 1);
daddr.ip_addr.ss_family = caddr.ss_family;
/* -- Process the PIDs list: remove exitted clients and execute workload balance functions ------------------ */
c = pids;
struct uvaddr tmp_daddr;
unsigned int tmp_daddr_len = sizeof(tmp_daddr.ip_addr);
memset(&tmp_daddr.ip_addr, 0, tmp_daddr_len);
memset(&tmp_daddr.name, 0, sizeof(tmp_daddr.name) - 1);
tmp_daddr.ip_addr.ss_family = caddr.ss_family;
while (c) {
push_ini = NULL;
if (!c->section_name || strlen(c->section_name) == 0) {
tmp_daddr.ip_addr = c->traffic.daddr;
if ((push_ini = ini_look_server(ini_root, tmp_daddr))) {
free(c->section_name);
c->section_name = strdup(push_ini->section_name);
}
}
if (c == pids && c->status >= 0) { /* Remove pidlist root entry */
pids = c->next;
if (!push_ini) push_ini = getsection(ini_root, c->section_name);
if (c->status && push_ini && push_ini->section_balance != SECTION_BALANCE_NONE)
pushback_ini(&ini_root, push_ini);
free(c->section_name);
free(c);
c = pids;
} else if (c && c->next && c->next->status >= 0) { /* Remove a pidlist entry */
d = c->next;
c->next = d->next;
if (!push_ini) push_ini = getsection(ini_root, c->section_name);
if (d->status && push_ini && push_ini->section_balance != SECTION_BALANCE_NONE)
pushback_ini(&ini_root, push_ini);
free(d->section_name);
free(d);
} else {
if (!push_ini) push_ini = getsection(ini_root, c->section_name);
if (push_ini && push_ini->section_balance == SECTION_BALANCE_ROUNDROBIN)
pushback_ini(&ini_root, push_ini);
}
if (c) c = c->next;
}
if ((cpid = fork()) == -1) {
printl(LOG_CRIT, "Failed fork() to serve a client request");
mexit(1, pfile_name, tfile_name);
}
if (cpid > 0) {
/* -- Main (parent process) ----------------------------------------------------------------------------- */
setpgid(cpid, pid);
close(csock);
/* Save the client into the list */
pids = pidlist_add(pids, s_ini ? s_ini->section_name : "", cpid, caddr, daddr.ip_addr);
}
if (cpid == 0) {
/* -- Client processing (child) ------------------------------------------------------------------------- */
ssock.t = CHS_SOCKET; /* Type socket */
#if (WITH_LIBSSH2)
ssock.c = NULL;
#endif
pid = getpid();
printl(LOG_VERB, "A new client process started");
if (isock == Tsock) {
/* -- Transparent proxy connections ----------------------------------------------------------------- */
close(Tsock);
if (Ssock != -1) close(Ssock);
if (Hsock != -1) close(Hsock);
#if defined(linux)
/* On Linux && nftabeles/iptables */
ret = getsockopt(csock, SOL_IP, SO_ORIGINAL_DST, &daddr.ip_addr, &daddr_len);
#else
/* On *BSD with PF */
ret = nat_lookup(pfd, &caddr, (struct sockaddr_storage *)tres->ai_addr, &daddr.ip_addr);
#endif
if (ret) {
printl(LOG_WARN, "Failed to find the real destination IP, trying to get it from the socket");
getpeername(csock, (struct sockaddr *)&daddr.ip_addr, &daddr_len);
}
printl(LOG_INFO, "The client destination address is: [%s]", inet2str(&daddr.ip_addr, buf));
if ((daddr.ip_addr.ss_family == AF_INET &&
S4_ADDR(daddr.ip_addr) == S4_ADDR(*tres->ai_addr) &&
SIN4_PORT(daddr.ip_addr) == SIN4_PORT(*tres->ai_addr)) ||
(daddr.ip_addr.ss_family == AF_INET6 &&
!memcmp(S6_ADDR(daddr.ip_addr), S6_ADDR(*tres->ai_addr), sizeof(S6_ADDR(daddr.ip_addr))) &&
SIN6_PORT(daddr.ip_addr) == SIN6_PORT(*tres->ai_addr)) ||
(daddr.ip_addr.ss_family == AF_INET &&
S4_ADDR(daddr.ip_addr) == S4_ADDR(*sres->ai_addr) &&
SIN4_PORT(daddr.ip_addr) == SIN4_PORT(*sres->ai_addr)) ||
(daddr.ip_addr.ss_family == AF_INET6 &&
!memcmp(S6_ADDR(daddr.ip_addr), S6_ADDR(*sres->ai_addr), sizeof(S6_ADDR(daddr.ip_addr))) &&
SIN6_PORT(daddr.ip_addr) == SIN6_PORT(*sres->ai_addr)) ||
(daddr.ip_addr.ss_family == AF_INET &&
S4_ADDR(daddr.ip_addr) == S4_ADDR(*hres->ai_addr) &&
SIN4_PORT(daddr.ip_addr) == SIN4_PORT(*hres->ai_addr)) ||
(daddr.ip_addr.ss_family == AF_INET6 &&
!memcmp(S6_ADDR(daddr.ip_addr), S6_ADDR(*hres->ai_addr), sizeof(S6_ADDR(daddr.ip_addr))) &&
SIN6_PORT(daddr.ip_addr) == SIN6_PORT(*hres->ai_addr))) {
/* Desination address:port is the same as ts-warp incominig (Taransparent, Socks or HTTP) ip:port,
i.e., a client contacted ts-warp dirctly: no NAT/redirection and TS-Warp is not defined as
proxy server */
printl(LOG_WARN, "Dropping loop connection with ts-warp");
close(csock);
exit(1);
}
if (!(s_ini = ini_look_server(ini_root, daddr))) {
/* -- Direct connection with the destination address bypassing proxy --------------------------- */
printl(LOG_INFO, "Making direct connection with the destination: [%s]",
inet2str(&daddr.ip_addr, buf));
if ((ssock.s = connect_desnation(*(struct sockaddr *)&daddr.ip_addr)) == -1) {
printl(LOG_WARN, "Unable to connect with destination: [%s]", inet2str(&daddr.ip_addr, buf));
close(csock);
exit(1);
}
printl(LOG_INFO, "Successfully connected with desination address: [%s]",
inet2str(&daddr.ip_addr, buf));
goto cfloop;
} else {
printl(LOG_INFO, "Serving request to [%s : %s] as Transparent, section: [%s]",
daddr.name, inet2str(&daddr.ip_addr, buf), s_ini->section_name);
}
} else if (isock == Ssock) {
/* -- Internal Socks5 server with AUTH_METHOD_NOAUTH support only ----------------------------------- */
if (Tsock != -1) close(Tsock);
close(Ssock);
if (Hsock != -1) close(Hsock);
printl(LOG_INFO, "Serving the client with embedded TS-Warp Socks-server");
if (socks5_server_hello(csock) == AUTH_METHOD_NOACCEPT) {
printl(LOG_WARN, "Embedded TS-Warp Socks server does not accept connections");
close(csock);
exit(1);
}
if (!socks5_server_request(csock, &daddr)) {
printl(LOG_WARN, "Embedded TS-Warp Socks server lost connection with the client");
close(csock);
exit(1);
}
s_ini = ini_look_server(ini_root, daddr);
if (!s_ini || (s_ini && SA_FAMILY(s_ini->proxy_server) == AF_INET ? \
S4_ADDR(s_ini->proxy_server) == S4_ADDR(*sres->ai_addr) : \
S6_ADDR(s_ini->proxy_server) == S6_ADDR(*sres->ai_addr))) {
printl(LOG_INFO, "Serving request to: [%s] with Internal TS-Warp SOCKS server",
daddr.name[0] ? daddr.name : inet2str(&daddr.ip_addr, buf));
if ((ssock.s = connect_desnation(*(struct sockaddr *)&daddr.ip_addr)) == -1) {
printl(LOG_WARN, "Unable to connect with destination: [%s]",
daddr.name[0] ? daddr.name : inet2str(&daddr.ip_addr, buf));
/* Replying Error to Socks5 client */
printl(LOG_VERB, "Replying the client, Internal Socks5 can't reach desination: [%s]",
daddr.name[0] ? daddr.name : inet2str(&daddr.ip_addr, buf));
socks5_server_reply(csock, (struct sockaddr_storage *)(sres->ai_addr), SOCKS5_REPLY_KO);
close(csock);
exit(1);
} else {
/* Replying OK to Socks5 client */
printl(LOG_VERB, "Replying the client, Internal Socks5 can reach desination: [%s]",
daddr.name[0] ? daddr.name : inet2str(&daddr.ip_addr, buf));
socks5_server_reply(csock, (struct sockaddr_storage *)(sres->ai_addr), SOCKS5_REPLY_OK);
}
goto cfloop;
} else {
printl(LOG_INFO, "Serving request to [%s : %s] with external proxy server, section: [%s]",
daddr.name, inet2str(&daddr.ip_addr, buf), s_ini->section_name);
/* Replying OK to Socks5 client */
printl(LOG_VERB,
"Replying Socks5 client [OK], the desination: [%s] is managed by external proxy",
daddr.name[0] ? daddr.name : inet2str(&daddr.ip_addr, buf));
socks5_server_reply(csock, (struct sockaddr_storage *)(tres->ai_addr), SOCKS5_REPLY_OK);
}
} else if (isock == Hsock) {
/* -- Internal HTTP server ------------------------------------------------------------------------- */
if (Tsock != -1) close(Tsock);
if (Ssock != -1) close(Ssock);
close(Hsock);
printl(LOG_INFO, "Serving the client with embedded TS-Warp HTTP-server");
if (http_server_request(csock, &daddr)) {
printl(LOG_WARN, "Embedded TS-Warp HTTP server lost connection with the client");
close(csock);
exit(1);
}
s_ini = ini_look_server(ini_root, daddr);
if (!s_ini || (s_ini && SA_FAMILY(s_ini->proxy_server) == AF_INET ? \
S4_ADDR(s_ini->proxy_server) == S4_ADDR(*hres->ai_addr) : \
S6_ADDR(s_ini->proxy_server) == S6_ADDR(*hres->ai_addr))) {
printl(LOG_INFO, "Serving request to: [%s] with Internal TS-Warp HTTP server",
daddr.name[0] ? daddr.name : inet2str(&daddr.ip_addr, buf));
if ((ssock.s = connect_desnation(*(struct sockaddr *)&daddr.ip_addr)) == -1) {
printl(LOG_WARN, "Unable to connect with destination: [%s]",
daddr.name[0] ? daddr.name : inet2str(&daddr.ip_addr, buf));
close(csock);
exit(1);
}
goto cfloop;
} else
printl(LOG_INFO, "Serving request to [%s : %s] with external proxy server, section: [%s]",
daddr.name, inet2str(&daddr.ip_addr, buf), s_ini->section_name);
}
/* -- Start external proxy forwarding ------------------------------------------------------------------- */
if (s_ini && s_ini->p_chain) {
/* -- Proxy chains ---------------------------------------------------------------------------------- */
struct proxy_chain *sc = s_ini->p_chain;
printl(LOG_INFO, "Connecting a CHAIN: [%s] proxy server: [%s] type [%c]", sc->chain_member->section_name,
inet2str(&sc->chain_member->proxy_server, buf), sc->chain_member->proxy_type);
/* Connect the first member of the chain */
if ((ssock.s = connect_desnation(*(struct sockaddr *)&sc->chain_member->proxy_server)) == -1) {
printl(LOG_WARN, "Unable to connect with CHAIN proxy server: [%s] type [%c]",
inet2str(&sc->chain_member->proxy_server, buf), sc->chain_member->proxy_type);
close(csock);
exit(2);
}
while (sc) {
switch (sc->chain_member->proxy_type) {
case PROXY_PROTO_SOCKS_V5:
if (sc->chain_member->proxy_user)
auth_method = socks5_client_hello(ssock, AUTH_METHOD_NOAUTH, AUTH_METHOD_UNAME,
AUTH_METHOD_NOACCEPT);
else
auth_method = socks5_client_hello(ssock, AUTH_METHOD_NOAUTH, AUTH_METHOD_NOACCEPT);
switch (auth_method) {
case AUTH_METHOD_NOAUTH:
/* No authentication required */
break;
case AUTH_METHOD_UNAME:
/* Perform user/password auth */
if (socks5_client_auth(ssock, sc->chain_member->proxy_user,
sc->chain_member->proxy_password)) {
printl(LOG_WARN, "CHAIN Socks5 server rejected user: [%s]",
sc->chain_member->proxy_user);
close(csock);
exit(2);
}
break;
case AUTH_METHOD_NOACCEPT:
default:
printl(LOG_WARN, "No (supported) auth methods were accepted by CHAIN Socks5 server");
close(csock);
exit(2);
}
if (sc->next) {
/* We want to connect with the next chain member */
printl(LOG_VERB, "Initiate CHAIN Socks5 protocol: request [%s] -> [%s]",
inet2str(&sc->chain_member->proxy_server, suf),
inet2str(&sc->next->chain_member->proxy_server, buf));
if (socks5_client_request(ssock, SOCKS5_CMD_TCPCONNECT,
&sc->next->chain_member->proxy_server, NULL)) {
printl(LOG_WARN, "CHAIN Socks5 server returned an error");
close(csock);
exit(2);
}
} else {
/* We are at the end of the chain, so connect with the section server */
printl(LOG_VERB, "Initiate CHAIN Socks5 protocol: request [%s] -> [%s]",
inet2str(&sc->chain_member->proxy_server, suf),
inet2str(&s_ini->proxy_server, buf));
if (socks5_client_request(ssock, SOCKS5_CMD_TCPCONNECT, &s_ini->proxy_server, NULL)) {
printl(LOG_WARN, "CHAIN Socks5 server returned an error");
close(csock);
exit(2);
}
goto single_server;
}
break;
case PROXY_PROTO_SOCKS_V4:
if (sc->next) {
/* We want to connect with the next chain member */
printl(LOG_VERB, "Initiate CHAIN Socks4 protocol: request [%s] -> [%s]",
inet2str(&sc->chain_member->proxy_server, suf),
inet2str(&sc->next->chain_member->proxy_server, buf));
if (socks4_client_request(ssock, SOCKS4_CMD_TCPCONNECT,
(struct sockaddr_in *)&sc->next->chain_member->proxy_server,
sc->next->chain_member->proxy_user)) {
printl(LOG_WARN, "CHAIN Socks4 server returned an error");
close(csock);
exit(2);
}
} else {
/* We are at the end of the chain, so connect with the section server */
printl(LOG_VERB, "Initiate CHAIN Socks4 protocol: request [%s] -> [%s]",
inet2str(&sc->chain_member->proxy_server, suf),
inet2str(&s_ini->proxy_server, buf));
if (socks4_client_request(ssock, SOCKS4_CMD_TCPCONNECT,
(struct sockaddr_in *)&s_ini->proxy_server, s_ini->proxy_user)) {
printl(LOG_WARN, "CHAIN Socks4 server returned an error");
close(csock);
exit(2);
}
goto single_server;
}
break;
case PROXY_PROTO_HTTP:
if (sc->next) {
/* We want to connect with the next chain member */
printl(LOG_VERB, "Initiate CHAIN HTTP protocol: request [%s] -> [%s]",
inet2str(&sc->chain_member->proxy_server, suf),
inet2str(&sc->next->chain_member->proxy_server, buf));
if (http_client_request(ssock, &sc->next->chain_member->proxy_server,
sc->next->chain_member->proxy_user,
sc->next->chain_member->proxy_password, sdpi)) {
printl(LOG_WARN, "CHAIN HTTP server returned an error");
close(csock);
exit(2);
}
} else {
/* We are at the end of the chain, so connect with the section server */
printl(LOG_VERB, "Initiate CHAIN HTTP protocol: request [%s] -> [%s]",
inet2str(&sc->chain_member->proxy_server, suf),
inet2str(&s_ini->proxy_server, buf));
if (http_client_request(ssock,
&s_ini->proxy_server, s_ini->proxy_user, s_ini->proxy_password, sdpi)) {
printl(LOG_WARN, "CHAIN HTTP server returned an error");
close(csock);
exit(2);
}
goto single_server;
}
break;
#if (WITH_LIBSSH2)
case PROXY_PROTO_SSH2:
if (ssh2sess || ssh2ch) {
printl(LOG_WARN, "Only ONE SSH2 proxy could be used per CHAIN");
close(csock);
exit(2);
}
if (!(ssh2sess = libssh2_session_init())) {
printl(LOG_WARN, "Unable to initialize SSH2 session");
close(csock);
exit(2);
}
if (sc->next) {
/* We want to connect with the next chain member */
printl(LOG_VERB, "Initiate CHAIN SSH2 protocol: request: [%s] -> [%s] mid chain cell",
inet2str(&sc->chain_member->proxy_server, suf),
inet2str(&sc->next->chain_member->proxy_server, buf));
p_server.ip_addr = sc->next->chain_member->proxy_server;
memset(p_server.name, 0, sizeof(p_server.name));
if (!(ssh2ch = ssh2_client_request(ssock.s, ssh2sess, &p_server,
sc->chain_member->proxy_user, sc->chain_member->proxy_password,
sc->chain_member->proxy_key, sc->chain_member->proxy_key_passphrase,
sc->chain_member->proxy_ssh_force_auth))) {
printl(LOG_WARN, "CHAIN SSH2 proxy server returned an error");
close(csock);
exit(2);