-
Notifications
You must be signed in to change notification settings - Fork 100
/
erldns_zone_cache.erl
730 lines (670 loc) · 27.6 KB
/
erldns_zone_cache.erl
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
%% Copyright (c) 2012-2020, DNSimple Corporation
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%% @doc A cache holding all of the zone data.
%%
%% Write operations occur through the cache process mailbox, whereas read
%% operations may occur either through the mailbox or directly through the
%% underlying data store, depending on performance requirements.
-module(erldns_zone_cache).
-behavior(gen_server).
-include_lib("dns_erlang/include/dns.hrl").
-include_lib("opentelemetry_api/include/otel_tracer.hrl").
-include_lib("opentelemetry_api/include/opentelemetry.hrl").
-include("erldns.hrl").
-export([start_link/0]).
% Read APIs
-export([
find_zone/1,
find_zone/2,
get_zone/1,
get_authority/1,
get_delegations/1,
get_zone_records/1,
get_records_by_name/1,
get_records_by_name_and_type/2,
in_zone/1,
record_name_in_zone/2,
zone_names_and_versions/0,
get_rrset_sync_counter/3
]).
% Deprecated APIs
-export([get_zone_with_records/1]).
% Write APIs
-export([
put_zone/1,
put_zone/2,
delete_zone/1,
update_zone_records_and_digest/3,
put_zone_rrset/4,
delete_zone_rrset/5
]).
% Gen server hooks
-export([
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-define(SERVER, ?MODULE).
-record(state, {parsers, tref = none}).
%% @doc Start the zone cache process.
-spec start_link() -> any().
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
% ----------------------------------------------------------------------------------------------------
% Read API
%% @doc Find a zone for a given qname.
-spec find_zone(dns:dname()) -> #zone{} | {error, zone_not_found} | {error, not_authoritative}.
find_zone(Qname) ->
find_zone(erldns:normalize_name(Qname), get_authority(Qname)).
%% @doc Find a zone for a given qname.
-spec find_zone(dns:dname(), {error, any()} | {ok, dns:rr()} | [dns:rr()] | dns:rr()) ->
#zone{} | {error, zone_not_found} | {error, not_authoritative}.
find_zone(Qname, {error, _}) ->
find_zone(Qname, []);
find_zone(Qname, {ok, Authority}) ->
find_zone(Qname, Authority);
find_zone(_Qname, []) ->
{error, not_authoritative};
find_zone(Qname, Authorities) when is_list(Authorities) ->
find_zone(Qname, lists:last(Authorities));
find_zone(Qname, Authority) when is_record(Authority, dns_rr) ->
Name = erldns:normalize_name(Qname),
case dns:dname_to_labels(Name) of
[] ->
{error, zone_not_found};
[_ | Labels] ->
case get_zone(Name) of
{ok, Zone} ->
Zone;
{error, zone_not_found} ->
case Name =:= Authority#dns_rr.name of
true ->
{error, zone_not_found};
false ->
find_zone(dns:labels_to_dname(Labels), Authority)
end
end
end.
%% @doc Get a zone for the specific name. This function will not attempt to resolve
%% the dname in any way, it will simply look up the name in the underlying data store.
-spec get_zone(dns:dname()) -> {ok, #zone{}} | {error, zone_not_found}.
get_zone(Name) ->
NormalizedName = erldns:normalize_name(Name),
case erldns_storage:select(zones, NormalizedName) of
[{NormalizedName, Zone}] ->
{ok, Zone#zone{
name = NormalizedName,
records = [],
records_by_name = trimmed
}};
_ ->
{error, zone_not_found}
end.
%% @doc Get a zone for the specific name, including the records for the zone.
%% @deprecated Use {@link erldns_zone_cache:get_zone/1} to get the zone meta data and
%% {@link erldns_zone_cache:get_zone_records/1} to get the records for the zone.
-spec get_zone_with_records(dns:dname()) -> {ok, #zone{}} | {error, zone_not_found}.
get_zone_with_records(Name) ->
NormalizedName = erldns:normalize_name(Name),
case erldns_storage:select(zones, NormalizedName) of
[{NormalizedName, Zone}] ->
{ok, Zone};
_ ->
{error, zone_not_found}
end.
%% @doc Find the SOA record for the given DNS question.
-spec get_authority(dns:message() | dns:dname()) -> {error, no_question} | {error, authority_not_found} | {ok, dns:authority()}.
get_authority(Message) when is_record(Message, dns_message) ->
case Message#dns_message.questions of
[] ->
{error, no_question};
Questions ->
Question = lists:last(Questions),
get_authority(Question#dns_query.name)
end;
get_authority(Name) ->
case find_zone_in_cache(erldns:normalize_name(Name)) of
{ok, Zone} ->
{ok, Zone#zone.authority};
_ ->
{error, authority_not_found}
end.
%% @doc Get the list of NS and glue records for the given name. This function
%% will always return a list, even if it is empty.
-spec get_delegations(dns:dname()) -> [dns:rr()] | [].
get_delegations(Name) ->
case find_zone_in_cache(Name) of
{ok, Zone} ->
Records =
lists:flatten(
erldns_storage:select(
zone_records_typed,
[{{{erldns:normalize_name(Zone#zone.name), erldns:normalize_name(Name), ?DNS_TYPE_NS}, '$1'}, [], ['$$']}],
infinite
)
),
lists:filter(erldns_records:match_delegation(Name), Records);
_ ->
[]
end.
%% @doc Get all records for the given zone.
-spec get_zone_records(dns:dname()) -> [dns:rr()].
get_zone_records(Name) ->
case find_zone_in_cache(Name) of
{ok, Zone} ->
lists:flatten(
erldns_storage:select(
zone_records_typed, [{{{erldns:normalize_name(Zone#zone.name), '_', '_'}, '$1'}, [], ['$$']}], infinite
)
);
_ ->
[]
end.
%% @doc Get all records for the given type and given name.
-spec get_records_by_name_and_type(dns:dname(), dns:type()) -> [dns:rr()].
get_records_by_name_and_type(Name, Type) ->
case find_zone_in_cache(Name) of
{ok, Zone} ->
lists:flatten(
erldns_storage:select(
zone_records_typed,
[{{{erldns:normalize_name(Zone#zone.name), erldns:normalize_name(Name), Type}, '$1'}, [], ['$$']}],
infinite
)
);
_ ->
[]
end.
%% @doc Get all DNSSEC records for zone
-spec get_zone_dnskey_records(dns:dname()) -> [dns:rr()].
get_zone_dnskey_records(Name) ->
case find_zone_in_cache(Name) of
{ok, _Zone} ->
get_records_by_name_and_type(Name, ?DNS_TYPE_DNSKEY);
_ ->
[]
end.
%% @doc Return the record set for the given dname.
-spec get_records_by_name(dns:dname()) -> [dns:rr()].
get_records_by_name(Name) ->
case find_zone_in_cache(Name) of
{ok, Zone} ->
lists:flatten(
erldns_storage:select(
zone_records_typed,
[{{{erldns:normalize_name(Zone#zone.name), erldns:normalize_name(Name), '_'}, '$1'}, [], ['$$']}],
infinite
)
);
_ ->
[]
end.
%% @doc Check if the name is in a zone.
-spec in_zone(binary()) -> boolean().
in_zone(Name) ->
case find_zone_in_cache(Name) of
{ok, Zone} ->
is_name_in_zone(Name, Zone);
_ ->
false
end.
%% @doc Check if the record name is in the zone. Will also return true if a wildcard is present at the node.
-spec record_name_in_zone(binary(), dns:dname()) -> boolean().
record_name_in_zone(ZoneName, Name) ->
case find_zone_in_cache(Name) of
{ok, Zone} ->
case
lists:flatten(
erldns_storage:select(
zone_records_typed, [{{{ZoneName, erldns:normalize_name(Name), '_'}, '$1'}, [], ['$$']}], infinite
)
)
of
[] ->
is_name_in_zone_with_wildcard(Name, Zone);
_ ->
true
end;
_ ->
false
end.
%% @doc Return a list of tuples with each tuple as a name and the version SHA
%% for the zone.
-spec zone_names_and_versions() -> [{dns:dname(), binary()}].
zone_names_and_versions() ->
% ETS and Mnesia foldl/3 differ in return values -> Mnesia's version is missing key
case erldns_config:storage_type() of
erldns_storage_json ->
erldns_storage:foldl(fun({_, Zone}, NamesAndShas) -> NamesAndShas ++ [{Zone#zone.name, Zone#zone.version}] end, [], zones);
erldns_storage_mnesia ->
erldns_storage:foldl(fun(Zone, NamesAndShas) -> NamesAndShas ++ [{Zone#zone.name, Zone#zone.version}] end, [], zones)
end.
%% @doc Return current sync counter
-spec get_rrset_sync_counter(dns:dname(), dns:dname(), dns:type()) -> integer().
get_rrset_sync_counter(ZoneName, RRFqdn, Type) ->
case
erldns_storage:select(
sync_counters, [{{erldns:normalize_name(ZoneName), erldns:normalize_name(RRFqdn), Type, '$1'}, [], ['$_']}], infinite
)
of
[{ZoneName, RRFqdn, Type, Counter}] ->
Counter;
[] ->
% return default value of 0
0
end.
%% @doc Update the RRSet sync counter for the given RR set name and type in the given zone.
-spec write_rrset_sync_counter({dns:dname(), dns:dname(), dns:type(), integer()}) -> ok.
write_rrset_sync_counter({ZoneName, RRFqdn, Type, Counter}) ->
erldns_storage:insert(sync_counters, {ZoneName, RRFqdn, Type, Counter}).
% ----------------------------------------------------------------------------------------------------
% Write API
%% @doc Put a name and its records into the cache, along with a SHA which can be
%% used to determine if the zone requires updating.
%%
%% This function will build the necessary Zone record before inserting.
-spec put_zone({Name, Sha, Records, Keys} | {Name, Sha, Records}) -> ok | {error, Reason :: term()} when
Name :: binary(),
Sha :: binary(),
Records :: [dns:rr()],
Keys :: [erldns:keyset()].
put_zone({Name, Sha, Records}) ->
put_zone({Name, Sha, Records, []});
put_zone({Name, Sha, Records, Keys}) ->
SignedZone = sign_zone(build_zone(Name, Sha, Records, Keys)),
NamedRecords = build_named_index(SignedZone#zone.records),
delete_zone_records(erldns:normalize_name(Name)),
case put_zone(erldns:normalize_name(Name), SignedZone#zone{records = trimmed}) of
ok ->
put_zone_records(erldns:normalize_name(Name), NamedRecords);
{error, Reason} ->
{error, Reason}
end.
%% @doc Put a zone into the cache and wait for a response.
-spec put_zone(dns:name(), erldns:zone()) -> ok | {error, Reason :: term()}.
put_zone(Name, Zone) ->
erldns_storage:insert(zones, {erldns:normalize_name(Name), Zone}).
-spec put_zone_records(dns:name(), map()) -> ok.
put_zone_records(Name, RecordsByName) ->
put_zone_records_entry(Name, maps:next(maps:iterator(RecordsByName))).
%% @doc Put zone RRSet
-spec put_zone_rrset(
{dns:dname(), binary(), [dns:rr()]} | {dns:dname(), binary(), [dns:rr()], [any()]}, dns:dname(), dns:type(), integer()
) ->
ok | {error, Reason :: term()}.
put_zone_rrset({ZoneName, Digest, Records}, RRFqdn, Type, Counter) ->
put_zone_rrset({ZoneName, Digest, Records, []}, RRFqdn, Type, Counter);
put_zone_rrset({ZoneName, Digest, Records, _Keys}, RRFqdn, Type, Counter) ->
case find_zone_in_cache(erldns:normalize_name(ZoneName)) of
{ok, Zone} ->
% TODO: remove debug
lager:debug("Putting RRSet (~p) with Type: ~p for Zone (~p): ~p", [RRFqdn, Type, ZoneName, Records]),
KeySets = Zone#zone.keysets,
DnsKeyRRs = get_zone_dnskey_records(ZoneName),
SignedRRSet = ?with_span(
<<"sign_rrset">>,
#{},
fun(_SpanCtx) ->
?set_attributes([{zone, ZoneName}, {type, Type}]),
sign_rrset(ZoneName, Records, DnsKeyRRs, KeySets)
end
),
{RRSigRecsCovering, RRSigRecsNotCovering} = filter_rrsig_records_with_type_covered(RRFqdn, Type),
% RRSet records + RRSIG records for the type + the rest of RRSIG records for FQDN
TypedRecords = build_typed_index(Records ++ SignedRRSet ++ RRSigRecsNotCovering),
CurrentRRSetRecords = get_records_by_name_and_type(RRFqdn, Type),
ZoneRecordsCount = Zone#zone.record_count,
% put zone_records_typed records first then create the records in zone_records
put_zone_records_typed_entry(ZoneName, RRFqdn, maps:next(maps:iterator(TypedRecords))),
?with_span(
<<"update_zone_recs">>,
#{},
fun(_SpanCtx) ->
?set_attributes([{zone, ZoneName}]),
UpdatedZoneRecordsCount =
ZoneRecordsCount +
(length(Records) - length(CurrentRRSetRecords)) +
(length(SignedRRSet) - length(RRSigRecsCovering)),
update_zone_records_and_digest(ZoneName, UpdatedZoneRecordsCount, Digest)
end
),
write_rrset_sync_counter({ZoneName, RRFqdn, Type, Counter}),
lager:debug("RRSet update completed for FQDN: ~p, Type: ~p", [RRFqdn, Type]),
ok;
% if zone is not in cache, return error
_ ->
{error, zone_not_found}
end.
put_zone_records_entry(_, none) ->
ok;
put_zone_records_entry(Name, {K, V, I}) ->
put_zone_records_typed_entry(Name, K, maps:next(maps:iterator(build_typed_index(V)))),
put_zone_records_entry(Name, maps:next(I)).
put_zone_records_typed_entry(_, _, none) ->
ok;
put_zone_records_typed_entry(ZoneName, Fqdn, {K, V, I}) ->
erldns_storage:insert(zone_records_typed, {{erldns:normalize_name(ZoneName), erldns:normalize_name(Fqdn), K}, V}),
put_zone_records_typed_entry(ZoneName, Fqdn, maps:next(I)).
%% @doc Remove a zone from the cache without waiting for a response.
-spec delete_zone(binary()) -> any().
delete_zone(Name) ->
gen_server:cast(?SERVER, {delete, Name}).
-spec delete_zone_records(binary()) -> any().
delete_zone_records(Name) ->
erldns_storage:select_delete(zone_records_typed, [{{{erldns:normalize_name(Name), '_', '_'}, '_'}, [], [true]}]).
%% @doc Remove zone RRSet
-spec delete_zone_rrset(binary(), binary(), binary(), integer(), integer()) -> any().
delete_zone_rrset(ZoneName, Digest, RRFqdn, Type, Counter) ->
case find_zone_in_cache(erldns:normalize_name(ZoneName)) of
{ok, Zone} ->
Zone,
CurrentCounter = get_rrset_sync_counter(ZoneName, RRFqdn, Type),
case Counter of
N when N =:= 0; CurrentCounter < N ->
lager:debug("Removing RRSet (~p) with type ~p", [RRFqdn, Type]),
ZoneRecordsCount = Zone#zone.record_count,
CurrentRRSetRecords = get_records_by_name_and_type(RRFqdn, Type),
erldns_storage:select_delete(
zone_records_typed,
[{{{erldns:normalize_name(ZoneName), erldns:normalize_name(RRFqdn), Type}, '_'}, [], [true]}]
),
% remove the RRSIG for the given record type
{RRSigsCovering, RRSigsNotCovering} =
lists:partition(
erldns_records:match_type_covered(Type), get_records_by_name_and_type(RRFqdn, ?DNS_TYPE_RRSIG_NUMBER)
),
erldns_storage:insert(
zone_records_typed,
{{erldns:normalize_name(ZoneName), erldns:normalize_name(RRFqdn), ?DNS_TYPE_RRSIG_NUMBER}, RRSigsNotCovering}
),
% only write counter if called explicitly with Counter value i.e. different than 0.
% this will not write the counter if called by put_zone_rrset/3 as it will prevent subsequent delete ops
case Counter of
N when N > 0 ->
% DELETE RRSet command has been sent
% we need to update the zone digest as the zone content changes
UpdatedZoneRecordsCount =
ZoneRecordsCount -
length(CurrentRRSetRecords) -
length(RRSigsCovering),
update_zone_records_and_digest(ZoneName, UpdatedZoneRecordsCount, Digest),
write_rrset_sync_counter({ZoneName, RRFqdn, Type, Counter});
_ ->
ok
end;
N when CurrentCounter > N ->
lager:debug("Not processing delete operation for RRSet (~p): counter (~p) provided is lower than system", [
RRFqdn, Counter
])
end;
_ ->
{error, zone_not_found}
end.
%% @doc Given a zone name, list of records, and a digest, update the zone metadata in cache.
-spec update_zone_records_and_digest(dns:dname(), integer(), binary()) -> ok | {error, Reason :: term()}.
update_zone_records_and_digest(ZoneName, RecordsCount, Digest) ->
case find_zone_in_cache(erldns:normalize_name(ZoneName)) of
{ok, Zone} ->
Zone,
UpdatedZone =
Zone#zone{
version = Digest,
authority = get_records_by_name_and_type(ZoneName, ?DNS_TYPE_SOA),
record_count = RecordsCount
},
?with_span(
<<"put_zone">>,
#{},
fun(_SpanCtx) ->
?set_attributes([{zone, ZoneName}]),
put_zone(Zone#zone.name, UpdatedZone)
end
);
_ ->
{error, zone_not_found}
end.
%% @doc Filter RRSig records for FQDN, removing type covered.
-spec filter_rrsig_records_with_type_covered(dns:dname(), dns:type()) -> {[dns:rr()], [dns:rr()]} | {[], []}.
filter_rrsig_records_with_type_covered(RRFqdn, TypeCovered) ->
% guards below do not allow fun calls to prevent side effects
case find_zone_in_cache(erldns:normalize_name(RRFqdn)) of
{ok, _Zone} ->
% {RRSigsCovering, RRSigsNotCovering} =
lists:partition(
erldns_records:match_type_covered(TypeCovered),
get_records_by_name_and_type(RRFqdn, ?DNS_TYPE_RRSIG_NUMBER)
);
_ ->
{[], []}
end.
% ----------------------------------------------------------------------------------------------------
% Gen server init
%% @doc Initialize the zone cache.
-spec init([]) -> {ok, #state{}}.
init([]) ->
erldns_storage:create(schema),
erldns_storage:create(zones),
erldns_storage:create(zone_records_typed),
erldns_storage:create(authorities),
erldns_storage:create(sync_counters),
{ok, #state{parsers = []}}.
% ----------------------------------------------------------------------------------------------------
% gen_server callbacks
handle_call(Message, _From, State) ->
lager:debug("Received unsupported call (message: ~p)", [Message]),
{reply, ok, State}.
handle_cast({delete, Name}, State) ->
erldns_storage:delete(zones, erldns:normalize_name(Name)),
delete_zone_records(Name),
{noreply, State};
handle_cast(Message, State) ->
lager:debug("Received unsupported cast (message: ~p)", [Message]),
{noreply, State}.
handle_info(_Message, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_PreviousVersion, State, _Extra) ->
{ok, State}.
% Internal API
is_name_in_zone(Name, Zone) ->
ZoneName = erldns:normalize_name(Zone#zone.name),
case
lists:flatten(
erldns_storage:select(zone_records_typed, [{{{ZoneName, erldns:normalize_name(Name), '_'}, '$1'}, [], ['$$']}], infinite)
)
of
[] ->
case dns:dname_to_labels(Name) of
[] ->
false;
[_] ->
false;
[_ | Labels] ->
is_name_in_zone(dns:labels_to_dname(Labels), Zone)
end;
_ ->
true
end.
is_name_in_zone_with_wildcard(Name, Zone) ->
ZoneName = erldns:normalize_name(Zone#zone.name),
WildcardName = erldns:normalize_name(erldns_records:wildcard_qname(Name)),
case lists:flatten(erldns_storage:select(zone_records_typed, [{{{ZoneName, WildcardName, '_'}, '$1'}, [], ['$$']}], infinite)) of
[] ->
case dns:dname_to_labels(Name) of
[] ->
false;
[_] ->
false;
[_ | Labels] ->
is_name_in_zone_with_wildcard(dns:labels_to_dname(Labels), Zone)
end;
_ ->
true
end.
find_zone_in_cache(Qname) ->
Name = erldns:normalize_name(Qname),
find_zone_in_cache(Name, dns:dname_to_labels(Name)).
find_zone_in_cache(_Name, []) ->
{error, zone_not_found};
find_zone_in_cache(Name, [_ | Labels]) ->
case erldns_storage:select(zones, Name) of
[{Name, Zone}] ->
{ok, Zone};
_ ->
case Labels of
[] ->
{error, zone_not_found};
_ ->
find_zone_in_cache(dns:labels_to_dname(Labels))
end
end.
build_zone(Qname, Version, Records, Keys) ->
Authorities = lists:filter(erldns_records:match_type(?DNS_TYPE_SOA), Records),
#zone{
name = Qname,
version = Version,
record_count = length(Records),
authority = Authorities,
records = Records,
records_by_name = trimmed,
keysets = Keys
}.
-spec build_named_index([#dns_rr{}]) -> #{binary() => [#dns_rr{}]}.
build_named_index(Records) ->
NamedIndex =
lists:foldl(
fun(R, Idx) ->
Name = erldns:normalize_name(R#dns_rr.name),
maps:update_with(Name, fun(RR) -> [R | RR] end, [R], Idx)
end,
#{},
Records
),
maps:map(fun(_K, V) -> lists:reverse(V) end, NamedIndex).
-spec build_typed_index([#dns_rr{}]) -> #{dns:type() => [#dns_rr{}]}.
build_typed_index(Records) ->
TypedIndex = lists:foldl(fun(R, Idx) -> maps:update_with(R#dns_rr.type, fun(RR) -> [R | RR] end, [R], Idx) end, #{}, Records),
maps:map(fun(_K, V) -> lists:reverse(V) end, TypedIndex).
-spec sign_zone(erldns:zone()) -> erldns:zone().
sign_zone(Zone = #zone{keysets = []}) ->
Zone;
sign_zone(Zone) ->
% lager:debug("Signing zone (name: ~p)", [Zone#zone.name]),
DnskeyRRs = lists:filter(erldns_records:match_type(?DNS_TYPE_DNSKEY), Zone#zone.records),
KeyRRSigRecords = lists:flatten(lists:map(erldns_dnssec:key_rrset_signer(Zone#zone.name, DnskeyRRs), Zone#zone.keysets)),
Verify = verify_zone(Zone, DnskeyRRs, KeyRRSigRecords),
lager:debug("Zone verified: ~p", [Verify]),
% TODO: remove wildcard signatures as they will not be used but are taking up space
ZoneRRSigRecords =
lists:flatten(
lists:map(
erldns_dnssec:zone_rrset_signer(
Zone#zone.name,
lists:filter(fun(RR) -> RR#dns_rr.type =/= ?DNS_TYPE_DNSKEY end, Zone#zone.records)
),
Zone#zone.keysets
)
),
Records =
Zone#zone.records ++
KeyRRSigRecords ++
rewrite_soa_rrsig_ttl(Zone#zone.records, ZoneRRSigRecords -- lists:filter(erldns_records:match_wildcard(), ZoneRRSigRecords)),
#zone{
name = Zone#zone.name,
version = Zone#zone.version,
record_count = length(Records),
authority = Zone#zone.authority,
records = Records,
records_by_name = build_named_index(Records),
keysets = Zone#zone.keysets
}.
-spec verify_zone(erldns:zone(), [dns:rr()], [dns:rr()]) -> boolean().
verify_zone(_Zone, DnskeyRRs, KeyRRSigRecords) ->
% lager:debug("Verify zone (name: ~p)", [Zone#zone.name]),
case lists:filter(fun(RR) -> RR#dns_rr.data#dns_rrdata_dnskey.flags =:= ?DNSKEY_KSK_TYPE end, DnskeyRRs) of
[] ->
false;
KSKs ->
% lager:debug("KSKs: ~p", [KSKs]),
KSKDnskey = lists:last(KSKs),
RRSig = lists:last(KeyRRSigRecords),
% lager:debug("Attempting to verify RRSIG (key: ~p)", [KSKDnskey]),
VerifyResult = dnssec:verify_rrsig(RRSig, DnskeyRRs, [KSKDnskey], []),
% lager:debug("KSK verification (verified?: ~p)", [VerifyResult]),
VerifyResult
end.
% Sign RRSet
-spec sign_rrset(binary(), [dns:rr()], [dns:rr()], [erldns:keyset()]) -> [dns:rr()].
sign_rrset(Name, Records, DnsKeyRRs, KeySets) ->
% lager:debug("Signing RRSet for zone (name: ~p)", [Name]),
KeyRRSigRecords = lists:flatten(lists:map(erldns_dnssec:key_rrset_signer(Name, DnsKeyRRs), KeySets)),
ZoneRecords = get_records_by_name_and_type(Name, ?DNS_TYPE_SOA),
RRSigRecords =
rewrite_soa_rrsig_ttl(
ZoneRecords,
lists:flatten(
lists:map(
erldns_dnssec:zone_rrset_signer(
Name,
lists:filter(
fun(RR) -> RR#dns_rr.type =/= ?DNS_TYPE_DNSKEY end,
Records
)
),
KeySets
)
)
),
verify_rrset(DnsKeyRRs, KeyRRSigRecords),
RRSigRecords.
% Verify RRSet
-spec verify_rrset([dns:rr()], [dns:rr()]) -> boolean().
verify_rrset(DnsKeyRRs, KeyRRSigRecords) ->
% lager:debug("Verify RRSet"),
case lists:filter(fun(RR) -> RR#dns_rr.data#dns_rrdata_dnskey.flags =:= ?DNSKEY_KSK_TYPE end, DnsKeyRRs) of
[] ->
false;
KSKs ->
case KeyRRSigRecords of
[] ->
false;
_ ->
% lager:debug("KSKs: ~p", [KSKs]),
KSKDnskey = lists:last(KSKs),
RRSig = lists:last(KeyRRSigRecords),
VerifyResult = dnssec:verify_rrsig(RRSig, DnsKeyRRs, [KSKDnskey], []),
VerifyResult
end
end.
% Rewrite the RRSIG TTL so it follows the same rewrite rules as the SOA TTL.
rewrite_soa_rrsig_ttl(ZoneRecords, RRSigRecords) ->
SoaRR = lists:last(lists:filter(erldns_records:match_type(?DNS_TYPE_SOA), ZoneRecords)),
lists:map(
fun(RR) ->
case RR#dns_rr.type of
?DNS_TYPE_RRSIG ->
case RR#dns_rr.data#dns_rrdata_rrsig.type_covered of
?DNS_TYPE_SOA -> erldns_records:minimum_soa_ttl(RR, SoaRR#dns_rr.data);
_ -> RR
end;
_ ->
RR
end
end,
RRSigRecords
).