/
pdnssec.cc
1887 lines (1709 loc) · 60.2 KB
/
pdnssec.cc
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
#include "dnsseckeeper.hh"
#include "dnssecinfra.hh"
#include "statbag.hh"
#include "base32.hh"
#include "base64.hh"
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <boost/assign/list_of.hpp>
#include "dnsbackend.hh"
#include "ueberbackend.hh"
#include "arguments.hh"
#include "packetcache.hh"
#include "zoneparser-tng.hh"
#include "signingpipe.hh"
#include <boost/scoped_ptr.hpp>
#include "dns_random.hh"
#ifdef HAVE_SQLITE3
#include "ssqlite3.hh"
#include "bind-dnssec.schema.sqlite3.sql.h"
#endif
StatBag S;
PacketCache PC;
using boost::scoped_ptr;
namespace po = boost::program_options;
po::variables_map g_vm;
string s_programname="pdns";
namespace {
bool g_verbose;
}
ArgvMap &arg()
{
static ArgvMap arg;
return arg;
}
string humanTime(time_t t)
{
char ret[256];
struct tm tm;
localtime_r(&t, &tm);
strftime(ret, sizeof(ret)-1, "%c", &tm); // %h:%M %Y-%m-%d
return ret;
}
static void algorithm2name(uint8_t algo, string &name) {
switch(algo) {
case 0:
name = "Reserved"; return;
case 1:
name = "RSAMD5"; return;
case 2:
name = "DH"; return;
case 3:
name = "DSA"; return;
case 4:
name = "ECC"; return;
case 5:
name = "RSASHA1"; return;
case 6:
name = "DSA-NSEC3-SHA1"; return;
case 7:
name = "RSASHA1-NSEC3-SHA1"; return;
case 8:
name = "RSASHA256"; return;
case 9:
name = "Reserved"; return;
case 10:
name = "RSASHA512"; return;
case 11:
name = "Reserved"; return;
case 12:
name = "ECC-GOST"; return;
case 13:
name = "ECDSAP256SHA256"; return;
case 14:
name = "ECDSAP384SHA384"; return;
case 252:
name = "INDIRECT"; return;
case 253:
name = "PRIVATEDNS"; return;
case 254:
name = "PRIVATEOID"; return;
default:
name = "Unallocated/Reserved"; return;
}
};
static int shorthand2algorithm(const string &algorithm)
{
if (!algorithm.compare("rsamd5")) return 1;
if (!algorithm.compare("dh")) return 2;
if (!algorithm.compare("dsa")) return 3;
if (!algorithm.compare("ecc")) return 4;
if (!algorithm.compare("rsasha1")) return 5;
if (!algorithm.compare("rsasha256")) return 8;
if (!algorithm.compare("rsasha512")) return 10;
if (!algorithm.compare("gost")) return 12;
if (!algorithm.compare("ecdsa256")) return 13;
if (!algorithm.compare("ecdsa384")) return 14;
if (!algorithm.compare("ed25519")) return 250;
return -1;
}
void loadMainConfig(const std::string& configdir)
{
::arg().set("config-dir","Location of configuration directory (pdns.conf)")=configdir;
::arg().set("pipebackend-abi-version","Version of the pipe backend ABI")="1";
::arg().set("default-ttl","Seconds a result is valid if not set otherwise")="3600";
::arg().set("launch","Which backends to launch");
::arg().set("dnssec","if we should do dnssec")="true";
::arg().set("config-name","Name of this virtual configuration - will rename the binary image")=g_vm["config-name"].as<string>();
::arg().setCmd("help","Provide a helpful message");
//::arg().laxParse(argc,argv);
if(::arg().mustDo("help")) {
cout<<"syntax:"<<endl<<endl;
cout<<::arg().helpstring(::arg()["help"])<<endl;
exit(0);
}
if(::arg()["config-name"]!="")
s_programname+="-"+::arg()["config-name"];
string configname=::arg()["config-dir"]+"/"+s_programname+".conf";
cleanSlashes(configname);
::arg().set("default-ksk-algorithms","Default KSK algorithms")="rsasha256";
::arg().set("default-ksk-size","Default KSK size (0 means default)")="0";
::arg().set("default-zsk-algorithms","Default ZSK algorithms")="rsasha256";
::arg().set("default-zsk-size","Default KSK size (0 means default)")="0";
::arg().set("max-ent-entries", "Maximum number of empty non-terminals in a zone")="100000";
::arg().set("module-dir","Default directory for modules")=LIBDIR;
::arg().set("entropy-source", "If set, read entropy from this file")="/dev/urandom";
::arg().setSwitch("direct-dnskey","Fetch DNSKEY RRs from backend during DNSKEY synthesis")="no";
::arg().laxFile(configname.c_str());
BackendMakers().launch(::arg()["launch"]); // vrooooom!
::arg().laxFile(configname.c_str());
//cerr<<"Backend: "<<::arg()["launch"]<<", '" << ::arg()["gmysql-dbname"] <<"'" <<endl;
S.declare("qsize-q","Number of questions waiting for database attention");
S.declare("deferred-cache-inserts","Amount of cache inserts that were deferred because of maintenance");
S.declare("deferred-cache-lookup","Amount of cache lookups that were deferred because of maintenance");
S.declare("query-cache-hit","Number of hits on the query cache");
S.declare("query-cache-miss","Number of misses on the query cache");
::arg().set("max-cache-entries", "Maximum number of cache entries")="1000000";
::arg().set("recursor","If recursion is desired, IP address of a recursing nameserver")="no";
::arg().set("recursive-cache-ttl","Seconds to store packets for recursive queries in the PacketCache")="10";
::arg().set("cache-ttl","Seconds to store packets in the PacketCache")="20";
::arg().set("negquery-cache-ttl","Seconds to store negative query results in the QueryCache")="60";
::arg().set("query-cache-ttl","Seconds to store query results in the QueryCache")="20";
::arg().set("default-soa-name","name to insert in the SOA record if none set in the backend")="a.misconfigured.powerdns.server";
::arg().set("default-soa-mail","mail address to insert in the SOA record if none set in the backend")="";
::arg().set("soa-refresh-default","Default SOA refresh")="10800";
::arg().set("soa-retry-default","Default SOA retry")="3600";
::arg().set("soa-expire-default","Default SOA expire")="604800";
::arg().setSwitch("query-logging","Hint backends that queries should be logged")="no";
::arg().set("soa-minimum-ttl","Default SOA minimum ttl")="3600";
UeberBackend::go();
}
// irritatingly enough, rectifyZone needs its own ueberbackend and can't therefore benefit from transactions outside its scope
// I think this has to do with interlocking transactions between B and DK, but unsure.
bool rectifyZone(DNSSECKeeper& dk, const std::string& zone)
{
if(dk.isPresigned(zone)){
cerr<<"Rectify presigned zone '"<<zone<<"' is not allowed/necessary."<<endl;
return false;
}
UeberBackend B("default");
bool doTransaction=true; // but see above
SOAData sd;
sd.db = (DNSBackend*)-1;
if(!B.getSOA(zone, sd)) {
cerr<<"No SOA known for '"<<zone<<"', is such a zone in the database?"<<endl;
return false;
}
sd.db->list(zone, sd.domain_id);
DNSResourceRecord rr;
set<string> qnames, nsset, dsnames, insnonterm, delnonterm;
map<string,bool> nonterm;
bool doent=true;
while(sd.db->get(rr)) {
if (rr.qtype.getCode())
{
qnames.insert(rr.qname);
if(rr.qtype.getCode() == QType::NS && !pdns_iequals(rr.qname, zone))
nsset.insert(rr.qname);
if(rr.qtype.getCode() == QType::DS)
dsnames.insert(rr.qname);
}
else
if(doent)
delnonterm.insert(rr.qname);
}
NSEC3PARAMRecordContent ns3pr;
bool narrow;
bool haveNSEC3=dk.getNSEC3PARAM(zone, &ns3pr, &narrow);
bool isOptOut=(haveNSEC3 && ns3pr.d_flags);
if(sd.db->doesDNSSEC())
{
if(!haveNSEC3)
cerr<<"Adding NSEC ordering information "<<endl;
else if(!narrow) {
if(!isOptOut)
cerr<<"Adding NSEC3 hashed ordering information for '"<<zone<<"'"<<endl;
else
cerr<<"Adding NSEC3 opt-out hashed ordering information for '"<<zone<<"'"<<endl;
} else
cerr<<"Erasing NSEC3 ordering since we are narrow, only setting 'auth' fields"<<endl;
}
else
cerr<<"Non DNSSEC zone, only adding empty non-terminals"<<endl;
if(doTransaction)
sd.db->startTransaction("", -1);
bool realrr=true;
string hashed;
uint32_t maxent = ::arg().asNum("max-ent-entries");
dononterm:;
BOOST_FOREACH(const string& qname, qnames)
{
bool auth=true;
string shorter(qname);
if(realrr) {
do {
if(nsset.count(shorter)) {
auth=false;
break;
}
} while(chopOff(shorter));
}
if(haveNSEC3)
{
if(!narrow && (realrr || !isOptOut || nonterm.find(qname)->second)) {
hashed=toBase32Hex(hashQNameWithSalt(ns3pr.d_iterations, ns3pr.d_salt, qname));
if(g_verbose)
cerr<<"'"<<qname<<"' -> '"<< hashed <<"'"<<endl;
sd.db->updateDNSSECOrderAndAuthAbsolute(sd.domain_id, qname, hashed, auth);
}
else {
if(!realrr)
auth=false;
sd.db->nullifyDNSSECOrderNameAndUpdateAuth(sd.domain_id, qname, auth);
}
}
else // NSEC
{
sd.db->updateDNSSECOrderAndAuth(sd.domain_id, zone, qname, auth);
if (!realrr)
sd.db->nullifyDNSSECOrderNameAndUpdateAuth(sd.domain_id, qname, auth);
}
if(realrr)
{
if (dsnames.count(qname))
sd.db->setDNSSECAuthOnDsRecord(sd.domain_id, qname);
if (!auth || nsset.count(qname)) {
if(isOptOut)
sd.db->nullifyDNSSECOrderNameAndAuth(sd.domain_id, qname, "NS");
sd.db->nullifyDNSSECOrderNameAndAuth(sd.domain_id, qname, "A");
sd.db->nullifyDNSSECOrderNameAndAuth(sd.domain_id, qname, "AAAA");
}
if(doent)
{
shorter=qname;
while(!pdns_iequals(shorter, zone) && chopOff(shorter))
{
if(!qnames.count(shorter))
{
if(!(maxent))
{
cerr<<"Zone '"<<zone<<"' has too many empty non terminals."<<endl;
insnonterm.clear();
delnonterm.clear();
doent=false;
break;
}
if (!delnonterm.count(shorter) && !nonterm.count(shorter))
insnonterm.insert(shorter);
else
delnonterm.erase(shorter);
if (!nonterm.count(shorter)) {
nonterm.insert(pair<string, bool>(shorter, auth));
--maxent;
} else if (auth)
nonterm[shorter]=true;
}
}
}
}
}
if(realrr)
{
//cerr<<"Total: "<<nonterm.size()<<" Insert: "<<insnonterm.size()<<" Delete: "<<delnonterm.size()<<endl;
if(!insnonterm.empty() || !delnonterm.empty() || !doent)
{
sd.db->updateEmptyNonTerminals(sd.domain_id, zone, insnonterm, delnonterm, !doent);
}
if(doent)
{
realrr=false;
qnames.clear();
pair<string,bool> nt;
BOOST_FOREACH(nt, nonterm){
qnames.insert(nt.first);
}
goto dononterm;
}
}
if(doTransaction)
sd.db->commitTransaction();
return true;
}
void rectifyAllZones(DNSSECKeeper &dk)
{
UeberBackend B("default");
vector<DomainInfo> domainInfo;
B.getAllDomains(&domainInfo);
BOOST_FOREACH(DomainInfo di, domainInfo) {
cerr<<"Rectifying "<<di.zone<<": ";
rectifyZone(dk, di.zone);
}
cout<<"Rectified "<<domainInfo.size()<<" zones."<<endl;
}
int checkZone(DNSSECKeeper &dk, UeberBackend &B, const std::string& zone)
{
SOAData sd;
sd.db=(DNSBackend*)-1;
if(!B.getSOA(zone, sd)) {
cout<<"No SOA for zone '"<<zone<<"'"<<endl;
return -1;
}
bool presigned=dk.isPresigned(zone);
sd.db->list(zone, sd.domain_id);
DNSResourceRecord rr;
uint64_t numrecords=0, numerrors=0, numwarnings=0;
bool hasNsAtApex = false;
set<string> records, cnames, noncnames;
map<string, unsigned int> ttl;
ostringstream content;
pair<map<string, unsigned int>::iterator,bool> ret;
while(sd.db->get(rr)) {
if(!rr.qtype.getCode())
continue;
numrecords++;
if(rr.qtype.getCode() == QType::SOA) {
vector<string>parts;
stringtok(parts, rr.content);
ostringstream o;
o<<rr.content;
for(int pleft=parts.size(); pleft < 7; ++pleft) {
o<<" 0";
}
rr.content=o.str();
}
if(rr.qtype.getCode() == QType::MX || rr.qtype.getCode() == QType::SRV)
rr.content = lexical_cast<string>(rr.priority)+" "+rr.content;
if(rr.qtype.getCode() == QType::TXT && !rr.content.empty() && rr.content[0]!='"')
rr.content = "\""+rr.content+"\"";
try {
shared_ptr<DNSRecordContent> drc(DNSRecordContent::mastermake(rr.qtype.getCode(), 1, rr.content));
string tmp=drc->serialize(rr.qname);
tmp = drc->getZoneRepresentation();
if (rr.qtype.getCode() != QType::AAAA) {
if (!pdns_iequals(tmp, rr.content)) {
cout<<"[Warning] Parsed and original record content are not equal: "<<rr.qname<<" IN " <<rr.qtype.getName()<< " '" << rr.content<<"' (Content parsed as '"<<tmp<<"')"<<endl;
rr.content=tmp;
numwarnings++;
}
} else {
struct addrinfo hint, *res;
memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_INET6;
hint.ai_flags = AI_NUMERICHOST;
if(getaddrinfo(rr.content.c_str(), 0, &hint, &res)) {
cout<<"[Warning] Following record is not a valid IPv6 address: "<<rr.qname<<" IN " <<rr.qtype.getName()<< " '" << rr.content<<"'"<<endl;
numwarnings++;
} else
freeaddrinfo(res);
rr.content=tmp;
}
}
catch(std::exception& e)
{
cout<<"[Error] Following record had a problem: "<<rr.qname<<" IN " <<rr.qtype.getName()<< " " << rr.content<<endl;
cout<<"[Error] Error was: "<<e.what()<<endl;
numerrors++;
continue;
}
if(!endsOn(rr.qname, zone)) {
cout<<"[Warning] Record '"<<rr.qname<<" IN "<<rr.qtype.getName()<<" "<<rr.content<<"' in zone '"<<zone<<"' is out-of-zone."<<endl;
numwarnings++;
continue;
}
content.str("");
content<<rr.qname<<" "<<rr.qtype.getName()<<" "<<rr.content;
if (records.count(toLower(content.str()))) {
cout<<"[Error] Duplicate record found in rrset: '"<<rr.qname<<" IN "<<rr.qtype.getName()<<" "<<rr.content<<"'"<<endl;
numerrors++;
continue;
} else
records.insert(toLower(content.str()));
content.str("");
content<<rr.qname<<" "<<rr.qtype.getName();
ret = ttl.insert(pair<string, unsigned int>(toLower(content.str()), rr.ttl));
if (ret.second == false && ret.first->second != rr.ttl) {
cout<<"[Error] TTL mismatch in rrset: '"<<rr.qname<<" IN " <<rr.qtype.getName()<<" "<<rr.content<<"' ("<<ret.first->second<<" != "<<rr.ttl<<")"<<endl;
numerrors++;
continue;
}
if(pdns_iequals(rr.qname, zone)) {
if (rr.qtype.getCode() == QType::NS) {
hasNsAtApex=true;
} else if (rr.qtype.getCode() == QType::DS) {
cout<<"[Warning] DS at apex in zone '"<<zone<<"', should no be here."<<endl;
numwarnings++;
}
} else {
if (rr.qtype.getCode() == QType::SOA) {
cout<<"[Error] SOA record not at apex '"<<rr.qname<<" IN "<<rr.qtype.getName()<<" "<<rr.content<<"' in zone '"<<zone<<"'"<<endl;
numerrors++;
continue;
} else if (rr.qtype.getCode() == QType::DNSKEY) {
cout<<"[Warning] DNSKEY record not at apex '"<<rr.qname<<" IN "<<rr.qtype.getName()<<" "<<rr.content<<"' in zone '"<<zone<<"', should not be here."<<endl;
numwarnings++;
}
}
if (rr.qtype.getCode() == QType::CNAME) {
if (!cnames.count(toLower(rr.qname)))
cnames.insert(toLower(rr.qname));
else {
cout<<"[Error] Duplicate CNAME found at '"<<rr.qname<<"'"<<endl;
numerrors++;
continue;
}
} else {
if (rr.qtype.getCode() == QType::RRSIG) {
if(!presigned) {
cout<<"[Error] RRSIG found at '"<<rr.qname<<"' in non-presigned zone. These do not belong in the database."<<endl;
numerrors++;
continue;
}
} else
noncnames.insert(toLower(rr.qname));
}
if(rr.qtype.getCode() == QType::NSEC || rr.qtype.getCode() == QType::NSEC3)
{
cout<<"[Error] NSEC or NSEC3 found at '"<<rr.qname<<"'. These do not belong in the database."<<endl;
numerrors++;
continue;
}
if(!presigned && rr.qtype.getCode() == QType::DNSKEY)
{
if(::arg().mustDo("direct-dnskey"))
{
if(rr.ttl != sd.default_ttl)
{
cout<<"[Warning] DNSKEY TTL of "<<rr.ttl<<" at '"<<rr.qname<<"' differs from SOA minimum of "<<sd.default_ttl<<endl;
numwarnings++;
}
}
else
{
cout<<"[Warning] DNSKEY at '"<<rr.qname<<"' in non-presigned zone will mostly be ignored and can cause problems."<<endl;
numwarnings++;
}
}
if(rr.qtype.getCode() == QType::URL || rr.qtype.getCode() == QType::MBOXFW) {
cout<<"[Error] The recordtype "<<rr.qtype.getName()<<" for record '"<<rr.qname<<"' is no longer supported."<<endl;
numerrors++;
continue;
}
if (rr.qname[rr.qname.size()-1] == '.') {
cout<<"[Error] Record '"<<rr.qname<<"' has a trailing dot. PowerDNS will ignore this record!"<<endl;
numerrors++;
}
if ( (rr.qtype.getCode() == QType::NS || rr.qtype.getCode() == QType::SRV || rr.qtype.getCode() == QType::MX || rr.qtype.getCode() == QType::CNAME) &&
rr.content[rr.content.size()-1] == '.') {
cout<<"[Warning] The record "<<rr.qname<<" with type "<<rr.qtype.getName()<<" has a trailing dot in the content ("<<rr.content<<"). Your backend might not work well with this."<<endl;
numwarnings++;
}
if(rr.auth == 0 && rr.qtype.getCode()!=QType::NS && rr.qtype.getCode()!=QType::A && rr.qtype.getCode()!=QType::AAAA)
{
cout<<"[Error] Following record is auth=0, run pdnssec rectify-zone?: "<<rr.qname<<" IN " <<rr.qtype.getName()<< " " << rr.content<<endl;
numerrors++;
}
}
for(set<string>::const_iterator i = cnames.begin(); i != cnames.end(); i++) {
if (noncnames.find(*i) != noncnames.end()) {
cout<<"[Error] CNAME "<<*i<<" found, but other records with same label exist."<<endl;
numerrors++;
}
}
if(!hasNsAtApex) {
cout<<"[Error] No NS record at zone apex in zone '"<<zone<<"'"<<endl;
numerrors++;
}
cout<<"Checked "<<numrecords<<" records of '"<<zone<<"', "<<numerrors<<" errors, "<<numwarnings<<" warnings."<<endl;
return numerrors;
}
int checkAllZones(DNSSECKeeper &dk)
{
UeberBackend B("default");
vector<DomainInfo> domainInfo;
B.getAllDomains(&domainInfo);
int errors=0;
BOOST_FOREACH(DomainInfo di, domainInfo) {
if (checkZone(dk, B, di.zone) > 0)
errors++;
}
cout<<"Checked "<<domainInfo.size()<<" zones, "<<errors<<" had errors."<<endl;
return 0;
}
int increaseSerial(const string& zone, DNSSECKeeper &dk)
{
UeberBackend B("default");
SOAData sd;
sd.db=(DNSBackend*)-1;
if(!B.getSOA(zone, sd)) {
cout<<"No SOA for zone '"<<zone<<"'"<<endl;
return -1;
}
string soaEditKind;
dk.getFromMeta(zone, "SOA-EDIT", soaEditKind);
sd.db->lookup(QType(QType::SOA), zone);
vector<DNSResourceRecord> rrs;
DNSResourceRecord rr;
while (sd.db->get(rr)) {
if (rr.qtype.getCode() == QType::SOA)
rrs.push_back(rr);
}
if (rrs.size() > 1) {
cerr<<rrs.size()<<" SOA records found for "<<zone<<"!"<<endl;
return -1;
}
if (rrs.size() < 1) {
cerr<<zone<<" not found!"<<endl;
}
if (soaEditKind.empty()) {
sd.serial++;
}
else if(pdns_iequals(soaEditKind,"INCREMENT-WEEKS")) {
sd.serial++;
}
else if(pdns_iequals(soaEditKind,"INCEPTION-INCREMENT")) {
uint32_t today_serial = localtime_format_YYYYMMDDSS(time(NULL), 1);
if (sd.serial < today_serial) {
sd.serial = today_serial;
}
else {
sd.serial++;
}
}
else {
sd.serial = calculateEditSOA(sd, soaEditKind) + 1;
}
rrs[0].content = serializeSOAData(sd);
if (! sd.db->replaceRRSet(sd.domain_id, zone, rr.qtype, rrs)) {
cerr<<"Backend did not replace SOA record. Backend might not support this operation."<<endl;
return -1;
}
cout<<"SOA serial for zone "<<zone<<" set to "<<sd.serial<<endl;
return 0;
}
int deleteZone(const string &zone) {
UeberBackend B;
DomainInfo di;
if (! B.getDomainInfo(zone, di)) {
cerr<<"Domain '"<<zone<<"' not found!";
return 1;
}
if(di.backend->deleteDomain(zone))
return 0;
cerr<<"Failed to delete domain '"+zone+"'"<<endl;;
return 1;
}
int listAllZones(const string &type) {
scoped_ptr<UeberBackend> B(new UeberBackend("default"));
vector<DomainInfo> domains;
B->getAllDomains(&domains);
int kindFilter = -1;
if (type.size()) {
if (toUpper(type) == "MASTER")
kindFilter = 0;
else if (toUpper(type) == "SLAVE")
kindFilter = 1;
else if (toUpper(type) == "NATIVE")
kindFilter = 2;
}
int count = 0;
for (vector<DomainInfo>::const_iterator di=domains.begin(); di != domains.end(); di++) {
if (di->kind == kindFilter || kindFilter == -1) {
cout<<di->zone<<endl;
count++;
}
}
if (kindFilter != -1)
cout<<type<<" zonecount:"<<count<<endl;
else
cout<<"All zonecount:"<<count<<endl;
return 0;
}
void testAlgorithm(int algo)
{
DNSCryptoKeyEngine::testOne(algo);
}
void testAlgorithms()
{
DNSCryptoKeyEngine::testAll();
}
void testSpeed(DNSSECKeeper& dk, const string& zone, const string& remote, int cores)
{
DNSResourceRecord rr;
rr.qname="blah."+zone;
rr.qtype=QType::A;
rr.ttl=3600;
rr.auth=1;
rr.qclass = QClass::IN;
rr.d_place=DNSResourceRecord::ANSWER;
rr.priority=0;
UeberBackend db("key-only");
if ( ! db.backends.size() )
{
throw runtime_error("No backends available for DNSSEC key storage");
}
ChunkedSigningPipe csp(zone, 1, remote, cores);
vector<DNSResourceRecord> signatures;
uint32_t rnd;
unsigned char* octets = (unsigned char*)&rnd;
char tmp[25];
DTime dt;
dt.set();
for(unsigned int n=0; n < 100000; ++n) {
rnd = random();
snprintf(tmp, sizeof(tmp), "%d.%d.%d.%d",
octets[0], octets[1], octets[2], octets[3]);
rr.content=tmp;
snprintf(tmp, sizeof(tmp), "r-%u", rnd);
rr.qname=string(tmp)+"."+zone;
if(csp.submit(rr))
while(signatures = csp.getChunk(), !signatures.empty())
;
}
cerr<<"Flushing the pipe, "<<csp.d_signed<<" signed, "<<csp.d_queued<<" queued, "<<csp.d_outstanding<<" outstanding"<< endl;
cerr<<"Net speed: "<<csp.d_signed/ (dt.udiffNoReset()/1000000.0) << " sigs/s"<<endl;
while(signatures = csp.getChunk(true), !signatures.empty())
;
cerr<<"Done, "<<csp.d_signed<<" signed, "<<csp.d_queued<<" queued, "<<csp.d_outstanding<<" outstanding"<< endl;
cerr<<"Net speed: "<<csp.d_signed/ (dt.udiff()/1000000.0) << " sigs/s"<<endl;
}
void verifyCrypto(const string& zone)
{
ZoneParserTNG zpt(zone);
DNSResourceRecord rr;
DNSKEYRecordContent drc;
RRSIGRecordContent rrc;
DSRecordContent dsrc;
vector<shared_ptr<DNSRecordContent> > toSign;
string qname, apex;
dsrc.d_digesttype=0;
while(zpt.get(rr)) {
if(rr.qtype.getCode() == QType::DNSKEY) {
cerr<<"got DNSKEY!"<<endl;
apex=rr.qname;
drc = *dynamic_cast<DNSKEYRecordContent*>(DNSRecordContent::mastermake(QType::DNSKEY, 1, rr.content));
}
else if(rr.qtype.getCode() == QType::RRSIG) {
cerr<<"got RRSIG"<<endl;
rrc = *dynamic_cast<RRSIGRecordContent*>(DNSRecordContent::mastermake(QType::RRSIG, 1, rr.content));
}
else if(rr.qtype.getCode() == QType::DS) {
cerr<<"got DS"<<endl;
dsrc = *dynamic_cast<DSRecordContent*>(DNSRecordContent::mastermake(QType::DS, 1, rr.content));
}
else {
qname = rr.qname;
toSign.push_back(shared_ptr<DNSRecordContent>(DNSRecordContent::mastermake(rr.qtype.getCode(), 1, rr.content)));
}
}
string msg = getMessageForRRSET(qname, rrc, toSign);
cerr<<"Verify: "<<DNSCryptoKeyEngine::makeFromPublicKeyString(drc.d_algorithm, drc.d_key)->verify(msg, rrc.d_signature)<<endl;
if(dsrc.d_digesttype) {
cerr<<"Calculated DS: "<<apex<<" IN DS "<<makeDSFromDNSKey(apex, drc, dsrc.d_digesttype).getZoneRepresentation()<<endl;
cerr<<"Original DS: "<<apex<<" IN DS "<<dsrc.getZoneRepresentation()<<endl;
}
#if 0
DNSCryptoKeyEngine*key=DNSCryptoKeyEngine::makeFromISCString(drc, "Private-key-format: v1.2\n"
"Algorithm: 12 (ECC-GOST)\n"
"GostAsn1: MEUCAQAwHAYGKoUDAgITMBIGByqFAwICIwEGByqFAwICHgEEIgQg/9MiXtXKg9FDXDN/R9CmVhJDyuzRAIgh4tPwCu4NHIs=\n");
string resign=key->sign(hash);
cerr<<Base64Encode(resign)<<endl;
cerr<<"Verify: "<<DNSCryptoKeyEngine::makeFromPublicKeyString(drc.d_algorithm, drc.d_key)->verify(hash, resign)<<endl;
#endif
}
bool disableDNSSECOnZone(DNSSECKeeper& dk, const string& zone)
{
UeberBackend B("default");
DomainInfo di;
if (!B.getDomainInfo(zone, di)){
cerr << "No such zone in the database" << endl;
return false;
}
if(!dk.isSecuredZone(zone)) {
cerr<<"Zone is not secured"<<endl;
return false;
}
DNSSECKeeper::keyset_t keyset=dk.getKeys(zone);
if(keyset.empty()) {
cerr << "No keys for zone '"<<zone<<"'."<<endl;
}
else {
BOOST_FOREACH(DNSSECKeeper::keyset_t::value_type value, keyset) {
dk.deactivateKey(zone, value.second.id);
dk.removeKey(zone, value.second.id);
}
}
dk.unsetNSEC3PARAM(zone);
dk.unsetPresigned(zone);
return true;
}
bool showZone(DNSSECKeeper& dk, const std::string& zone)
{
UeberBackend B("default");
DomainInfo di;
std::vector<std::string> meta;
if (!B.getDomainInfo(zone, di)){
cerr << "No such zone in the database" << endl;
return false;
}
if(!dk.isSecuredZone(zone)) {
cerr<<"Zone is not actively secured"<<endl;
}
NSEC3PARAMRecordContent ns3pr;
bool narrow;
bool haveNSEC3=dk.getNSEC3PARAM(zone, &ns3pr, &narrow);
DNSSECKeeper::keyset_t keyset=dk.getKeys(zone);
if (B.getDomainMetadata(zone, "TSIG-ALLOW-AXFR", meta) && meta.size() > 0) {
cerr << "Zone has following allowed TSIG key(s): " << boost::join(meta, ",") << endl;
}
meta.clear();
if (B.getDomainMetadata(zone, "AXFR-MASTER-TSIG", meta) && meta.size() > 0) {
cerr << "Zone uses following TSIG key(s): " << boost::join(meta, ",") << endl;
}
cout <<"Zone is " << (dk.isPresigned(zone) ? "" : "not ") << "presigned"<<endl;
if(keyset.empty()) {
cerr << "No keys for zone '"<<zone<<"'."<<endl;
}
else {
if(!haveNSEC3)
cout<<"Zone has NSEC semantics"<<endl;
else
cout<<"Zone has " << (narrow ? "NARROW " : "") <<"hashed NSEC3 semantics, configuration: "<<ns3pr.getZoneRepresentation()<<endl;
cout << "keys: "<<endl;
BOOST_FOREACH(DNSSECKeeper::keyset_t::value_type value, keyset) {
string algname;
algorithm2name(value.first.d_algorithm, algname);
cout<<"ID = "<<value.second.id<<" ("<<(value.second.keyOrZone ? "KSK" : "ZSK")<<"), tag = "<<value.first.getDNSKEY().getTag();
cout<<", algo = "<<(int)value.first.d_algorithm<<", bits = "<<value.first.getKey()->getBits()<<"\tActive: "<<value.second.active<< " ( " + algname + " ) "<<endl;
if(value.second.keyOrZone || ::arg().mustDo("direct-dnskey") || g_verbose)
cout<<(value.second.keyOrZone ? "KSK" : "ZSK")<<" DNSKEY = "<<zone<<" IN DNSKEY "<< value.first.getDNSKEY().getZoneRepresentation() << " ; ( " + algname + " )" << endl;
if(value.second.keyOrZone || g_verbose) {
cout<<"DS = "<<zone<<" IN DS "<<makeDSFromDNSKey(zone, value.first.getDNSKEY(), 1).getZoneRepresentation() << " ; ( SHA1 digest )" << endl;
cout<<"DS = "<<zone<<" IN DS "<<makeDSFromDNSKey(zone, value.first.getDNSKEY(), 2).getZoneRepresentation() << " ; ( SHA256 digest )" << endl;
try {
string output=makeDSFromDNSKey(zone, value.first.getDNSKEY(), 3).getZoneRepresentation();
cout<<"DS = "<<zone<<" IN DS "<< output << " ; ( GOST R 34.11-94 digest )" << endl;
}
catch(...)
{
}
try {
string output=makeDSFromDNSKey(zone, value.first.getDNSKEY(), 4).getZoneRepresentation();
cout<<"DS = "<<zone<<" IN DS "<< output << " ; ( SHA-384 digest )" << endl;
}
catch(...)
{
}
cout<<endl;
}
}
}
return true;
}
bool secureZone(DNSSECKeeper& dk, const std::string& zone)
{
// parse attribute
vector<string> k_algos;
vector<string> z_algos;
int k_size;
int z_size;
stringtok(k_algos, ::arg()["default-ksk-algorithms"], " ,");
k_size = ::arg().asNum("default-ksk-size");
stringtok(z_algos, ::arg()["default-zsk-algorithms"], " ,");
z_size = ::arg().asNum("default-zsk-size");
if (k_size < 0) {
throw runtime_error("KSK key size must be equal to or greater than 0");
}
if (k_algos.size() < 1) {
throw runtime_error("No algorithm(s) given for KSK");
}
if (z_size < 0) {
throw runtime_error("ZSK key size must be equal to or greater than 0");
}
if (z_algos.size() < 1) {
throw runtime_error("No algorithm(s) given for ZSK");
}
if(dk.isSecuredZone(zone)) {
cerr << "Zone '"<<zone<<"' already secure, remove keys with pdnssec remove-zone-key if needed"<<endl;
return false;
}
DomainInfo di;
UeberBackend B("default");
if(!B.getDomainInfo(zone, di) || !di.backend) { // di.backend and B are mostly identical
cout<<"Can't find a zone called '"<<zone<<"'"<<endl;
return false;
}
if(di.kind == DomainInfo::Slave)
{
cout<<"Warning! This is a slave domain! If this was a mistake, please run"<<endl;
cout<<"pdnssec disable-dnssec "<<zone<<" right now!"<<endl;
}
if (k_size)
cout << "Securing zone with " << k_algos[0] << " algorithm with key size " << k_size << endl;
else
cout << "Securing zone with " << k_algos[0] << " algorithm with default key size" << endl;
// run secure-zone with first default algorith, then add keys
if(!dk.secureZone(zone, shorthand2algorithm(k_algos[0]), k_size)) {
cerr<<"No backend was able to secure '"<<zone<<"', most likely because no DNSSEC"<<endl;
cerr<<"capable backends are loaded, or because the backends have DNSSEC disabled."<<endl;
cerr<<"For the Generic SQL backends, set the 'gsqlite3-dnssec', 'gmysql-dnssec' or"<<endl;
cerr<<"'gpgsql-dnssec' flag. Also make sure the schema has been updated for DNSSEC!"<<endl;
return false;
}
if(!dk.isSecuredZone(zone)) {
cerr<<"Failed to secure zone. Is your backend dnssec enabled? (set "<<endl;
cerr<<"gsqlite3-dnssec, or gmysql-dnssec etc). Check this first."<<endl;
cerr<<"If you run with the BIND backend, make sure you have configured"<<endl;
cerr<<"it to use DNSSEC with 'bind-dnssec-db=/path/fname' and"<<endl;
cerr<<"'pdnssec create-bind-db /path/fname'!"<<endl;
return false;
}
DNSSECKeeper::keyset_t zskset=dk.getKeys(zone, false);
if(!zskset.empty()) {
cerr<<"There were ZSKs already for zone '"<<zone<<"', no need to add more"<<endl;
return false;
}
for(vector<string>::iterator i = k_algos.begin()+1; i != k_algos.end(); i++)
dk.addKey(zone, true, shorthand2algorithm(*i), k_size, true); // obvious errors will have been caught above
BOOST_FOREACH(string z_algo, z_algos)
{
int algo = shorthand2algorithm(z_algo);
dk.addKey(zone, false, algo, z_size);
}
// rectifyZone(dk, zone);
// showZone(dk, zone);
cout<<"Zone "<<zone<<" secured"<<endl;
return true;
}
void testSchema(DNSSECKeeper& dk, const std::string& zone)
{
cout<<"Note: test-schema will try to create the zone, but it will not remove it."<<endl;
cout<<"Please clean up after this."<<endl;
cout<<endl;
cout<<"Constructing UeberBackend"<<endl;
UeberBackend B("default");
cout<<"Picking first backend - if this is not what you want, edit launch line!"<<endl;
DNSBackend *db = B.backends[0];
cout<<"Creating slave domain "<<zone<<endl;
db->createSlaveDomain("127.0.0.1", zone, "", "_testschema");
cout<<"Slave domain created"<<endl;
DomainInfo di;
if(!B.getDomainInfo(zone, di) || !di.backend) { // di.backend and B are mostly identical
cout<<"Can't find domain we just created, aborting"<<endl;
return;
}
db=di.backend;
DNSResourceRecord rr, rrget;
cout<<"Starting transaction to feed records"<<endl;
db->startTransaction(zone, di.id);
rr.qtype=QType::SOA;
rr.qname=zone;
rr.ttl=86400;
rr.domain_id=di.id;
rr.auth=1;
rr.content="ns1.example.com. ahu.example.com. 2012081039 7200 3600 1209600 3600";
cout<<"Feeding SOA"<<endl;
db->feedRecord(rr);
rr.qtype=QType::TXT;