-
-
Notifications
You must be signed in to change notification settings - Fork 185
/
dnsmasq_interface.c
2697 lines (2361 loc) · 78.8 KB
/
dnsmasq_interface.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
/* Pi-hole: A black hole for Internet advertisements
* (c) 2017 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
*
* FTL Engine
* dnsmasq interfacing routines
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
#define FTLDNS
#include "dnsmasq/dnsmasq.h"
#undef __USE_XOPEN
#include "FTL.h"
#include "enums.h"
#include "dnsmasq_interface.h"
#include "shmem.h"
#include "overTime.h"
#include "database/common.h"
#include "database/database-thread.h"
#include "datastructure.h"
#include "database/gravity-db.h"
#include "setupVars.h"
#include "daemon.h"
#include "timers.h"
#include "gc.h"
#include "api/socket.h"
#include "regex_r.h"
#include "config.h"
#include "capabilities.h"
#include "resolve.h"
#include "files.h"
#include "log.h"
// Prototype of getCacheInformation()
#include "api/api.h"
// global variable daemonmode
#include "args.h"
// handle_realtime_signals()
#include "signals.h"
// atomic_flag_test_and_set()
#include <stdatomic.h>
// Eventqueue routines
#include "events.h"
#include <netinet/in.h>
// offsetof()
#include <stddef.h>
// get_edestr()
#include "api/api_helper.h"
// Private prototypes
static void print_flags(const unsigned int flags);
#define query_set_reply(flags, addr, query, response) _query_set_reply(flags, addr, query, response, __FILE__, __LINE__)
static void _query_set_reply(const unsigned int flags, const union all_addr *addr, queriesData* query, const struct timeval response,
const char *file, const int line);
#define FTL_check_blocking(queryID, domainID, clientID) _FTL_check_blocking(queryID, domainID, clientID, __FILE__, __LINE__)
static bool _FTL_check_blocking(int queryID, int domainID, int clientID, const char* file, const int line);
static unsigned long converttimeval(const struct timeval time) __attribute__((const));
static enum query_status detect_blocked_IP(const unsigned short flags, const union all_addr *addr, const queriesData *query, const domainsData *domain);
static void query_blocked(queriesData* query, domainsData* domain, clientsData* client, const unsigned char new_status);
static void FTL_forwarded(const unsigned int flags, const char *name, const union all_addr *addr, const int id, const char* file, const int line);
static void FTL_reply(const unsigned int flags, const char *name, const union all_addr *addr, const char* arg, const int id, const char* file, const int line);
static void FTL_upstream_error(const union all_addr *addr, const int id, const char* file, const int line);
static void FTL_dnssec(const char *result, const union all_addr *addr, const int id, const char* file, const int line);
static void mysockaddr_extract_ip_port(union mysockaddr *server, char ip[ADDRSTRLEN+1], in_port_t *port);
static void alladdr_extract_ip(union all_addr *addr, const sa_family_t family, char ip[ADDRSTRLEN+1]);
static const char *dns_name(char *name);
// Static blocking metadata
static const char *blockingreason = NULL;
static union all_addr null_addrp = {{ 0 }};
static enum reply_type force_next_DNS_reply = REPLY_UNKNOWN;
// Fork-private copy of the interface name the most recent query came from
static struct {
char name[IFNAMSIZ];
union all_addr addr4;
union all_addr addr6;
} next_iface = {"", {{0}}, {{0}}};
// Fork-private copy of the server data the most recent reply came from
static union mysockaddr last_server = {{ 0 }};
unsigned char* pihole_privacylevel = &config.privacylevel;
const char flagnames[][12] = {"F_IMMORTAL ", "F_NAMEP ", "F_REVERSE ", "F_FORWARD ", "F_DHCP ", "F_NEG ", "F_HOSTS ", "F_IPV4 ", "F_IPV6 ", "F_BIGNAME ", "F_NXDOMAIN ", "F_CNAME ", "F_DNSKEY ", "F_CONFIG ", "F_DS ", "F_DNSSECOK ", "F_UPSTREAM ", "F_RRNAME ", "F_SERVER ", "F_QUERY ", "F_NOERR ", "F_AUTH ", "F_DNSSEC ", "F_KEYTAG ", "F_SECSTAT ", "F_NO_RR ", "F_IPSET ", "F_NOEXTRA ", "F_SERVFAIL", "F_RCODE"};
void FTL_hook(unsigned int flags, char *name, union all_addr *addr, char *arg, int id, const char* file, const int line)
{
// Extract filename from path
const char *path = short_path(file);
if(config.debug & DEBUG_FLAGS)
{
logg("Processing FTL hook from %s:%d...", path, line);
print_flags(flags);
}
// Note: The order matters here!
if(strcmp(path, "src/dnsmasq_interface.c") == 0)
; // Ignored - loopback from FTL_make_answer() below
else if((flags & F_QUERY) && (flags & F_FORWARD))
; // New query, handled by FTL_new_query via separate call
else if(flags & F_FORWARD && flags & F_SERVER)
// forwarded upstream
FTL_forwarded(flags, name, addr, id, path, line);
else if(flags == F_SECSTAT)
// DNSSEC validation result
FTL_dnssec(arg, addr, id, path, line);
else if(flags == (F_UPSTREAM | F_RCODE) && name && strcasecmp(name, "error") == 0)
// upstream sent something different than NOERROR or NXDOMAIN
FTL_upstream_error(addr, id, path, line);
else if(flags & F_NOEXTRA && flags & F_DNSSEC)
{
// This is a new DNSSEC query (dnssec-query[DS])
if(!config.show_dnssec)
return;
const int qtype = strcmp(arg, "dnssec-query[DS]") == 0 ? T_DS : T_DNSKEY;
const ednsData edns = { 0 };
union mysockaddr saddr = {{ 0 }};
if(flags & F_IPV4)
{
saddr.in.sin_addr = addr->addr4;
saddr.sa.sa_family = AF_INET;
}
else
{
memcpy(&saddr.in6.sin6_addr, &addr->addr6, sizeof(addr->addr6));
saddr.sa.sa_family = AF_INET;
}
_FTL_new_query(flags, name, NULL, arg, qtype, id, &edns, INTERNAL, file, line);
FTL_forwarded(flags, name, addr, id, path, line);
}
else if(flags & F_AUTH)
; // Ignored
else if(flags & F_IPSET)
; // Ignored
else
FTL_reply(flags, name, addr, arg, id, path, line);
}
// This is inspired by make_local_answer()
size_t _FTL_make_answer(struct dns_header *header, char *limit, const size_t len, int *ede, const char *file, const int line)
{
// Exit early if there are no questions in this query
if(ntohs(header->qdcount) == 0)
return 0;
// Get question name
char name[MAXDNAME] = { 0 };
unsigned char *p = (unsigned char *)(header+1);
if (!extract_name(header, len, &p, name, 1, 4))
return 0;
// Debug logging
if(config.debug & DEBUG_FLAGS)
{
if(*ede != -1)
logg("Preparing reply for \"%s\", EDE: %s (%d)", dns_name(name), edestr(*ede), *ede);
else
logg("Preparing reply for \"%s\", EDE: N/A", dns_name(name));
}
// Get question type
int qtype, flags;
GETSHORT(qtype, p);
// Set flag based on what we will reply with
if(qtype == T_A)
flags = F_IPV4; // A type
else if(qtype == T_AAAA)
flags = F_IPV6; // AAAA type
else if(qtype == T_ANY)
flags = F_IPV4 | F_IPV6; // ANY type
else
flags = F_NOERR; // empty record
// Prepare answer records
bool forced_ip = false;
// Check first if we need to force our reply to something different than the
// default/configured blocking mode. For instance, we need to force NXDOMAIN
// for intercepted _esni.* queries.
if(force_next_DNS_reply == REPLY_NXDOMAIN)
{
flags = F_NXDOMAIN;
// Reset DNS reply forcing
force_next_DNS_reply = REPLY_UNKNOWN;
// Debug logging
if(config.debug & DEBUG_FLAGS)
logg("Forced DNS reply to NXDOMAIN");
}
else if(force_next_DNS_reply == REPLY_REFUSED)
{
// Empty flags result in REFUSED
flags = 0;
// Reset DNS reply forcing
force_next_DNS_reply = REPLY_UNKNOWN;
// Debug logging
if(config.debug & DEBUG_FLAGS)
logg("Forced DNS reply to REFUSED");
// Set EDE code to blocked
*ede = EDE_BLOCKED;
}
else if(force_next_DNS_reply == REPLY_IP)
{
// We do not need to change the flags here,
// they are already properly set (F_IPV4 and/or F_IPV6)
forced_ip = true;
// Reset DNS reply forcing
force_next_DNS_reply = REPLY_UNKNOWN;
// Debug logging
if(config.debug & DEBUG_FLAGS)
logg("Forced DNS reply to IP");
}
else
{
// Overwrite flags only if not replying with a forced reply
if(config.blockingmode == MODE_NX)
{
// If we block in NXDOMAIN mode, we add the NEGATIVE response
// and the NXDOMAIN flags
flags = F_NXDOMAIN;
if(config.debug & DEBUG_FLAGS)
logg("Configured blocking mode is NXDOMAIN");
}
else if(config.blockingmode == MODE_NODATA ||
(config.blockingmode == MODE_IP_NODATA_AAAA && (flags & F_IPV6)))
{
// If we block in NODATA mode or NODATA for AAAA queries, we apply
// the NOERROR response flag. This ensures we're sending an empty response
flags = F_NOERR;
if(config.debug & DEBUG_FLAGS)
logg("Configured blocking mode is NODATA%s",
config.blockingmode == MODE_IP_NODATA_AAAA ? "-IPv6" : "");
}
}
// Debug logging
if(config.debug & DEBUG_FLAGS)
print_flags(flags);
// Setup reply header
setup_reply(header, flags, *ede);
// Add flags according to current blocking mode
// Set blocking_flags to F_HOSTS so dnsmasq logs blocked queries being answered from a specific source
// (it would otherwise assume it knew the blocking status from cache which would prevent us from
// printing the blocking source (blacklist, regex, gravity) in dnsmasq's log file, our pihole.log)
flags |= F_HOSTS;
// Skip questions so we can start adding answers (if applicable)
if (!(p = skip_questions(header, len)))
return 0;
int trunc = 0;
// Add A answer record if requested
if(flags & F_IPV4)
{
union all_addr *addr;
if(config.blockingmode == MODE_IP ||
config.blockingmode == MODE_IP_NODATA_AAAA ||
forced_ip)
addr = &next_iface.addr4;
else
addr = &null_addrp;
// Debug logging
if(config.debug & DEBUG_QUERIES)
{
char ip[ADDRSTRLEN+1] = { 0 };
alladdr_extract_ip(addr, AF_INET, ip);
logg(" Adding RR: \"%s A %s\"", dns_name(name), ip);
}
// Add A resource record
header->ancount = htons(ntohs(header->ancount) + 1);
add_resource_record(header, limit, &trunc, sizeof(struct dns_header),
&p, daemon->local_ttl, NULL, T_A, C_IN,
(char*)"4", &addr->addr4);
log_query(flags & ~F_IPV6, name, addr, (char*)blockingreason);
}
// Add AAAA answer record if requested
if(flags & F_IPV6)
{
union all_addr *addr;
if(config.blockingmode == MODE_IP ||
forced_ip)
addr = &next_iface.addr6;
else
addr = &null_addrp;
// Debug logging
if(config.debug & DEBUG_QUERIES)
{
char ip[ADDRSTRLEN+1] = { 0 };
alladdr_extract_ip(addr, AF_INET6, ip);
logg(" Adding RR: \"%s AAAA %s\"", dns_name(name), ip);
}
// Add AAAA resource record
header->ancount = htons(ntohs(header->ancount) + 1);
add_resource_record(header, limit, &trunc, sizeof(struct dns_header),
&p, daemon->local_ttl, NULL, T_AAAA, C_IN,
(char*)"6", &addr->addr6);
log_query(flags & ~F_IPV4, name, addr, (char*)blockingreason);
}
// Indicate if truncated (client should retry over TCP)
if (trunc)
header->hb3 |= HB3_TC;
return p - (unsigned char *)header;
}
bool _FTL_new_query(const unsigned int flags, const char *name,
union mysockaddr *addr, const char *types,
const unsigned short qtype, const int id,
const ednsData *edns, const enum protocol proto,
const char* file, const int line)
{
// Create new query in data structure
// Get timestamp
const time_t querytimestamp = time(NULL);
// Save request time
struct timeval request;
gettimeofday(&request, 0);
// Determine query type
enum query_types querytype;
switch(qtype)
{
case T_A:
querytype = TYPE_A;
break;
case T_AAAA:
querytype = TYPE_AAAA;
break;
case T_ANY:
querytype = TYPE_ANY;
break;
case T_SRV:
querytype = TYPE_SRV;
break;
case T_SOA:
querytype = TYPE_SOA;
break;
case T_PTR:
querytype = TYPE_PTR;
break;
case T_TXT:
querytype = TYPE_TXT;
break;
case T_NAPTR:
querytype = TYPE_NAPTR;
break;
case T_MX:
querytype = TYPE_MX;
break;
case T_DS:
querytype = TYPE_DS;
break;
case T_RRSIG:
querytype = TYPE_RRSIG;
break;
case T_DNSKEY:
querytype = TYPE_DNSKEY;
break;
case T_NS:
querytype = TYPE_NS;
break;
case 64: // Scn. 2 of https://datatracker.ietf.org/doc/draft-ietf-dnsop-svcb-https/
querytype = TYPE_SVCB;
break;
case 65: // Scn. 2 of https://datatracker.ietf.org/doc/draft-ietf-dnsop-svcb-https/
querytype = TYPE_HTTPS;
break;
default:
querytype = TYPE_OTHER;
break;
}
// If domain is "pi.hole" or the local hostname we skip analyzing this query
// and, instead, immediately reply with the IP address - these queries are not further analyzed
if(strcasecmp(name, "pi.hole") == 0 || strcasecmp(name, hostname()) == 0)
{
if(querytype == TYPE_A || querytype == TYPE_AAAA || querytype == TYPE_ANY)
{
// "Block" this query by sending the interface IP address
force_next_DNS_reply = REPLY_IP;
blockingreason = "internal";
if(config.debug & DEBUG_QUERIES)
logg("Replying to %s with interface-local IP address", name);
return true;
}
else
{
// Don't block this query
return false;
}
}
// Skip AAAA queries if user doesn't want to have them analyzed
if(!config.analyze_AAAA && querytype == TYPE_AAAA)
{
if(config.debug & DEBUG_QUERIES)
logg("Not analyzing AAAA query");
return false;
}
// Convert domain to lower case
char *domainString = strdup(name);
strtolower(domainString);
// Get client IP address
// The requestor's IP address can be rewritten using EDNS(0) client
// subnet (ECS) data), however, we do not rewrite the IPs ::1 and
// 127.0.0.1 to avoid queries originating from localhost of the
// *distant* machine as queries coming from the *local* machine
const sa_family_t family = addr ? addr->sa.sa_family : AF_INET;
in_port_t clientPort = daemon->port;
bool internal_query = false;
char clientIP[ADDRSTRLEN+1] = { 0 };
if(config.edns0_ecs && edns && edns->client_set)
{
// Use ECS provided client
strncpy(clientIP, edns->client, ADDRSTRLEN);
clientIP[ADDRSTRLEN] = '\0';
}
else if(addr)
{
// Use original requestor
mysockaddr_extract_ip_port(addr, clientIP, &clientPort);
}
else
{
// No client address available, this is an automatically generated (e.g.
// DNSSEC) query
internal_query = true;
strcpy(clientIP, "::");
}
// Check if user wants to skip queries coming from localhost
if(config.ignore_localhost &&
(strcmp(clientIP, "127.0.0.1") == 0 || strcmp(clientIP, "::1") == 0))
{
free(domainString);
return false;
}
// Lock shared memory
lock_shm();
const int queryID = counters->queries;
// Find client IP
const int clientID = findClientID(clientIP, true, false);
// Get client pointer
clientsData* client = getClient(clientID, true);
if(client == NULL)
{
// Encountered memory error, skip query
// Free allocated memory
free(domainString);
// Release thread lock
unlock_shm();
return false;
}
// Interface name is only available for regular queries, not for
// automatically generated DNSSEC queries
const char *interface = internal_query ? "-" : next_iface.name;
// Check rate-limit for this client
if(!internal_query && config.rate_limit.count > 0 &&
++client->rate_limit > config.rate_limit.count)
{
if(config.debug & DEBUG_QUERIES)
{
logg("Rate-limiting %sIPv%d %s query \"%s\" from %s:%s#%d",
proto == TCP ? "TCP " : proto == UDP ? "UDP " : "",
family == AF_INET ? 4 : 6, types, domainString, interface,
clientIP, clientPort);
}
// Block this query
force_next_DNS_reply = REPLY_REFUSED;
// Do not further process this query, Pi-hole has never seen it
unlock_shm();
return true;
}
// Log new query if in debug mode
if(config.debug & DEBUG_QUERIES)
{
logg("**** new %sIPv%d %s query \"%s\" from %s:%s#%d (ID %i, FTL %i, %s:%i)",
proto == TCP ? "TCP " : proto == UDP ? "UDP " : "",
family == AF_INET ? 4 : 6, types, domainString, interface,
internal_query ? "<internal>" : clientIP, clientPort,
id, queryID, short_path(file), line);
}
// Update counters
counters->querytype[querytype-1]++;
// Update overTime
const unsigned int timeidx = getOverTimeID(querytimestamp);
// Skip rest of the analysis if this query is not of type A or AAAA
// but user wants to see only A and AAAA queries (pre-v4.1 behavior)
if(config.analyze_only_A_AAAA && querytype != TYPE_A && querytype != TYPE_AAAA)
{
// Don't process this query further here, we already counted it
if(config.debug & DEBUG_QUERIES) logg("Notice: Skipping new query: %s (%i)", types, id);
free(domainString);
unlock_shm();
return false;
}
// Go through already knows domains and see if it is one of them
const int domainID = findDomainID(domainString, true);
// Save everything
queriesData* query = getQuery(queryID, false);
if(query == NULL)
{
// Encountered memory error, skip query
logg("WARN: No memory available, skipping query analysis");
// Free allocated memory
free(domainString);
// Release thread lock
unlock_shm();
return false;
}
// Fill query object with available data
query->magic = MAGICBYTE;
query->timestamp = querytimestamp;
query->type = querytype;
query->qtype = qtype;
query->id = id; // Has to be set before calling query_set_status()
// This query is unknown as long as no reply has been found and analyzed
counters->status[QUERY_UNKNOWN]++;
query_set_status(query, QUERY_UNKNOWN);
query->domainID = domainID;
query->clientID = clientID;
// Initialize database field, will be set when the query is stored in the long-term DB
query->flags.database = false;
query->flags.complete = false;
query->response = converttimeval(request);
// Initialize reply type
query->reply = REPLY_UNKNOWN;
// Store DNSSEC result for this domain
query->dnssec = DNSSEC_UNSPECIFIED;
query->CNAME_domainID = -1;
// This query is not yet known ad forwarded or blocked
query->flags.blocked = false;
query->flags.whitelisted = false;
// Indicator that this query was not forwarded so far
query->upstreamID = -1;
// Check and apply possible privacy level rules
// The currently set privacy level (at the time the query is
// generated) is stored in the queries structure
query->privacylevel = config.privacylevel;
// Query extended DNS error
query->ede = -1;
// Increase DNS queries counter
counters->queries++;
// Update overTime data
overTime[timeidx].total++;
// Update overTime data structure with the new client
change_clientcount(client, 0, 0, timeidx, 1);
// Set lastQuery timer and add one query for network table
client->lastQuery = querytimestamp;
client->numQueriesARP++;
// Process interface information of client (if available)
// Skip interface name length 1 to skip "-". No real interface should
// have a name with a length of 1...
if(!internal_query && strlen(interface) > 1)
{
if(client->ifacepos == 0u)
{
// Store in the client data if unknown so far
client->ifacepos = addstr(interface);
}
else
{
// Check if this is still the same interface or
// if the client moved to another interface
// (may require group re-processing)
const char *oldiface = getstr(client->ifacepos);
if(strcasecmp(oldiface, interface) != 0)
{
if(config.debug & DEBUG_CLIENTS)
{
const char *clientName = getstr(client->namepos);
logg("Client %s (%s) changed interface: %s -> %s",
clientIP, clientName, oldiface, interface);
}
gravityDB_reload_groups(client);
}
}
}
// Set client MAC address from EDNS(0) information (if available)
if(config.edns0_ecs && edns->mac_set)
{
memcpy(client->hwaddr, edns->mac_byte, 6);
client->hwlen = 6;
}
// Try to obtain MAC address from dnsmasq's cache (also asks the kernel)
if(client->hwlen < 1)
{
client->hwlen = find_mac(addr, client->hwaddr, 1, time(NULL));
if(config.debug & DEBUG_ARP)
{
if(client->hwlen == 6)
logg("find_mac(\"%s\") returned hardware address "
"%02X:%02X:%02X:%02X:%02X:%02X", clientIP,
client->hwaddr[0], client->hwaddr[1], client->hwaddr[2],
client->hwaddr[3], client->hwaddr[4], client->hwaddr[5]);
else
logg("find_mac(\"%s\") returned %i bytes of data",
clientIP, client->hwlen);
}
}
bool blockDomain = false;
// Check if this should be blocked only for active queries
// (skipped for internally generated ones, e.g., DNSSEC)
if(!internal_query)
blockDomain = FTL_check_blocking(queryID, domainID, clientID);
// Free allocated memory
free(domainString);
// Release thread lock
unlock_shm();
return blockDomain;
}
void FTL_iface(const int ifidx, const struct irec *ifaces)
{
// Invalidate data we have from the last interface/query
// Set addresses to 0.0.0.0 and ::, respectively
memset(&next_iface.addr4, 0, sizeof(next_iface.addr4));
memset(&next_iface.addr6, 0, sizeof(next_iface.addr6));
// Copy overwrite addresses if configured via REPLY_ADDR4 and/or REPLY_ADDR6 settings
if(config.reply_addr.overwrite_v4)
{
memcpy(&next_iface.addr4, &config.reply_addr.v4, sizeof(config.reply_addr.v4));
if(config.debug & DEBUG_NETWORKING)
{
char buffer[ADDRSTRLEN+1] = { 0 };
inet_ntop(AF_INET, &next_iface.addr4, buffer, ADDRSTRLEN);
logg("Interface (%d) %s OVERWRITES IPv4 address %s", ifidx, next_iface.name, buffer);
}
}
if(config.reply_addr.overwrite_v6)
{
memcpy(&next_iface.addr6, &config.reply_addr.v6, sizeof(config.reply_addr.v6));
if(config.debug & DEBUG_NETWORKING)
{
char buffer[ADDRSTRLEN+1] = { 0 };
inet_ntop(AF_INET6, &next_iface.addr6, buffer, ADDRSTRLEN);
logg("Interface (%d) %s OVERWRITES IPv6 address %s", ifidx, next_iface.name, buffer);
}
}
// Use dummy when interface record is not available
next_iface.name[0] = '-';
next_iface.name[1] = '\0';
// Return early when there is no interface available at this point
if(ifidx == -1 || ifaces == NULL)
return;
// Determine addresses of this interface
const struct irec *iface;
bool haveIPv4 = false, haveGUAv6 = false, haveULAv6 = false;
for (iface = ifaces; iface != NULL; iface = iface->next)
{
// If this interface has no name, we skip it
if(iface->name == NULL)
continue;
// Check if this is the interface we want
if(iface->index != ifidx)
continue;
// Check if this family type is overwritten by config settings
const sa_family_t family = iface->addr.sa.sa_family;
if((config.reply_addr.overwrite_v4 && family == AF_INET) ||
(config.reply_addr.overwrite_v6 && family == AF_INET6))
continue;
// Copy interface name
strncpy(next_iface.name, iface->name, sizeof(next_iface.name)-1);
next_iface.name[sizeof(next_iface.name)-1] = '\0';
bool isULA = false, isGUA = false, isLL = false;
// Check if this address is different from 0000:0000:0000:0000:0000:0000:0000:0000
if(family == AF_INET6 && memcmp(&next_iface.addr6.addr6, &iface->addr.in6.sin6_addr, sizeof(iface->addr.in6.sin6_addr)) != 0)
{
// Extract first byte
// We do not directly access the underlying union as
// MUSL defines it differently than GNU C
uint8_t bytes[2];
memcpy(&bytes, &iface->addr.in6.sin6_addr, 2);
// Global Unicast Address (2000::/3, RFC 4291)
isGUA = (bytes[0] & 0x70) == 0x20;
// Unique Local Address (fc00::/7, RFC 4193)
isULA = (bytes[0] & 0xfe) == 0xfc;
// Link Local Address (fe80::/10, RFC 4291)
isLL = (bytes[0] & 0xff) == 0xfe && (bytes[1] & 0x30) == 0;
// Store IPv6 address only if we don't already have a GUA or ULA address
// This makes the preference:
// 1. ULA
// 2. GUA
// 3. Link-local
if((!haveGUAv6 && !haveULAv6) || (haveGUAv6 && isULA))
{
memcpy(&next_iface.addr6.addr6, &iface->addr.in6.sin6_addr, sizeof(iface->addr.in6.sin6_addr));
if(isGUA)
haveGUAv6 = true;
else if(isULA)
haveULAv6 = true;
}
}
// Check if this address is different from 0.0.0.0
else if(family == AF_INET && memcmp(&next_iface.addr4.addr4, &iface->addr.in.sin_addr, sizeof(iface->addr.in.sin_addr)) != 0)
{
haveIPv4 = true;
// Store IPv4 address
memcpy(&next_iface.addr4.addr4, &iface->addr.in.sin_addr, sizeof(iface->addr.in.sin_addr));
}
// Debug logging
if(config.debug & DEBUG_NETWORKING)
{
char buffer[ADDRSTRLEN+1] = { 0 };
if(family == AF_INET)
inet_ntop(AF_INET, &iface->addr.in.sin_addr, buffer, ADDRSTRLEN);
else if(family == AF_INET6)
inet_ntop(AF_INET6, &iface->addr.in6.sin6_addr, buffer, ADDRSTRLEN);
const char *type = family == AF_INET6 ? isGUA ? " (GUA)" : isULA ? " (ULA)" : isLL ? " (LL)" : " (other)" : "";
logg("Interface (%d) %s has IPv%i address %s%s", ifidx, next_iface.name,
family == AF_INET ? 4 : 6, buffer, type);
}
// Exit loop early if we already have everything we need
// (a valid IPv4 address + a valid ULA IPv6 address)
if(haveIPv4 && haveULAv6)
break;
}
}
static bool check_domain_blocked(const char *domain, const int clientID,
clientsData *client, queriesData *query, DNSCacheData *dns_cache,
unsigned char *new_status)
{
// Check domains against exact blacklist
// Skipped when the domain is whitelisted
bool blockDomain = false;
if(in_blacklist(domain, client))
{
// We block this domain
blockDomain = true;
*new_status = QUERY_BLACKLIST;
blockingreason = "exactly blacklisted";
// Mark domain as exactly blacklisted for this client
dns_cache->blocking_status = BLACKLIST_BLOCKED;
return true;
}
// Check domains against gravity domains
// Skipped when the domain is whitelisted or blocked by exact blacklist
if(!query->flags.whitelisted && !blockDomain &&
in_gravity(domain, client))
{
// We block this domain
blockDomain = true;
*new_status = QUERY_GRAVITY;
blockingreason = "gravity blocked";
// Mark domain as gravity blocked for this client
dns_cache->blocking_status = GRAVITY_BLOCKED;
return true;
}
// Check domain against blacklist regex filters
// Skipped when the domain is whitelisted or blocked by exact blacklist or gravity
int regex_idx = 0;
if(!query->flags.whitelisted && !blockDomain &&
(regex_idx = match_regex(domain, dns_cache, client->id, REGEX_BLACKLIST, false)) > -1)
{
// We block this domain
blockDomain = true;
*new_status = QUERY_REGEX;
blockingreason = "regex blacklisted";
// Mark domain as regex matched for this client
dns_cache->blocking_status = REGEX_BLOCKED;
dns_cache->black_regex_idx = regex_idx;
return true;
}
// Not blocked
return false;
}
// Special domain checking
static bool special_domain(const queriesData *query, const char *domain)
{
// Mozilla canary domain
// Network administrators may configure their networks as follows to signal
// that their local DNS resolver implemented special features that make the
// network unsuitable for DoH:
// DNS queries for the A and AAAA records for the domain
// “use-application-dns.net” must respond with either: a response code other
// than NOERROR, such as NXDOMAIN (non-existent domain) or SERVFAIL; or
// respond with NOERROR, but return no A or AAAA records.
// https://support.mozilla.org/en-US/kb/configuring-networks-disable-dns-over-https
if(config.special_domains.mozilla_canary &&
strcasecmp(domain, "use-application-dns.net") == 0 &&
(query->type == TYPE_A || query->type == TYPE_AAAA))
{
blockingreason = "Mozilla canary domain";
force_next_DNS_reply = REPLY_NXDOMAIN;
return true;
}
return false;
}
static bool _FTL_check_blocking(int queryID, int domainID, int clientID, const char* file, const int line)
{
// Only check blocking conditions when global blocking is enabled
if(blockingstatus == BLOCKING_DISABLED)
{
return false;
}
// Get query, domain and client pointers
queriesData *query = getQuery(queryID, true);
domainsData *domain = getDomain(domainID, true);
clientsData *client = getClient(clientID, true);
if(query == NULL || domain == NULL || client == NULL)
{
logg("Error: No memory available, skipping query analysis");
return false;
}
// Get cache pointer
unsigned int cacheID = findCacheID(domainID, clientID, query->type);
DNSCacheData *dns_cache = getDNSCache(cacheID, true);
if(dns_cache == NULL)
{
logg("WARN: No memory available, skipping query analysis");
return false;
}
// Skip the entire chain of tests if we already know the answer for this
// particular client
unsigned char blockingStatus = dns_cache->blocking_status;
char *domainstr = (char*)getstr(domain->domainpos);
switch(blockingStatus)
{
case UNKNOWN_BLOCKED:
// New domain/client combination.
// We have to go through all the tests below
if(config.debug & DEBUG_QUERIES)
{
logg("%s is not known", domainstr);
}
break;
case BLACKLIST_BLOCKED:
// Known as exactly blacklistes, we
// return this result early, skipping
// all the lengthy tests below
blockingreason = "exactly blacklisted";
if(config.debug & DEBUG_QUERIES)
{
logg("%s is known as %s", domainstr, blockingreason);
}
// Do not block if the entire query is to be permitted
// as something along the CNAME path hit the whitelist
if(!query->flags.whitelisted)
{
force_next_DNS_reply = dns_cache->force_reply;
query_blocked(query, domain, client, QUERY_BLACKLIST);
return true;
}
break;
case GRAVITY_BLOCKED:
// Known as gravity blocked, we
// return this result early, skipping
// all the lengthy tests below
blockingreason = "gravity blocked";
if(config.debug & DEBUG_QUERIES)
{
logg("%s is known as %s", domainstr, blockingreason);
}
// Do not block if the entire query is to be permitted
// as sometving along the CNAME path hit the whitelist
if(!query->flags.whitelisted)
{
force_next_DNS_reply = dns_cache->force_reply;
query_blocked(query, domain, client, QUERY_GRAVITY);
return true;
}
break;
case REGEX_BLOCKED:
// Known as regex blacklisted, we
// return this result early, skipping
// all the lengthy tests below
blockingreason = "regex blacklisted";
if(config.debug & DEBUG_QUERIES)
{
logg("%s is known as %s", domainstr, blockingreason);
force_next_DNS_reply = dns_cache->force_reply;
}
// Do not block if the entire query is to be permitted
// as sometving along the CNAME path hit the whitelist
if(!query->flags.whitelisted)
{
query_blocked(query, domain, client, QUERY_REGEX);
return true;
}
break;
case WHITELISTED:
// Known as whitelisted, we
// return this result early, skipping
// all the lengthy tests below
if(config.debug & DEBUG_QUERIES)
{
logg("%s is known as not to be blocked (whitelisted)", domainstr);
}
query->flags.whitelisted = true;
return false;
break;
case SPECIAL_DOMAIN:
// Known as a special domain, we
// return this result early, skipping
// all the lengthy tests below
blockingreason = "special domain";
if(config.debug & DEBUG_QUERIES)
{
logg("%s is known as special domain", domainstr);;
}
force_next_DNS_reply = dns_cache->force_reply;
query_blocked(query, domain, client, QUERY_CACHE);
return true;
break;
case NOT_BLOCKED:
// Known as not blocked, we
// return this result early, skipping
// all the lengthy tests below
if(config.debug & DEBUG_QUERIES)
{
logg("%s is known as not to be blocked", domainstr);
}
return false;