forked from andreafabrizi/DNSProxy
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdnsp-h2.c
3872 lines (3256 loc) · 132 KB
/
dnsp-h2.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
/*
*
* Copyright (c) 2010-2023 Massimiliano Fantuzzi HB3YOE/HB9GUS <[email protected]>
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <fcntl.h>
#include <sched.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/utsname.h>
#include <sys/timeb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <netdb.h>
#include <ctype.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <signal.h>
#include <pthread.h>
//#include "hexdump.h"
//#include "librb64u.h"
//#include "base64.h"
//#include "b64.h"
#include "deps/ok/ok.h"
#include "deps/b64/b64.h"
/*
#include <semaphore.h>
#include <spawn.h>
#include <omp.h>
*/
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)
#define handle_error(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)
#define VERSION "3.3.0"
#define TCP_Z_OFFSET 2
#define TTL_IN_DEFAULT 0
#define STACK_SIZE (1024 * 20) // Stack size for cloned child
#define MAXCONN 2
#define UDP_DATAGRAM_SIZE 4096 // was 512
#define TCP_DATAGRAM_SIZE 512
#define DNSREWRITE 512
#define HTTP_RESPONSE_SIZE 4096
#define URL_SIZE 512
#define DNS_MODE_ANSWER 0
#define DNS_MODE_ERROR 1
#define TYPEQ 2
#define DEFAULT_LOCAL_PORT 53
#define DEFAULT_WEB_PORT 80
#define DEFAULT_PRX_PORT 1080 // 9050, 8080, 3128
/* experimental options for threaded model, not in use at the moment */
#define NUMT 1
#define NUM_THREADS 1
#define NUM_HANDLER_THREADS 1
//#define FILE_CONTENTTYPE_DEFAULT "application/dns-message"
#define RESOLVER "dns.google"
/* use nghttp2 library to establish, no ALPN/NPN. CURL is not enough, you need builting NGHTTP2 support */
#define USE_NGHTTP2 1
/* DELAY for CURL to wait ? do not remember, needs documentation */
#define DELAY 0
//#define STR_SIZE 65536
#define REV(X) ((X << 24) | (( X & 0xff00 ) << 8) | (( X >> 8) & 0xff00 ) | ( X >> 24 ))
#define R4(X) ((X >> 24 ) &0xff)
#define R3(X) ((X >> 16) & 0xff )
#define R2(X) ((X >> 8) & 0xff )
#define R1(X) (X & 0xff )
//#define R1(X) ((X & 0x000000ff ) << 24 )
//#define R2(X) ((X & 0x0000ff00 ) << 8 )
//#define R3(X) ((X & 0x00ff0000 ) >> 8 )
//#define R4(X) ((X & 0xff000000 ) >> 24 )
#ifndef CURLPIPE_MULTIPLEX
#error " ### libcurl too old, can't use HTTP/2 server push!"
#endif
//#define for_each_item(item, list) \
// for(T * item = list->head; item != NULL; item = item->next)
/* This little trick will just make sure that we don't enable pipelining for libcurls old enough
to not have this symbol. It is _not_ defined to zero in a recent libcurl header. */
#ifndef CURLPIPE_MULTIPLEX
#define CURLPIPE_MULTIPLEX 1
#endif
#ifndef SOMAXCONN
#define SOMAXCONN 1
#endif
#ifndef SIGCLD
#define SIGCLD SIGCHLD
#endif
#ifndef HEXDUMP_COLS
#define HEXDUMP_COLS 16
#endif
#define NUM_HANDLES 4
#define S(x) # x
#define t(m, a, b) ({ \
char tmp[1024]; \
sprintf(tmp, "%s(%s) = %s", S(m), S(a), S(b)); \
char *r = (char *) m(a, strlen((char *) a)); \
assert(0 == strcmp(b, r)); \
free(r); \
ok(tmp); \
})
struct Memory {
char *memory;
size_t size;
};
void* custom_malloc(size_t size){
if (size == 0){
/* On some systems malloc doesn't allow for size = 0 */
return NULL;
}
return malloc(size);
}
void* custom_realloc(void* ptr, size_t size){
return realloc(ptr, size);
}
int DEBUG, DNSDUMP, DEBUGCURLTTL, DEBUGCURL, EXT_DEBUG, CNT_DEBUG, THR_DEBUG, LOCK_DEBUG;
char* substring(char*, int, int);
static int ttl_out_test = 3600;
static int size_test = 0;
static char data_test = NULL;
static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'};
//static char *decoding_table = NULL;
static int mod_table[] = {0, 2, 1};
void copy_string(char *target, char *source) {
while (*source) {
*target = *source;
source++;
target++;
}
*target = '\0';
}
static void init_memory(struct Memory *chunk) {
chunk->memory = malloc(1); /* grown as needed with realloc */
chunk->size = 0; /* no data at this point */
}
/*
unsigned char *base64_decode(const char *data, size_t input_length, size_t *output_length) {
if (decoding_table == NULL) build_decoding_table();
if (input_length % 4 != 0) return NULL;
*output_length = input_length / 4 * 3;
if (data[input_length - 1] == '=') (*output_length)--;
if (data[input_length - 2] == '=') (*output_length)--;
unsigned char *decoded_data = malloc(*output_length);
if (decoded_data == NULL) return NULL;
for (int i = 0, j = 0; i < input_length;) {
uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t triple = (sextet_a << 3 * 6)
+ (sextet_b << 2 * 6)
+ (sextet_c << 1 * 6)
+ (sextet_d << 0 * 6);
if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
}
return decoded_data;
}
void build_decoding_table() {
decoding_table = malloc(256);
for (int i = 0; i < 64; i++)
decoding_table[(unsigned char) encoding_table[i]] = i;
}
void base64_cleanup() {
free(decoding_table);
}
*/
void remchar(char *s, char chr) {
int i, j = 0;
for ( i = 0; s[i] != '\0'; i++ ) /* 'i' moves through all of original 's' */ {
if ( s[i] != chr ) {
s[j++] = s[i]; /* 'j' only moves after we write a non-'chr' */
}
}
s[j] = '\0'; // re-null-terminate
}
static void *curl_hnd[NUM_HANDLES];
static int num_transfers = 1;
static char *workdir = "./";
/* configure default behaviour when initializing threads */
pthread_key_t glob_var_key_ip;
pthread_key_t glob_var_key_client;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//static pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_mutexattr_t MAttr;
#ifdef TLS
__thread int i;
#else
pthread_key_t key_i;
#endif
pthread_t *tid;
struct readThreadParams {
size_t xrequestlen;
char* xproxy_user;
char* xproxy_pass;
char* xproxy_host;
int xproxy_port;
char* xlookup_script;
char* xtypeq;
char* xworkdir;
int xwport;
int xttl;
int xtcpoff;
int sockfd;
int xsockfd;
struct dns_request *xhostname;
struct sockaddr_in *xclient;
struct sockaddr_in *yclient;
struct dns_request *xproto;
struct dns_request *dns_req;
//struct dns_request *xdns_req;
struct dns_request *xpost_data;
//char* xpost_data;
struct dns_request *xrfcstring;
//char* xrfcstring;
};
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id; /* ID returned by pthread_create() */
int thread_num; /* Application-defined thread # */
char *argv_string; /* From command-line argument */
};
struct dns_request {
uint16_t transaction_id, questions_num, flags, qtype, qclass, tcp_size;
char hostname[256], query[256], rfcstring[256]; // 20230107 - REVIEW
//char hostname[], query[], rfcstring[]; // 20230107 - REVIEW
size_t hostname_len;
};
struct dns_response {
size_t length;
char *payload;
};
/*
void start_thread(pthread_t *mt) {
mystruct *data = malloc(sizeof(*data));
...;
pthread_create(mt, NULL, do_work_son, data);
}
*/
/*
void start_thread(pthread_t *mt) {
//mystruct local_data = {};
//mystruct *data = malloc(sizeof(*data));
struct readThreadParams local_data = {};
struct readThreadParams *data = malloc(sizeof(*data));
*data = local_data;
//pthread_create(mt, NULL, threadFunc,readParams);
pthread_create(mt, NULL, thread_start,data);
//pthread_create(mt, NULL, threadFunc,data);
//ret = pthread_create(&pth[i],NULL,threadFunc,readParams);
//pthread_create(&pth[i],NULL,threadFunc,readParams);
}
*/
static void *thread_start(void *arg) {
struct thread_info *tinfo = arg;
char *uargv, *p;
printf("Thread %d: top of stack near %p; argv_string=%s\n",
tinfo->thread_num, &p, tinfo->argv_string);
uargv = strdup(tinfo->argv_string);
if (uargv == NULL)
handle_error("strdup");
for (p = uargv; *p != '\0'; p++)
*p = toupper(*p);
return uargv;
}
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp) {
if (a_delim == *tmp) {
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result) {
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token) {
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
char * rtrim(char * str, const char * del) {
if (str) {
char * pc;
while (pc = strpbrk(str, del)) {
*pc = 0;
}
}
return str;
}
static void *hexdump(void *mem, unsigned int len) {
unsigned int i, j;
for(i = 0; i < len + ((len % HEXDUMP_COLS) ? (HEXDUMP_COLS - len % HEXDUMP_COLS) : 0); i++) {
/* print offset */
if(i % HEXDUMP_COLS == 0) {
//printf("0x%06x: ", i);
printf("%04x: ", i);
}
if(i < len) {
/* print hex data */
printf("%02x ", 0xFF & ((char*)mem)[i]);
} else {
/* end of block, just aligning for ASCII dump */
printf(" ");
}
/* print ASCII dump */
if(i % HEXDUMP_COLS == (HEXDUMP_COLS - 1)) {
for(j = i - (HEXDUMP_COLS - 1); j <= i; j++) {
if(j >= len) {
/* end of block, not really printing */
putchar(' ');
} else if(isprint(((char*)mem)[j])) {
/* printable char */
putchar(0xFF & ((char*)mem)[j]);
} else {
/* other char */
putchar('.');
}
}
putchar('\n');
}
}
}
unsigned reverse16binary(unsigned val) {
/* reverse bits in a 16-bit binary number */
unsigned rv = 0;
for (int bit = 0; bit < 16; bit++) {
int digit = (val >> bit) & 1; // extract a digit
rv |= digit << (15 - bit); // stick it in the result
}
return rv;
}
/* reverse hex digits in a 16-bit binary number */
unsigned reverse16hex(unsigned val) {
unsigned rv = 0;
for (int bit = 0; bit < 16; bit += 4) {
int digit = (val >> bit) & 0xf; // extract a digit
rv |= digit << (12 - bit); // stick it in the result
}
return rv;
}
/*
reverse base 2**"base" digits in a "bits"-bit binary number
bits must be <= sizeof(unsigned) * CHAR_BIT and a multiple of base
base must be < sizeof(unsigned) * CHAR_BIT
*/
unsigned reverse_general(unsigned val, int bits, int base) {
unsigned rv = 0;
for (int bit = 0; bit < bits; bit += base) {
int digit = (val >> bit) & ((1 << base) - 1); // extract a digit
rv |= digit << (bits - base - bit); // stick it in the result
}
return rv;
}
//struct thread_data{
// int threads;
// int thread_id;
// int exec; //total number of executions
// int max_req_client;
// int random; //1=yes 0=no whether requests are the max or randomdouble
// int ssl; //1=yes 0=no
// int uselogin; //1=yes 0=no
// char domain[256];
// char login[256];
// char password[256];
//};
void usage(void) {
fprintf(stderr, "\n dnsp-h2 v%s, copyright 2010-2023 Massimiliano Fantuzzi HB9GUS, MIT License\n\n"
" usage: dnsp-h2 [-l <local_host_address>] [-p <local_port>] [-H <proxy_host>]\n"
"\t[-r <proxy_port>] [-u <user>] [-k <pass>] [-d <path>] [-Q] \n"
"\t[ -s <DNS_lookup_resolving_service_URL> ] [-w <lookup_port>]\n"
"\n"
" OPTIONS:\n"
" [ -Q ]\t Extract TTL from DoH provider HTTP response (suggested)\n"
" [ -l <IP/FQDN> ]\t Local server address, default to all active interfaces\n"
" [ -p <53> ]\t Local server port, default to 53\n"
" [ -H <IP/FQDN> ]\t MITM/Cache Proxy Address (HTTPS-capable as charles)\n"
" [ -r <3128> ]\t MITM/Cache Proxy Port\n"
" [ -u <user> ]\t MITM/Cache Proxy Username\n"
" [ -k <pass> ]\t MITM/Cache Proxy Password\n"
" [ -d <path> ]\t Output directory for storage of responses\n"
"\n"
" ADVANCED OPTIONS:\n"
" [ -T <n> ]\t Override TTL [0-2147483647] defined in RFC-2181\n"
" [ -Z <n> ]\t Override TCP response size to be any 2 bytes at choice\n"
"\n"
" [ -v ]\t Enable debug\n"
" [ -n ]\t Enable raw DNS dump\n"
" [ -C ]\t Enable CURL debug\n"
" [ -N ]\t Enable COUNTERS debug\n"
" [ -R ]\t Enable THREADS debug\n"
" [ -L ]\t Enable LOCKS debug\n"
" [ -X ]\t Enable EXTRA debug\n"
"\n"
" EXPERT OPTIONS:\n"
" [ -s <URL> ]\t Webservice Lookup Script URL (deprecated, old dnsp)\n"
" [ -w <443> ]\t Webservice Lookup Port (deprecated, old dnsp)\n"
" [ -r ]\t Enable CURL resolve and avoid extra gethostbyname\n"
" [ -t <n> ]\t Stack size in format 0x1000000 (MB)\n"
"\n"
//" Example with direct HTTPS:\n"
//"\t./dnsp-h2 -s https://php-dns.appspot.com/\n"
//" Example with direct HTTP:\n"
//"\t./dnsp-h2 -s http://www.fantuz.net/nslookup.php\n"
//" Example with HTTP caching proxy:\n"
//"\t./dnsp-h2 -r 8118 -H http://your.proxy.com/ -s http://www.fantuz.net/nslookup.php\n"
//" Testing new features:\n"
//"\t./dnsp-h2 -T 3600 -v -X -C -n -s https://php-dns.appspot.com/ 2>&1\n\n"
"\n"
" For a more inclusive list of DoH providers, clients, servers and protocol details, see:\n"
" - https://tools.ietf.org/html/rfc8484\n"
" - https://github.com/curl/curl/wiki/DNS-over-HTTPS\n"
" - https://it.wikipedia.org/wiki/DNS_over_HTTPS#cite_note-8\n"
//" - https://sslretail.com/blog/dns-over-https-ultimate-guide/\n"
"\n"
,VERSION);
exit(EXIT_FAILURE);
}
/* Prints an error message and exit */
void error(const char *msg) {
fprintf(stderr," *** %s: %s\n", msg, strerror(errno));
exit(EXIT_FAILURE);
}
/* Prints debug messages */
void debug_msg(const char* fmt, ...) {
va_list ap;
if (DEBUG) {
fprintf(stdout, " [%d]> ", getpid());
va_start(ap, fmt);
vfprintf(stdout, fmt, ap);
va_end(ap);
}
}
int generic_print(const void *ptr, size_t n) {
printf("%x\n", ptr);
}
/* SHUFFLES OPPORTUNE MSB/LSB AGAINST NETWORK BYTE ORDER */
void *be32(void *ptr, unsigned long int n) {
unsigned char *bp = ptr;
bp[3] = n & 0xff;
bp[2] = n >> 8 & 0xff;
bp[1] = n >> 16 & 0xff;
bp[0] = n >> 24 & 0xff;
/*
bp[7] = n & 0xff;
bp[6] = n >> 8 & 0xff;
bp[5] = n >> 16 & 0xff;
bp[4] = n >> 24 & 0xff;
bp[3] = n >> 32 & 0xff;
bp[2] = n >> 40 & 0xff;
bp[1] = n >> 48 & 0xff;
bp[0] = n >> 56 & 0xff;
*/
return ptr;
}
/* Return the length of the pointed buffer */
size_t memlen(const char *buff) {
size_t len = 0;
while (1) {
if (buff[len] == 0) break;
len ++;
}
return len;
}
void append(char* s, char c) {
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
/* Parses the dns request and returns the pointer to dns_request struct. Returns NULL on errors */
struct dns_request *parse_dns_request(const char *wire_request, size_t request_len, int proton, int reset) {
//parsing incoming query
struct dns_request *dns_req;
if (reset == 1) {
//wire_request += 0; // 20221225
return NULL;
}
/* proto TCP, first 2 octets represent the UDP wire-format size */
if (proton == 1) {
dns_req = malloc(sizeof(struct dns_request)+2);
if (EXT_DEBUG) {
printf(" *** TCP .. sizeof(wire_request) : (%08x) // (%d)\n", (uint8_t) sizeof(wire_request),sizeof(wire_request));
printf(" *** TCP .. strlen(wire_request) : (%08x) // (%d)\n", (uint8_t) strlen(wire_request),strlen(wire_request));
printf(" *** TCP .. dns_req->tcp_size : (%08x) // (%d)\n", (uint8_t) dns_req->tcp_size,dns_req->tcp_size);
}
dns_req->tcp_size = (uint8_t)wire_request[1] + (uint16_t)(wire_request[0] << 8);
wire_request+=2;
} else {
dns_req = malloc(sizeof(struct dns_request));
if (EXT_DEBUG) {
printf(" *** UDP .. sizeof(wire_request) : (%08x) // (%d)\n", (uint8_t) sizeof(wire_request),sizeof(wire_request));
printf(" *** UDP .. strlen(wire_request) : (%08x) // (%d)\n", (uint8_t) strlen(wire_request),strlen(wire_request));
printf(" *** UDP .. dns_req->udp_size : (%08x) // (%d)\n", (uint8_t) dns_req->tcp_size,dns_req->tcp_size);
}
}
/* See: http://www.tcpipguide.com/free/t_DNSMessageHeaderandQuestionSectionFormat.htm */
/* query TX-ID */
dns_req->transaction_id = (uint8_t)wire_request[1] + (uint16_t)(wire_request[0] << 8);
wire_request+=2;
/* Flags (QR+OPCODE) */
/* QR (1) 0 for q, 1 for r */
/* OPCODE (4) 0-5. 0 for our purpose */
/* AA (1) */
/* TC (1) */
/* RD (1) */
/* RA (1) */
/* Z (1) */
/* RCODE (4) */
dns_req->flags = (uint8_t)wire_request[1] + (uint16_t)(wire_request[0] << 8);
wire_request+=2;
/* number of questions */
dns_req->questions_num = (uint8_t)wire_request[1] + (uint16_t)(wire_request[0] << 8);
wire_request+=2;
/* WHERE IS EDNS ? at the end of DNS query, 6 to 11 bytes */
/* Skipping 6 not interesting bytes because we provide "shortened answers" - one of the initial purposes of DNSProxy */
/*
uint16_t Answers number
uint16_t Records number
uint16_t Additionals records number
*/
/* Skip reading answers, authority, additional */
wire_request+=6;
//int c, r;
//b64ue_t s;
//base64url_encode_reset(&s);
bzero(dns_req->query, sizeof(dns_req->query));
memcpy(dns_req->query, wire_request, sizeof(dns_req->query)-1); // 20230701 - TODO REVIEW
bzero(dns_req->hostname, sizeof(dns_req->hostname));
//memcpy(dns_req->hostname, wire_request, sizeof(dns_req->hostname)-1);
dns_req->hostname_len = 0;
// begin restamping packet and building response
int dots = 0;
int total = 0;
while (1) {
/* Length of the next label */
uint8_t len = wire_request[0];
if (len == 0) {
//str[k] = dns_req->query[k];
//str[0] = '\n';
wire_request++;
break;
}
wire_request++;
if (dns_req->hostname_len + len >= sizeof(dns_req->hostname)) {
fprintf(stderr, "\n *** size issue ! maybe due to TCP request ?\n");
//free(dns_req);
return NULL;
}
strncat(dns_req->hostname, wire_request, len); /* Append the current label to dns_req->hostname */
strncat(dns_req->hostname, ".", 1); /* Append a dot '.' */
dns_req->hostname_len+=len+1;
dots++; // increase dots by 1
wire_request+=len;
}
/* query type */
dns_req->qtype = (uint8_t)wire_request[1] + (uint16_t)(wire_request[0] << 8);
wire_request+=2;
/* query class */
dns_req->qclass = (uint8_t)wire_request[1] + (uint16_t)(wire_request[0] << 8);
wire_request+=2;
// 20230107 - based on minimal DNS overhead = 16~17 bytes
// composed of: 12 (2 qid 2 flags 2 qnum 2 anum 2 rnum 2 addnum) + 4 (2 type 2 class)
char str[strlen(dns_req->hostname)+16];
bzero(str, sizeof(str));
//str == NULL;
// TXID: generated by the client, as per RFC-1035
// TXID: 0000 as per CloudFlare implementation
// TXID: ABCD as per RFC-8484 and Google DNS
str[0] = (uint8_t)(dns_req->transaction_id >> 8);
str[1] = (uint8_t)dns_req->transaction_id;
//str[0] = 0x00;
//str[1] = 0x00;
//str[0] = 0xAB;
//str[1] = 0xCD;
// flags: QR (1) OPCODE (4) AA (1) TC (1) RD (1) RA (1) Z (3) RCODE (4)
// flags in a 0x0120 request:
// - 0 -> 0 query, 1 response
// - 0 -> opcode ( 0 query, 1 iquery, 2 status, 3 reserved, 4 notify, 5 update )
// - 0 -> opcode
// - 0 -> opcode
// - 0 -> opcode
// - 0 -> AA flag set to 0 in request
// - 0 -> not truncated
// - 1 -> recursion desired
//
// - 0 -> recursion available (empty in request)
// - 0 -> Z: 0 reserved
// - 1 -> AD flag: 0 no auth, 1 authenticated data (see cookie section)
// - 0 -> unauthenticated data: 0 unacceptable, 1 acceptable
// - 0 -> empty in request
// - 0 -> empty in request
// - 0 -> empty in request
// - 0 -> empty in request
//str[2] = 0x01;
//str[3] = 0x00; // cloudflare uses AD 0x20
str[2] = (uint8_t)(dns_req->flags >> 8);
str[3] = (uint8_t)dns_req->flags;
// count questions
str[4] = (uint8_t)(dns_req->questions_num >> 8);
str[5] = (uint8_t)dns_req->questions_num;
// answer RR // override
str[6] = 0x00;
str[7] = 0x00;
// authority RR // override
str[8] = 0x00;
str[9] = 0x00;
// additional RR // override
// (0x0001 if you want to use DNSSEC, EDNS, cookies)
str[10] = 0x00;
str[11] = 0x00;
// first block of fixed 12 bytes overhead
//*str+=12;
// 20230107 - WARNING - dots represents the subdomain-separators' "." count
fprintf(stderr," --- PRB dots : %d\n", dots);
//for (int k=0;k < (dns_req->hostname_len+dots+1); k++) // 20230107
//for (int k=0;k < (strlen(dns_req->query)+dots+2); k++) // 20230107
for (int k=0;k < (strlen(dns_req->query)+strlen(dns_req->hostname)-dots-2*dots); k++) {
//append(str[k+12], dns_req->query[k]);
str[k+12] = dns_req->query[k];
//*str++ = dns_req->query[k];
//termination of query record field // 20230107 - WARNING
if (k%2 == 0) { total=k+13; } else { total=k+12; } // 20230107
//total=k+12;
//*str+= 0x00;
fprintf(stderr," --- PRB k\%2 == 0 k : %d\n", k);
}
fprintf(stderr," --- PRB total: %d\n", total);
fprintf(stderr," --- PRB ocalc: %d\n", strlen(dns_req->query)+dots+2);
fprintf(stderr," --- PRB ncalc: %d\n", strlen(dns_req->query)+strlen(dns_req->hostname)-2*dots-dots);
//*str+=0x01;
//str[total+1]++;
//str[total+1]= 0x0001;
// add default flags to each query object
// type A 0001
//str[total+1] = 0x00; // type A
//str[total+2] = 0x01; // type A
// class IN 0001
//str[total+3] = 0x00; // class IN
//str[total+4] = 0x01; // class IN
str[total+1] = (uint8_t)(dns_req->qtype >> 8);
str[total+2] = (uint8_t)dns_req->qtype;
str[total+3] = (uint8_t)(dns_req->qclass >> 8);
str[total+4] = (uint8_t)dns_req->qclass;
if (DNSDUMP) {
printf(" --- dns_req->query : %s\n",b64_encode(dns_req->query,strlen(dns_req->query)));
hexdump(dns_req->query,strlen(dns_req->query));
printf(" --- dns_req->hostname : %s\n",b64_encode(dns_req->hostname,strlen(dns_req->hostname)));
hexdump(dns_req->hostname,strlen(dns_req->hostname));
printf(" --- dns_req->hostname_len : %d\n",dns_req->hostname_len);
hexdump(str,sizeof(str)+1);
}
/*
for (int f=0;f<sizeof(wire_request);f++) {
r = base64url_encode_ingest(&s, wire_request[f]);
if (r < 0) return -1;
if (r > 0) printf("%c", base64url_encode_getc(&s));
}
for (;;) { r = base64url_encode_finish(&s); if (r < 0) return -1; if (r == 0) break; printf("%c", base64url_encode_getc(&s)); }
*/
/*
//int ok = base64url_encode(test64,(((4 * sizeof(str) / 3) + 3) & ~3),str,sizeof(str),NULL);
for (int f=0;f<sizeof(dns_req->hostname-1);f++) {
//for (int f=0;f != '\0';f++)
//while (EOF != (c = getchar()))
//while (dns_req->query != '\0' || dns_req->query != NULL)
//r = base64url_encode_ingest(&s, c);
//r = base64url_encode_ingest(&s, dns_req->query[f]);
r = base64url_encode_ingest(&s, dns_req->hostname);
if (r < 0) return -1;
if (r > 0) printf("%c", base64url_encode_getc(&s));
}
for (;;) {
r = base64url_encode_finish(&s); if (r < 0) return -1; if (r == 0) break; printf("%c", base64url_encode_getc(&s));
}
*/
/* Encode query string in base64url */
bzero(dns_req->rfcstring, sizeof(dns_req->rfcstring));
//bzero(dns_req->rfcstring, sizeof(str)+1);
//memcpy(dns_req->rfcstring, str, sizeof(dns_req->hostname)+16);
//char *tttt;
//tttt = b64_encode(dns_req->rfcstring,sizeof(str)+1);
//remchar(tttt, '=');
//dns_req->rfcstring = tttt;
for (int q=0;q <= sizeof(str); q++) {
//remchar(str[q], '=');
dns_req->rfcstring[q] = str[q];
//dns_req->rfcstring[q] = tttt[q];
}
//if (DEBUG) {
// printf("str : %s\n",b64_encode(str,sizeof(str)+1));
// printf("dnsreqrfcstring : %s\n",b64_encode(dns_req->rfcstring,sizeof(str)+1));
// printf("dnsreqrfcstring : %x\n",dns_req->rfcstring);
// //printf("dnsreqrfcstring : %s\n",dns_req->rfcstring);
// //printf("dnsreqrfcstring : %s\n",tttt);
//}
if (DNSDUMP) {
printf(" *** dns_req->rfcstring\n");
hexdump(dns_req->rfcstring,sizeof(str)+1);
//printf(" *** dns_req->rfcstring\n");
//hexdump(dns_req->rfcstring,sizeof(dns_req->rfcstring));
//printf(" *** DNS RAW packet:\n");
//hexdump(dns_req->rfcstring,sizeof(dns_req->rfcstring)+strlen(dns_req->rfcstring)+9); // 20221225
}
//free(str); // 20230107
return dns_req;
}
/* Build and return DNS datagram in compatibility with RFC-8484's format */
void build_dns(int sd, struct sockaddr_in *yclient, struct dns_request *dns_req, const char *ip, int mode, size_t xrequestlen, long int ttl, int xproto, int xtcpoff) {
//char *rip = malloc(4096 * sizeof(char));
int i,ppch, check = 0, sockfd, xsockfd;
char *response, *finalresponse, *qhostname, *token, *pch, *maxim, *rr, *tt, *response_ptr, *finalresponse_ptr;
ssize_t bytes_sent, bytes_sent_tcp, bytes_sent_udp, bytes_encoded;
if (DEBUG) {
printf("\n");
printf("-> BUILD-xrequestlen : %d\n", (uint32_t)(xrequestlen));
printf("-> BUILD-ttl : %d\n", (uint32_t)(ttl));
printf("-> BUILD-xtcpoff : %d\n", (uint32_t)(xtcpoff));
//printf("-> BUILD-Xsockfd : %u\n", xsockfd); // 20221225
//printf("-> BUILD- sockfd : %d\n", sockfd); // 20221225
printf("-> BUILD-proto : %d\n", xproto);
}
response = malloc(UDP_DATAGRAM_SIZE);
bzero(response, UDP_DATAGRAM_SIZE);
finalresponse = malloc(TCP_DATAGRAM_SIZE);
bzero(finalresponse, TCP_DATAGRAM_SIZE);
maxim = malloc (DNSREWRITE);
bzero(maxim, DNSREWRITE);
response_ptr = response;
finalresponse_ptr = finalresponse;
/* DNS header added to TCP replies: 2-bytes lenght of the corresponding UDP/DNS usual wireformat. limit 64K */
if (xproto == 1) {
int norm = (dns_req->tcp_size);
response[0] = (uint8_t)(norm >> 8);
response[1] = (uint8_t)norm;
response+=2;
//if (DNSDUMP) {
// printf(" *** TCP HEADER ON DNS WIRE PACKET: read tcp_size : %d\n",(uint8_t)(dns_req->tcp_size));
// printf(" *** TCP HEADER ON DNS WIRE PACKET: read dns_req : %d\n",(uint8_t)(sizeof(dns_req) - 2));
//}
}
// TX ID as set by client
response[0] = (uint8_t)(dns_req->transaction_id >> 8);
response[1] = (uint8_t)dns_req->transaction_id;
// CLOUDFLARE //response[0] = 0x00; //response[1] = 0x00;
// RFC/GOOGLE //response[0] = 0xAB; //response[1] = 0xCD;
//response+=2;
int kkk = 0;
//for (int x=2;x<get_size()+2;x++) {
for (int x=2;x<get_size();x++) {
//*response++ = ip[x];
response[x] = ip[x];
kkk++;
}
response+=kkk+2;
if (mode == DNS_MODE_ANSWER) {
int yclient_len = sizeof(yclient);
yclient->sin_family = AF_INET;
yclient->sin_port = yclient->sin_port;
memset(&(yclient->sin_zero), 0, sizeof(yclient->sin_zero));
/* TCP packet-length DNS header re-stamping */
if (xproto == 1) {
int resulttt = NULL;
int norm2 = (response - response_ptr - xtcpoff); // account for 2 extra tcp bytes
check = 1;
if (DNSDUMP) { printf(" *** OFFSET from norm2 -> %d\n",norm2); }
finalresponse[0] = (uint8_t)(norm2 >> 8);
finalresponse[1] = (uint8_t)norm2;
// start off 3rd byte and leave the overwritten tcp_size value intact
for (int i=2; i < (response - response_ptr); i++) {
resulttt <<= 8;
resulttt |= response_ptr[i];
finalresponse_ptr[i]+= resulttt;
}
finalresponse+=(response-response_ptr);
// dump to TCP wireformat
if (DNSDUMP) {
printf(" *** TCP SENT %d bytes of finalresponse\n", finalresponse - finalresponse_ptr);
printf(" *** DUMP of (finalresponse_ptr, LENGTH response - response_ptr)\n");
hexdump(finalresponse_ptr, response - response_ptr);
printf(" *** TCP SENT %d bytes of finalresponse (including +2 for TCP)\n", finalresponse - finalresponse_ptr);
printf(" *** DUMP of (finalresponse_ptr, LENGTH finalresponse - finalresponse_ptr)\n");
hexdump(finalresponse_ptr, finalresponse - finalresponse_ptr);
}
} else {
// dump to UDP wireformat
if (DNSDUMP) {
//printf(" *** UDP SENT %d bytes of finalresponse\n", finalresponse - finalresponse_ptr);
//printf(" *** DUMP of (finalresponse_ptr, LENGTH response - response_ptr)\n");
//hexdump(finalresponse_ptr, response - response_ptr);
printf(" *** UDP SENT %d bytes of response\n", response - response_ptr);
printf(" *** DUMP of (response_ptr, LENGTH response - response_ptr)\n");
hexdump(response_ptr, response - response_ptr);
}
}
// send data back onto original socket
if (check != 1) {
// UDP sendto
bytes_sent_udp = sendto(sd, (const char*)response_ptr, response - response_ptr, 0, (struct sockaddr *)yclient, 16);
wait(bytes_sent_udp);
close(sd);
free(response_ptr);
check = 0;
} else if (xproto == 1) {
// TCP sendto
check = 0;
bytes_sent_tcp = sendto(sd, finalresponse_ptr, finalresponse - finalresponse_ptr, MSG_DONTWAIT, (struct sockaddr *)yclient, 16);