-
-
Notifications
You must be signed in to change notification settings - Fork 185
/
dnsmasq_interface.c
2302 lines (2011 loc) · 64.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"
static void print_flags(const unsigned int flags);
static void save_reply_type(const unsigned int flags, const union all_addr *addr,
queriesData* query, const struct timeval response);
static unsigned long converttimeval(const struct timeval time) __attribute__((const));
static void detect_blocked_IP(const unsigned short flags, const union all_addr *addr, const int queryID);
static void query_externally_blocked(const int queryID, const unsigned char status);
static void prepare_blocking_metadata(void);
static void query_blocked(queriesData* query, domainsData* domain, clientsData* client, const unsigned char new_status);
// Static blocking metadata (stored precomputed as time-critical)
static unsigned int blocking_flags = 0;
static union all_addr blocking_addrp_v4 = {{ 0 }};
static union all_addr blocking_addrp_v6 = {{ 0 }};
static unsigned char force_next_DNS_reply = 0u;
// Adds debug information to the regular pihole.log file
char debug_dnsmasq_lines = 0;
// Fork-private copy of the interface name the most recent query came from
static char next_iface[IFNAMSIZ] = "";
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"};
// Store interface the next query will come from for later usage
void FTL_next_iface(const char *newiface)
{
if(newiface != NULL)
{
// Copy interface name if available
strncpy(next_iface, newiface, sizeof(next_iface)-1);
next_iface[sizeof(next_iface)-1] = '\0';
}
else
{
// Use dummy when interface record is not available
next_iface[0] = '-';
next_iface[1] = '\0';
}
}
static bool check_domain_blocked(const char *domain, const int clientID,
clientsData *client, queriesData *query, DNSCacheData *dns_cache,
const char **blockingreason, 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;
}
static bool _FTL_check_blocking(int queryID, int domainID, int clientID, const char **blockingreason,
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);
unsigned int cacheID = findCacheID(domainID, clientID, query->type);
DNSCacheData *dns_cache = getDNSCache(cacheID, true);
if(query == NULL || domain == NULL || client == NULL || dns_cache == NULL)
{
// Encountered memory error, skip query
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 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;
break;
}
// Skip all checks and continue if we hit already at least one whitelist in the chain
if(query->flags.whitelisted)
{
if(config.debug & DEBUG_QUERIES)
{
logg("Query is permitted as at least one whitelist entry matched");
}
return false;
}
// Make a local copy of the domain string. The string memory may get
// reorganized in the following. We cannot expect domainstr to remain
// valid for all time.
domainstr = strdup(domainstr);
const char *blockedDomain = domainstr;
// Check whitelist (exact + regex) for match
query->flags.whitelisted = in_whitelist(domainstr, dns_cache, client);
bool blockDomain = false;
unsigned char new_status = QUERY_UNKNOWN;
// Check blacklist (exact + regex) and gravity for queried domain
if(!query->flags.whitelisted)
{
blockDomain = check_domain_blocked(domainstr, clientID, client, query, dns_cache, blockingreason, &new_status);
}
// Check blacklist (exact + regex) and gravity for _esni.domain if enabled (defaulting to true)
if(config.block_esni && !query->flags.whitelisted && !blockDomain && strncasecmp(domainstr, "_esni.", 6u) == 0)
{
blockDomain = check_domain_blocked(domainstr + 6u, clientID, client, query, dns_cache, blockingreason, &new_status);
if(blockDomain)
{
// Truncate "_esni." from queried domain if the parenting domain was the reason for blocking this query
blockedDomain = domainstr + 6u;
// Force next DNS reply to be NXDOMAIN for _esni.* queries
force_next_DNS_reply = NXDOMAIN;
dns_cache->force_reply = NXDOMAIN;
}
}
// Common actions regardless what the possible blocking reason is
if(blockDomain)
{
// Adjust counters
query_blocked(query, domain, client, new_status);
// Debug output
if(config.debug & DEBUG_QUERIES)
logg("Blocking %s as %s is %s", domainstr, blockedDomain, *blockingreason);
}
else
{
// Explicitly mark as not blocked to skip the entire
// gravity/blacklist chain when the same client asks
// for the same domain in the future. Explicitly store
// domain as whitelisted if this is the case
dns_cache->blocking_status = query->flags.whitelisted ? WHITELISTED : NOT_BLOCKED;
}
free(domainstr);
return blockDomain;
}
bool _FTL_CNAME(const char *domain, const struct crec *cpp, const int id, const char* file, const int line)
{
// Does the user want to skip deep CNAME inspection?
if(!config.cname_inspection)
{
return false;
}
// Lock shared memory
lock_shm();
// Get CNAME destination and source (if applicable)
const char *src = cpp != NULL ? cpp->flags & F_BIGNAME ? cpp->name.bname->name : cpp->name.sname : NULL;
const char *dst = domain;
// Save status and upstreamID in corresponding query identified by dnsmasq's ID
const int queryID = findQueryID(id);
if(queryID < 0)
{
// This may happen e.g. if the original query was a PTR query
// or "pi.hole" and we ignored them altogether
unlock_shm();
return false;
}
// Get query pointer so we can later extract the client requesting this domain for
// the per-client blocking evaluation
queriesData* query = getQuery(queryID, true);
if(query == NULL)
{
// Nothing to be done here
unlock_shm();
return false;
}
// Example to make the terminology used in here clear:
// CNAME abc -> 123
// CNAME 123 -> 456
// CNAME 456 -> 789
// parent_domain: abc
// child_domains: [123, 456, 789]
// parent_domain = Domain at the top of the CNAME path
// This is the domain which was queried first in this chain
const int parent_domainID = query->domainID;
// child_domain = Intermediate domain in CNAME path
// This is the domain which was queried later in this chain
char *child_domain = strdup(domain);
// Convert to lowercase for matching
strtolower(child_domain);
const int child_domainID = findDomainID(child_domain, false);
// Get client ID from the original query (the entire chain always
// belongs to the same client)
const int clientID = query->clientID;
// Check per-client blocking for the child domain
const char *blockingreason = NULL;
const bool block = FTL_check_blocking(queryID, child_domainID, clientID, &blockingreason);
// If we find during a CNAME inspection that we want to block the entire chain,
// the originally queried domain itself was not counted as blocked. We have to
// correct this when we are going to short-circuit the entire query
if(block)
{
// Increase blocked count of parent domain
domainsData* parent_domain = getDomain(parent_domainID, true);
parent_domain->blockedcount++;
// Store query response as CNAME type
struct timeval response;
gettimeofday(&response, 0);
save_reply_type(F_CNAME, NULL, query, response);
// Store domain that was the reason for blocking the entire chain
query->CNAME_domainID = child_domainID;
// Change blocking reason into CNAME-caused blocking
if(query->status == QUERY_GRAVITY)
{
query->status = QUERY_GRAVITY_CNAME;
}
else if(query->status == QUERY_REGEX)
{
// Get parent and child DNS cache entries
const int parent_cacheID = findCacheID(parent_domainID, clientID, query->type);
const int child_cacheID = findCacheID(child_domainID, clientID, query->type);
// Get cache pointers
DNSCacheData *parent_cache = getDNSCache(parent_cacheID, true);
DNSCacheData *child_cache = getDNSCache(child_cacheID, true);
// Propagate ID of responsible regex up from the child to the parent domain
if(parent_cache != NULL && child_cache != NULL)
{
child_cache->black_regex_idx = parent_cache->black_regex_idx;
}
// Set status
query->status = QUERY_REGEX_CNAME;
}
else if(query->status == QUERY_BLACKLIST)
{
// Only set status
query->status = QUERY_BLACKLIST_CNAME;
}
}
// Debug logging for deep CNAME inspection (if enabled)
if(config.debug & DEBUG_QUERIES)
{
if(src == NULL)
logg("CNAME %s", dst);
else
logg("CNAME %s ---> %s", src, dst);
}
// Return result
free(child_domain);
unlock_shm();
return block;
}
bool _FTL_new_query(const unsigned int flags, const char *name,
const char **blockingreason, const union all_addr *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;
}
// 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;
}
// If domain is "pi.hole" we skip this query
if(strcasecmp(name, "pi.hole") == 0)
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 = (flags & F_IPV4) ? AF_INET : AF_INET6;
char clientIP[ADDRSTRLEN+1] = { 0 };
if(config.edns0_ecs && edns->client_set)
{
// Use ECS provided client
strncpy(clientIP, edns->client, ADDRSTRLEN);
clientIP[ADDRSTRLEN] = '\0';
}
else
{
// Use original requestor
inet_ntop(family, addr, clientIP, ADDRSTRLEN);
}
// 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;
}
// Check rate-limit for this client
if(config.rate_limit.count > 0 &&
++client->rate_limit > config.rate_limit.count)
{
if(config.debug & DEBUG_QUERIES)
{
logg("Rate-limiting %s %s query \"%s\" from %s:%s",
proto == TCP ? "TCP" : "UDP",
types, domainString, next_iface, clientIP);
}
// Block this query
force_next_DNS_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 %s %s query \"%s\" from %s:%s (ID %i, FTL %i, %s:%i)",
proto == TCP ? "TCP" : "UDP",
types, domainString, next_iface, clientIP, id, queryID, file, line);
}
// Update counters
counters->querytype[querytype-1]++;
// Update overTime
const unsigned int timeidx = getOverTimeID(querytimestamp);
overTime[timeidx].querytypedata[querytype-1]++;
// 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;
}
query->magic = MAGICBYTE;
query->timestamp = querytimestamp;
query->type = querytype;
query->qtype = qtype;
query->status = QUERY_UNKNOWN;
query->domainID = domainID;
query->clientID = clientID;
query->timeidx = timeidx;
// Initialize database rowID with zero, will be set when the query is stored in the long-term DB
query->db = 0;
query->id = id;
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;
// Increase DNS queries counter
counters->queries++;
// Count this query as unknown as long as no reply has
// been found and analyzed
counters->unknown++;
// 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++;
// Preocess interface information of client (if available)
if(next_iface != NULL)
{
if(client->ifacepos == 0u)
{
// Store in the client data if unknown so far
client->ifacepos = addstr(next_iface);
}
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, next_iface) != 0)
{
if(config.debug & DEBUG_CLIENTS)
{
const char *clientName = getstr(client->namepos);
logg("Client %s (%s) changed interface: %s -> %s",
clientIP, clientName, oldiface, next_iface);
}
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)
{
union mysockaddr hwaddr = {{ 0 }};
hwaddr.sa.sa_family = family;
if(family == AF_INET)
{
hwaddr.sa.sa_family = AF_INET;
hwaddr.in.sin_addr.s_addr = addr->addr4.s_addr;
}
else // AF_INET6
{
hwaddr.sa.sa_family = AF_INET6;
memcpy(&hwaddr.in6.sin6_addr, &addr->addr6, sizeof(addr->addr6));
hwaddr.in.sin_addr.s_addr = addr->addr4.s_addr;
}
client->hwlen = find_mac(&hwaddr, 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 = FTL_check_blocking(queryID, domainID, clientID, blockingreason);
// Free allocated memory
free(domainString);
// Release thread lock
unlock_shm();
return blockDomain;
}
void _FTL_get_blocking_metadata(union all_addr **addrp, unsigned int *flags, const char* file, const int line)
{
// 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 == NXDOMAIN)
{
*flags = F_NXDOMAIN;
// Reset DNS reply forcing
force_next_DNS_reply = 0u;
return;
}
else if(force_next_DNS_reply == REFUSED)
{
// Empty flags result in REFUSED
*flags = 0;
// Reset DNS reply forcing
force_next_DNS_reply = 0u;
return;
}
// Add flags according to current blocking mode
// We bit-add here as flags already contains either F_IPV4 or F_IPV6
*flags |= blocking_flags;
if(*flags & F_IPV6)
{
// Pass blocking IPv6 address (will be :: in most cases)
*addrp = &blocking_addrp_v6;
}
else
{
// Pass blocking IPv4 address (will be 0.0.0.0 in most cases)
*addrp = &blocking_addrp_v4;
}
if(config.blockingmode == MODE_NX)
{
// If we block in NXDOMAIN mode, we add the NEGATIVE response
// and the NXDOMAIN flags
*flags = F_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;
}
}
void _FTL_forwarded(const unsigned int flags, const char *name, const struct server *serv, const int id,
const char* file, const int line)
{
// Save that this query got forwarded to an upstream server
// Lock shared memory
lock_shm();
// Get forward destination IP address and port
in_port_t upstreamPort = 53;
char dest[ADDRSTRLEN];
// If addr == NULL, we will only duplicate an empty string instead of uninitialized memory
dest[0] = '\0';
if(serv != NULL)
{
if(serv->addr.sa.sa_family == AF_INET)
{
inet_ntop(AF_INET, &serv->addr.in.sin_addr, dest, ADDRSTRLEN);
upstreamPort = ntohs(serv->addr.in.sin_port);
}
else
{
inet_ntop(AF_INET6, &serv->addr.in6.sin6_addr, dest, ADDRSTRLEN);
upstreamPort = ntohs(serv->addr.in6.sin6_port);
}
}
// Convert upstreamIP to lower case
char *upstreamIP = strdup(dest);
strtolower(upstreamIP);
// Debug logging
if(config.debug & DEBUG_QUERIES)
logg("**** forwarded %s to %s#%u (ID %i, %s:%i)",
name, upstreamIP, upstreamPort, id, file, line);
// Save status and upstreamID in corresponding query identified by dnsmasq's ID
const int queryID = findQueryID(id);
if(queryID < 0)
{
// This may happen e.g. if the original query was a PTR query or "pi.hole"
// as we ignore them altogether
free(upstreamIP);
unlock_shm();
return;
}
// Get query pointer
queriesData* query = getQuery(queryID, true);
// Proceed only if
// - current query has not been marked as replied to so far
// (it could be that answers from multiple forward
// destinations are coming in for the same query)
// - the query was formally known as cached but had to be forwarded
// (this is a special case further described below)
// Use short-circuit evaluation to check if query is NULL
if(query == NULL || (query->flags.complete && query->status != QUERY_CACHE))
{
free(upstreamIP);
unlock_shm();
return;
}
// Get ID of upstream destination, create new upstream record
// if not found in current data structure
const int upstreamID = findUpstreamID(upstreamIP, upstreamPort);
query->upstreamID = upstreamID;
upstreamsData *upstream = getUpstream(upstreamID, true);
if(upstream != NULL)
{
upstream->count++;
upstream->lastQuery = time(NULL);
}
// Update counter for forwarded queries
counters->forwarded++;
// Get time index for this query
const unsigned int timeidx = query->timeidx;
if(query->status == QUERY_CACHE)
{
// Detect if we cached the <CNAME> but need to ask the upstream
// servers for the actual IPs now, we remove this query from the
// counters for cache replied queries as we had to forward a
// request for it. Example:
// Assume a domain a.com is a CNAME which is cached and has a very
// long TTL. It point to another domain server.a.com which has an
// A record but this has a much lower TTL.
// If you now query a.com and then again after some time, you end
// up in a situation where dnsmasq can answer the first level of
// the DNS result (the CNAME) from cache, hence the status of this
// query is marked as "answered from cache" in FTLDNS. However, for
// server.a.com wit the much shorter TTL, we still have to forward
// something and ask the upstream server for the final IP address.
// This code section acknowledges this by removing one entry from
// the cached counters as we will re-brand this query as having been
// forwarded in the following.
counters->cached--;
// Also correct overTime data
overTime[timeidx].cached--;
// Correct reply timer
struct timeval response;
gettimeofday(&response, 0);
// Reset timer, shift slightly into the past to acknowledge the time
// FTLDNS needed to look up the CNAME in its cache
query->response = converttimeval(response) - query->response;
}
else
{
// Normal forwarded query (status is set below)
// Query is no longer unknown
counters->unknown--;
// Hereby, this query is now fully determined
query->flags.complete = true;
}
// Set query status to forwarded only after the
// if(query->status == QUERY_CACHE) { ... }
// from above as otherwise this check will always
// be negative
query->status = QUERY_FORWARDED;
// Update overTime data
overTime[timeidx].forwarded++;
// Release allocated memory
free(upstreamIP);
// Unlock shared memory
unlock_shm();
}
void FTL_dnsmasq_reload(void)
{
// This function is called by the dnsmasq code on receive of SIGHUP
// *before* clearing the cache and rereading the lists
logg("Reloading DNS cache");
// (Re-)open FTL database connection
piholeFTLDB_reopen();
// Request reload the privacy level
set_event(RELOAD_PRIVACY_LEVEL);
// Inspect 01-pihole.conf to see if Pi-hole blocking is enabled,
// i.e. if /etc/pihole/gravity.list is sourced as addn-hosts file
check_blocking_status();
// Reread pihole-FTL.conf to see which blocking mode the user wants to use
// It is possible to change the blocking mode here as we anyhow clear the
// cache and reread all blocking lists
// Passing NULL to this function means it has to open the config file on
// its own behalf (on initial reading, the config file is already opened)
get_blocking_mode(NULL);
// Update blocking metadata (target IP addresses and DNS header flags)
// as the blocking mode might have changed
prepare_blocking_metadata();
// Reread pihole-FTL.conf to see which debugging flags are set
read_debuging_settings(NULL);
// Gravity database updates
// - (Re-)open gravity database connection
// - Get number of blocked domains
// - Read and compile regex filters (incl. per-client)
// - Flush FTL's DNS cache
set_event(RELOAD_GRAVITY);
// Print current set of capabilities if requested via debug flag
if(config.debug & DEBUG_CAPS)
check_capabilities();
// Set resolver as ready