-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathzdtun.c
2111 lines (1646 loc) · 59.5 KB
/
zdtun.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
/* ----------------------------------------------------------------------------
* Zero Dep Tunnel: VPN library without dependencies
* ----------------------------------------------------------------------------
*
* Copyright (C) 2018-22 - Emanuele Faranda
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#include "zdtun.h"
#include "utils.h"
#include "socks5.h"
#include "third_party/uthash.h"
#include "third_party/net_headers.h"
#define REPLY_BUF_SIZE 65535
#define DEFAULT_TCP_WINDOW 65535
#define TCP_HEADER_LEN 20
#define IPV4_HEADER_LEN 20
#define IPV6_HEADER_LEN 40
#define UDP_HEADER_LEN 8
#define ICMP_TIMEOUT_SEC 5
#define UDP_TIMEOUT_SEC 30
#define TCP_TIMEOUT_SEC 60
#ifdef WIN32
// 64 is the per-thread limit on Winsocks
// use a lower value to leave room for user defined connections
#define MAX_NUM_SOCKETS 55
#define NUM_SOCKETS_AFTER_PURGE 40
#else
// on linux, the maximum open files limit is 1024
#define MAX_NUM_SOCKETS 128
#define NUM_SOCKETS_AFTER_PURGE 96
#endif
/* ******************************************************* */
static void destroy_conn(zdtun_t *tun, zdtun_conn_t *conn);
#define default_mss(tun, conn) (tun->mtu - sizeof(struct tcphdr) -\
((sock_ipver(tun, conn) == 4) ? sizeof(struct iphdr) : sizeof(struct ipv6_hdr)))
/* ******************************************************* */
typedef struct tcp_data {
struct tcp_data* next;
uint16_t len;
uint16_t sofar;
uint8_t flags;
char data[];
} tcp_data_t;
// used to resolve port numbers for IP fragments
typedef struct {
uint16_t sport;
uint16_t dport;
} ip_frag_ports_t;
// Keeps track of the client UDP ports numbers (see bind_and_connect_udp)
typedef struct {
uint32_t key; // combination of ipver and port number
uint16_t port; // the local port associated to the client port
uint16_t num_uses; // number of connections using this client port
UT_hash_handle hh;
} udp_mapping_t;
typedef enum {
PROXY_NONE = 0,
PROXY_DNAT,
PROXY_SOCKS5,
} proxy_mode_t;
typedef struct {
zdtun_ip_t ip;
uint16_t port;
uint8_t ipver;
} proxy_t;
/* ******************************************************* */
typedef struct zdtun_conn {
zdtun_5tuple_t tuple;
time_t tstamp;
socket_t sock;
zdtun_conn_status_t status;
int error;
proxy_t *dnat;
proxy_mode_t proxy_mode;
socks5_status_t socks5_status;
uint8_t socks5_skip;
union {
struct {
tcp_data_t *tx_queue; // contains TCP segment data to send via the socket
u_int32_t tx_queue_size; // queued bytes in partial_send
u_int32_t client_seq; // next client sequence number
u_int32_t zdtun_seq; // next proxy sequence number
u_int32_t window_size; // scaled client window size
u_int16_t mss; // client MSS
u_int8_t window_scale; // client/zdtun TCP window scale
struct {
uint8_t fin_ack_sent:1;
uint8_t client_closed:1;
};
} tcp;
};
struct {
u_int8_t pending_queries;
} dns;
void *user_data;
UT_hash_handle hh; // tuple -> conn
} zdtun_conn_t;
/* ******************************************************* */
typedef struct zdtun_t {
struct zdtun_callbacks callbacks;
void *user_data;
fd_set all_fds;
fd_set write_fds;
uint32_t mtu;
zdtun_statistics_t stats;
time_t now;
zdtun_pkt_t last_pkt; // store pkt here to prevent invalid memory access by subsequent API calls
ip_frag_ports_t id2ports[65536];
char reply_buf[REPLY_BUF_SIZE];
proxy_t socks5;
char *socks5_user;
char *socks5_pass;
zdtun_conn_t *conn_table;
udp_mapping_t *udp_mappings;
} zdtun_t;
/* ******************************************************* */
struct dns_packet {
uint16_t transaction_id;
uint16_t flags;
uint16_t questions;
uint16_t answ_rrs;
uint16_t auth_rrs;
uint16_t additional_rrs;
uint8_t initial_dot; // just skip
uint8_t queries[];
} __attribute__((packed));
#define DNS_FLAGS_MASK 0x8000
#define DNS_TYPE_REQUEST 0x0000
#define DNS_TYPE_RESPONSE 0x8000
/* ******************************************************* */
struct ippseudo {
uint32_t ippseudo_src; /* source internet address */
uint32_t ippseudo_dst; /* destination internet address */
u_int8_t ippseudo_pad; /* pad, must be zero */
u_int8_t ippseudo_p; /* protocol */
u_int16_t ippseudo_len; /* protocol length */
};
struct ip6_hdr_pseudo {
struct in6_addr ip6ph_src;
struct in6_addr ip6ph_dst;
u_int32_t ip6ph_len;
u_int8_t ip6ph_zero[3];
u_int8_t ip6ph_nxt;
} __attribute__((packed));
/* ******************************************************* */
void zdtun_fds(zdtun_t *tun, int *max_fd, fd_set *rdfd, fd_set *wrfd) {
*max_fd = tun->stats.all_max_fd;
*rdfd = tun->all_fds;
*wrfd = tun->write_fds;
}
/* ******************************************************* */
static uint8_t sock_ipver(zdtun_t *tun, zdtun_conn_t *conn) {
if(conn->proxy_mode == PROXY_DNAT)
return conn->dnat->ipver;
else if(conn->proxy_mode == PROXY_SOCKS5)
return tun->socks5.ipver;
else
return conn->tuple.ipver;
}
/* ******************************************************* */
static inline uint32_t udp_mapping_key(const zdtun_5tuple_t *tuple) {
// ignoring the src IP, assume only 1 client
return (uint32_t)tuple->ipver << 16 | tuple->src_port;
}
/* ******************************************************* */
static socket_t open_socket(zdtun_t *tun, int domain, int type, int protocol) {
if(tun->stats.num_open_sockets >= MAX_NUM_SOCKETS)
return(INVALID_SOCKET);
socket_t sock = socket(domain, type, protocol);
if(sock == INVALID_SOCKET)
return(INVALID_SOCKET);
#ifndef WIN32
if(sock < 0)
return(INVALID_SOCKET);
/* FD_SETSIZE should never be execeeded, otherwise FD_SET will crash */
if(sock >= FD_SETSIZE) {
error("socket exceeds FD_SETSIZE");
closesocket(sock);
return(INVALID_SOCKET);
}
#endif
if(tun->callbacks.on_socket_open)
tun->callbacks.on_socket_open(tun, sock);
FD_SET(sock, &tun->all_fds);
tun->stats.num_open_sockets++;
#ifndef WIN32
tun->stats.all_max_fd = max(tun->stats.all_max_fd, sock);
#endif
switch(protocol) {
case IPPROTO_UDP:
tun->stats.num_udp_opened++;
break;
case IPPROTO_TCP:
tun->stats.num_tcp_opened++;
break;
case IPPROTO_ICMP:
case IPPROTO_ICMPV6:
tun->stats.num_icmp_opened++;
break;
}
return(sock);
}
/* ******************************************************* */
static void close_socket(zdtun_t *tun, socket_t sock) {
if(sock == INVALID_SOCKET)
return;
int rv = closesocket(sock);
if(rv == SOCKET_ERROR) {
error("closesocket failed[%d]", socket_errno);
} else if(tun->callbacks.on_socket_close)
tun->callbacks.on_socket_close(tun, sock);
FD_CLR(sock, &tun->all_fds);
FD_CLR(sock, &tun->write_fds);
tun->stats.num_open_sockets = max(tun->stats.num_open_sockets-1, 0);
}
/* ******************************************************* */
// Returns != 0 if the error is related to a client side problem
static int close_with_socket_error(zdtun_t *tun, zdtun_conn_t *conn, const char *ctx) {
int rv = 0;
zdtun_conn_status_t status;
char buf[256];
switch(socket_errno) {
case socket_con_reset:
status = CONN_STATUS_RESET;
break;
case socket_broken_pipe:
status = CONN_STATUS_SOCKET_ERROR;
break;
case socket_con_refused:
status = CONN_STATUS_SOCKET_ERROR;
break;
case socket_con_aborted:
status = CONN_STATUS_SOCKET_ERROR;
break;
case socket_net_unreachable:
case socket_host_unreachable:
status = CONN_STATUS_UNREACHABLE;
rv = -1;
break;
default:
status = CONN_STATUS_SOCKET_ERROR;
rv = -1;
break;
}
zdtun_5tuple2str(&conn->tuple, buf, sizeof(buf));
if(rv == 0) {
log("%s error[%d]: %s - %s", ctx, socket_errno, strerror(socket_errno), buf);
} else {
error("%s error[%d]: %s - %s", ctx, socket_errno, strerror(socket_errno), buf);
}
conn->error = socket_errno;
zdtun_conn_close(tun, conn, status);
return(rv);
}
/* ******************************************************* */
void* zdtun_userdata(zdtun_t *tun) {
return(tun->user_data);
}
/* ******************************************************* */
static time_t zdtun_now(zdtun_t *tun) {
struct timespec ts;
if(!clock_gettime(CLOCK_MONOTONIC_COARSE, &ts))
tun->now = ts.tv_sec;
else
error("clock_gettime failed");
return tun->now;
}
/* ******************************************************* */
void zdtun_set_socks5_proxy(zdtun_t *tun, const zdtun_ip_t *proxy_ip,
uint16_t proxy_port, uint8_t ipver) {
tun->socks5.ip = *proxy_ip;
tun->socks5.port = proxy_port;
tun->socks5.ipver = ipver;
}
/* ******************************************************* */
void zdtun_set_socks5_userpass(zdtun_t *tun, const char *username, const char *password) {
free(tun->socks5_user);
free(tun->socks5_pass);
tun->socks5_user = strdup(username);
tun->socks5_pass = strdup(password);
}
/* ******************************************************* */
/* Connection methods */
void* zdtun_conn_get_userdata(const zdtun_conn_t *conn) {
return conn->user_data;
}
void zdtun_conn_set_userdata(zdtun_conn_t *conn, void *userdata) {
conn->user_data = userdata;
}
const zdtun_5tuple_t* zdtun_conn_get_5tuple(const zdtun_conn_t *conn) {
return &conn->tuple;
}
time_t zdtun_conn_get_last_seen(const zdtun_conn_t *conn) {
return conn->tstamp;
}
zdtun_conn_status_t zdtun_conn_get_status(const zdtun_conn_t *conn) {
return conn->status;
}
int zdtun_conn_get_error(const zdtun_conn_t *conn) {
return conn->error;
}
socket_t zdtun_conn_get_socket(const zdtun_conn_t *conn) {
return conn->sock;
}
void zdtun_conn_proxy(zdtun_conn_t *conn) {
// NOTE: only TCP is currently supported
if(conn->tuple.ipproto == IPPROTO_TCP)
conn->proxy_mode = PROXY_SOCKS5;
}
void zdtun_conn_dnat(zdtun_conn_t *conn, const zdtun_ip_t *proxy_ip, uint16_t proxy_port, uint8_t ipver) {
proxy_t *proxy;
safe_alloc(proxy, proxy_t);
proxy->ip = *proxy_ip;
proxy->port = proxy_port;
proxy->ipver = ipver;
if(conn->dnat)
free(conn->dnat);
conn->dnat = proxy;
conn->proxy_mode = PROXY_DNAT;
}
/* ******************************************************* */
zdtun_t* zdtun_init(struct zdtun_callbacks *callbacks, void *udata) {
zdtun_t *tun;
safe_alloc(tun, zdtun_t);
if(!tun) {
error("zdtun_t calloc error");
return NULL;
}
/* Verify mandatory callbacks */
if(!callbacks) {
error("callbacks parameter is NULL");
return NULL;
}
if(!callbacks->send_client) {
error("missing mandatory send_client callback");
return NULL;
}
tun->user_data = udata;
tun->mtu = 1500;
memcpy(&tun->callbacks, callbacks, sizeof(tun->callbacks));
FD_ZERO(&tun->all_fds);
FD_ZERO(&tun->write_fds);
return tun;
}
/* ******************************************************* */
void zdtun_finalize(zdtun_t *tun) {
zdtun_conn_t *conn, *tmp;
HASH_ITER(hh, tun->conn_table, conn, tmp) {
destroy_conn(tun, conn);
}
// tun->udp_mappings is cleaned up during destroy_conn
free(tun->socks5_user);
free(tun->socks5_pass);
free(tun);
}
/* ******************************************************* */
static int send_to_client(zdtun_t *tun, zdtun_conn_t *conn, int l3_len) {
int size = l3_len + zdtun_iphdr_len(tun, conn);
if(zdtun_parse_pkt(tun, tun->reply_buf, size, &tun->last_pkt) < 0) {
error("zdtun_parse_pkt failed, this should never happen");
return -1;
}
int rv = tun->callbacks.send_client(tun, &tun->last_pkt, conn);
if(rv == 0) {
if(tun->callbacks.account_packet)
tun->callbacks.account_packet(tun, &tun->last_pkt, 0 /* from zdtun */, conn);
} else {
debug("send_client failed [%d]", rv);
if(conn->tuple.ipproto == IPPROTO_TCP)
// important: set this to prevent close_conn to call send_to_client again in a loop
conn->tcp.fin_ack_sent = 1;
zdtun_conn_close(tun, conn, CONN_STATUS_CLIENT_ERROR);
}
return(rv);
}
/* ******************************************************* */
#ifndef WIN32
// Try to get the free space in the socket TX buffer. The value returned
// is just an approximation which helps tuning the TCP receiver window
// seen by the client, thus possibly throttling the upload before
// reaching the bottleneck and subsequent retransmissions.
//
// http://lkml.iu.edu/hypermail/linux/kernel/0502.2/1087.html
// https://gitlab.torproject.org/tpo/core/tor/-/issues/12890
static int get_available_sndbuf(zdtun_conn_t *conn) {
int bufsize = 0;
int queued = 0;
socklen_t len = sizeof(bufsize);
// Get the available bytes in the send buffer
getsockopt(conn->sock, SOL_SOCKET, SO_SNDBUF, &bufsize, &len);
if(bufsize == 0)
bufsize = DEFAULT_TCP_WINDOW;
ioctl(conn->sock, SIOCOUTQ, &queued);
int sockbuf_avail = bufsize - queued - conn->tcp.tx_queue_size;
return max(sockbuf_avail, 0);
}
#endif
/* ******************************************************* */
int zdtun_iphdr_len(zdtun_t *tun, zdtun_conn_t *conn) {
return (sock_ipver(tun, conn) == 4) ? IPV4_HEADER_LEN : IPV6_HEADER_LEN;
}
/* ******************************************************* */
void zdtun_make_iphdr(zdtun_t *tun, zdtun_conn_t *conn, char *pkt_buf, u_int16_t l3_len) {
if(sock_ipver(tun, conn) == 4) {
struct iphdr *ip = (struct iphdr*)pkt_buf;
uint16_t tot_len = l3_len + IPV4_HEADER_LEN;
memset(ip, 0, IPV4_HEADER_LEN);
ip->ihl = 5; // 5 * 4 = 20 = IPV4_HEADER_LEN
ip->version = 4;
ip->frag_off = htons(0x4000); // don't fragment
ip->tot_len = htons(tot_len);
ip->ttl = 64; // hops
ip->protocol = conn->tuple.ipproto;
ip->saddr = conn->tuple.dst_ip.ip4;
ip->daddr = conn->tuple.src_ip.ip4;
ip->check = ~calc_checksum(0, (u_int8_t*)ip, IPV4_HEADER_LEN);
} else {
struct ipv6_hdr *ip = (struct ipv6_hdr*)pkt_buf;
memset(ip, 0, IPV6_HEADER_LEN);
ip->version = 6;
ip->payload_len = htons(l3_len);
ip->nexthdr = (conn->tuple.ipproto != IPPROTO_ICMP) ? conn->tuple.ipproto : IPPROTO_ICMPV6;
ip->hop_limit = 64;
ip->saddr = conn->tuple.dst_ip.ip6;
ip->daddr = conn->tuple.src_ip.ip6;
}
}
/* ******************************************************* */
uint16_t zdtun_l3_checksum(zdtun_t *tun, zdtun_conn_t *conn, char *ipbuf, char *l3, uint16_t l3_len) {
uint8_t ipver = sock_ipver(tun, conn);
uint8_t ipproto = conn->tuple.ipproto;
uint16_t rv = calc_checksum(0, (uint8_t*)l3, l3_len);
if(ipver == 4) {
struct iphdr *ip_header = (struct iphdr*)ipbuf;
struct ippseudo pseudo = {0};
pseudo.ippseudo_src = ip_header->saddr;
pseudo.ippseudo_dst = ip_header->daddr;
pseudo.ippseudo_p = ipproto;
pseudo.ippseudo_len = htons(l3_len);
rv = calc_checksum(rv, (uint8_t*)&pseudo, sizeof(pseudo));
} else {
struct ipv6_hdr *ip_header = (struct ipv6_hdr*)ipbuf;
struct ip6_hdr_pseudo pseudo;
memset(&pseudo, 0, sizeof(pseudo));
pseudo.ip6ph_src = ip_header->saddr;
pseudo.ip6ph_dst = ip_header->daddr;
pseudo.ip6ph_len = ip_header->payload_len;
pseudo.ip6ph_nxt = ((ipver == 6) && (ipproto == IPPROTO_ICMP)) ? IPPROTO_ICMPV6 : ipproto;
rv = calc_checksum(rv, (uint8_t*)&pseudo, sizeof(pseudo));
}
return ~rv;
}
/* ******************************************************* */
static void build_reply_tcpip(zdtun_t *tun, zdtun_conn_t *conn, u_int8_t flags,
u_int16_t l4_len, u_int16_t optsoff) {
uint8_t ipver = sock_ipver(tun, conn);
int iphdr_len = zdtun_iphdr_len(tun, conn);
const u_int16_t l3_len = l4_len + TCP_HEADER_LEN + (optsoff * 4);
struct tcphdr *tcp = (struct tcphdr *)&tun->reply_buf[iphdr_len];
uint32_t max_win = ((uint32_t)0xFFFF) << conn->tcp.window_scale;
uint32_t tcpwin;
memset(tcp, 0, TCP_HEADER_LEN);
tcp->th_sport = conn->tuple.dst_port;
tcp->th_dport = conn->tuple.src_port;
tcp->th_seq = htonl(conn->tcp.zdtun_seq);
tcp->th_ack = (flags & TH_ACK) ? htonl(conn->tcp.client_seq) : 0;
tcp->th_off = 5 + optsoff;
tcp->th_flags = flags;
#ifdef WIN32
tcpwin = max_win;
#else
// To avoid slowdowns, it's better to check the free space in the send
// buffer and reduce the TCP window accordingly. If a 0 window is sent,
// the client will periodically send TCP_KEEPALIVE to wake the connection.
// This prevents connection stall.
tcpwin = min(get_available_sndbuf(conn), max_win);
#endif
tcp->th_win = htons(tcpwin >> conn->tcp.window_scale);
zdtun_make_iphdr(tun, conn, tun->reply_buf, l3_len);
tcp->th_sum = zdtun_l3_checksum(tun, conn, tun->reply_buf, (char*)tcp, l3_len);
}
/* ******************************************************* */
// It is used to defer the destroy_conn function to let the user
// consume the connection without accessing invalid memory. The connections
// will be (later) destroyed by zdtun_purge_expired.
// May be called multiple times.
void zdtun_conn_close(zdtun_t *tun, zdtun_conn_t *conn, zdtun_conn_status_t status) {
if(conn->status >= CONN_STATUS_CLOSED)
return;
if(conn->tuple.ipproto == IPPROTO_UDP) {
udp_mapping_t *mapping;
uint32_t key = udp_mapping_key(&conn->tuple);
HASH_FIND(hh, tun->udp_mappings, &key, sizeof(key), mapping);
if(mapping && (--mapping->num_uses == 0)) {
HASH_DELETE(hh, tun->udp_mappings, mapping);
free(mapping);
}
}
close_socket(tun, conn->sock);
conn->sock = INVALID_SOCKET;
if((conn->tuple.ipproto == IPPROTO_TCP)
&& !conn->tcp.fin_ack_sent) {
// Send TCP RST
build_reply_tcpip(tun, conn, TH_RST | TH_ACK, 0, 0);
send_to_client(tun, conn, TCP_HEADER_LEN);
}
if(conn->tuple.ipproto == IPPROTO_TCP) {
tcp_data_t *cur = conn->tcp.tx_queue;
// free tx_queue
while(cur) {
tcp_data_t *next = cur->next;
free(cur);
cur = next;
}
conn->tcp.tx_queue = NULL;
}
conn->status = (status >= CONN_STATUS_CLOSED) ? status : CONN_STATUS_CLOSED;
if(tun->callbacks.on_connection_close)
tun->callbacks.on_connection_close(tun, conn);
}
/* ******************************************************* */
// Avoid calling destroy_conn inside zdtun_forward_full as it may
// generate dangling pointers. Use close_conn instead.
static void destroy_conn(zdtun_t *tun, zdtun_conn_t *conn) {
debug("PURGE SOCKET (type=%d)", conn->tuple.ipproto);
zdtun_conn_close(tun, conn, CONN_STATUS_CLOSED);
if(conn->dnat)
free(conn->dnat);
switch(conn->tuple.ipproto) {
case IPPROTO_TCP:
tun->stats.num_tcp_conn--;
break;
case IPPROTO_UDP:
tun->stats.num_udp_conn--;
break;
case IPPROTO_ICMP:
tun->stats.num_icmp_conn--;
break;
}
HASH_DELETE(hh, tun->conn_table, conn);
free(conn);
}
/* ******************************************************* */
static int send_syn_ack(zdtun_t *tun, zdtun_conn_t *conn) {
int rv;
int iphdr_len = zdtun_iphdr_len(tun, conn);
uint8_t *opts = (uint8_t*) &tun->reply_buf[iphdr_len + TCP_HEADER_LEN];
// MSS option
*(opts++) = 2;
*(opts++) = 4;
*((uint16_t*)opts) = htons(default_mss(tun, conn));
opts += 2;
// Window Scale
*(opts++) = 3;
*(opts++) = 3;
*(opts++) = conn->tcp.window_scale;
// End, aligned to 32 bits
*(opts++) = 0;
build_reply_tcpip(tun, conn, TH_SYN | TH_ACK, 0, 2 /* n. 32bit words*/);
if((rv = send_to_client(tun, conn, TCP_HEADER_LEN + 8 /* opts length */)) == 0)
conn->tcp.zdtun_seq += 1;
return rv;
}
/* ******************************************************* */
static int tcp_socket_syn(zdtun_t *tun, zdtun_conn_t *conn) {
// disable non-blocking mode from now on
#ifdef WIN32
unsigned nonblocking = 0;
ioctlsocket(conn->sock, FIONBIO, &nonblocking);
#else
int flags = fcntl(conn->sock, F_GETFL);
if(fcntl(conn->sock, F_SETFL, flags &(~O_NONBLOCK)) == -1)
error("Cannot disable non-blocking: %d", errno);
#endif
FD_CLR(conn->sock, &tun->write_fds);
conn->status = CONN_STATUS_CONNECTED;
if(conn->proxy_mode == PROXY_SOCKS5) {
// wait before sending the SYN+ACK
return socks5_connect(tun, conn);
}
return send_syn_ack(tun, conn);
}
/* ******************************************************* */
static void tcp_socket_fin_ack(zdtun_t *tun, zdtun_conn_t *conn) {
build_reply_tcpip(tun, conn, TH_FIN | TH_ACK, 0, 0);
if(send_to_client(tun, conn, TCP_HEADER_LEN) == 0)
conn->tcp.zdtun_seq += 1;
}
/* ******************************************************* */
zdtun_conn_t* zdtun_lookup(zdtun_t *tun, const zdtun_5tuple_t *tuple, uint8_t create) {
zdtun_conn_t *conn = NULL;
HASH_FIND(hh, tun->conn_table, tuple, sizeof(*tuple), conn);
if(conn && (conn->status >= CONN_STATUS_CLOSED)) {
// avoid returning connections to purge, for which the close_callback was already called and
// user data was probably already deallocated.
destroy_conn(tun, conn);
conn = NULL;
}
if(!conn && create) {
if(tun->stats.num_open_sockets >= MAX_NUM_SOCKETS) {
debug("Force purge!");
zdtun_purge_expired(tun);
}
/* Add a new connection */
safe_alloc(conn, zdtun_conn_t);
conn->sock = INVALID_SOCKET;
conn->tuple = *tuple;
conn->tstamp = zdtun_now(tun);
if(tun->callbacks.on_connection_open) {
if(tun->callbacks.on_connection_open(tun, conn) != 0) {
debug("Dropping connection");
free(conn);
return NULL;
}
}
HASH_ADD(hh, tun->conn_table, tuple, sizeof(*tuple), conn);
switch(conn->tuple.ipproto) {
case IPPROTO_TCP:
tun->stats.num_tcp_conn++;
break;
case IPPROTO_UDP:
tun->stats.num_udp_conn++;
break;
case IPPROTO_ICMP:
tun->stats.num_icmp_conn++;
break;
}
}
return conn;
}
/* ******************************************************* */
static void check_dns_request(zdtun_conn_t *conn, char *l4_payload, uint16_t l4_len) {
struct dns_packet *dns;
if((l4_len < sizeof(struct dns_packet)) || (conn->tuple.dst_port != ntohs(53)))
return;
dns = (struct dns_packet*)l4_payload;
if((dns->flags & DNS_FLAGS_MASK) == DNS_TYPE_REQUEST)
conn->dns.pending_queries++;
}
/* ******************************************************* */
static int check_dns_purge(zdtun_t *tun, zdtun_conn_t *conn,
char *l4_payload, uint16_t l4_len) {
struct dns_packet *dns;
if((l4_len < sizeof(struct dns_packet)) || (conn->tuple.dst_port != ntohs(53)))
return(1);
dns = (struct dns_packet*)l4_payload;
if(((dns->flags & DNS_FLAGS_MASK) == DNS_TYPE_RESPONSE)
&& (conn->dns.pending_queries > 0)) {
conn->dns.pending_queries--;
if(conn->dns.pending_queries == 0) {
char buf[256];
/* DNS responses received, can now purge the conn */
debug("DNS purge: %s", zdtun_5tuple2str(&conn->tuple, buf, sizeof(buf)));
zdtun_conn_close(tun, conn, CONN_STATUS_CLOSED);
/* purged */
return(0);
}
}
return(1);
}
/* ******************************************************* */
static int is_upper_layer(int proto) {
return (proto == IPPROTO_TCP ||
proto == IPPROTO_UDP ||
proto == IPPROTO_ICMP ||
proto == IPPROTO_ICMPV6);
}
/* ******************************************************* */
int zdtun_parse_pkt(zdtun_t *tun, const char *_pkt_buf, uint16_t pkt_len, zdtun_pkt_t *pkt) {
memset(pkt, 0, sizeof(zdtun_pkt_t));
if(pkt_len < IPV4_HEADER_LEN) {
debug("Ignoring non IP packet (len: %d)", pkt_len);
return -1;
}
char *pkt_buf = (char *)_pkt_buf; /* needed to set the zdtun_pkt_t pointers */
uint8_t ipver = (*pkt_buf) >> 4;
uint8_t ipproto;
int iphdr_len;
if((ipver != 4) && (ipver != 6)) {
debug("Ignoring non IP packet (len: %d, v: %d)", pkt_len, ipver);
return -1;
}
if(ipver == 4) {
struct iphdr *ip_header = (struct iphdr*) pkt_buf;
iphdr_len = ip_header->ihl * 4;
if(pkt_len < iphdr_len) {
debug("IPv4 packet too short: %d bytes", pkt_len);
return -1;
}
uint16_t tot_len = ntohs(ip_header->tot_len);
if(tot_len < iphdr_len) {
debug("Invalid IPv4 packet: tot_len=%d, hdr_len=%d", tot_len, iphdr_len);
return -1;
}
// exclude non-IP data
pkt_len = min(pkt_len, tot_len);
pkt->tuple.src_ip.ip4 = ip_header->saddr;
pkt->tuple.dst_ip.ip4 = ip_header->daddr;
ipproto = ip_header->protocol;
if (ip_header->frag_off & htons(0x1FFF)) {
// this an IP fragment (not the first one)
pkt->flags |= ZDTUN_PKT_IS_FRAGMENT;
} else if (ip_header->frag_off & htons(0x2000)) { // IP_MF
// this the first IP fragment
pkt->flags |= ZDTUN_PKT_IS_FRAGMENT;
pkt->flags |= ZDTUN_PKT_IS_FIRST_FRAGMENT;
}
} else {
struct ipv6_hdr *ip_header = (struct ipv6_hdr*) pkt_buf;
if(pkt_len < sizeof(struct ipv6_hdr)) {
debug("IPv6 packet too short: %d bytes", pkt_len);
return -1;
}
iphdr_len = sizeof(struct ipv6_hdr);
if(!is_upper_layer(ip_header->nexthdr)) {
debug("IPv6 extensions not supported: %d", ip_header->nexthdr);
return -1;
}
// exclude non-IP data
uint16_t payload_len = ntohs(ip_header->payload_len);
pkt_len = min(pkt_len, payload_len + iphdr_len);
pkt->tuple.src_ip.ip6 = ip_header->saddr;
pkt->tuple.dst_ip.ip6 = ip_header->daddr;
// Treat IPPROTO_ICMPV6 as IPPROTO_ICMP for simplicity
ipproto = (ip_header->nexthdr != IPPROTO_ICMPV6) ? ip_header->nexthdr : IPPROTO_ICMP;
}
pkt->buf = pkt_buf;
pkt->l3 = pkt_buf;
pkt->tuple.ipproto = ipproto;
pkt->tuple.ipver = ipver;
pkt->len = pkt_len;
pkt->ip_hdr_len = iphdr_len;
pkt->l4 = &pkt_buf[iphdr_len];
if((pkt->flags & ZDTUN_PKT_IS_FRAGMENT) &&
!(pkt->flags & ZDTUN_PKT_IS_FIRST_FRAGMENT)) {
// this an IP fragment (not the first one)
ip_frag_ports_t *ports = &tun->id2ports[pkt->ip4->id];
// may be 0
pkt->tuple.src_port = ports->sport;
pkt->tuple.dst_port = ports->dport;
pkt->l4_hdr_len = 0;
if(!(pkt->ip4->frag_off & htons(0x2000))) { // !IP_MF
// this is the last fragment. Reset the ports to avoid matching unrelated fragments.
// This assumes that the previous fragments are not lost and retransmitted afterwards.
ports->sport = 0;
ports->dport = 0;
}
} else if(ipproto == IPPROTO_TCP) {
struct tcphdr *data = pkt->tcp;
int32_t tcp_header_len;
if(pkt_len < (iphdr_len + TCP_HEADER_LEN)) {
debug("Packet too small for TCP[%d]", pkt_len);
return -1;
}
tcp_header_len = data->th_off * 4;
if(pkt_len < (iphdr_len + tcp_header_len)) {
debug("Malformed TCP packet");
return -1;
}
pkt->l4_hdr_len = tcp_header_len;
pkt->tuple.src_port = data->th_sport;
pkt->tuple.dst_port = data->th_dport;
} else if(ipproto == IPPROTO_UDP) {
struct udphdr *data = pkt->udp;