]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/pdnsutil.cc
Add some notes explaining why some validations are not relevant in the dnstap case.
[thirdparty/pdns.git] / pdns / pdnsutil.cc
CommitLineData
6177a176 1
870a0fe4
AT
2#ifdef HAVE_CONFIG_H
3#include "config.h"
4#endif
1d211b1b 5#include "dnsseckeeper.hh"
d3151289 6#include "dnssecinfra.hh"
1d211b1b 7#include "statbag.hh"
01fde57c 8#include "base32.hh"
ed3f8559 9#include "base64.hh"
fa8fd4d2 10
1d211b1b 11#include <boost/program_options.hpp>
8daea594 12#include <boost/assign/std/vector.hpp>
451ba512 13#include <boost/assign/list_of.hpp>
ac5298aa 14#include "tsigutils.hh"
20002664
BH
15#include "dnsbackend.hh"
16#include "ueberbackend.hh"
17#include "arguments.hh"
bf269e28
RG
18#include "auth-packetcache.hh"
19#include "auth-querycache.hh"
aa65a832 20#include "zoneparser-tng.hh"
ea937fd4 21#include "signingpipe.hh"
a56bc64d 22#include "dns_random.hh"
5d5d8c2e 23#include "ipcipher.hh"
a0a6cb58 24#include <fstream>
c2e0881c 25#include <termios.h> //termios, TCSANOW, ECHO, ICANON
04c74848 26#include "opensslsigners.hh"
d4f29089
KM
27#ifdef HAVE_LIBSODIUM
28#include <sodium.h>
29#endif
a2b0e9b5
KM
30#ifdef HAVE_SQLITE3
31#include "ssqlite3.hh"
fd9f80de 32#include "bind-dnssec.schema.sqlite3.sql.h"
a2b0e9b5 33#endif
49449751 34
20002664 35StatBag S;
bf269e28
RG
36AuthPacketCache PC;
37AuthQueryCache QC;
1d211b1b 38
1d211b1b
BH
39namespace po = boost::program_options;
40po::variables_map g_vm;
41
39a8b5c0 42string s_programname="pdns";
20002664 43
b3ce3dec 44namespace {
b8572438 45 bool g_verbose;
49449751
BH
46}
47
20002664
BH
48ArgvMap &arg()
49{
50 static ArgvMap arg;
51 return arg;
52}
53
1d211b1b
BH
54string humanTime(time_t t)
55{
56 char ret[256];
57 struct tm tm;
58 localtime_r(&t, &tm);
59 strftime(ret, sizeof(ret)-1, "%c", &tm); // %h:%M %Y-%m-%d
60 return ret;
61}
62
7d9dcde0 63void loadMainConfig(const std::string& configdir)
20002664 64{
7d9dcde0 65 ::arg().set("config-dir","Location of configuration directory (pdns.conf)")=configdir;
f2e7d77b 66 ::arg().set("default-ttl","Seconds a result is valid if not set otherwise")="3600";
20002664 67 ::arg().set("launch","Which backends to launch");
6dfa0aa0 68 ::arg().set("dnssec","if we should do dnssec")="true";
4f6cf113 69 ::arg().set("config-name","Name of this virtual configuration - will rename the binary image")=g_vm["config-name"].as<string>();
20002664 70 ::arg().setCmd("help","Provide a helpful message");
c524989b 71 ::arg().set("load-modules","Load this module - supply absolute or relative path")="";
20002664
BH
72 //::arg().laxParse(argc,argv);
73
74 if(::arg().mustDo("help")) {
ff5ba4f9
WA
75 cout<<"syntax:"<<endl<<endl;
76 cout<<::arg().helpstring(::arg()["help"])<<endl;
77 exit(0);
20002664
BH
78 }
79
488bcb39 80 if(::arg()["config-name"]!="")
20002664
BH
81 s_programname+="-"+::arg()["config-name"];
82
83 string configname=::arg()["config-dir"]+"/"+s_programname+".conf";
84 cleanSlashes(configname);
36758d25 85
542febb3 86 ::arg().set("resolver","Use this resolver for ALIAS and the internal stub resolver")="no";
28080ce6 87 ::arg().set("default-ksk-algorithm","Default KSK algorithm")="ecdsa256";
36758d25 88 ::arg().set("default-ksk-size","Default KSK size (0 means default)")="0";
28080ce6 89 ::arg().set("default-zsk-algorithm","Default ZSK algorithm")="";
92bdc094 90 ::arg().set("default-zsk-size","Default ZSK size (0 means default)")="0";
4192773a
KM
91 ::arg().set("default-soa-edit","Default SOA-EDIT value")="";
92 ::arg().set("default-soa-edit-signed","Default SOA-EDIT value for signed zones")="";
b5baefaf 93 ::arg().set("max-ent-entries", "Maximum number of empty non-terminals in a zone")="100000";
0949b8ae 94 ::arg().set("module-dir","Default directory for modules")=PKGLIBDIR;
a56bc64d 95 ::arg().set("entropy-source", "If set, read entropy from this file")="/dev/urandom";
0f310932 96 ::arg().setSwitch("query-logging","Hint backends that queries should be logged")="no";
e509229b 97 ::arg().set("loglevel","Amount of logging. Higher is more.")="3";
16d72778 98 ::arg().setSwitch("direct-dnskey","Fetch DNSKEY, CDS and CDNSKEY RRs from backend during DNSKEY or CDS/CDNSKEY synthesis")="no";
28b66a94 99 ::arg().set("max-nsec3-iterations","Limit the number of NSEC3 hash iterations")="500"; // RFC5155 10.3
bba84134 100 ::arg().set("max-signature-cache-entries", "Maximum number of signatures cache entries")="";
e97cb679 101 ::arg().set("rng", "Specify random number generator to use. Valid values are auto,sodium,openssl,getrandom,arc4random,urandom.")="auto";
966828ac 102 ::arg().laxFile(configname.c_str());
12a92688 103
d4168b30
CHB
104 if(!::arg()["load-modules"].empty()) {
105 vector<string> modules;
106
107 stringtok(modules,::arg()["load-modules"], ", ");
108 if (!UeberBackend::loadModules(modules, ::arg()["module-dir"])) {
109 exit(1);
110 }
111 }
c524989b 112
e6a9dde5 113 g_log.toConsole(Logger::Error); // so we print any errors
20002664 114 BackendMakers().launch(::arg()["launch"]); // vrooooom!
e509229b 115 if(::arg().asNum("loglevel") >= 3) // so you can't kill our errors
488bcb39 116 g_log.toConsole((Logger::Urgency)::arg().asNum("loglevel"));
3f3fa13e 117
9abd98d3 118 //cerr<<"Backend: "<<::arg()["launch"]<<", '" << ::arg()["gmysql-dbname"] <<"'" <<endl;
20002664
BH
119
120 S.declare("qsize-q","Number of questions waiting for database attention");
488bcb39 121
20002664 122 ::arg().set("max-cache-entries", "Maximum number of cache entries")="1000000";
488bcb39 123 ::arg().set("cache-ttl","Seconds to store packets in the PacketCache")="20";
ec7f535c 124 ::arg().set("negquery-cache-ttl","Seconds to store negative query results in the QueryCache")="60";
488bcb39 125 ::arg().set("query-cache-ttl","Seconds to store query results in the QueryCache")="20";
da6a2926 126 ::arg().set("default-soa-name","name to insert in the SOA record if none set in the backend")="a.misconfigured.powerdns.server";
326a1978 127 ::arg().set("default-soa-mail","mail address to insert in the SOA record if none set in the backend")="";
20002664
BH
128 ::arg().set("soa-refresh-default","Default SOA refresh")="10800";
129 ::arg().set("soa-retry-default","Default SOA retry")="3600";
130 ::arg().set("soa-expire-default","Default SOA expire")="604800";
488bcb39 131 ::arg().set("soa-minimum-ttl","Default SOA minimum ttl")="3600";
c2e972e8 132 ::arg().set("chroot","Switch to this chroot jail")="";
030850a9
RG
133 ::arg().set("dnssec-key-cache-ttl","Seconds to cache DNSSEC keys from the database")="30";
134 ::arg().set("domain-metadata-cache-ttl","Seconds to cache domain metadata from the database")="60";
12a92688 135
3b655a7a
PL
136 // Keep this line below all ::arg().set() statements
137 if (! ::arg().laxFile(configname.c_str()))
a524be6b 138 cerr<<"Warning: unable to read configuration file '"<<configname<<"': "<<strerror(errno)<<endl;
3b655a7a 139
7c3ee3dc
RG
140#ifdef HAVE_LIBSODIUM
141 if (sodium_init() == -1) {
142 cerr<<"Unable to initialize sodium crypto library"<<endl;
143 exit(99);
144 }
145#endif
7c3ee3dc 146 openssl_seed();
e97cb679
AT
147 /* init rng before chroot */
148 dns_random_init();
7c3ee3dc 149
c2e972e8
PL
150 if (!::arg()["chroot"].empty()) {
151 if (chroot(::arg()["chroot"].c_str())<0 || chdir("/") < 0) {
152 cerr<<"Unable to chroot to '"+::arg()["chroot"]+"': "<<strerror (errno)<<endl;
153 exit(1);
154 }
155 }
156
20002664
BH
157 UeberBackend::go();
158}
159
64dea5c2 160bool rectifyZone(DNSSECKeeper& dk, const DNSName& zone, bool quiet = false)
20002664 161{
59102608 162 string output;
25b1ce13 163 string error;
59102608 164 bool ret = dk.rectifyZone(zone, error, output, true);
64dea5c2
CHB
165 if (!quiet || !ret) {
166 // When quiet, only print output if there was an error
167 if (!output.empty()) {
168 cerr<<output<<endl;
169 }
170 if (!ret && !error.empty()) {
171 cerr<<error<<endl;
172 }
9bd211e1 173 }
25b1ce13 174 return ret;
20002664
BH
175}
176
a0a6cb58 177void dbBench(const std::string& fname)
178{
179 ::arg().set("query-cache-ttl")="0";
180 ::arg().set("negquery-cache-ttl")="0";
181 UeberBackend B("default");
182
183 vector<string> domains;
184 if(!fname.empty()) {
185 ifstream ifs(fname.c_str());
186 if(!ifs) {
187 cerr<<"Could not open '"<<fname<<"' for reading domain names to query"<<endl;
188 }
189 string line;
190 while(getline(ifs,line)) {
191 trim(line);
192 domains.push_back(line);
193 }
194 }
195 if(domains.empty())
196 domains.push_back("powerdns.com");
197
198 int n=0;
d83581f8 199 DNSZoneRecord rr;
a0a6cb58 200 DTime dt;
201 dt.set();
202 unsigned int hits=0, misses=0;
203 for(; n < 10000; ++n) {
b51ef4f9 204 DNSName domain(domains[dns_random(domains.size())]);
a0a6cb58 205 B.lookup(QType(QType::NS), domain);
206 while(B.get(rr)) {
207 hits++;
208 }
335da0ba 209 B.lookup(QType(QType::A), DNSName(std::to_string(random()))+domain);
a0a6cb58 210 while(B.get(rr)) {
211 }
212 misses++;
213
214 }
215 cout<<0.001*dt.udiff()/n<<" millisecond/lookup"<<endl;
216 cout<<"Retrieved "<<hits<<" records, did "<<misses<<" queries which should have no match"<<endl;
217 cout<<"Packet cache reports: "<<S.read("query-cache-hit")<<" hits (should be 0) and "<<S.read("query-cache-miss") <<" misses"<<endl;
218}
219
64dea5c2 220bool rectifyAllZones(DNSSECKeeper &dk, bool quiet = false)
1325e8a2 221{
ba86110a 222 UeberBackend B("default");
1325e8a2 223 vector<DomainInfo> domainInfo;
64dea5c2 224 bool result = true;
1325e8a2 225
ba86110a 226 B.getAllDomains(&domainInfo);
ff05fd12 227 for(DomainInfo di : domainInfo) {
64dea5c2
CHB
228 if (!quiet) {
229 cerr<<"Rectifying "<<di.zone<<": ";
230 }
231 if (!rectifyZone(dk, di.zone, quiet)) {
232 result = false;
233 }
234 }
235 if (!quiet) {
236 cout<<"Rectified "<<domainInfo.size()<<" zones."<<endl;
1325e8a2 237 }
6a935fb1 238 return result;
1325e8a2
PD
239}
240
c2e0881c 241int checkZone(DNSSECKeeper &dk, UeberBackend &B, const DNSName& zone, const vector<DNSResourceRecord>* suppliedrecords=0)
5d2e58b0 242{
4d76766d
PL
243 uint64_t numerrors=0, numwarnings=0;
244
245 DomainInfo di;
246 try {
247 B.getDomainInfo(zone, di);
248 } catch(const PDNSException &e) {
249 if (di.kind == DomainInfo::Slave) {
250 cout<<"[Error] non-IP address for masters: "<<e.reason<<endl;
251 numerrors++;
252 }
253 }
254
5d2e58b0 255 SOAData sd;
79ba7763 256 if(!B.getSOAUncached(zone, sd)) {
904eb65d 257 cout<<"[Error] No SOA record present, or active, in zone '"<<zone<<"'"<<endl;
4d76766d
PL
258 numerrors++;
259 cout<<"Checked 0 records of '"<<zone<<"', "<<numerrors<<" errors, 0 warnings."<<endl;
fdc0adaf 260 return 1;
bb0bbee2 261 }
74bf221f
KM
262
263 NSEC3PARAMRecordContent ns3pr;
264 bool narrow = false;
265 bool haveNSEC3 = dk.getNSEC3PARAM(zone, &ns3pr, &narrow);
266 bool isOptOut=(haveNSEC3 && ns3pr.d_flags);
267
268 bool isSecure=dk.isSecuredZone(zone);
bb0bbee2 269 bool presigned=dk.isPresigned(zone);
ac3f3893
PL
270 vector<string> checkKeyErrors;
271 bool validKeys=dk.checkKeys(zone, &checkKeyErrors);
74bf221f 272
89c8b2ce
PL
273 if (haveNSEC3) {
274 if(isSecure && zone.wirelength() > 222) {
275 numerrors++;
276 cout<<"[Error] zone '" << zone << "' has NSEC3 semantics but is too long to have the hash prepended. Zone name is " << zone.wirelength() << " bytes long, whereas the maximum is 222 bytes." << endl;
277 }
278
279 vector<DNSBackend::KeyData> dbkeyset;
9c1c5d49 280 B.getDomainKeys(zone, dbkeyset);
89c8b2ce
PL
281
282 for(DNSBackend::KeyData& kd : dbkeyset) {
283 DNSKEYRecordContent dkrc;
284 shared_ptr<DNSCryptoKeyEngine>(DNSCryptoKeyEngine::makeFromISCString(dkrc, kd.content));
285
902c4e9c 286 if(dkrc.d_algorithm == DNSSECKeeper::RSASHA1) {
89c8b2ce
PL
287 cout<<"[Warning] zone '"<<zone<<"' has NSEC3 semantics, but the "<< (kd.active ? "" : "in" ) <<"active key with id "<<kd.id<<" has 'Algorithm: 5'. This should be corrected to 'Algorithm: 7' in the database (or NSEC3 should be disabled)."<<endl;
288 numwarnings++;
289 }
290 }
3155c04a 291 }
95ba91f7 292
8ca3ea33
RG
293 if (!validKeys) {
294 numerrors++;
0b34684a 295 cout<<"[Error] zone '" << zone << "' has at least one invalid DNS Private Key." << endl;
ac3f3893
PL
296 for (const auto &msg : checkKeyErrors) {
297 cout<<"\t"<<msg<<endl;
f59c4313 298 }
8ca3ea33
RG
299 }
300
95ba91f7 301 // Check for delegation in parent zone
21a3792f
KM
302 DNSName parent(zone);
303 while(parent.chopOff()) {
95ba91f7
KM
304 SOAData sd_p;
305 if(B.getSOAUncached(parent, sd_p)) {
306 bool ns=false;
d83581f8 307 DNSZoneRecord zr;
95ba91f7 308 B.lookup(QType(QType::ANY), zone, NULL, sd_p.domain_id);
d83581f8
CH
309 while(B.get(zr))
310 ns |= (zr.dr.d_type == QType::NS);
95ba91f7 311 if (!ns) {
0b34684a 312 cout<<"[Error] No delegation for zone '"<<zone<<"' in parent '"<<parent<<"'"<<endl;
95ba91f7
KM
313 numerrors++;
314 }
315 break;
316 }
317 }
318
319
1e2e9565 320 bool hasNsAtApex = false;
2e5f6225 321 set<DNSName> tlsas, cnames, noncnames, glue, checkglue;
2a8b9d77 322 set<pair<DNSName, QType> > checkOcclusion;
c2e0881c 323 set<string> recordcontents;
bb0bbee2 324 map<string, unsigned int> ttl;
f1b672ae
KM
325
326 ostringstream content;
bb0bbee2 327 pair<map<string, unsigned int>::iterator,bool> ret;
61717a51 328
c2e0881c 329 vector<DNSResourceRecord> records;
330 if(!suppliedrecords) {
2010ac95 331 DNSResourceRecord drr;
c889dde8 332 sd.db->list(zone, sd.domain_id, g_verbose);
2010ac95
RG
333 while(sd.db->get(drr)) {
334 records.push_back(drr);
c2e0881c 335 }
336 }
488bcb39 337 else
c2e0881c 338 records=*suppliedrecords;
95ba91f7 339
2a8b9d77 340 for(auto &rr : records) { // we modify this
2e5f6225
PL
341 if(rr.qtype.getCode() == QType::TLSA)
342 tlsas.insert(rr.qname);
84a0d08c
KM
343 if(rr.qtype.getCode() == QType::SOA) {
344 vector<string>parts;
345 stringtok(parts, rr.content);
346
347 ostringstream o;
348 o<<rr.content;
349 for(int pleft=parts.size(); pleft < 7; ++pleft) {
350 o<<" 0";
351 }
352 rr.content=o.str();
bb0bbee2
KM
353 }
354
77da04f6
KM
355 if(rr.qtype.getCode() == QType::TXT && !rr.content.empty() && rr.content[0]!='"')
356 rr.content = "\""+rr.content+"\"";
357
358 try {
359 shared_ptr<DNSRecordContent> drc(DNSRecordContent::mastermake(rr.qtype.getCode(), 1, rr.content));
360 string tmp=drc->serialize(rr.qname);
f21fc0aa 361 tmp = drc->getZoneRepresentation(true);
0f470360
KM
362 if (rr.qtype.getCode() != QType::AAAA) {
363 if (!pdns_iequals(tmp, rr.content)) {
657c0bf7 364 if(rr.qtype.getCode() == QType::SOA) {
365 tmp = drc->getZoneRepresentation(false);
366 }
367 if(!pdns_iequals(tmp, rr.content)) {
0b34684a 368 cout<<"[Warning] Parsed and original record content are not equal: "<<rr.qname<<" IN " <<rr.qtype.getName()<< " '" << rr.content<<"' (Content parsed as '"<<tmp<<"')"<<endl;
657c0bf7 369 numwarnings++;
370 }
0f470360
KM
371 }
372 } else {
1cac2653
KM
373 struct in6_addr tmpbuf;
374 if (inet_pton(AF_INET6, rr.content.c_str(), &tmpbuf) != 1 || rr.content.find('.') != string::npos) {
0b34684a 375 cout<<"[Warning] Following record is not a valid IPv6 address: "<<rr.qname<<" IN " <<rr.qtype.getName()<< " '" << rr.content<<"'"<<endl;
0f470360 376 numwarnings++;
1cac2653 377 }
77da04f6
KM
378 }
379 }
380 catch(std::exception& e)
381 {
0519f44f 382 cout<<"[Error] Following record had a problem: \""<<rr.qname<<" IN "<<rr.qtype.getName()<<" "<<rr.content<<"\""<<endl;
77da04f6
KM
383 cout<<"[Error] Error was: "<<e.what()<<endl;
384 numerrors++;
385 continue;
386 }
387
675fa24c 388 if(!rr.qname.isPartOf(zone)) {
0b34684a 389 cout<<"[Error] Record '"<<rr.qname<<" IN "<<rr.qtype.getName()<<" "<<rr.content<<"' in zone '"<<zone<<"' is out-of-zone."<<endl;
e977acfd 390 numerrors++;
a6230867
KM
391 continue;
392 }
393
f1b672ae 394 content.str("");
0b34684a 395 content<<rr.qname<<" "<<rr.qtype.getName()<<" "<<rr.content;
c2e0881c 396 if (recordcontents.count(toLower(content.str()))) {
0b34684a 397 cout<<"[Error] Duplicate record found in rrset: '"<<rr.qname<<" IN "<<rr.qtype.getName()<<" "<<rr.content<<"'"<<endl;
befcd641
KM
398 numerrors++;
399 continue;
400 } else
c2e0881c 401 recordcontents.insert(toLower(content.str()));
befcd641 402
f1b672ae 403 content.str("");
0b34684a 404 content<<rr.qname<<" "<<rr.qtype.getName();
63372f34
KM
405 if (rr.qtype.getCode() == QType::RRSIG) {
406 RRSIGRecordContent rrc(rr.content);
407 content<<" ("<<DNSRecordContent::NumberToType(rrc.d_type)<<")";
408 }
bb0bbee2
KM
409 ret = ttl.insert(pair<string, unsigned int>(toLower(content.str()), rr.ttl));
410 if (ret.second == false && ret.first->second != rr.ttl) {
0b34684a 411 cout<<"[Error] TTL mismatch in rrset: '"<<rr.qname<<" IN " <<rr.qtype.getName()<<" "<<rr.content<<"' ("<<ret.first->second<<" != "<<rr.ttl<<")"<<endl;
f1b672ae
KM
412 numerrors++;
413 continue;
414 }
415
675fa24c 416 if (isSecure && isOptOut && (rr.qname.countLabels() && rr.qname.getRawLabels()[0] == "*")) {
0b34684a
PL
417 cout<<"[Warning] wildcard record '"<<rr.qname<<" IN " <<rr.qtype.getName()<<" "<<rr.content<<"' is insecure"<<endl;
418 cout<<"[Info] Wildcard records in opt-out zones are insecure. Disable the opt-out flag for this zone to avoid this warning. Command: pdnsutil set-nsec3 "<<zone<<endl;
74bf221f
KM
419 numwarnings++;
420 }
421
675fa24c 422 if(rr.qname==zone) {
1e2e9565
KM
423 if (rr.qtype.getCode() == QType::NS) {
424 hasNsAtApex=true;
425 } else if (rr.qtype.getCode() == QType::DS) {
0b34684a 426 cout<<"[Warning] DS at apex in zone '"<<zone<<"', should not be here."<<endl;
1e2e9565
KM
427 numwarnings++;
428 }
429 } else {
430 if (rr.qtype.getCode() == QType::SOA) {
0b34684a 431 cout<<"[Error] SOA record not at apex '"<<rr.qname<<" IN "<<rr.qtype.getName()<<" "<<rr.content<<"' in zone '"<<zone<<"'"<<endl;
1e2e9565
KM
432 numerrors++;
433 continue;
434 } else if (rr.qtype.getCode() == QType::DNSKEY) {
0b34684a 435 cout<<"[Warning] DNSKEY record not at apex '"<<rr.qname<<" IN "<<rr.qtype.getName()<<" "<<rr.content<<"' in zone '"<<zone<<"', should not be here."<<endl;
1e2e9565 436 numwarnings++;
6056b9c8
PL
437 } else if (rr.qtype.getCode() == QType::NS) {
438 if (DNSName(rr.content).isPartOf(rr.qname)) {
439 checkglue.insert(DNSName(toLower(rr.content)));
440 }
4c024de2 441 checkOcclusion.insert({rr.qname, rr.qtype});
95ba91f7 442 } else if (rr.qtype.getCode() == QType::A || rr.qtype.getCode() == QType::AAAA) {
b873e23a 443 glue.insert(rr.qname);
4c024de2
PL
444 } else if (rr.qtype == QType::DNAME) {
445 checkOcclusion.insert({rr.qname, rr.qtype});
1e2e9565
KM
446 }
447 }
32cd4eb1
PL
448 if((rr.qtype.getCode() == QType::A || rr.qtype.getCode() == QType::AAAA) && !rr.qname.isWildcard() && !rr.qname.isHostname())
449 cout<<"[Info] "<<rr.qname.toString()<<" record for '"<<rr.qtype.getName()<<"' is not a valid hostname."<<endl;
450
451 // Check if the DNSNames that should be hostnames, are hostnames
97c8ea81
CHB
452 try {
453 checkHostnameCorrectness(rr);
454 } catch (const std::exception& e) {
455 cout << "[Warning] " << rr.qtype.getName() << " record in zone '" << zone << ": " << e.what() << endl;
456 numwarnings++;
277bec35
HL
457 }
458
61717a51 459 if (rr.qtype.getCode() == QType::CNAME) {
675fa24c
PD
460 if (!cnames.count(rr.qname))
461 cnames.insert(rr.qname);
c90d822b 462 else {
0b34684a 463 cout<<"[Error] Duplicate CNAME found at '"<<rr.qname<<"'"<<endl;
ca57aa98
KM
464 numerrors++;
465 continue;
466 }
c90d822b
KM
467 } else {
468 if (rr.qtype.getCode() == QType::RRSIG) {
3aa5b00f 469 if(!presigned) {
0b34684a 470 cout<<"[Error] RRSIG found at '"<<rr.qname<<"' in non-presigned zone. These do not belong in the database."<<endl;
c90d822b 471 numerrors++;
befcd641 472 continue;
c90d822b
KM
473 }
474 } else
675fa24c 475 noncnames.insert(rr.qname);
61717a51
PD
476 }
477
0aabca97
PD
478 if(rr.qtype.getCode() == QType::NSEC || rr.qtype.getCode() == QType::NSEC3)
479 {
0b34684a 480 cout<<"[Error] NSEC or NSEC3 found at '"<<rr.qname<<"'. These do not belong in the database."<<endl;
0aabca97
PD
481 numerrors++;
482 continue;
483 }
484
0a0f82c8 485 if(!presigned && rr.qtype.getCode() == QType::DNSKEY)
12a92688 486 {
cc8df07f 487 if(::arg().mustDo("direct-dnskey"))
12a92688 488 {
0a0f82c8 489 if(rr.ttl != sd.default_ttl)
12a92688 490 {
0b34684a 491 cout<<"[Warning] DNSKEY TTL of "<<rr.ttl<<" at '"<<rr.qname<<"' differs from SOA minimum of "<<sd.default_ttl<<endl;
c90d822b 492 numwarnings++;
12a92688
PD
493 }
494 }
0a0f82c8
KM
495 else
496 {
0b34684a 497 cout<<"[Warning] DNSKEY at '"<<rr.qname<<"' in non-presigned zone will mostly be ignored and can cause problems."<<endl;
0a0f82c8
KM
498 numwarnings++;
499 }
12a92688 500 }
035297ad 501 }
61717a51 502
675fa24c
PD
503 for(auto &i: cnames) {
504 if (noncnames.find(i) != noncnames.end()) {
0b34684a 505 cout<<"[Error] CNAME "<<i<<" found, but other records with same label exist."<<endl;
61717a51
PD
506 numerrors++;
507 }
508 }
509
2e5f6225
PL
510 for(const auto &i: tlsas) {
511 DNSName name = DNSName(i);
f48c35c0 512 name.trimToLabels(name.countLabels()-2);
2e5f6225
PL
513 if (cnames.find(name) == cnames.end() && noncnames.find(name) == noncnames.end()) {
514 // No specific record for the name in the TLSA record exists, this
515 // is already worth emitting a warning. Let's see if a wildcard exist.
516 cout<<"[Warning] ";
517 DNSName wcname(name);
518 wcname.chopOff();
519 wcname.prependRawLabel("*");
520 if (cnames.find(wcname) != cnames.end() || noncnames.find(wcname) != noncnames.end()) {
0b34684a 521 cout<<"A wildcard record exist for '"<<wcname<<"' and a TLSA record for '"<<i<<"'.";
2e5f6225 522 } else {
0b34684a 523 cout<<"No record for '"<<name<<"' exists, but a TLSA record for '"<<i<<"' does.";
2e5f6225
PL
524 }
525 numwarnings++;
0b34684a 526 cout<<" A query for '"<<name<<"' will yield an empty response. This is most likely a mistake, please create records for '"<<name<<"'."<<endl;
2e5f6225
PL
527 }
528 }
529
1e2e9565 530 if(!hasNsAtApex) {
0b34684a 531 cout<<"[Error] No NS record at zone apex in zone '"<<zone<<"'"<<endl;
1e2e9565
KM
532 numerrors++;
533 }
534
95ba91f7
KM
535 for(const auto &qname : checkglue) {
536 if (!glue.count(qname)) {
0b34684a 537 cout<<"[Warning] Missing glue for '"<<qname<<"' in zone '"<<zone<<"'"<<endl;
13a9aa3e 538 numwarnings++;
95ba91f7
KM
539 }
540 }
541
2a8b9d77
KM
542 for( const auto &qname : checkOcclusion ) {
543 for( const auto &rr : records ) {
544 if( qname.first == rr.qname && ((( rr.qtype == QType::NS || rr.qtype == QType::DS ) && qname.second == QType::NS ) || ( rr.qtype == QType::DNAME && qname.second == QType::DNAME ) ) ) {
aa9a6887 545 continue;
2a8b9d77
KM
546 }
547 if( rr.qname.isPartOf( qname.first ) ) {
548 if( qname.second == QType::DNAME || ( rr.qtype != QType::ENT && rr.qtype.getCode() != QType::A && rr.qtype.getCode() != QType::AAAA ) ) {
549 cout << "[Warning] '" << rr.qname << "|" << rr.qtype.getName() << "' in zone '" << zone << "' is occluded by a ";
550 if( qname.second == QType::NS ) {
551 cout << "delegation";
552 } else {
553 cout << "DNAME";
554 }
555 cout << " at '" << qname.first << "'" << endl;
556 numwarnings++;
4c024de2 557 }
6056b9c8
PL
558 }
559 }
560 }
561
aa9a6887
KM
562 bool ok, ds_ns, done;
563 for( const auto &rr : records ) {
564 ok = ( rr.auth == 1 );
565 ds_ns = false;
566 done = (suppliedrecords || !sd.db->doesDNSSEC());
567 for( const auto &qname : checkOcclusion ) {
568 if( qname.second == QType::NS ) {
569 if( qname.first == rr.qname ) {
570 ds_ns = true;
4c024de2 571 }
aa9a6887
KM
572 if ( done ) {
573 continue;
574 }
575 if( rr.auth == 0 ) {
576 if( rr.qname.isPartOf( qname.first ) && ( qname.first != rr.qname || rr.qtype != QType::DS ) ) {
577 ok = done = true;
578 }
579 if( rr.qtype == QType::ENT && qname.first.isPartOf( rr.qname ) ) {
580 ok = done = true;
581 }
582 } else if( rr.qname.isPartOf( qname.first ) && ( ( qname.first != rr.qname || rr.qtype != QType::DS ) || rr.qtype == QType::NS ) ) {
583 ok = false;
584 done = true;
4c024de2 585 }
6056b9c8
PL
586 }
587 }
aa9a6887
KM
588 if( ! ds_ns && rr.qtype.getCode() == QType::DS && rr.qname != zone ) {
589 cout << "[Warning] DS record without a delegation '" << rr.qname<<"'." << endl;
590 numwarnings++;
591 }
592 if( ! ok && ! suppliedrecords ) {
593 cout << "[Error] Following record is auth=" << rr.auth << ", run pdnsutil rectify-zone?: " << rr.qname << " IN " << rr.qtype.getName() << " " << rr.content << endl;
594 numerrors++;
595 }
6056b9c8
PL
596 }
597
2a8b9d77 598 cout<<"Checked "<<records.size()<<" records of '"<<zone<<"', "<<numerrors<<" errors, "<<numwarnings<<" warnings."<<endl;
d6ddb28a 599 if(!numerrors)
2a8b9d77
KM
600 return EXIT_SUCCESS;
601 return EXIT_FAILURE;
5d2e58b0
BH
602}
603
d6ddb28a 604int checkAllZones(DNSSECKeeper &dk, bool exitOnError)
1325e8a2 605{
ba86110a 606 UeberBackend B("default");
1325e8a2 607 vector<DomainInfo> domainInfo;
b9e61eb7
CH
608 multi_index_container<
609 DomainInfo,
610 indexed_by<
611 ordered_non_unique< member<DomainInfo,DNSName,&DomainInfo::zone>, CanonDNSNameCompare >,
612 ordered_non_unique< member<DomainInfo,uint32_t,&DomainInfo::id> >
613 >
614 > seenInfos;
615 auto& seenNames = seenInfos.get<0>();
616 auto& seenIds = seenInfos.get<1>();
1325e8a2 617
fdc0adaf 618 B.getAllDomains(&domainInfo, true);
1325e8a2 619 int errors=0;
d6ddb28a
PL
620 for(auto di : domainInfo) {
621 if (checkZone(dk, B, di.zone) > 0) {
622 errors++;
d6ddb28a 623 }
b9e61eb7
CH
624
625 auto seenName = seenNames.find(di.zone);
626 if (seenName != seenNames.end()) {
627 cout<<"[Error] Another SOA for zone '"<<di.zone<<"' (serial "<<di.serial<<") has already been seen (serial "<<seenName->serial<<")."<<endl;
628 errors++;
629 }
630
631 auto seenId = seenIds.find(di.id);
632 if (seenId != seenIds.end()) {
633 cout<<"[Error] Domain ID "<<di.id<<" of '"<<di.zone<<"' in backend "<<di.backend->getPrefix()<<" has already been used by zone '"<<seenId->zone<<"' in backend "<<seenId->backend->getPrefix()<<"."<<endl;
634 errors++;
635 }
636
637 seenInfos.insert(di);
638
639 if(errors && exitOnError)
640 return EXIT_FAILURE;
1325e8a2
PD
641 }
642 cout<<"Checked "<<domainInfo.size()<<" zones, "<<errors<<" had errors."<<endl;
d6ddb28a 643 if(!errors)
3af9bc3b
JA
644 return EXIT_SUCCESS;
645 return EXIT_FAILURE;
1325e8a2
PD
646}
647
675fa24c 648int increaseSerial(const DNSName& zone, DNSSECKeeper &dk)
04576eed
RA
649{
650 UeberBackend B("default");
651 SOAData sd;
79ba7763 652 if(!B.getSOAUncached(zone, sd)) {
0b34684a 653 cerr<<"No SOA for zone '"<<zone<<"'"<<endl;
04576eed
RA
654 return -1;
655 }
4192773a
KM
656
657 if (dk.isPresigned(zone)) {
658 cerr<<"Serial increase of presigned zone '"<<zone<<"' is not allowed."<<endl;
659 return -1;
660 }
13f9e280 661
04576eed 662 string soaEditKind;
4192773a 663 dk.getSoaEdit(zone, soaEditKind);
04576eed 664
04576eed 665 DNSResourceRecord rr;
13f9e280 666 makeIncreasedSOARecord(sd, "SOA-EDIT-INCREASE", soaEditKind, rr);
04576eed 667
7da05748 668 sd.db->startTransaction(zone, -1);
0881012f 669
13f9e280 670 if (!sd.db->replaceRRSet(sd.domain_id, zone, rr.qtype, vector<DNSResourceRecord>(1, rr))) {
0881012f 671 sd.db->abortTransaction();
04576eed
RA
672 cerr<<"Backend did not replace SOA record. Backend might not support this operation."<<endl;
673 return -1;
674 }
481350e4
AT
675
676 if (sd.db->doesDNSSEC()) {
677 NSEC3PARAMRecordContent ns3pr;
678 bool narrow;
679 bool haveNSEC3=dk.getNSEC3PARAM(zone, &ns3pr, &narrow);
488bcb39 680
4fcd7e9b
KM
681 DNSName ordername;
682 if(haveNSEC3) {
683 if(!narrow)
28e2e78e 684 ordername=DNSName(toBase32Hex(hashQNameWithSalt(ns3pr, zone))) + zone;
4fcd7e9b
KM
685 } else
686 ordername=zone;
687 if(g_verbose)
13f9e280
CH
688 cerr<<"'"<<rr.qname<<"' -> '"<< ordername <<"'"<<endl;
689 sd.db->updateDNSSECOrderNameAndAuth(sd.domain_id, rr.qname, ordername, true);
481350e4
AT
690 }
691
0881012f
AT
692 sd.db->commitTransaction();
693
0b34684a 694 cout<<"SOA serial for zone "<<zone<<" set to "<<sd.serial<<endl;
04576eed
RA
695 return 0;
696}
697
675fa24c 698int deleteZone(const DNSName &zone) {
51f6bca1
RA
699 UeberBackend B;
700 DomainInfo di;
701 if (! B.getDomainInfo(zone, di)) {
0b34684a 702 cerr<<"Domain '"<<zone<<"' not found!"<<endl;
3af9bc3b 703 return EXIT_FAILURE;
51f6bca1
RA
704 }
705
706 if(di.backend->deleteDomain(zone))
3af9bc3b 707 return EXIT_SUCCESS;
51f6bca1 708
0b34684a 709 cerr<<"Failed to delete domain '"<<zone<<"'"<<endl;;
3af9bc3b 710 return EXIT_FAILURE;
51f6bca1
RA
711}
712
597b9b3e
PL
713void listKey(DomainInfo const &di, DNSSECKeeper& dk, bool printHeader = true) {
714 if (printHeader) {
715 cout<<"Zone Type Size Algorithm ID Location Keytag"<<endl;
716 cout<<"----------------------------------------------------------------------------------"<<endl;
717 }
718 unsigned int spacelen = 0;
719 for (auto const &key : dk.getKeys(di.zone)) {
0b34684a 720 cout<<di.zone;
597b9b3e
PL
721 if (di.zone.toStringNoDot().length() > 29)
722 cout<<endl<<string(30, ' ');
723 else
724 cout<<string(30 - di.zone.toStringNoDot().length(), ' ');
725
b6bd795c 726 cout<<DNSSECKeeper::keyTypeToString(key.second.keyType)<<" ";
597b9b3e 727
335da0ba 728 spacelen = (std::to_string(key.first.getKey()->getBits()).length() >= 8) ? 1 : 8 - std::to_string(key.first.getKey()->getBits()).length();
597b9b3e
PL
729 if (key.first.getKey()->getBits() < 1) {
730 cout<<"invalid "<<endl;
488bcb39 731 continue;
597b9b3e
PL
732 } else {
733 cout<<key.first.getKey()->getBits()<<string(spacelen, ' ');
734 }
735
b6bd795c 736 string algname = DNSSECKeeper::algorithm2name(key.first.d_algorithm);
597b9b3e
PL
737 spacelen = (algname.length() >= 13) ? 1 : 13 - algname.length();
738 cout<<algname<<string(spacelen, ' ');
739
335da0ba 740 spacelen = (std::to_string(key.second.id).length() > 5) ? 1 : 5 - std::to_string(key.second.id).length();
597b9b3e
PL
741 cout<<key.second.id<<string(spacelen, ' ');
742
743#ifdef HAVE_P11KIT1
744 auto stormap = key.first.getKey()->convertToISCVector();
745 string engine, slot, label = "";
746 for (auto const &elem : stormap) {
747 //cout<<elem.first<<" "<<elem.second<<endl;
748 if (elem.first == "Engine")
749 engine = elem.second;
750 if (elem.first == "Slot")
751 slot = elem.second;
752 if (elem.first == "Label")
753 label = elem.second;
754 }
755 if (engine.empty() || slot.empty()){
756 cout<<"cryptokeys ";
757 } else {
758 spacelen = (engine.length()+slot.length()+label.length()+2 >= 12) ? 1 : 12 - engine.length()-slot.length()-label.length()-2;
759 cout<<engine<<","<<slot<<","<<label<<string(spacelen, ' ');
760 }
761#else
762 cout<<"cryptokeys ";
763#endif
764 cout<<key.first.getDNSKEY().getTag()<<endl;
765 }
766}
767
3af9bc3b 768int listKeys(const string &zname, DNSSECKeeper& dk){
597b9b3e
PL
769 UeberBackend B("default");
770
771 if (zname != "all") {
772 DomainInfo di;
773 if(!B.getDomainInfo(DNSName(zname), di)) {
774 cerr << "Zone "<<zname<<" not found."<<endl;
3af9bc3b 775 return EXIT_FAILURE;
597b9b3e
PL
776 }
777 listKey(di, dk);
778 } else {
779 vector<DomainInfo> domainInfo;
780 B.getAllDomains(&domainInfo);
781 bool printHeader = true;
782 for (auto const di : domainInfo) {
783 listKey(di, dk, printHeader);
784 printHeader = false;
785 }
786 }
3af9bc3b 787 return EXIT_SUCCESS;
597b9b3e
PL
788}
789
675fa24c 790int listZone(const DNSName &zone) {
c9865bc5 791 UeberBackend B;
792 DomainInfo di;
488bcb39 793
c9865bc5 794 if (! B.getDomainInfo(zone, di)) {
0b34684a 795 cerr<<"Domain '"<<zone<<"' not found!"<<endl;
3af9bc3b 796 return EXIT_FAILURE;
c9865bc5 797 }
798 di.backend->list(zone, di.id);
799 DNSResourceRecord rr;
211e704b 800 cout<<"$ORIGIN ."<<endl;
6a40fc00 801 cout.sync_with_stdio(false);
802
c9865bc5 803 while(di.backend->get(rr)) {
804 if(rr.qtype.getCode()) {
488bcb39 805 if ( (rr.qtype.getCode() == QType::NS || rr.qtype.getCode() == QType::SRV || rr.qtype.getCode() == QType::MX || rr.qtype.getCode() == QType::CNAME) && !rr.content.empty() && rr.content[rr.content.size()-1] != '.')
c9865bc5 806 rr.content.append(1, '.');
488bcb39 807
6a40fc00 808 cout<<rr.qname<<"\t"<<rr.ttl<<"\tIN\t"<<rr.qtype.getName()<<"\t"<<rr.content<<"\n";
c9865bc5 809 }
810 }
6a40fc00 811 cout.flush();
3af9bc3b 812 return EXIT_SUCCESS;
c9865bc5 813}
814
c2e0881c 815// lovingly copied from http://stackoverflow.com/questions/1798511/how-to-avoid-press-enter-with-any-getchar
488bcb39
RG
816int read1char(){
817 int c;
c2e0881c 818 static struct termios oldt, newt;
819
820 /*tcgetattr gets the parameters of the current terminal
821 STDIN_FILENO will tell tcgetattr that it should write the settings
822 of stdin to oldt*/
823 tcgetattr( STDIN_FILENO, &oldt);
824 /*now the settings will be copied*/
825 newt = oldt;
826
827 /*ICANON normally takes care that one line at a time will be processed
828 that means it will return if it sees a "\n" or an EOF or an EOL*/
488bcb39 829 newt.c_lflag &= ~(ICANON);
c2e0881c 830
831 /*Those new settings will be set to STDIN
832 TCSANOW tells tcsetattr to change attributes immediately. */
833 tcsetattr( STDIN_FILENO, TCSANOW, &newt);
834
835 c=getchar();
836
837 /*restore the old settings*/
838 tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
839
840 return c;
841}
842
eed2ecbe 843int clearZone(DNSSECKeeper& dk, const DNSName &zone) {
844 UeberBackend B;
845 DomainInfo di;
488bcb39 846
eed2ecbe 847 if (! B.getDomainInfo(zone, di)) {
0b34684a 848 cerr<<"Domain '"<<zone<<"' not found!"<<endl;
3af9bc3b 849 return EXIT_FAILURE;
eed2ecbe 850 }
851 if(!di.backend->startTransaction(zone, di.id)) {
0b34684a 852 cerr<<"Unable to start transaction for load of zone '"<<zone<<"'"<<endl;
3af9bc3b 853 return EXIT_FAILURE;
eed2ecbe 854 }
855 di.backend->commitTransaction();
3af9bc3b 856 return EXIT_SUCCESS;
eed2ecbe 857}
c2e0881c 858
859int editZone(DNSSECKeeper& dk, const DNSName &zone) {
860 UeberBackend B;
861 DomainInfo di;
488bcb39 862
c2e0881c 863 if (! B.getDomainInfo(zone, di)) {
0b34684a 864 cerr<<"Domain '"<<zone<<"' not found!"<<endl;
3af9bc3b 865 return EXIT_FAILURE;
c2e0881c 866 }
867 vector<DNSRecord> pre, post;
868 char tmpnam[]="/tmp/pdnsutil-XXXXXX";
869 int tmpfd=mkstemp(tmpnam);
870 if(tmpfd < 0)
871 unixDie("Making temporary filename in "+string(tmpnam));
872 struct deleteme {
873 ~deleteme() { unlink(d_name.c_str()); }
874 deleteme(string name) : d_name(name) {}
875 string d_name;
876 } dm(tmpnam);
877
c2e0881c 878 vector<DNSResourceRecord> checkrr;
879 int gotoline=0;
880 string editor="editor";
881 if(auto e=getenv("EDITOR")) // <3
882 editor=e;
883 string cmdline;
884 editAgain:;
885 di.backend->list(zone, di.id);
886 pre.clear(); post.clear();
c2e0881c 887 {
896c251e 888 if(tmpfd < 0 && (tmpfd=open(tmpnam, O_CREAT | O_WRONLY | O_TRUNC, 0600)) < 0)
c2e0881c 889 unixDie("Error reopening temporary file "+string(tmpnam));
21dd5918 890 string header("; Warning - every name in this file is ABSOLUTE!\n$ORIGIN .\n");
c2e0881c 891 if(write(tmpfd, header.c_str(), header.length()) < 0)
892 unixDie("Writing zone to temporary file");
d83581f8 893 DNSResourceRecord rr;
c2e0881c 894 while(di.backend->get(rr)) {
6945584f 895 if(!rr.qtype.getCode())
896 continue;
c2e0881c 897 DNSRecord dr(rr);
898 pre.push_back(dr);
518b1adc 899 }
23721d33 900 sort(pre.begin(), pre.end(), DNSRecord::prettyCompare);
518b1adc 901 for(const auto& dr : pre) {
c2e0881c 902 ostringstream os;
903 os<<dr.d_name<<"\t"<<dr.d_ttl<<"\tIN\t"<<DNSRecordContent::NumberToType(dr.d_type)<<"\t"<<dr.d_content->getZoneRepresentation(true)<<endl;
904 if(write(tmpfd, os.str().c_str(), os.str().length()) < 0)
905 unixDie("Writing zone to temporary file");
906 }
c2e0881c 907 close(tmpfd);
908 tmpfd=-1;
909 }
910 editMore:;
c2e0881c 911 cmdline=editor+" ";
912 if(gotoline > 0)
913 cmdline+="+"+std::to_string(gotoline)+" ";
914 cmdline += tmpnam;
21dd5918 915 int err=system(cmdline.c_str());
916 if(err) {
917 unixDie("Editing file with: '"+cmdline+"', perhaps set EDITOR variable");
c2e0881c 918 }
919 cmdline.clear();
12c06211 920 ZoneParserTNG zpt(tmpnam, g_rootdnsname);
2010ac95 921 DNSResourceRecord zrr;
c2e0881c 922 map<pair<DNSName,uint16_t>, vector<DNSRecord> > grouped;
7002805f
PD
923 try {
924 while(zpt.get(zrr)) {
925 DNSRecord dr(zrr);
926 post.push_back(dr);
927 grouped[{dr.d_name,dr.d_type}].push_back(dr);
c2e0881c 928 }
929 }
7002805f
PD
930 catch(std::exception& e) {
931 cerr<<"Problem: "<<e.what()<<" "<<zpt.getLineOfFile()<<endl;
932 auto fnum = zpt.getLineNumAndFile();
933 gotoline = fnum.second;
934 goto reAsk;
935 }
936
23721d33 937 sort(post.begin(), post.end(), DNSRecord::prettyCompare);
c2e0881c 938 checkrr.clear();
939
940 for(const DNSRecord& rr : post) {
d83581f8 941 DNSResourceRecord drr = DNSResourceRecord::fromWire(rr);
c2e0881c 942 drr.domain_id = di.id;
943 checkrr.push_back(drr);
944 }
945 if(checkZone(dk, B, zone, &checkrr)) {
946 reAsk:;
947 cerr<<"\x1b[31;1mThere was a problem with your zone\x1b[0m\nOptions are: (e)dit your changes, (r)etry with original zone, (a)pply change anyhow, (q)uit: "<<endl;
948 int c=read1char();
949 cerr<<"\n";
6945584f 950 if(c!='a')
951 post.clear();
488bcb39 952 if(c=='e')
c2e0881c 953 goto editMore;
954 else if(c=='r')
955 goto editAgain;
956 else if(c=='q')
957 return EXIT_FAILURE;
958 else if(c!='a')
959 goto reAsk;
960 }
961
c2e0881c 962
963 vector<DNSRecord> diff;
518b1adc 964
3c6ad4e2 965 map<pair<DNSName,uint16_t>, string> changed;
23721d33 966 set_difference(pre.cbegin(), pre.cend(), post.cbegin(), post.cend(), back_inserter(diff), DNSRecord::prettyCompare);
c2e0881c 967 for(const auto& d : diff) {
3c6ad4e2 968 ostringstream str;
70ff5c9b 969 str<<"\033[0;31m-"<< d.d_name <<" "<<d.d_ttl<<" IN "<<DNSRecordContent::NumberToType(d.d_type)<<" "<<d.d_content->getZoneRepresentation(true)<<"\033[0m"<<endl;
3c6ad4e2 970 changed[{d.d_name,d.d_type}] += str.str();
971
c2e0881c 972 }
973 diff.clear();
23721d33 974 set_difference(post.cbegin(), post.cend(), pre.cbegin(), pre.cend(), back_inserter(diff), DNSRecord::prettyCompare);
c2e0881c 975 for(const auto& d : diff) {
3c6ad4e2 976 ostringstream str;
c2e0881c 977
70ff5c9b 978 str<<"\033[0;32m+"<< d.d_name <<" "<<d.d_ttl<<" IN "<<DNSRecordContent::NumberToType(d.d_type)<<" "<<d.d_content->getZoneRepresentation(true)<<"\033[0m"<<endl;
3c6ad4e2 979 changed[{d.d_name,d.d_type}]+=str.str();
980 }
70891734
HY
981 if (changed.size() > 0)
982 cout<<"Detected the following changes:"<<endl;
3c6ad4e2 983 for(const auto& c : changed) {
984 cout<<c.second;
985 }
c2e0881c 986 reAsk2:;
70891734
HY
987 if(changed.empty()) {
988 cout<<endl<<"No changes to apply."<<endl;
989 return(EXIT_SUCCESS);
990 }
991 cout<<endl<<"(a)pply these changes, (e)dit again, (r)etry with original zone, (q)uit: ";
c2e0881c 992 int c=read1char();
993 post.clear();
994 cerr<<'\n';
995 if(c=='q')
996 return(EXIT_SUCCESS);
997 else if(c=='e')
998 goto editMore;
999 else if(c=='r')
1000 goto editAgain;
6945584f 1001 else if(changed.empty() || c!='a')
c2e0881c 1002 goto reAsk2;
1003
2010ac95 1004 for(const auto& change : changed) {
c2e0881c 1005 vector<DNSResourceRecord> vrr;
2010ac95
RG
1006 for(const DNSRecord& rr : grouped[change.first]) {
1007 DNSResourceRecord crr = DNSResourceRecord::fromWire(rr);
1008 crr.domain_id = di.id;
1009 vrr.push_back(crr);
c2e0881c 1010 }
2010ac95 1011 di.backend->replaceRRSet(di.id, change.first.first, QType(change.first.second), vrr);
c2e0881c 1012 }
6945584f 1013 rectifyZone(dk, zone);
3af9bc3b 1014 return EXIT_SUCCESS;
c2e0881c 1015}
1016
2ae24e09 1017static int xcryptIP(const std::string& cmd, const std::string& ip, const std::string& rkey)
caff6e16 1018{
2ae24e09 1019
caff6e16 1020 ComboAddress ca(ip), ret;
488bcb39 1021
caff6e16 1022 if(cmd=="ipencrypt")
1023 ret = encryptCA(ca, rkey);
1024 else
1025 ret = decryptCA(ca, rkey);
1026
1027 cout<<ret.toString()<<endl;
1028 return EXIT_SUCCESS;
1029}
1030
c2e0881c 1031
675fa24c 1032int loadZone(DNSName zone, const string& fname) {
c9865bc5 1033 UeberBackend B;
1034 DomainInfo di;
1035
1036 if (B.getDomainInfo(zone, di)) {
0b34684a 1037 cerr<<"Domain '"<<zone<<"' exists already, replacing contents"<<endl;
c9865bc5 1038 }
1039 else {
0b34684a 1040 cerr<<"Creating '"<<zone<<"'"<<endl;
c9865bc5 1041 B.createDomain(zone);
488bcb39 1042
c9865bc5 1043 if(!B.getDomainInfo(zone, di)) {
0b34684a 1044 cerr<<"Domain '"<<zone<<"' was not created - perhaps backend ("<<::arg()["launch"]<<") does not support storing new zones."<<endl;
3af9bc3b 1045 return EXIT_FAILURE;
c9865bc5 1046 }
1047 }
1048 DNSBackend* db = di.backend;
1049 ZoneParserTNG zpt(fname, zone);
488bcb39 1050
c9865bc5 1051 DNSResourceRecord rr;
1052 if(!db->startTransaction(zone, di.id)) {
0b34684a 1053 cerr<<"Unable to start transaction for load of zone '"<<zone<<"'"<<endl;
3af9bc3b 1054 return EXIT_FAILURE;
c9865bc5 1055 }
488bcb39 1056 rr.domain_id=di.id;
8fb3318d 1057 bool haveSOA = false;
c9865bc5 1058 while(zpt.get(rr)) {
675fa24c 1059 if(!rr.qname.isPartOf(zone) && rr.qname!=zone) {
0b34684a 1060 cerr<<"File contains record named '"<<rr.qname<<"' which is not part of zone '"<<zone<<"'"<<endl;
3af9bc3b 1061 return EXIT_FAILURE;
c9865bc5 1062 }
8fb3318d
PL
1063 if (rr.qtype == QType::SOA) {
1064 if (haveSOA)
1065 continue;
1066 else
1067 haveSOA = true;
1068 }
c9b43446 1069 db->feedRecord(rr, DNSName());
c9865bc5 1070 }
1071 db->commitTransaction();
3af9bc3b 1072 return EXIT_SUCCESS;
c9865bc5 1073}
1074
66d34461 1075int createZone(const DNSName &zone, const DNSName& nsname) {
c9865bc5 1076 UeberBackend B;
1077 DomainInfo di;
1078 if (B.getDomainInfo(zone, di)) {
0b34684a 1079 cerr<<"Domain '"<<zone<<"' exists already"<<endl;
3af9bc3b 1080 return EXIT_FAILURE;
c9865bc5 1081 }
0b34684a 1082 cerr<<"Creating empty zone '"<<zone<<"'"<<endl;
c9865bc5 1083 B.createDomain(zone);
c9865bc5 1084 if(!B.getDomainInfo(zone, di)) {
0b34684a 1085 cerr<<"Domain '"<<zone<<"' was not created!"<<endl;
3af9bc3b 1086 return EXIT_FAILURE;
c9865bc5 1087 }
8e1864cc
CH
1088
1089 DNSResourceRecord rr;
1090 rr.qname = zone;
1091 rr.auth = 1;
1092 rr.ttl = ::arg().asNum("default-ttl");
1093 rr.qtype = "SOA";
488bcb39 1094
8e1864cc 1095 string soa = (boost::format("%s %s 1")
66d34461 1096 % (nsname.empty() ? ::arg()["default-soa-name"] : nsname.toString())
1097 % (::arg().isEmpty("default-soa-mail") ? (DNSName("hostmaster.") + zone).toString() : ::arg()["default-soa-mail"])
8e1864cc
CH
1098 ).str();
1099 SOAData sd;
1100 fillSOAData(soa, sd); // fills out default values for us
13f9e280 1101 rr.content = makeSOAContent(sd)->getZoneRepresentation(true);
8e1864cc
CH
1102 rr.domain_id = di.id;
1103 di.backend->startTransaction(zone, di.id);
c9b43446 1104 di.backend->feedRecord(rr, DNSName());
66d34461 1105 if(!nsname.empty()) {
1106 cout<<"Also adding one NS record"<<endl;
1107 rr.qtype=QType::NS;
8898a65c 1108 rr.content=nsname.toStringNoDot();
c9b43446 1109 di.backend->feedRecord(rr, DNSName());
66d34461 1110 }
488bcb39 1111
8e1864cc
CH
1112 di.backend->commitTransaction();
1113
3af9bc3b 1114 return EXIT_SUCCESS;
c9865bc5 1115}
1116
e85a76ad 1117int createSlaveZone(const vector<string>& cmds) {
1118 UeberBackend B;
1119 DomainInfo di;
1120 DNSName zone(cmds[1]);
1121 if (B.getDomainInfo(zone, di)) {
0b34684a 1122 cerr<<"Domain '"<<zone<<"' exists already"<<endl;
3af9bc3b 1123 return EXIT_FAILURE;
e85a76ad 1124 }
af3a3769
HY
1125 vector<string> masters;
1126 for (unsigned i=2; i < cmds.size(); i++) {
21546442 1127 ComboAddress master(cmds[i], 53);
af3a3769
HY
1128 masters.push_back(master.toStringWithPort());
1129 }
1130 cerr<<"Creating slave zone '"<<zone<<"', with master(s) '"<<boost::join(masters, ",")<<"'"<<endl;
e85a76ad 1131 B.createDomain(zone);
1132 if(!B.getDomainInfo(zone, di)) {
0b34684a 1133 cerr<<"Domain '"<<zone<<"' was not created!"<<endl;
3af9bc3b 1134 return EXIT_FAILURE;
e85a76ad 1135 }
1136 di.backend->setKind(zone, DomainInfo::Slave);
af3a3769 1137 di.backend->setMaster(zone, boost::join(masters, ","));
e85a76ad 1138 return EXIT_SUCCESS;
1139}
1140
324ead90
HY
1141int changeSlaveZoneMaster(const vector<string>& cmds) {
1142 UeberBackend B;
1143 DomainInfo di;
1144 DNSName zone(cmds[1]);
1145 if (!B.getDomainInfo(zone, di)) {
1146 cerr<<"Domain '"<<zone<<"' doesn't exist"<<endl;
1147 return EXIT_FAILURE;
1148 }
1149 vector<string> masters;
1150 for (unsigned i=2; i < cmds.size(); i++) {
1151 ComboAddress master(cmds[i], 53);
1152 masters.push_back(master.toStringWithPort());
1153 }
1154 cerr<<"Updating slave zone '"<<zone<<"', master(s) to '"<<boost::join(masters, ",")<<"'"<<endl;
919d2720
HY
1155 try {
1156 di.backend->setMaster(zone, boost::join(masters, ","));
1157 return EXIT_SUCCESS;
1158 }
1159 catch (PDNSException& e) {
1160 cerr<<"Setting master for zone '"<<zone<<"' failed: "<<e.reason<<endl;
1161 return EXIT_FAILURE;
1162 }
324ead90
HY
1163}
1164
66d34461 1165// add-record ZONE name type [ttl] "content" ["content"]
1166int addOrReplaceRecord(bool addOrReplace, const vector<string>& cmds) {
1167 DNSResourceRecord rr;
1168 vector<DNSResourceRecord> newrrs;
1169 DNSName zone(cmds[1]);
1170 DNSName name;
1171 if(cmds[2]=="@")
1172 name=zone;
488bcb39 1173 else
66d34461 1174 name=DNSName(cmds[2])+zone;
1175
1176 rr.qtype = DNSRecordContent::TypeToNumber(cmds[3]);
1177 rr.ttl = ::arg().asNum("default-ttl");
1178
1179 UeberBackend B;
1180 DomainInfo di;
1181
1182 if(!B.getDomainInfo(zone, di)) {
1183 cerr<<"Domain '"<<zone<<"' does not exist"<<endl;
3af9bc3b 1184 return EXIT_FAILURE;
66d34461 1185 }
1186 rr.auth = 1;
1187 rr.domain_id = di.id;
1188 rr.qname = name;
c07a0c6d 1189 DNSResourceRecord oldrr;
66d34461 1190 if(addOrReplace) { // the 'add' case
d83581f8 1191 di.backend->lookup(rr.qtype, rr.qname, 0, di.id);
c07a0c6d 1192
d83581f8 1193 while(di.backend->get(oldrr))
66d34461 1194 newrrs.push_back(oldrr);
1195 }
1196
1197 unsigned int contentStart = 4;
1198 if(cmds.size() > 5) {
1199 rr.ttl=atoi(cmds[4].c_str());
1200 if(std::to_string(rr.ttl)==cmds[4]) {
1201 contentStart++;
1202 }
65516ea4
CHB
1203 else {
1204 rr.ttl = ::arg().asNum("default-ttl");
1205 }
66d34461 1206 }
1207
d83581f8 1208 di.backend->lookup(QType(QType::ANY), rr.qname, 0, di.id);
66d34461 1209 bool found=false;
1210 if(rr.qtype.getCode() == QType::CNAME) { // this will save us SO many questions
1211
d83581f8 1212 while(di.backend->get(oldrr)) {
c07a0c6d 1213 if(addOrReplace || oldrr.qtype.getCode() != QType::CNAME) // the replace case is ok if we replace one CNAME by the other
66d34461 1214 found=true;
1215 }
1216 if(found) {
1217 cerr<<"Attempting to add CNAME to "<<rr.qname<<" which already had existing records"<<endl;
1218 return EXIT_FAILURE;
1219 }
1220 }
1221 else {
d83581f8 1222 while(di.backend->get(oldrr)) {
c07a0c6d 1223 if(oldrr.qtype.getCode() == QType::CNAME)
66d34461 1224 found=true;
1225 }
1226 if(found) {
1227 cerr<<"Attempting to add record to "<<rr.qname<<" which already had a CNAME record"<<endl;
1228 return EXIT_FAILURE;
1229 }
1230 }
1231
17df2abf 1232 if(!addOrReplace) {
0b34684a 1233 cout<<"Current records for "<<rr.qname<<" IN "<<rr.qtype.getName()<<" will be replaced"<<endl;
17df2abf 1234 }
1235 for(auto i = contentStart ; i < cmds.size() ; ++i) {
65516ea4 1236 rr.content = DNSRecordContent::mastermake(rr.qtype.getCode(), QClass::IN, cmds[i])->getZoneRepresentation(true);
17df2abf 1237
1238 newrrs.push_back(rr);
1239 }
66d34461 1240
488bcb39 1241
17df2abf 1242 di.backend->replaceRRSet(di.id, name, rr.qtype, newrrs);
1243 // need to be explicit to bypass the ueberbackend cache!
1244 di.backend->lookup(rr.qtype, name, 0, di.id);
1245 cout<<"New rrset:"<<endl;
1246 while(di.backend->get(rr)) {
52fa03ca 1247 cout<<rr.qname.toString()<<" "<<rr.ttl<<" IN "<<rr.qtype.getName()<<" "<<rr.content<<endl;
17df2abf 1248 }
3af9bc3b 1249 return EXIT_SUCCESS;
66d34461 1250}
1251
1252// delete-rrset zone name type
488bcb39 1253int deleteRRSet(const std::string& zone_, const std::string& name_, const std::string& type_)
66d34461 1254{
1255 UeberBackend B;
1256 DomainInfo di;
1257 DNSName zone(zone_);
1258 if(!B.getDomainInfo(zone, di)) {
1259 cerr<<"Domain '"<<zone<<"' does not exist"<<endl;
3af9bc3b 1260 return EXIT_FAILURE;
66d34461 1261 }
1262
1263 DNSName name;
1264 if(name_=="@")
1265 name=zone;
488bcb39 1266 else
66d34461 1267 name=DNSName(name_)+zone;
1268
1269 QType qt(QType::chartocode(type_.c_str()));
1270 di.backend->replaceRRSet(di.id, name, qt, vector<DNSResourceRecord>());
3af9bc3b 1271 return EXIT_SUCCESS;
66d34461 1272}
c9865bc5 1273
22c68348 1274int listAllZones(const string &type="") {
bd108049
RA
1275
1276 int kindFilter = -1;
1277 if (type.size()) {
1278 if (toUpper(type) == "MASTER")
1279 kindFilter = 0;
1280 else if (toUpper(type) == "SLAVE")
1281 kindFilter = 1;
1282 else if (toUpper(type) == "NATIVE")
1283 kindFilter = 2;
22c68348 1284 else {
fd5076c8 1285 cerr<<"Syntax: pdnsutil list-all-zones [master|slave|native]"<<endl;
22c68348
KM
1286 return 1;
1287 }
bd108049
RA
1288 }
1289
8ecfea3a 1290 UeberBackend B("default");
bd108049 1291
8ecfea3a 1292 vector<DomainInfo> domains;
9c4a4ddc 1293 B.getAllDomains(&domains, true);
8ecfea3a
KM
1294
1295 int count = 0;
cb167afd
CHB
1296 for (const auto& di: domains) {
1297 if (di.kind == kindFilter || kindFilter == -1) {
1298 cout<<di.zone<<endl;
bd108049
RA
1299 count++;
1300 }
1301 }
1302
a1a986ad
KO
1303 if (g_verbose) {
1304 if (kindFilter != -1)
1305 cout<<type<<" zonecount: "<<count<<endl;
1306 else
1307 cout<<"All zonecount: "<<count<<endl;
1308 }
1309
bd108049
RA
1310 return 0;
1311}
1312
166d8647 1313bool testAlgorithm(int algo)
cbb0025b 1314{
166d8647 1315 return DNSCryptoKeyEngine::testOne(algo);
cbb0025b 1316}
1325e8a2 1317
166d8647 1318bool testAlgorithms()
189bb9d2 1319{
166d8647 1320 return DNSCryptoKeyEngine::testAll();
189bb9d2
BH
1321}
1322
b873e23a 1323void testSpeed(DNSSECKeeper& dk, const DNSName& zone, const string& remote, int cores)
ea937fd4
BH
1324{
1325 DNSResourceRecord rr;
b873e23a 1326 rr.qname=DNSName("blah")+zone;
ea937fd4
BH
1327 rr.qtype=QType::A;
1328 rr.ttl=3600;
1329 rr.auth=1;
703761cc 1330 rr.qclass = QClass::IN;
488bcb39 1331
49449751 1332 UeberBackend db("key-only");
488bcb39 1333
f0c4b9d5
PD
1334 if ( ! db.backends.size() )
1335 {
1336 throw runtime_error("No backends available for DNSSEC key storage");
1337 }
1338
e3200e07 1339 ChunkedSigningPipe csp(DNSName(zone), 1, cores);
488bcb39 1340
90ba52e0 1341 vector<DNSZoneRecord> signatures;
ea937fd4
BH
1342 uint32_t rnd;
1343 unsigned char* octets = (unsigned char*)&rnd;
1344 char tmp[25];
1345 DTime dt;
1346 dt.set();
1347 for(unsigned int n=0; n < 100000; ++n) {
b51ef4f9 1348 rnd = dns_random(UINT32_MAX);
488bcb39 1349 snprintf(tmp, sizeof(tmp), "%d.%d.%d.%d",
ea937fd4
BH
1350 octets[0], octets[1], octets[2], octets[3]);
1351 rr.content=tmp;
488bcb39 1352
ea937fd4 1353 snprintf(tmp, sizeof(tmp), "r-%u", rnd);
b873e23a 1354 rr.qname=DNSName(tmp)+zone;
90ba52e0 1355 DNSZoneRecord dzr;
1356 dzr.dr=DNSRecord(rr);
1357 if(csp.submit(dzr))
ea937fd4
BH
1358 while(signatures = csp.getChunk(), !signatures.empty())
1359 ;
1360 }
1361 cerr<<"Flushing the pipe, "<<csp.d_signed<<" signed, "<<csp.d_queued<<" queued, "<<csp.d_outstanding<<" outstanding"<< endl;
451ba512 1362 cerr<<"Net speed: "<<csp.d_signed/ (dt.udiffNoReset()/1000000.0) << " sigs/s"<<endl;
ea937fd4
BH
1363 while(signatures = csp.getChunk(true), !signatures.empty())
1364 ;
1365 cerr<<"Done, "<<csp.d_signed<<" signed, "<<csp.d_queued<<" queued, "<<csp.d_outstanding<<" outstanding"<< endl;
451ba512 1366 cerr<<"Net speed: "<<csp.d_signed/ (dt.udiff()/1000000.0) << " sigs/s"<<endl;
ea937fd4
BH
1367}
1368
aa65a832
BH
1369void verifyCrypto(const string& zone)
1370{
1371 ZoneParserTNG zpt(zone);
1372 DNSResourceRecord rr;
1373 DNSKEYRecordContent drc;
1374 RRSIGRecordContent rrc;
c3e26094 1375 DSRecordContent dsrc;
aa65a832 1376 vector<shared_ptr<DNSRecordContent> > toSign;
675fa24c 1377 DNSName qname, apex;
c3e26094 1378 dsrc.d_digesttype=0;
aa65a832
BH
1379 while(zpt.get(rr)) {
1380 if(rr.qtype.getCode() == QType::DNSKEY) {
1381 cerr<<"got DNSKEY!"<<endl;
c3e26094 1382 apex=rr.qname;
6177a176 1383 drc = *std::dynamic_pointer_cast<DNSKEYRecordContent>(DNSRecordContent::mastermake(QType::DNSKEY, 1, rr.content));
aa65a832
BH
1384 }
1385 else if(rr.qtype.getCode() == QType::RRSIG) {
1386 cerr<<"got RRSIG"<<endl;
6177a176 1387 rrc = *std::dynamic_pointer_cast<RRSIGRecordContent>(DNSRecordContent::mastermake(QType::RRSIG, 1, rr.content));
aa65a832 1388 }
c3e26094
BH
1389 else if(rr.qtype.getCode() == QType::DS) {
1390 cerr<<"got DS"<<endl;
6177a176 1391 dsrc = *std::dynamic_pointer_cast<DSRecordContent>(DNSRecordContent::mastermake(QType::DS, 1, rr.content));
c3e26094 1392 }
aa65a832
BH
1393 else {
1394 qname = rr.qname;
6177a176 1395 toSign.push_back(DNSRecordContent::mastermake(rr.qtype.getCode(), 1, rr.content));
aa65a832
BH
1396 }
1397 }
488bcb39 1398
6177a176 1399 string msg = getMessageForRRSET(qname, rrc, toSign);
49449751 1400 cerr<<"Verify: "<<DNSCryptoKeyEngine::makeFromPublicKeyString(drc.d_algorithm, drc.d_key)->verify(msg, rrc.d_signature)<<endl;
c3e26094 1401 if(dsrc.d_digesttype) {
675fa24c
PD
1402 cerr<<"Calculated DS: "<<apex.toString()<<" IN DS "<<makeDSFromDNSKey(apex, drc, dsrc.d_digesttype).getZoneRepresentation()<<endl;
1403 cerr<<"Original DS: "<<apex.toString()<<" IN DS "<<dsrc.getZoneRepresentation()<<endl;
c3e26094 1404 }
295812a1 1405#if 0
e69c2dac 1406 std::shared_ptr<DNSCryptoKeyEngine> key=DNSCryptoKeyEngine::makeFromISCString(drc, "Private-key-format: v1.2\n"
295812a1
BH
1407 "Algorithm: 12 (ECC-GOST)\n"
1408 "GostAsn1: MEUCAQAwHAYGKoUDAgITMBIGByqFAwICIwEGByqFAwICHgEEIgQg/9MiXtXKg9FDXDN/R9CmVhJDyuzRAIgh4tPwCu4NHIs=\n");
1409 string resign=key->sign(hash);
1410 cerr<<Base64Encode(resign)<<endl;
8d9f38f2 1411 cerr<<"Verify: "<<DNSCryptoKeyEngine::makeFromPublicKeyString(drc.d_algorithm, drc.d_key)->verify(hash, resign)<<endl;
295812a1
BH
1412#endif
1413
aa65a832 1414}
675fa24c 1415bool disableDNSSECOnZone(DNSSECKeeper& dk, const DNSName& zone)
5935cede 1416{
032e3906
PD
1417 UeberBackend B("default");
1418 DomainInfo di;
1419
1420 if (!B.getDomainInfo(zone, di)){
1421 cerr << "No such zone in the database" << endl;
1422 return false;
1423 }
1424
cbe8b186
PL
1425 string error, info;
1426 bool ret = dk.unSecureZone(zone, error, info);
1427 if (!ret) {
1428 cerr << error << endl;
5935cede 1429 }
cbe8b186 1430 return ret;
5935cede 1431}
bddc5d92 1432
6617c29e
MS
1433int setZoneAccount(const DNSName& zone, const string &account)
1434{
1435 UeberBackend B("default");
1436 DomainInfo di;
6617c29e
MS
1437
1438 if (!B.getDomainInfo(zone, di)){
1439 cerr << "No such zone "<<zone<<" in the database" << endl;
1440 return EXIT_FAILURE;
1441 }
1442 if(!di.backend->setAccount(zone, account)) {
1443 cerr<<"Could not find backend willing to accept new zone configuration"<<endl;
1444 return EXIT_FAILURE;
1445 }
1446 return EXIT_SUCCESS;
1447}
1448
bddc5d92 1449int setZoneKind(const DNSName& zone, const DomainInfo::DomainKind kind)
1450{
1451 UeberBackend B("default");
1452 DomainInfo di;
bddc5d92 1453
1454 if (!B.getDomainInfo(zone, di)){
1455 cerr << "No such zone "<<zone<<" in the database" << endl;
1456 return EXIT_FAILURE;
1457 }
1458 if(!di.backend->setKind(zone, kind)) {
1459 cerr<<"Could not find backend willing to accept new zone configuration"<<endl;
1460 return EXIT_FAILURE;
1461 }
1462 return EXIT_SUCCESS;
1463}
1464
84dc0cd2 1465bool showZone(DNSSECKeeper& dk, const DNSName& zone, bool exportDS = false)
ade1b1e9 1466{
032e3906
PD
1467 UeberBackend B("default");
1468 DomainInfo di;
1469
1470 if (!B.getDomainInfo(zone, di)){
1471 cerr << "No such zone in the database" << endl;
1472 return false;
1473 }
1474
c353c45b
MS
1475 if (!di.account.empty()) {
1476 cout<<"This zone is owned by "<<di.account<<endl;
1477 }
84dc0cd2
JW
1478 if (!exportDS) {
1479 cout<<"This is a "<<DomainInfo::getKindString(di.kind)<<" zone"<<endl;
1480 if(di.kind == DomainInfo::Master) {
1481 cout<<"Last SOA serial number we notified: "<<di.notified_serial<<" ";
1482 SOAData sd;
1483 if(B.getSOAUncached(zone, sd)) {
1484 if(sd.serial == di.notified_serial)
1485 cout<< "== ";
1486 else
1487 cout << "!= ";
1488 cout<<sd.serial<<" (serial in the database)"<<endl;
1489 }
176fdd7e 1490 }
84dc0cd2
JW
1491 else if(di.kind == DomainInfo::Slave) {
1492 cout<<"Master"<<addS(di.masters)<<": ";
1493 for(const auto& m : di.masters)
d622042f 1494 cout<<m.toStringWithPort()<<" ";
84dc0cd2
JW
1495 cout<<endl;
1496 struct tm tm;
1497 localtime_r(&di.last_check, &tm);
1498 char buf[80];
1499 if(di.last_check)
1500 strftime(buf, sizeof(buf)-1, "%a %F %H:%M:%S", &tm);
1501 else
1502 strncpy(buf, "Never", sizeof(buf)-1);
1503 buf[sizeof(buf)-1] = '\0';
1504 cout<<"Last time we got update from master: "<<buf<<endl;
1505 SOAData sd;
1506 if(B.getSOAUncached(zone, sd)) {
1507 cout<<"SOA serial in database: "<<sd.serial<<endl;
1508 cout<<"Refresh interval: "<<sd.refresh<<" seconds"<<endl;
1509 }
1510 else
1511 cout<<"No SOA serial found in database"<<endl;
176fdd7e 1512 }
176fdd7e 1513 }
1514
d3e7090c 1515 if(!dk.isSecuredZone(zone)) {
cae148f1
JW
1516 auto &outstream = (exportDS ? cerr : cout);
1517 outstream << "Zone is not actively secured" << endl;
84dc0cd2
JW
1518 if (exportDS) {
1519 // it does not make sense to proceed here, and it might be useful
1520 // for scripts to know that something is odd here
1521 return false;
1522 }
d3e7090c 1523 }
84dc0cd2 1524
ade1b1e9
BH
1525 NSEC3PARAMRecordContent ns3pr;
1526 bool narrow;
3c873e66 1527 bool haveNSEC3=dk.getNSEC3PARAM(zone, &ns3pr, &narrow);
84dc0cd2 1528
d4a4176d 1529 DNSSECKeeper::keyset_t keyset=dk.getKeys(zone);
4831df57 1530
84dc0cd2
JW
1531 if (!exportDS) {
1532 std::vector<std::string> meta;
1533
1534 if (B.getDomainMetadata(zone, "TSIG-ALLOW-AXFR", meta) && meta.size() > 0) {
1535 cout << "Zone has following allowed TSIG key(s): " << boost::join(meta, ",") << endl;
1536 }
1537
1538 meta.clear();
1539 if (B.getDomainMetadata(zone, "AXFR-MASTER-TSIG", meta) && meta.size() > 0) {
1540 cout << "Zone uses following TSIG key(s): " << boost::join(meta, ",") << endl;
1541 }
1542
1543 std::map<std::string, std::vector<std::string> > metamap;
1544 if(B.getAllDomainMetadata(zone, metamap)) {
1545 cout<<"Metadata items: ";
1546 if(metamap.empty())
1547 cout<<"None";
1548 cout<<endl;
176fdd7e 1549
84dc0cd2
JW
1550 for(const auto& m : metamap) {
1551 for(const auto i : m.second)
1552 cout << '\t' << m.first<<'\t' << i <<endl;
1553 }
5911b051 1554 }
84dc0cd2 1555
5911b051 1556 }
1557
120b4dc6 1558 if (dk.isPresigned(zone)) {
84dc0cd2
JW
1559 if (!exportDS) {
1560 cout <<"Zone is presigned"<<endl;
1561 }
1562
120b4dc6
AT
1563 // get us some keys
1564 vector<DNSKEYRecordContent> keys;
d83581f8 1565 DNSZoneRecord zr;
ade1b1e9 1566
1dda62a3 1567 B.lookup(QType(QType::DNSKEY), zone);
d83581f8
CH
1568 while(B.get(zr)) {
1569 if (zr.dr.d_type != QType::DNSKEY) continue;
1570 keys.push_back(*getRR<DNSKEYRecordContent>(zr.dr));
120b4dc6
AT
1571 }
1572
1573 if(keys.empty()) {
0b34684a 1574 cerr << "No keys for zone '"<<zone<<"'."<<endl;
120b4dc6
AT
1575 return true;
1576 }
1577
84dc0cd2
JW
1578 if (!exportDS) {
1579 if(!haveNSEC3)
1580 cout<<"Zone has NSEC semantics"<<endl;
1581 else
1582 cout<<"Zone has " << (narrow ? "NARROW " : "") <<"hashed NSEC3 semantics, configuration: "<<ns3pr.getZoneRepresentation()<<endl;
1583 cout << "keys: "<<endl;
1584 }
1585
120b4dc6
AT
1586 sort(keys.begin(),keys.end());
1587 reverse(keys.begin(),keys.end());
1588 for(const auto& key : keys) {
b6bd795c 1589 string algname = DNSSECKeeper::algorithm2name(key.d_algorithm);
d3ccf8a3 1590
1591 int bits = -1;
1592 try {
e69c2dac 1593 std::shared_ptr<DNSCryptoKeyEngine> engine(DNSCryptoKeyEngine::makeFromPublicKeyString(key.d_algorithm, key.d_key)); // throws on unknown algo or bad key
d3ccf8a3 1594 bits=engine->getBits();
1595 }
1596 catch(std::exception& e) {
84dc0cd2
JW
1597 cerr<<"Could not process key to extract metadata: "<<e.what()<<endl;
1598 }
1599 if (!exportDS) {
1600 cout << (key.d_flags == 257 ? "KSK" : "ZSK") << ", tag = " << key.getTag() << ", algo = "<<(int)key.d_algorithm << ", bits = " << bits << endl;
1601 cout << "DNSKEY = " <<zone.toString()<<" IN DNSKEY "<< key.getZoneRepresentation() << "; ( " + algname + " ) " <<endl;
d3ccf8a3 1602 }
84dc0cd2 1603
8dd7cf3d 1604 const std::string prefix(exportDS ? "" : "DS = ");
8455425c
RG
1605 cout<<prefix<<zone.toString()<<" IN DS "<<makeDSFromDNSKey(zone, key, DNSSECKeeper::SHA1).getZoneRepresentation() << " ; ( SHA1 digest )" << endl;
1606 cout<<prefix<<zone.toString()<<" IN DS "<<makeDSFromDNSKey(zone, key, DNSSECKeeper::SHA256).getZoneRepresentation() << " ; ( SHA256 digest )" << endl;
120b4dc6 1607 try {
8455425c 1608 string output=makeDSFromDNSKey(zone, key, DNSSECKeeper::GOST).getZoneRepresentation();
4743dfd0 1609 cout<<prefix<<zone.toString()<<" IN DS "<<output<< " ; ( GOST R 34.11-94 digest )" << endl;
120b4dc6
AT
1610 }
1611 catch(...)
1612 {}
1613 try {
8455425c 1614 string output=makeDSFromDNSKey(zone, key, DNSSECKeeper::SHA384).getZoneRepresentation();
4743dfd0 1615 cout<<prefix<<zone.toString()<<" IN DS "<<output<< " ; ( SHA-384 digest )" << endl;
120b4dc6
AT
1616 }
1617 catch(...)
1618 {}
1619 }
1620 }
1621 else if(keyset.empty()) {
0b34684a 1622 cerr << "No keys for zone '"<<zone<<"'."<<endl;
ade1b1e9 1623 }
84dc0cd2
JW
1624 else {
1625 if (!exportDS) {
1626 if(!haveNSEC3)
1627 cout<<"Zone has NSEC semantics"<<endl;
1628 else
1629 cout<<"Zone has " << (narrow ? "NARROW " : "") <<"hashed NSEC3 semantics, configuration: "<<ns3pr.getZoneRepresentation()<<endl;
1630 cout << "keys: "<<endl;
1631 }
1632
ff05fd12 1633 for(DNSSECKeeper::keyset_t::value_type value : keyset) {
b6bd795c 1634 string algname = DNSSECKeeper::algorithm2name(value.first.d_algorithm);
84dc0cd2
JW
1635 if (!exportDS) {
1636 cout<<"ID = "<<value.second.id<<" ("<<DNSSECKeeper::keyTypeToString(value.second.keyType)<<")";
1637 }
95b3e84b 1638 if (value.first.getKey()->getBits() < 1) {
84dc0cd2 1639 cerr<<" <key missing or defunct>" <<endl;
95b3e84b
AT
1640 continue;
1641 }
84dc0cd2
JW
1642 if (!exportDS) {
1643 cout<<", flags = "<<std::to_string(value.first.d_flags);
1644 cout<<", tag = "<<value.first.getDNSKEY().getTag();
1645 cout<<", algo = "<<(int)value.first.d_algorithm<<", bits = "<<value.first.getKey()->getBits()<<"\t"<<((int)value.second.active == 1 ? " A" : "Ina")<<"ctive ( " + algname + " ) "<<endl;
1646 }
1647
1648 if (!exportDS) {
1649 if (value.second.keyType == DNSSECKeeper::KSK || value.second.keyType == DNSSECKeeper::CSK || ::arg().mustDo("direct-dnskey")) {
1650 cout<<DNSSECKeeper::keyTypeToString(value.second.keyType)<<" DNSKEY = "<<zone.toString()<<" IN DNSKEY "<< value.first.getDNSKEY().getZoneRepresentation() << " ; ( " + algname + " )" << endl;
1651 }
1652 }
1653 if (value.second.keyType == DNSSECKeeper::KSK || value.second.keyType == DNSSECKeeper::CSK) {
1654 const auto &key = value.first.getDNSKEY();
8dd7cf3d 1655 const std::string prefix(exportDS ? "" : "DS = ");
8455425c
RG
1656 cout<<prefix<<zone.toString()<<" IN DS "<<makeDSFromDNSKey(zone, key, DNSSECKeeper::SHA1).getZoneRepresentation() << " ; ( SHA1 digest )" << endl;
1657 cout<<prefix<<zone.toString()<<" IN DS "<<makeDSFromDNSKey(zone, key, DNSSECKeeper::SHA256).getZoneRepresentation() << " ; ( SHA256 digest )" << endl;
608d776f 1658 try {
8455425c 1659 string output=makeDSFromDNSKey(zone, key, DNSSECKeeper::GOST).getZoneRepresentation();
4743dfd0 1660 cout<<prefix<<zone.toString()<<" IN DS "<<output<< " ; ( GOST R 34.11-94 digest )" << endl;
e0ad7bb1
PD
1661 }
1662 catch(...)
84dc0cd2 1663 {}
e0ad7bb1 1664 try {
8455425c 1665 string output=makeDSFromDNSKey(zone, key, DNSSECKeeper::SHA384).getZoneRepresentation();
4743dfd0 1666 cout<<prefix<<zone.toString()<<" IN DS "<<output<< " ; ( SHA-384 digest )" << endl;
608d776f
BH
1667 }
1668 catch(...)
84dc0cd2 1669 {}
ade1b1e9
BH
1670 }
1671 }
1672 }
032e3906 1673 return true;
ade1b1e9 1674}
5d2e58b0 1675
675fa24c 1676bool secureZone(DNSSECKeeper& dk, const DNSName& zone)
ddac7145 1677{
36758d25 1678 // parse attribute
36758d25 1679 int k_size;
82cc0761
BZ
1680 int z_size;
1681 // temp var for addKey
1682 int64_t id;
36758d25 1683
c01b3507 1684 string k_algo = ::arg()["default-ksk-algorithm"];
36758d25 1685 k_size = ::arg().asNum("default-ksk-size");
c01b3507 1686 string z_algo = ::arg()["default-zsk-algorithm"];
36758d25
PD
1687 z_size = ::arg().asNum("default-zsk-size");
1688
1689 if (k_size < 0) {
1690 throw runtime_error("KSK key size must be equal to or greater than 0");
1691 }
1692
c01b3507 1693 if (k_algo == "" && z_algo == "") {
5209ee17 1694 throw runtime_error("Zero algorithms given for KSK+ZSK in total");
36758d25
PD
1695 }
1696
1697 if (z_size < 0) {
1698 throw runtime_error("ZSK key size must be equal to or greater than 0");
1699 }
1700
f60f4bcd 1701 if(dk.isSecuredZone(zone)) {
0b34684a 1702 cerr << "Zone '"<<zone<<"' already secure, remove keys with pdnsutil remove-zone-key if needed"<<endl;
f60f4bcd
BH
1703 return false;
1704 }
1705
2402c558
BH
1706 DomainInfo di;
1707 UeberBackend B("default");
1708 if(!B.getDomainInfo(zone, di) || !di.backend) { // di.backend and B are mostly identical
0b34684a 1709 cerr<<"Can't find a zone called '"<<zone<<"'"<<endl;
2402c558
BH
1710 return false;
1711 }
1712
3bf07122
PD
1713 if(di.kind == DomainInfo::Slave)
1714 {
694ea7ae 1715 cerr<<"Warning! This is a slave domain! If this was a mistake, please run"<<endl;
0b34684a 1716 cerr<<"pdnsutil disable-dnssec "<<zone<<" right now!"<<endl;
3bf07122
PD
1717 }
1718
c01b3507
PL
1719 if (k_algo != "") { // Add a KSK
1720 if (k_size)
1721 cout << "Securing zone with key size " << k_size << endl;
1722 else
1723 cout << "Securing zone with default key size" << endl;
36758d25 1724
c01b3507 1725 cout << "Adding "<<(z_algo == "" ? "CSK (257)" : "KSK")<<" with algorithm " << k_algo << endl;
5209ee17 1726
c01b3507 1727 int k_real_algo = DNSSECKeeper::shorthand2algorithm(k_algo);
5209ee17 1728
c01b3507 1729 if (!dk.addKey(zone, true, k_real_algo, id, k_size, true)) {
0b34684a 1730 cerr<<"No backend was able to secure '"<<zone<<"', most likely because no DNSSEC"<<endl;
5209ee17
PD
1731 cerr<<"capable backends are loaded, or because the backends have DNSSEC disabled."<<endl;
1732 cerr<<"For the Generic SQL backends, set the 'gsqlite3-dnssec', 'gmysql-dnssec' or"<<endl;
1733 cerr<<"'gpgsql-dnssec' flag. Also make sure the schema has been updated for DNSSEC!"<<endl;
1734 return false;
1735 }
1736 }
1737
c01b3507
PL
1738 if (z_algo != "") {
1739 cout << "Adding "<<(k_algo == "" ? "CSK (256)" : "ZSK")<<" with algorithm " << z_algo << endl;
5209ee17 1740
c01b3507 1741 int z_real_algo = DNSSECKeeper::shorthand2algorithm(z_algo);
5209ee17 1742
c01b3507 1743 if (!dk.addKey(zone, false, z_real_algo, id, z_size, true)) {
0b34684a 1744 cerr<<"No backend was able to secure '"<<zone<<"', most likely because no DNSSEC"<<endl;
36a885a9
PD
1745 cerr<<"capable backends are loaded, or because the backends have DNSSEC disabled."<<endl;
1746 cerr<<"For the Generic SQL backends, set the 'gsqlite3-dnssec', 'gmysql-dnssec' or"<<endl;
1747 cerr<<"'gpgsql-dnssec' flag. Also make sure the schema has been updated for DNSSEC!"<<endl;
1748 return false;
1749 }
1750 }
1751
f60f4bcd 1752 if(!dk.isSecuredZone(zone)) {
451ba512
AT
1753 cerr<<"Failed to secure zone. Is your backend dnssec enabled? (set "<<endl;
1754 cerr<<"gsqlite3-dnssec, or gmysql-dnssec etc). Check this first."<<endl;
1755 cerr<<"If you run with the BIND backend, make sure you have configured"<<endl;
1756 cerr<<"it to use DNSSEC with 'bind-dnssec-db=/path/fname' and"<<endl;
fd5076c8 1757 cerr<<"'pdnsutil create-bind-db /path/fname'!"<<endl;
f60f4bcd 1758 return false;
36758d25
PD
1759 }
1760
f60f4bcd
BH
1761 // rectifyZone(dk, zone);
1762 // showZone(dk, zone);
0b34684a 1763 cout<<"Zone "<<zone<<" secured"<<endl;
d6c16697 1764 return true;
ddac7145
BH
1765}
1766
675fa24c 1767void testSchema(DNSSECKeeper& dk, const DNSName& zone)
46d2e0d6
PD
1768{
1769 cout<<"Note: test-schema will try to create the zone, but it will not remove it."<<endl;
1770 cout<<"Please clean up after this."<<endl;
1771 cout<<endl;
1772 cout<<"Constructing UeberBackend"<<endl;
2402c558 1773 UeberBackend B("default");
46d2e0d6 1774 cout<<"Picking first backend - if this is not what you want, edit launch line!"<<endl;
2402c558 1775 DNSBackend *db = B.backends[0];
0b34684a 1776 cout<<"Creating slave domain "<<zone<<endl;
719f9024 1777 db->createSlaveDomain("127.0.0.1", zone, "", "_testschema");
46d2e0d6
PD
1778 cout<<"Slave domain created"<<endl;
1779
1780 DomainInfo di;
2402c558 1781 if(!B.getDomainInfo(zone, di) || !di.backend) { // di.backend and B are mostly identical
46d2e0d6
PD
1782 cout<<"Can't find domain we just created, aborting"<<endl;
1783 return;
1784 }
1785 db=di.backend;
1786 DNSResourceRecord rr, rrget;
1787 cout<<"Starting transaction to feed records"<<endl;
1788 db->startTransaction(zone, di.id);
1789
1790 rr.qtype=QType::SOA;
1791 rr.qname=zone;
1792 rr.ttl=86400;
1793 rr.domain_id=di.id;
1794 rr.auth=1;
1795 rr.content="ns1.example.com. ahu.example.com. 2012081039 7200 3600 1209600 3600";
1796 cout<<"Feeding SOA"<<endl;
c9b43446 1797 db->feedRecord(rr, DNSName());
46d2e0d6
PD
1798 rr.qtype=QType::TXT;
1799 // 300 As
1800 rr.content="\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"";
1801 cout<<"Feeding overlong TXT"<<endl;
c9b43446 1802 db->feedRecord(rr, DNSName());
46d2e0d6
PD
1803 cout<<"Committing"<<endl;
1804 db->commitTransaction();
1805 cout<<"Querying TXT"<<endl;
1806 db->lookup(QType(QType::TXT), zone, NULL, di.id);
1807 if(db->get(rrget))
1808 {
1809 DNSResourceRecord rrthrowaway;
1810 if(db->get(rrthrowaway)) // should not touch rr but don't assume anything
1811 {
1812 cout<<"Expected one record, got multiple, aborting"<<endl;
1813 return;
1814 }
1815 int size=rrget.content.size();
1816 if(size != 302)
1817 {
1818 cout<<"Expected 302 bytes, got "<<size<<", aborting"<<endl;
1819 return;
1820 }
1821 }
1822 cout<<"[+] content field is over 255 bytes"<<endl;
1823
1824 cout<<"Dropping all records, inserting SOA+2xA"<<endl;
1825 db->startTransaction(zone, di.id);
1826
1827 rr.qtype=QType::SOA;
1828 rr.qname=zone;
1829 rr.ttl=86400;
1830 rr.domain_id=di.id;
1831 rr.auth=1;
1832 rr.content="ns1.example.com. ahu.example.com. 2012081039 7200 3600 1209600 3600";
1833 cout<<"Feeding SOA"<<endl;
c9b43446 1834 db->feedRecord(rr, DNSName());
46d2e0d6
PD
1835
1836 rr.qtype=QType::A;
b873e23a 1837 rr.qname=DNSName("_underscore")+zone;
46d2e0d6 1838 rr.content="127.0.0.1";
c9b43446 1839 db->feedRecord(rr, DNSName());
46d2e0d6 1840
b873e23a 1841 rr.qname=DNSName("bla")+zone;
46d2e0d6
PD
1842 cout<<"Committing"<<endl;
1843 db->commitTransaction();
1844
1845 cout<<"Securing zone"<<endl;
1846 secureZone(dk, zone);
1847 cout<<"Rectifying zone"<<endl;
1848 rectifyZone(dk, zone);
1849 cout<<"Checking underscore ordering"<<endl;
675fa24c 1850 DNSName before, after;
b873e23a 1851 db->getBeforeAndAfterNames(di.id, zone, DNSName("z")+zone, before, after);
675fa24c 1852 cout<<"got '"<<before.toString()<<"' < 'z."<<zone.toString()<<"' < '"<<after.toString()<<"'"<<endl;
b873e23a 1853 if(before != DNSName("_underscore")+zone)
46d2e0d6 1854 {
675fa24c 1855 cout<<"before is wrong, got '"<<before.toString()<<"', expected '_underscore."<<zone.toString()<<"', aborting"<<endl;
46d2e0d6
PD
1856 return;
1857 }
1858 if(after != zone)
1859 {
675fa24c 1860 cout<<"after is wrong, got '"<<after.toString()<<"', expected '"<<zone.toString()<<"', aborting"<<endl;
46d2e0d6
PD
1861 return;
1862 }
1863 cout<<"[+] ordername sorting is correct for names starting with _"<<endl;
1864 cout<<endl;
0b34684a 1865 cout<<"End of tests, please remove "<<zone<<" from domains+records"<<endl;
46d2e0d6
PD
1866}
1867
6995cfa7
PL
1868int addOrSetMeta(const DNSName& zone, const string& kind, const vector<string>& values, bool clobber) {
1869 UeberBackend B("default");
1870 DomainInfo di;
1871
1872 if (!B.getDomainInfo(zone, di)) {
1873 cerr << "Invalid zone '" << zone << "'" << endl;
1874 return 1;
1875 }
1876
1877 vector<string> all_metadata;
1878
1879 if (!clobber) {
1880 B.getDomainMetadata(zone, kind, all_metadata);
1881 }
1882
1883 all_metadata.insert(all_metadata.end(), values.begin(), values.end());
1884
1885 if (!B.setDomainMetadata(zone, kind, all_metadata)) {
1886 cerr << "Unable to set meta for '" << zone << "'" << endl;
1887 return 1;
1888 }
1889
1890 cout << "Set '" << zone << "' meta " << kind << " = " << boost::join(all_metadata, ", ") << endl;
1891 return 0;
1892}
1893
1d211b1b 1894int main(int argc, char** argv)
20002664 1895try
488bcb39 1896{
1d211b1b
BH
1897 po::options_description desc("Allowed options");
1898 desc.add_options()
1899 ("help,h", "produce help message")
d2395dfd 1900 ("version", "show version")
b3ce3dec 1901 ("verbose,v", "be verbose")
1d211b1b 1902 ("force", "force an action")
aa952078 1903 ("config-name", po::value<string>()->default_value(""), "virtual configuration name")
7d9dcde0 1904 ("config-dir", po::value<string>()->default_value(SYSCONFDIR), "location of pdns.conf")
1d211b1b
BH
1905 ("commands", po::value<vector<string> >());
1906
1907 po::positional_options_description p;
1908 p.add("commands", -1);
1909 po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), g_vm);
1910 po::notify(g_vm);
1911
1912 vector<string> cmds;
1913
d2395dfd 1914 if(g_vm.count("commands"))
1d211b1b
BH
1915 cmds = g_vm["commands"].as<vector<string> >();
1916
b3ce3dec
BH
1917 g_verbose = g_vm.count("verbose");
1918
d2395dfd
PL
1919 if (g_vm.count("version")) {
1920 cout<<"pdnsutil "<<VERSION<<endl;
1921 return 0;
1922 }
1923
0f413d52 1924 if(cmds.empty() || g_vm.count("help") || cmds[0] == "help") {
e230941e 1925 cout<<"Usage: \npdnsutil [options] <command> [params ..]\n"<<endl;
1926 cout<<"Commands:"<<endl;
1927 cout<<"activate-tsig-key ZONE NAME {master|slave}"<<endl;
ad7568d5 1928 cout<<" Enable TSIG authenticated AXFR using the key NAME for ZONE"<<endl;
e230941e 1929 cout<<"activate-zone-key ZONE KEY-ID Activate the key with key id KEY-ID in ZONE"<<endl;
1930 cout<<"add-record ZONE NAME TYPE [ttl] content"<<endl;
1931 cout<<" [content..] Add one or more records to ZONE"<<endl;
1932 cout<<"add-zone-key ZONE {zsk|ksk} [BITS] [active|inactive]"<<endl;
cd2565d4 1933 cout<<" [rsasha1|rsasha256|rsasha512|ecdsa256|ecdsa384";
21a8834a 1934#if defined(HAVE_LIBSODIUM) || defined(HAVE_LIBDECAF)
9d3727e0 1935 cout<<"|ed25519";
21a8834a
KM
1936#endif
1937#ifdef HAVE_LIBDECAF
1938 cout<<"|ed448";
feafa2f3 1939#endif
e230941e 1940 cout<<"]"<<endl;
1941 cout<<" Add a ZSK or KSK to zone and specify algo&bits"<<endl;
1942 cout<<"backend-cmd BACKEND CMD [CMD..] Perform one or more backend commands"<<endl;
1943 cout<<"b2b-migrate OLD NEW Move all data from one backend to another"<<endl;
1944 cout<<"bench-db [filename] Bench database backend with queries, one domain per line"<<endl;
1945 cout<<"check-zone ZONE Check a zone for correctness"<<endl;
1946 cout<<"check-all-zones [exit-on-error] Check all zones for correctness. Set exit-on-error to exit immediately"<<endl;
1947 cout<<" after finding an error in a zone."<<endl;
1948 cout<<"clear-zone ZONE Clear all records of a zone, but keep everything else"<<endl;
1949 cout<<"create-bind-db FNAME Create DNSSEC db for BIND backend (bind-dnssec-db)"<<endl;
1950 cout<<"create-slave-zone ZONE master-ip [master-ip..]"<<endl;
1951 cout<<" Create slave zone ZONE with master IP address master-ip"<<endl;
324ead90
HY
1952 cout<<"change-slave-zone-master ZONE master-ip [master-ip..]"<<endl;
1953 cout<<" Change slave zone ZONE master IP address to master-ip"<<endl;
e230941e 1954 cout<<"create-zone ZONE [nsname] Create empty zone ZONE"<<endl;
1955 cout<<"deactivate-tsig-key ZONE NAME {master|slave}"<<endl;
ad7568d5 1956 cout<<" Disable TSIG authenticated AXFR using the key NAME for ZONE"<<endl;
e230941e 1957 cout<<"deactivate-zone-key ZONE KEY-ID Deactivate the key with key id KEY-ID in ZONE"<<endl;
1958 cout<<"delete-rrset ZONE NAME TYPE Delete named RRSET from zone"<<endl;
1959 cout<<"delete-tsig-key NAME Delete TSIG key (warning! will not unmap key!)"<<endl;
1960 cout<<"delete-zone ZONE Delete the zone"<<endl;
1961 cout<<"disable-dnssec ZONE Deactivate all keys and unset PRESIGNED in ZONE"<<endl;
1962 cout<<"edit-zone ZONE Edit zone contents using $EDITOR"<<endl;
1963 cout<<"export-zone-dnskey ZONE KEY-ID Export to stdout the public DNSKEY described"<<endl;
84dc0cd2 1964 cout<<"export-zone-ds ZONE Export to stdout all KSK DS records for ZONE"<<endl;
e230941e 1965 cout<<"export-zone-key ZONE KEY-ID Export to stdout the private key described"<<endl;
1966 cout<<"generate-tsig-key NAME ALGORITHM Generate new TSIG key"<<endl;
1967 cout<<"generate-zone-key {zsk|ksk} [ALGORITHM] [BITS]"<<endl;
1968 cout<<" Generate a ZSK or KSK to stdout with specified ALGORITHM and BITS"<<endl;
1969 cout<<"get-meta ZONE [KIND ...] Get zone metadata. If no KIND given, lists all known"<<endl;
1970 cout<<"hash-zone-record ZONE RNAME Calculate the NSEC3 hash for RNAME in ZONE"<<endl;
3c12a7e9 1971#ifdef HAVE_P11KIT1
e230941e 1972 cout<<"hsm assign ZONE ALGORITHM {ksk|zsk} MODULE SLOT PIN LABEL"<<endl<<
3c12a7e9 1973 " Assign a hardware signing module to a ZONE"<<endl;
488bcb39 1974 cout<<"hsm create-key ZONE KEY-ID [BITS] Create a key using hardware signing module for ZONE (use assign first)"<<endl;
e230941e 1975 cout<<" BITS defaults to 2048"<<endl;
3c12a7e9 1976#endif
e230941e 1977 cout<<"increase-serial ZONE Increases the SOA-serial by 1. Uses SOA-EDIT"<<endl;
1978 cout<<"import-tsig-key NAME ALGORITHM KEY Import TSIG key"<<endl;
1979 cout<<"import-zone-key ZONE FILE Import from a file a private key, ZSK or KSK"<<endl;
2ae24e09 1980 cout<<" [active|inactive] [ksk|zsk] Defaults to KSK and active"<<endl;
488bcb39 1981 cout<<"ipdecrypt IP passphrase/key [key] Encrypt IP address using passphrase or base64 key"<<endl;
2ae24e09 1982 cout<<"ipencrypt IP passphrase/key [key] Encrypt IP address using passphrase or base64 key"<<endl;
e230941e 1983 cout<<"load-zone ZONE FILE Load ZONE from FILE, possibly creating zone or atomically"<<endl;
1984 cout<<" replacing contents"<<endl;
1985 cout<<"list-algorithms [with-backend] List all DNSSEC algorithms supported, optionally also listing the crypto library used"<<endl;
1986 cout<<"list-keys [ZONE] List DNSSEC keys for ZONE. When ZONE is unset or \"all\", display all keys for all zones"<<endl;
1987 cout<<"list-zone ZONE List zone contents"<<endl;
1988 cout<<"list-all-zones [master|slave|native]"<<endl;
1989 cout<<" List all zone names"<<endl;;
1990 cout<<"list-tsig-keys List all TSIG keys"<<endl;
1991 cout<<"rectify-zone ZONE [ZONE ..] Fix up DNSSEC fields (order, auth)"<<endl;
6a935fb1 1992 cout<<"rectify-all-zones [quiet] Rectify all zones. Optionally quiet output with errors only"<<endl;
e230941e 1993 cout<<"remove-zone-key ZONE KEY-ID Remove key with KEY-ID from ZONE"<<endl;
1994 cout<<"replace-rrset ZONE NAME TYPE [ttl] Replace named RRSET from zone"<<endl;
1995 cout<<" content [content..]"<<endl;
1996 cout<<"secure-all-zones [increase-serial] Secure all zones without keys"<<endl;
1997 cout<<"secure-zone ZONE [ZONE ..] Add DNSSEC to zone ZONE"<<endl;
1998 cout<<"set-kind ZONE KIND Change the kind of ZONE to KIND (master, slave native)"<<endl;
6617c29e 1999 cout<<"set-account ZONE ACCOUNT Change the account (owner) of ZONE to ACCOUNT"<<endl;
e230941e 2000 cout<<"set-nsec3 ZONE ['PARAMS' [narrow]] Enable NSEC3 with PARAMS. Optionally narrow"<<endl;
2001 cout<<"set-presigned ZONE Use presigned RRSIGs from storage"<<endl;
2002 cout<<"set-publish-cdnskey ZONE Enable sending CDNSKEY responses for ZONE"<<endl;
1ec08a2b 2003 cout<<"set-publish-cds ZONE [DIGESTALGOS] Enable sending CDS responses for ZONE, using DIGESTALGOS as signature algorithms"<<endl;
47dbee2b 2004 cout<<" DIGESTALGOS should be a comma separated list of numbers, it is '1,2' by default"<<endl;
6995cfa7
PL
2005 cout<<"add-meta ZONE KIND VALUE Add zone metadata, this adds to the existing KIND"<<endl;
2006 cout<<" [VALUE ...]"<<endl;
a6d1641f 2007 cout<<"set-meta ZONE KIND [VALUE] [VALUE] Set zone metadata, optionally providing a value. *No* value clears meta"<<endl;
e230941e 2008 cout<<" Note - this will replace all metadata records of KIND!"<<endl;
2009 cout<<"show-zone ZONE Show DNSSEC (public) key details about a zone"<<endl;
2010 cout<<"unset-nsec3 ZONE Switch back to NSEC"<<endl;
2011 cout<<"unset-presigned ZONE No longer use presigned RRSIGs"<<endl;
2012 cout<<"unset-publish-cdnskey ZONE Disable sending CDNSKEY responses for ZONE"<<endl;
2013 cout<<"unset-publish-cds ZONE Disable sending CDS responses for ZONE"<<endl;
2014 cout<<"test-schema ZONE Test DB schema - will create ZONE"<<endl;
2015 cout<<desc<<endl;
1d211b1b
BH
2016 return 0;
2017 }
ca8e1742 2018
bf269e28 2019 loadMainConfig(g_vm["config-dir"].as<string>());
7581a35b 2020
cbb0025b 2021 if (cmds[0] == "test-algorithm") {
2551cc18 2022 if(cmds.size() != 2) {
fd5076c8 2023 cerr << "Syntax: pdnsutil test-algorithm algonum"<<endl;
2551cc18
PD
2024 return 0;
2025 }
335da0ba 2026 if (testAlgorithm(pdns_stou(cmds[1])))
166d8647
KM
2027 return 0;
2028 return 1;
cbb0025b
PD
2029 }
2030
caff6e16 2031 if(cmds[0] == "ipencrypt" || cmds[0]=="ipdecrypt") {
2ae24e09 2032 if(cmds.size() < 3 || (cmds.size()== 4 && cmds[3]!="key")) {
2033 cerr<<"Syntax: pdnsutil [ipencrypt|ipdecrypt] IP passphrase [key]"<<endl;
caff6e16 2034 return 0;
2035 }
2ae24e09 2036 string key;
2037 if(cmds.size()==4) {
2038 if(B64Decode(cmds[2], key) < 0) {
2039 cerr<<"Could not parse '"<<cmds[3]<<"' as base64"<<endl;
2040 return 0;
2041 }
2042 }
2043 else {
2044 key = makeIPCipherKey(cmds[2]);
2045 }
2046 exit(xcryptIP(cmds[0], cmds[1], key));
caff6e16 2047 }
2048
2049
ea937fd4 2050 if(cmds[0] == "test-algorithms") {
166d8647
KM
2051 if (testAlgorithms())
2052 return 0;
2053 return 1;
ea937fd4
BH
2054 }
2055
98d13a90
PL
2056 if(cmds[0] == "list-algorithms") {
2057 if((cmds.size() == 2 && cmds[1] != "with-backend") || cmds.size() > 2) {
2058 cerr<<"Syntax: pdnsutil list-algorithms [with-backend]"<<endl;
2059 return 1;
2060 }
2061
2062 cout<<"DNSKEY algorithms supported by this installation of PowerDNS:"<<endl;
2063
2064 auto algosWithBackend = DNSCryptoKeyEngine::listAllAlgosWithBackend();
2065 for (auto const algoWithBackend : algosWithBackend){
2066 string algoName = DNSSECKeeper::algorithm2name(algoWithBackend.first);
2067 cout<<std::to_string(algoWithBackend.first)<<" - "<<algoName;
2068 if (cmds.size() == 2 && cmds[1] == "with-backend")
2069 cout<<" using "<<algoWithBackend.second;
2070 cout<<endl;
2071 }
2072 return 0;
2073 }
2074
6dfa0aa0 2075 reportAllTypes();
b925384e 2076
2717b8b3 2077 if(cmds[0] == "create-bind-db") {
a2b0e9b5 2078#ifdef HAVE_SQLITE3
fbe72b7a 2079 if(cmds.size() != 2) {
fd5076c8 2080 cerr << "Syntax: pdnsutil create-bind-db FNAME"<<endl;
fbe72b7a
BH
2081 return 0;
2082 }
080f5d57 2083 try {
a2b0e9b5
KM
2084 SSQLite3 db(cmds[1], true); // create=ok
2085 vector<string> statements;
2086 stringtok(statements, sqlCreate, ";");
ff05fd12 2087 for(const string& statement : statements) {
0f310932
AT
2088 db.execute(statement);
2089 }
080f5d57 2090 }
a2b0e9b5
KM
2091 catch(SSqlException& se) {
2092 throw PDNSException("Error creating database in BIND backend: "+se.txtReason());
080f5d57
PD
2093 }
2094 return 0;
a2b0e9b5 2095#else
bd6c6334 2096 cerr<<"bind-dnssec-db requires building PowerDNS with SQLite3"<<endl;
a2b0e9b5
KM
2097 return 1;
2098#endif
2717b8b3 2099 }
9a798fb0 2100
fbe72b7a
BH
2101 DNSSECKeeper dk;
2102
46d2e0d6
PD
2103 if (cmds[0] == "test-schema") {
2104 if(cmds.size() != 2) {
fd5076c8 2105 cerr << "Syntax: pdnsutil test-schema ZONE"<<endl;
46d2e0d6
PD
2106 return 0;
2107 }
b873e23a 2108 testSchema(dk, DNSName(cmds[1]));
46d2e0d6
PD
2109 return 0;
2110 }
fbe72b7a 2111 if(cmds[0] == "rectify-zone") {
d4904322 2112 if(cmds.size() < 2) {
fd5076c8 2113 cerr << "Syntax: pdnsutil rectify-zone ZONE [ZONE..]"<<endl;
81b39e4b
BH
2114 return 0;
2115 }
032e3906 2116 unsigned int exitCode = 0;
488bcb39
RG
2117 for(unsigned int n = 1; n < cmds.size(); ++n)
2118 if (!rectifyZone(dk, DNSName(cmds[n])))
b873e23a 2119 exitCode = 1;
032e3906 2120 return exitCode;
20002664 2121 }
1325e8a2 2122 else if (cmds[0] == "rectify-all-zones") {
64dea5c2
CHB
2123 bool quiet = (cmds.size() >= 2 && cmds[1] == "quiet");
2124 if (!rectifyAllZones(dk, quiet)) {
2125 return 1;
2126 }
1325e8a2 2127 }
9abd98d3 2128 else if(cmds[0] == "check-zone") {
5d2e58b0 2129 if(cmds.size() != 2) {
fd5076c8 2130 cerr << "Syntax: pdnsutil check-zone ZONE"<<endl;
5d2e58b0
BH
2131 return 0;
2132 }
ba86110a 2133 UeberBackend B("default");
b873e23a 2134 exit(checkZone(dk, B, DNSName(cmds[1])));
5d2e58b0 2135 }
a0a6cb58 2136 else if(cmds[0] == "bench-db") {
2137 dbBench(cmds.size() > 1 ? cmds[1] : "");
2138 }
1325e8a2 2139 else if (cmds[0] == "check-all-zones") {
f6eb8c48 2140 bool exitOnError = ((cmds.size() >= 2 ? cmds[1] : "") == "exit-on-error");
d6ddb28a 2141 exit(checkAllZones(dk, exitOnError));
1325e8a2 2142 }
bd108049 2143 else if (cmds[0] == "list-all-zones") {
22c68348 2144 if (cmds.size() > 2) {
fd5076c8 2145 cerr << "Syntax: pdnsutil list-all-zones [master|slave|native]"<<endl;
22c68348
KM
2146 return 0;
2147 }
2148 if (cmds.size() == 2)
2149 return listAllZones(cmds[1]);
2150 return listAllZones();
bd108049 2151 }
81e9ba89
PD
2152 else if (cmds[0] == "test-zone") {
2153 cerr << "Did you mean check-zone?"<<endl;
2154 return 0;
2155 }
2156 else if (cmds[0] == "test-all-zones") {
2157 cerr << "Did you mean check-all-zones?"<<endl;
2158 return 0;
2159 }
49449751
BH
2160#if 0
2161 else if(cmds[0] == "signing-server" )
2162 {
2163 signingServer();
2164 }
2165 else if(cmds[0] == "signing-slave")
2166 {
2167 launchSigningService(0);
2168 }
2169#endif
ea937fd4 2170 else if(cmds[0] == "test-speed") {
37fd8771 2171 if(cmds.size() < 2) {
fd5076c8 2172 cerr << "Syntax: pdnsutil test-speed numcores [signing-server]"<<endl;
ea937fd4
BH
2173 return 0;
2174 }
335da0ba 2175 testSpeed(dk, DNSName(cmds[1]), (cmds.size() > 3) ? cmds[3] : "", pdns_stou(cmds[2]));
189bb9d2 2176 }
aa65a832
BH
2177 else if(cmds[0] == "verify-crypto") {
2178 if(cmds.size() != 2) {
fd5076c8 2179 cerr << "Syntax: pdnsutil verify-crypto FILE"<<endl;
aa65a832
BH
2180 return 0;
2181 }
2182 verifyCrypto(cmds[1]);
2183 }
da11ed0e 2184 else if(cmds[0] == "show-zone") {
a0472099 2185 if(cmds.size() != 2) {
fd5076c8 2186 cerr << "Syntax: pdnsutil show-zone ZONE"<<endl;
a0472099
BH
2187 return 0;
2188 }
b873e23a 2189 if (!showZone(dk, DNSName(cmds[1]))) return 1;
1d211b1b 2190 }
84dc0cd2
JW
2191 else if(cmds[0] == "export-zone-ds") {
2192 if(cmds.size() != 2) {
2193 cerr << "Syntax: pdnsutil export-zone-ds ZONE"<<endl;
2194 return 0;
2195 }
2196 if (!showZone(dk, DNSName(cmds[1]), true)) return 1;
2197 }
5935cede
BH
2198 else if(cmds[0] == "disable-dnssec") {
2199 if(cmds.size() != 2) {
fd5076c8 2200 cerr << "Syntax: pdnsutil disable-dnssec ZONE"<<endl;
5935cede
BH
2201 return 0;
2202 }
b873e23a 2203 DNSName zone(cmds[1]);
0b8e59ea
AT
2204 if(!disableDNSSECOnZone(dk, zone)) {
2205 cerr << "Cannot disable DNSSEC on " << zone << endl;
032e3906 2206 return 1;
0b8e59ea 2207 }
5935cede 2208 }
bed962b5 2209 else if(cmds[0] == "activate-zone-key") {
37fd8771 2210 if(cmds.size() != 3) {
fd5076c8 2211 cerr << "Syntax: pdnsutil activate-zone-key ZONE KEY-ID"<<endl;
37fd8771
BH
2212 return 0;
2213 }
b873e23a 2214 DNSName zone(cmds[1]);
da21e55a 2215 unsigned int id=atoi(cmds[2].c_str()); // if you make this pdns_stou, the error gets worse
77b909cc
PD
2216 if(!id)
2217 {
da21e55a 2218 cerr<<"Invalid KEY-ID '"<<cmds[2]<<"'"<<endl;
77b909cc
PD
2219 return 1;
2220 }
a84a8203
PD
2221 if (!dk.activateKey(zone, id)) {
2222 cerr<<"Activation of key failed"<<endl;
2223 return 1;
2224 }
2225 return 0;
bed962b5
BH
2226 }
2227 else if(cmds[0] == "deactivate-zone-key") {
37fd8771 2228 if(cmds.size() != 3) {
fd5076c8 2229 cerr << "Syntax: pdnsutil deactivate-zone-key ZONE KEY-ID"<<endl;
37fd8771
BH
2230 return 0;
2231 }
b873e23a 2232 DNSName zone(cmds[1]);
335da0ba 2233 unsigned int id=pdns_stou(cmds[2]);
77b909cc
PD
2234 if(!id)
2235 {
2236 cerr<<"Invalid KEY-ID"<<endl;
2237 return 1;
2238 }
a84a8203
PD
2239 if (!dk.deactivateKey(zone, id)) {
2240 cerr<<"Deactivation of key failed"<<endl;
2241 return 1;
2242 }
2243 return 0;
bed962b5
BH
2244 }
2245 else if(cmds[0] == "add-zone-key") {
37fd8771 2246 if(cmds.size() < 3 ) {
cd2565d4
MN
2247 cerr << "Syntax: pdnsutil add-zone-key ZONE zsk|ksk [BITS] [active|inactive] [rsasha1|rsasha256|rsasha512|ecdsa256|ecdsa384";
2248#if defined(HAVE_LIBSODIUM) || defined(HAVE_LIBDECAF)
2249 cerr << "|ed25519";
2250#endif
2251#ifdef HAVE_LIBDECAF
2252 cerr << "|ed448";
2253#endif
2254 cerr << "]"<<endl;
37fd8771
BH
2255 return 0;
2256 }
b873e23a 2257 DNSName zone(cmds[1]);
032e3906
PD
2258
2259 UeberBackend B("default");
2260 DomainInfo di;
2261
2262 if (!B.getDomainInfo(zone, di)){
2263 cerr << "No such zone in the database" << endl;
2264 return 0;
2265 }
2266
36c394e5
BH
2267 // need to get algorithm, bits & ksk or zsk from commandline
2268 bool keyOrZone=false;
36758d25 2269 int tmp_algo=0;
36c394e5 2270 int bits=0;
902c4e9c 2271 int algorithm=DNSSECKeeper::ECDSA256;
4af49b80 2272 bool active=false;
36c394e5
BH
2273 for(unsigned int n=2; n < cmds.size(); ++n) {
2274 if(pdns_iequals(cmds[n], "zsk"))
2275 keyOrZone = false;
2276 else if(pdns_iequals(cmds[n], "ksk"))
2277 keyOrZone = true;
b6bd795c 2278 else if((tmp_algo = DNSSECKeeper::shorthand2algorithm(cmds[n]))>0) {
36758d25 2279 algorithm = tmp_algo;
4af49b80 2280 } else if(pdns_iequals(cmds[n], "active")) {
2281 active=true;
d9db3d7e 2282 } else if(pdns_iequals(cmds[n], "inactive") || pdns_iequals(cmds[n], "passive")) { // 'passive' eventually needs to be removed
4af49b80 2283 active=false;
335da0ba
AT
2284 } else if(pdns_stou(cmds[n])) {
2285 bits = pdns_stou(cmds[n]);
488bcb39 2286 } else {
a254438f 2287 cerr<<"Unknown algorithm, key flag or size '"<<cmds[n]<<"'"<<endl;
07bf35d1 2288 exit(EXIT_FAILURE);;
36c394e5
BH
2289 }
2290 }
82cc0761
BZ
2291 int64_t id;
2292 if (!dk.addKey(zone, keyOrZone, algorithm, id, bits, active)) {
07bf35d1 2293 cerr<<"Adding key failed, perhaps DNSSEC not enabled in configuration?"<<endl;
2294 exit(1);
82cc0761 2295 } else {
07bf35d1 2296 cerr<<"Added a " << (keyOrZone ? "KSK" : "ZSK")<<" with algorithm = "<<algorithm<<", active="<<active<<endl;
82cc0761 2297 if (bits)
232f0877 2298 cerr<<"Requested specific key size of "<<bits<<" bits"<<endl;
82cc0761
BZ
2299 if (id == -1) {
2300 cerr<<std::to_string(id)<<"Key was added, but backend does not support returning of key id"<<endl;
2301 } else if (id < -1) {
2302 cerr<<std::to_string(id)<<"Key was added, but there was a failure while returning the key id"<<endl;
2303 } else {
2304 cout<<std::to_string(id)<<endl;
2305 }
07bf35d1 2306 }
bed962b5
BH
2307 }
2308 else if(cmds[0] == "remove-zone-key") {
471304cc 2309 if(cmds.size() < 3) {
fd5076c8 2310 cerr<<"Syntax: pdnsutil remove-zone-key ZONE KEY-ID"<<endl;
471304cc
BH
2311 return 0;
2312 }
b873e23a 2313 DNSName zone(cmds[1]);
335da0ba 2314 unsigned int id=pdns_stou(cmds[2]);
a84a8203 2315 if (!dk.removeKey(zone, id)) {
0b8e59ea 2316 cerr<<"Cannot remove key " << id << " from " << zone <<endl;
a84a8203
PD
2317 return 1;
2318 }
2319 return 0;
bed962b5 2320 }
51f6bca1
RA
2321 else if(cmds[0] == "delete-zone") {
2322 if(cmds.size() != 2) {
fd5076c8 2323 cerr<<"Syntax: pdnsutil delete-zone ZONE"<<endl;
51f6bca1
RA
2324 return 0;
2325 }
b873e23a 2326 exit(deleteZone(DNSName(cmds[1])));
51f6bca1 2327 }
c9865bc5 2328 else if(cmds[0] == "create-zone") {
66d34461 2329 if(cmds.size() != 2 && cmds.size()!=3 ) {
2330 cerr<<"Syntax: pdnsutil create-zone ZONE [nsname]"<<endl;
2331 return 0;
2332 }
2333 exit(createZone(DNSName(cmds[1]), cmds.size() > 2 ? DNSName(cmds[2]): DNSName()));
2334 }
e85a76ad 2335 else if(cmds[0] == "create-slave-zone") {
2336 if(cmds.size() < 3 ) {
2337 cerr<<"Syntax: pdnsutil create-slave-zone ZONE master-ip [master-ip..]"<<endl;
2338 return 0;
2339 }
2340 exit(createSlaveZone(cmds));
2341 }
324ead90
HY
2342 else if(cmds[0] == "change-slave-zone-master") {
2343 if(cmds.size() < 3 ) {
2344 cerr<<"Syntax: pdnsutil change-slave-zone-master ZONE master-ip [master-ip..]"<<endl;
2345 return 0;
2346 }
2347 exit(changeSlaveZoneMaster(cmds));
2348 }
66d34461 2349 else if(cmds[0] == "add-record") {
2350 if(cmds.size() < 5) {
2351 cerr<<"Syntax: pdnsutil add-record ZONE name type [ttl] \"content\" [\"content\"...]"<<endl;
2352 return 0;
2353 }
2354 exit(addOrReplaceRecord(true, cmds));
2355 }
2356 else if(cmds[0] == "replace-rrset") {
2357 if(cmds.size() < 5) {
a37c972b 2358 cerr<<"Syntax: pdnsutil replace-rrset ZONE name type [ttl] \"content\" [\"content\"...]"<<endl;
66d34461 2359 return 0;
2360 }
2361 exit(addOrReplaceRecord(false , cmds));
2362 }
2363 else if(cmds[0] == "delete-rrset") {
2364 if(cmds.size() != 4) {
2365 cerr<<"Syntax: pdnsutil delete-rrset ZONE name type"<<endl;
c9865bc5 2366 return 0;
2367 }
66d34461 2368 exit(deleteRRSet(cmds[1], cmds[2], cmds[3]));
c9865bc5 2369 }
2370 else if(cmds[0] == "list-zone") {
2371 if(cmds.size() != 2) {
fd5076c8 2372 cerr<<"Syntax: pdnsutil list-zone ZONE"<<endl;
c9865bc5 2373 return 0;
2374 }
2375 if(cmds[1]==".")
2376 cmds[1].clear();
2377
b873e23a 2378 exit(listZone(DNSName(cmds[1])));
c9865bc5 2379 }
c2e0881c 2380 else if(cmds[0] == "edit-zone") {
2381 if(cmds.size() != 2) {
2382 cerr<<"Syntax: pdnsutil edit-zone ZONE"<<endl;
2383 return 0;
2384 }
2385 if(cmds[1]==".")
2386 cmds[1].clear();
2387
2388 exit(editZone(dk, DNSName(cmds[1])));
2389 }
eed2ecbe 2390 else if(cmds[0] == "clear-zone") {
2391 if(cmds.size() != 2) {
2392 cerr<<"Syntax: pdnsutil edit-zone ZONE"<<endl;
2393 return 0;
2394 }
2395 if(cmds[1]==".")
2396 cmds[1].clear();
c2e0881c 2397
eed2ecbe 2398 exit(clearZone(dk, DNSName(cmds[1])));
2399 }
597b9b3e
PL
2400 else if(cmds[0] == "list-keys") {
2401 if(cmds.size() > 2) {
fd5076c8 2402 cerr<<"Syntax: pdnsutil list-keys [ZONE]"<<endl;
597b9b3e
PL
2403 return 0;
2404 }
2405 string zname = (cmds.size() == 2) ? cmds[1] : "all";
2406 exit(listKeys(zname, dk));
2407 }
c9865bc5 2408 else if(cmds[0] == "load-zone") {
d24632fe 2409 if(cmds.size() < 3) {
2410 cerr<<"Syntax: pdnsutil load-zone ZONE FILENAME [ZONE FILENAME] .."<<endl;
c9865bc5 2411 return 0;
2412 }
2413 if(cmds[1]==".")
2414 cmds[1].clear();
2415
867aa684 2416 for(size_t n=1; n + 2 <= cmds.size(); n+=2)
d24632fe 2417 loadZone(DNSName(cmds[n]), cmds[n+1]);
2418 return 0;
c9865bc5 2419 }
c3c89361 2420 else if(cmds[0] == "secure-zone") {
ddac7145 2421 if(cmds.size() < 2) {
fd5076c8 2422 cerr << "Syntax: pdnsutil secure-zone ZONE"<<endl;
a9175ad6
BH
2423 return 0;
2424 }
b873e23a 2425 vector<DNSName> mustRectify;
1325e8a2 2426 unsigned int zoneErrors=0;
ddac7145 2427 for(unsigned int n = 1; n < cmds.size(); ++n) {
b873e23a 2428 DNSName zone(cmds[n]);
7da05748 2429 dk.startTransaction(zone, -1);
f60f4bcd 2430 if(secureZone(dk, zone)) {
d6c16697 2431 mustRectify.push_back(zone);
1325e8a2
PD
2432 } else {
2433 zoneErrors++;
d6c16697 2434 }
7da05748 2435 dk.commitTransaction();
f60f4bcd 2436 }
488bcb39 2437
b873e23a 2438 for(const auto& zone : mustRectify)
d6c16697 2439 rectifyZone(dk, zone);
1325e8a2
PD
2440
2441 if (zoneErrors) {
2442 return 1;
2443 }
2444 return 0;
1d211b1b 2445 }
fa377773 2446 else if (cmds[0] == "secure-all-zones") {
f84dba01 2447 if (cmds.size() >= 2 && !pdns_iequals(cmds[1], "increase-serial")) {
fd5076c8 2448 cerr << "Syntax: pdnsutil secure-all-zones [increase-serial]"<<endl;
f84dba01
KM
2449 return 0;
2450 }
2451
fa377773
KM
2452 UeberBackend B("default");
2453
fa377773
KM
2454 vector<DomainInfo> domainInfo;
2455 B.getAllDomains(&domainInfo);
2456
f84dba01 2457 unsigned int zonesSecured=0, zoneErrors=0;
ff05fd12 2458 for(DomainInfo di : domainInfo) {
fa377773 2459 if(!dk.isSecuredZone(di.zone)) {
0b34684a 2460 cout<<"Securing "<<di.zone<<": ";
f84dba01
KM
2461 if (secureZone(dk, di.zone)) {
2462 zonesSecured++;
2463 if (cmds.size() == 2) {
2464 if (!increaseSerial(di.zone, dk))
2465 continue;
2466 } else
2467 continue;
2468 }
2469 zoneErrors++;
fa377773
KM
2470 }
2471 }
fa377773 2472
f84dba01 2473 cout<<"Secured: "<<zonesSecured<<" zones. Errors: "<<zoneErrors<<endl;
fa377773
KM
2474
2475 if (zoneErrors) {
2476 return 1;
2477 }
2478 return 0;
2479 }
bddc5d92 2480 else if(cmds[0]=="set-kind") {
2481 if(cmds.size() != 3) {
2482 cerr<<"Syntax: pdnsutil set-kind ZONE KIND"<<endl;
044dfb9b 2483 return 0;
bddc5d92 2484 }
2485 DNSName zone(cmds[1]);
2486 auto kind=DomainInfo::stringToKind(cmds[2]);
2487 exit(setZoneKind(zone, kind));
2488 }
6617c29e
MS
2489 else if(cmds[0]=="set-account") {
2490 if(cmds.size() != 3) {
2491 cerr<<"Syntax: pdnsutil set-account ZONE ACCOUNT"<<endl;
044dfb9b 2492 return 0;
6617c29e
MS
2493 }
2494 DNSName zone(cmds[1]);
2495 exit(setZoneAccount(zone, cmds[2]));
2496 }
da11ed0e 2497 else if(cmds[0]=="set-nsec3") {
37fd8771 2498 if(cmds.size() < 2) {
fd5076c8 2499 cerr<<"Syntax: pdnsutil set-nsec3 ZONE 'params' [narrow]"<<endl;
37fd8771
BH
2500 return 0;
2501 }
b8adb30d 2502 string nsec3params = cmds.size() > 2 ? cmds[2] : "1 0 1 ab";
22c5aa60 2503 bool narrow = cmds.size() > 3 && cmds[3]=="narrow";
da11ed0e 2504 NSEC3PARAMRecordContent ns3pr(nsec3params);
7649cd71 2505
675fa24c 2506 DNSName zone(cmds[1]);
3155c04a 2507 if (zone.wirelength() > 222) {
0b34684a 2508 cerr<<"Cannot enable NSEC3 for " << zone << " as it is too long (" << zone.wirelength() << " bytes, maximum is 222 bytes)"<<endl;
3155c04a
PL
2509 return 1;
2510 }
265a7bbc
PL
2511 if(ns3pr.d_algorithm != 1) {
2512 cerr<<"NSEC3PARAM algorithm set to '"<<std::to_string(ns3pr.d_algorithm)<<"', but '1' is the only valid value"<<endl;
2513 return EXIT_FAILURE;
2514 }
7649cd71 2515 if (! dk.setNSEC3PARAM(zone, ns3pr, narrow)) {
0b34684a 2516 cerr<<"Cannot set NSEC3 param for " << zone << endl;
7649cd71 2517 return 1;
775acd9e 2518 }
7649cd71 2519
b8adb30d 2520 if (!ns3pr.d_flags)
7649cd71 2521 cerr<<"NSEC3 set, ";
b8adb30d 2522 else
7649cd71
KM
2523 cerr<<"NSEC3 (opt-out) set, ";
2524
2525 if(dk.isSecuredZone(zone))
2526 cerr<<"please rectify your zone if your backend needs it"<<endl;
2527 else
2528 cerr<<"please secure and rectify your zone."<<endl;
2529
2530 return 0;
da11ed0e 2531 }
d3e7090c 2532 else if(cmds[0]=="set-presigned") {
5935cede 2533 if(cmds.size() < 2) {
fd5076c8 2534 cerr<<"Syntax: pdnsutil set-presigned ZONE"<<endl;
488bcb39 2535 return 0;
5935cede 2536 }
b873e23a 2537 if (! dk.setPresigned(DNSName(cmds[1]))) {
e65b1b74 2538 cerr << "Could not set presigned for " << cmds[1] << " (is DNSSEC enabled in your backend?)" << endl;
a84a8203
PD
2539 return 1;
2540 }
2541 return 0;
d3e7090c 2542 }
088370cd
PL
2543 else if(cmds[0]=="set-publish-cdnskey") {
2544 if(cmds.size() < 2) {
fd5076c8 2545 cerr<<"Syntax: pdnsutil set-publish-cdnskey ZONE"<<endl;
088370cd
PL
2546 return 0;
2547 }
da347642 2548 if (! dk.setPublishCDNSKEY(DNSName(cmds[1]))) {
088370cd
PL
2549 cerr << "Could not set publishing for CDNSKEY records for "<< cmds[1]<<endl;
2550 return 1;
2551 }
2552 return 0;
2553 }
ef542223
PL
2554 else if(cmds[0]=="set-publish-cds") {
2555 if(cmds.size() < 2) {
fd5076c8 2556 cerr<<"Syntax: pdnsutil set-publish-cds ZONE [DIGESTALGOS]"<<endl;
ef542223
PL
2557 return 0;
2558 }
2559
2560 // If DIGESTALGOS is unset
2561 if(cmds.size() == 2)
2562 cmds.push_back("1,2");
2563
da347642 2564 if (! dk.setPublishCDS(DNSName(cmds[1]), cmds[2])) {
ef542223
PL
2565 cerr << "Could not set publishing for CDS records for "<< cmds[1]<<endl;
2566 return 1;
2567 }
2568 return 0;
2569 }
d3e7090c 2570 else if(cmds[0]=="unset-presigned") {
37fd8771 2571 if(cmds.size() < 2) {
fd5076c8 2572 cerr<<"Syntax: pdnsutil unset-presigned ZONE"<<endl;
488bcb39 2573 return 0;
37fd8771 2574 }
b873e23a 2575 if (! dk.unsetPresigned(DNSName(cmds[1]))) {
e15dce0c 2576 cerr << "Could not unset presigned on for " << cmds[1] << endl;
a84a8203
PD
2577 return 1;
2578 }
2579 return 0;
d3e7090c 2580 }
088370cd
PL
2581 else if(cmds[0]=="unset-publish-cdnskey") {
2582 if(cmds.size() < 2) {
fd5076c8 2583 cerr<<"Syntax: pdnsutil unset-publish-cdnskey ZONE"<<endl;
088370cd
PL
2584 return 0;
2585 }
da347642 2586 if (! dk.unsetPublishCDNSKEY(DNSName(cmds[1]))) {
088370cd
PL
2587 cerr << "Could not unset publishing for CDNSKEY records for "<< cmds[1]<<endl;
2588 return 1;
2589 }
2590 return 0;
2591 }
ef542223
PL
2592 else if(cmds[0]=="unset-publish-cds") {
2593 if(cmds.size() < 2) {
fd5076c8 2594 cerr<<"Syntax: pdnsutil unset-publish-cds ZONE"<<endl;
ef542223
PL
2595 return 0;
2596 }
da347642 2597 if (! dk.unsetPublishCDS(DNSName(cmds[1]))) {
ef542223
PL
2598 cerr << "Could not unset publishing for CDS records for "<< cmds[1]<<endl;
2599 return 1;
2600 }
2601 return 0;
2602 }
65c87942
BH
2603 else if(cmds[0]=="hash-zone-record") {
2604 if(cmds.size() < 3) {
fd5076c8 2605 cerr<<"Syntax: pdnsutil hash-zone-record ZONE RNAME"<<endl;
65c87942
BH
2606 return 0;
2607 }
675fa24c 2608 DNSName zone(cmds[1]);
b873e23a 2609 DNSName record(cmds[2]);
65c87942
BH
2610 NSEC3PARAMRecordContent ns3pr;
2611 bool narrow;
2612 if(!dk.getNSEC3PARAM(zone, &ns3pr, &narrow)) {
0b34684a 2613 cerr<<"The '"<<zone<<"' zone does not use NSEC3"<<endl;
65c87942
BH
2614 return 0;
2615 }
5e42374c 2616 if(narrow) {
0b34684a 2617 cerr<<"The '"<<zone<<"' zone uses narrow NSEC3, but calculating hash anyhow"<<endl;
65c87942 2618 }
488bcb39 2619
28e2e78e 2620 cout<<toBase32Hex(hashQNameWithSalt(ns3pr, record))<<endl;
65c87942 2621 }
da11ed0e 2622 else if(cmds[0]=="unset-nsec3") {
37fd8771 2623 if(cmds.size() < 2) {
fd5076c8 2624 cerr<<"Syntax: pdnsutil unset-nsec3 ZONE"<<endl;
a84a8203 2625 return 0;
37fd8771 2626 }
b873e23a 2627 if ( ! dk.unsetNSEC3PARAM(DNSName(cmds[1]))) {
e15dce0c 2628 cerr<<"Cannot unset NSEC3 param for " << cmds[1] << endl;
a84a8203
PD
2629 return 1;
2630 }
2631 return 0;
da11ed0e
BH
2632 }
2633 else if(cmds[0]=="export-zone-key") {
7ddd79a7 2634 if(cmds.size() < 3) {
fd5076c8 2635 cerr<<"Syntax: pdnsutil export-zone-key ZONE KEY-ID"<<endl;
a84a8203 2636 return 0;
7ddd79a7
BH
2637 }
2638
da11ed0e 2639 string zone=cmds[1];
335da0ba 2640 unsigned int id=pdns_stou(cmds[2]);
b873e23a 2641 DNSSECPrivateKey dpk=dk.getKeyById(DNSName(zone), id);
189bb9d2 2642 cout << dpk.getKey()->convertToISC() <<endl;
488bcb39 2643 }
04576eed
RA
2644 else if(cmds[0]=="increase-serial") {
2645 if (cmds.size() < 2) {
fd5076c8 2646 cerr<<"Syntax: pdnsutil increase-serial ZONE"<<endl;
04576eed
RA
2647 return 0;
2648 }
b873e23a 2649 return increaseSerial(DNSName(cmds[1]), dk);
04576eed 2650 }
ed3f8559
BH
2651 else if(cmds[0]=="import-zone-key-pem") {
2652 if(cmds.size() < 4) {
fd5076c8 2653 cerr<<"Syntax: pdnsutil import-zone-key-pem ZONE FILE ALGORITHM {ksk|zsk}"<<endl;
ed3f8559
BH
2654 exit(1);
2655 }
2656 string zone=cmds[1];
2657 string fname=cmds[2];
2658 string line;
2659 ifstream ifs(fname.c_str());
2660 string tmp, interim, raw;
2661 while(getline(ifs, line)) {
2662 if(line[0]=='-')
2663 continue;
2664 trim(line);
2665 interim += line;
2666 }
2667 B64Decode(interim, raw);
2668 DNSSECPrivateKey dpk;
699e6e37 2669 DNSKEYRecordContent drc;
8d9f38f2 2670 shared_ptr<DNSCryptoKeyEngine> key(DNSCryptoKeyEngine::makeFromPEMString(drc, raw));
699e6e37 2671 dpk.setKey(key);
488bcb39 2672
335da0ba 2673 dpk.d_algorithm = pdns_stou(cmds[3]);
488bcb39 2674
902c4e9c
CH
2675 if(dpk.d_algorithm == DNSSECKeeper::RSASHA1NSEC3SHA1)
2676 dpk.d_algorithm = DNSSECKeeper::RSASHA1;
488bcb39 2677
ed3f8559 2678 cerr<<(int)dpk.d_algorithm<<endl;
488bcb39 2679
ed3f8559
BH
2680 if(cmds.size() > 4) {
2681 if(pdns_iequals(cmds[4], "ZSK"))
2682 dpk.d_flags = 256;
2683 else if(pdns_iequals(cmds[4], "KSK"))
2684 dpk.d_flags = 257;
2685 else {
451ba512 2686 cerr<<"Unknown key flag '"<<cmds[4]<<"'"<<endl;
ed3f8559
BH
2687 exit(1);
2688 }
2689 }
2690 else
2691 dpk.d_flags = 257; // ksk
db0c616e 2692
82cc0761
BZ
2693 int64_t id;
2694 if (!dk.addKey(DNSName(zone), dpk, id)) {
07bf35d1 2695 cerr<<"Adding key failed, perhaps DNSSEC not enabled in configuration?"<<endl;
2696 exit(1);
2697 }
82cc0761
BZ
2698 if (id == -1) {
2699 cerr<<std::to_string(id)<<"Key was added, but backend does not support returning of key id"<<endl;
2700 } else if (id < -1) {
2701 cerr<<std::to_string(id)<<"Key was added, but there was a failure while returning the key id"<<endl;
2702 } else {
2703 cout<<std::to_string(id)<<endl;
2704 }
488bcb39 2705
ed3f8559 2706 }
976b6541 2707 else if(cmds[0]=="import-zone-key") {
d1eacbeb 2708 if(cmds.size() < 3) {
d9db3d7e 2709 cerr<<"Syntax: pdnsutil import-zone-key ZONE FILE [ksk|zsk] [active|inactive]"<<endl;
4496f66f
BH
2710 exit(1);
2711 }
976b6541
BH
2712 string zone=cmds[1];
2713 string fname=cmds[2];
2714 DNSSECPrivateKey dpk;
699e6e37 2715 DNSKEYRecordContent drc;
8d9f38f2 2716 shared_ptr<DNSCryptoKeyEngine> key(DNSCryptoKeyEngine::makeFromISCFile(drc, fname.c_str()));
699e6e37 2717 dpk.setKey(key);
7ddd79a7 2718 dpk.d_algorithm = drc.d_algorithm;
488bcb39 2719
902c4e9c
CH
2720 if(dpk.d_algorithm == DNSSECKeeper::RSASHA1NSEC3SHA1)
2721 dpk.d_algorithm = DNSSECKeeper::RSASHA1;
488bcb39
RG
2722
2723 dpk.d_flags = 257;
4cec6ac5 2724 bool active=true;
4af49b80 2725
2726 for(unsigned int n = 3; n < cmds.size(); ++n) {
2727 if(pdns_iequals(cmds[n], "ZSK"))
232f0877 2728 dpk.d_flags = 256;
4af49b80 2729 else if(pdns_iequals(cmds[n], "KSK"))
232f0877 2730 dpk.d_flags = 257;
4af49b80 2731 else if(pdns_iequals(cmds[n], "active"))
232f0877 2732 active = 1;
d9db3d7e 2733 else if(pdns_iequals(cmds[n], "passive") || pdns_iequals(cmds[n], "inactive")) // passive eventually needs to be removed
232f0877 2734 active = 0;
488bcb39 2735 else {
232f0877
CH
2736 cerr<<"Unknown key flag '"<<cmds[n]<<"'"<<endl;
2737 exit(1);
488bcb39 2738 }
aa952078 2739 }
82cc0761
BZ
2740 int64_t id;
2741 if (!dk.addKey(DNSName(zone), dpk, id, active)) {
07bf35d1 2742 cerr<<"Adding key failed, perhaps DNSSEC not enabled in configuration?"<<endl;
2743 exit(1);
2744 }
82cc0761
BZ
2745 if (id == -1) {
2746 cerr<<std::to_string(id)<<"Key was added, but backend does not support returning of key id"<<endl;
2747 } else if (id < -1) {
2748 cerr<<std::to_string(id)<<"Key was added, but there was a failure while returning the key id"<<endl;
2749 } else {
2750 cout<<std::to_string(id)<<endl;
2751 }
976b6541 2752 }
da11ed0e 2753 else if(cmds[0]=="export-zone-dnskey") {
7ddd79a7 2754 if(cmds.size() < 3) {
fd5076c8 2755 cerr<<"Syntax: pdnsutil export-zone-dnskey ZONE KEY-ID"<<endl;
7ddd79a7
BH
2756 exit(1);
2757 }
2758
b873e23a 2759 DNSName zone(cmds[1]);
335da0ba 2760 unsigned int id=pdns_stou(cmds[2]);
da11ed0e
BH
2761 DNSSECPrivateKey dpk=dk.getKeyById(zone, id);
2762 cout << zone<<" IN DNSKEY "<<dpk.getDNSKEY().getZoneRepresentation() <<endl;
da11ed0e 2763 }
950bdddf
PD
2764 else if(cmds[0] == "generate-zone-key") {
2765 if(cmds.size() < 2 ) {
cd2565d4
MN
2766 cerr << "Syntax: pdnsutil generate-zone-key zsk|ksk [rsasha1|rsasha256|rsasha512|ecdsa256|ecdsa384";
2767#if defined(HAVE_LIBSODIUM) || defined(HAVE_LIBDECAF)
2768 cerr << "|ed25519";
2769#endif
2770#ifdef HAVE_LIBDECAF
2771 cerr << "|ed448";
2772#endif
2773 cerr << "] [bits]"<<endl;
950bdddf
PD
2774 return 0;
2775 }
2776 // need to get algorithm, bits & ksk or zsk from commandline
2777 bool keyOrZone=false;
2778 int tmp_algo=0;
2779 int bits=0;
902c4e9c 2780 int algorithm=DNSSECKeeper::ECDSA256;
950bdddf
PD
2781 for(unsigned int n=1; n < cmds.size(); ++n) {
2782 if(pdns_iequals(cmds[n], "zsk"))
2783 keyOrZone = false;
2784 else if(pdns_iequals(cmds[n], "ksk"))
2785 keyOrZone = true;
b6bd795c 2786 else if((tmp_algo = DNSSECKeeper::shorthand2algorithm(cmds[n]))>0) {
950bdddf 2787 algorithm = tmp_algo;
335da0ba
AT
2788 } else if(pdns_stou(cmds[n]))
2789 bits = pdns_stou(cmds[n]);
950bdddf
PD
2790 else {
2791 cerr<<"Unknown algorithm, key flag or size '"<<cmds[n]<<"'"<<endl;
2792 return 0;
2793 }
2794 }
2795 cerr<<"Generating a " << (keyOrZone ? "KSK" : "ZSK")<<" with algorithm = "<<algorithm<<endl;
2796 if(bits)
2797 cerr<<"Requesting specific key size of "<<bits<<" bits"<<endl;
2798
cd2565d4
MN
2799 DNSSECPrivateKey dspk;
2800 shared_ptr<DNSCryptoKeyEngine> dpk(DNSCryptoKeyEngine::make(algorithm));
950bdddf
PD
2801 if(!bits) {
2802 if(algorithm <= 10)
2803 bits = keyOrZone ? 2048 : 1024;
2804 else {
902c4e9c 2805 if(algorithm == DNSSECKeeper::ECCGOST || algorithm == DNSSECKeeper::ECDSA256 || algorithm == DNSSECKeeper::ED25519)
950bdddf 2806 bits = 256;
902c4e9c 2807 else if(algorithm == DNSSECKeeper::ECDSA384)
950bdddf 2808 bits = 384;
902c4e9c 2809 else if(algorithm == DNSSECKeeper::ED448)
21a8834a 2810 bits = 456;
950bdddf 2811 else {
902c4e9c 2812 throw runtime_error("Can not guess key size for algorithm "+std::to_string(algorithm));
950bdddf
PD
2813 }
2814 }
2815 }
488bcb39
RG
2816 dpk->create(bits);
2817 dspk.setKey(dpk);
2818 dspk.d_algorithm = algorithm;
2819 dspk.d_flags = keyOrZone ? 257 : 256;
950bdddf 2820
488bcb39
RG
2821 // print key to stdout
2822 cout << "Flags: " << dspk.d_flags << endl <<
2823 dspk.getKey()->convertToISC() << endl;
79b4ea54 2824 } else if (cmds[0]=="generate-tsig-key") {
bacb7628 2825 string usage = "Syntax: " + cmds[0] + " name (hmac-md5|hmac-sha1|hmac-sha224|hmac-sha256|hmac-sha384|hmac-sha512)";
4643d268
PL
2826 if (cmds.size() < 3) {
2827 cerr << usage << endl;
2828 return 0;
2829 }
2830 DNSName name(cmds[1]);
ac5298aa 2831 DNSName algo(cmds[2]);
4643d268 2832 string key;
ac5298aa
PL
2833 try {
2834 key = makeTSIGKey(algo);
2835 } catch(const PDNSException& e) {
2836 cerr << "Could not create new TSIG key " << name << " " << algo << ": "<< e.reason << endl;
4643d268
PL
2837 return 1;
2838 }
6f872b78 2839
4643d268
PL
2840 UeberBackend B("default");
2841 if (B.setTSIGKey(name, DNSName(algo), key)) { // you are feeling bored, put up DNSName(algo) up earlier
2842 cout << "Create new TSIG key " << name << " " << algo << " " << key << endl;
2843 } else {
2844 cerr << "Failure storing new TSIG key " << name << " " << algo << " " << key << endl;
2845 return 1;
2846 }
2847 return 0;
6f872b78
AT
2848 } else if (cmds[0]=="import-tsig-key") {
2849 if (cmds.size() < 4) {
2850 cerr << "Syntax: " << cmds[0] << " name algorithm key" << endl;
2851 return 0;
2852 }
b873e23a 2853 DNSName name(cmds[1]);
6f872b78
AT
2854 string algo = cmds[2];
2855 string key = cmds[3];
2856
2857 UeberBackend B("default");
b873e23a 2858 if (B.setTSIGKey(name, DNSName(algo), key)) {
6f872b78
AT
2859 cout << "Imported TSIG key " << name << " " << algo << endl;
2860 } else {
694ea7ae 2861 cerr << "Failure importing TSIG key " << name << " " << algo << endl;
6f872b78
AT
2862 return 1;
2863 }
2864 return 0;
2865 } else if (cmds[0]=="delete-tsig-key") {
2866 if (cmds.size() < 2) {
2867 cerr << "Syntax: " << cmds[0] << " name" << endl;
2868 return 0;
2869 }
b873e23a 2870 DNSName name(cmds[1]);
6f872b78
AT
2871
2872 UeberBackend B("default");
2873 if (B.deleteTSIGKey(name)) {
2874 cout << "Deleted TSIG key " << name << endl;
2875 } else {
694ea7ae 2876 cerr << "Failure deleting TSIG key " << name << endl;
6f872b78
AT
2877 return 1;
2878 }
2879 return 0;
2880 } else if (cmds[0]=="list-tsig-keys") {
2881 std::vector<struct TSIGKey> keys;
2882 UeberBackend B("default");
2883 if (B.getTSIGKeys(keys)) {
8ce9e4e6 2884 for(const TSIGKey &key : keys) {
675fa24c 2885 cout << key.name.toString() << " " << key.algorithm.toString() << " " << key.key << endl;
6f872b78
AT
2886 }
2887 }
2888 return 0;
79b4ea54 2889 } else if (cmds[0]=="activate-tsig-key") {
4831df57
AT
2890 string metaKey;
2891 if (cmds.size() < 4) {
ec53ae22 2892 cerr << "Syntax: " << cmds[0] << " ZONE NAME {master|slave}" << endl;
6f872b78
AT
2893 return 0;
2894 }
b873e23a 2895 DNSName zname(cmds[1]);
6f872b78 2896 string name = cmds[2];
4831df57
AT
2897 if (cmds[3] == "master")
2898 metaKey = "TSIG-ALLOW-AXFR";
2899 else if (cmds[3] == "slave")
2900 metaKey = "AXFR-MASTER-TSIG";
2901 else {
2902 cerr << "Invalid parameter '" << cmds[3] << "', expected master or slave" << endl;
2903 return 1;
2904 }
6f872b78 2905 UeberBackend B("default");
488bcb39 2906 std::vector<std::string> meta;
4831df57 2907 if (!B.getDomainMetadata(zname, metaKey, meta)) {
694ea7ae 2908 cerr << "Failure enabling TSIG key " << name << " for " << zname << endl;
6f872b78
AT
2909 return 1;
2910 }
2911 bool found = false;
ff05fd12 2912 for(std::string tmpname : meta) {
6f872b78
AT
2913 if (tmpname == name) { found = true; break; }
2914 }
2915 if (!found) meta.push_back(name);
4831df57 2916 if (B.setDomainMetadata(zname, metaKey, meta)) {
6f872b78
AT
2917 cout << "Enabled TSIG key " << name << " for " << zname << endl;
2918 } else {
694ea7ae 2919 cerr << "Failure enabling TSIG key " << name << " for " << zname << endl;
6f872b78
AT
2920 return 1;
2921 }
2922 return 0;
79b4ea54 2923 } else if (cmds[0]=="deactivate-tsig-key") {
4831df57
AT
2924 string metaKey;
2925 if (cmds.size() < 4) {
ec53ae22 2926 cerr << "Syntax: " << cmds[0] << " ZONE NAME {master|slave}" << endl;
6f872b78
AT
2927 return 0;
2928 }
b873e23a 2929 DNSName zname(cmds[1]);
6f872b78 2930 string name = cmds[2];
4831df57
AT
2931 if (cmds[3] == "master")
2932 metaKey = "TSIG-ALLOW-AXFR";
2933 else if (cmds[3] == "slave")
2934 metaKey = "AXFR-MASTER-TSIG";
2935 else {
2936 cerr << "Invalid parameter '" << cmds[3] << "', expected master or slave" << endl;
2937 return 1;
2938 }
6f872b78
AT
2939
2940 UeberBackend B("default");
2941 std::vector<std::string> meta;
4831df57 2942 if (!B.getDomainMetadata(zname, metaKey, meta)) {
694ea7ae 2943 cerr << "Failure disabling TSIG key " << name << " for " << zname << endl;
6f872b78
AT
2944 return 1;
2945 }
2946 std::vector<std::string>::iterator iter = meta.begin();
cb167afd 2947 for(;iter != meta.end(); ++iter) if (*iter == name) break;
6f872b78 2948 if (iter != meta.end()) meta.erase(iter);
4831df57 2949 if (B.setDomainMetadata(zname, metaKey, meta)) {
6f872b78
AT
2950 cout << "Disabled TSIG key " << name << " for " << zname << endl;
2951 } else {
694ea7ae 2952 cerr << "Failure disabling TSIG key " << name << " for " << zname << endl;
6f872b78
AT
2953 return 1;
2954 }
2955 return 0;
451ba512
AT
2956 } else if (cmds[0]=="get-meta") {
2957 UeberBackend B("default");
2958 if (cmds.size() < 2) {
2959 cerr << "Syntax: " << cmds[0] << " zone [kind kind ..]" << endl;
2960 return 1;
2961 }
b873e23a 2962 DNSName zone(cmds[1]);
451ba512
AT
2963 vector<string> keys;
2964 DomainInfo di;
2965
2966 if (!B.getDomainInfo(zone, di)) {
2967 cerr << "Invalid zone '" << zone << "'" << endl;
2968 return 1;
2969 }
2970
2971 if (cmds.size() > 2) {
2e050d2c
AT
2972 keys.assign(cmds.begin() + 2, cmds.end());
2973 std::cout << "Metadata for '" << zone << "'" << endl;
ff05fd12 2974 for(const string kind : keys) {
2e050d2c
AT
2975 vector<string> meta;
2976 meta.clear();
2977 if (B.getDomainMetadata(zone, kind, meta)) {
2978 cout << kind << " = " << boost::join(meta, ", ") << endl;
2979 }
2980 }
451ba512 2981 } else {
2e050d2c
AT
2982 std::map<std::string, std::vector<std::string> > meta;
2983 std::cout << "Metadata for '" << zone << "'" << endl;
2984 B.getAllDomainMetadata(zone, meta);
cb167afd
CHB
2985 for(const auto& each_meta: meta) {
2986 cout << each_meta.first << " = " << boost::join(each_meta.second, ", ") << endl;
451ba512 2987 }
488bcb39 2988 }
2e050d2c
AT
2989 return 0;
2990
6995cfa7 2991 } else if (cmds[0]=="set-meta" || cmds[0]=="add-meta") {
451ba512 2992 if (cmds.size() < 3) {
6995cfa7 2993 cerr << "Syntax: " << cmds[0] << " ZONE KIND [VALUE VALUE ..]" << endl;
451ba512
AT
2994 return 1;
2995 }
b873e23a 2996 DNSName zone(cmds[1]);
451ba512 2997 string kind = cmds[2];
6995cfa7
PL
2998 static vector<string> multiMetaWhitelist = {"ALLOW-AXFR-FROM", "ALLOW-DNSUPDATE-FROM",
2999 "ALSO-NOTIFY", "TSIG-ALLOW-AXFR", "TSIG-ALLOW-DNSUPDATE", "GSS-ALLOW-AXFR-PRINCIPAL",
3000 "PUBLISH-CDS"};
3001 bool clobber = true;
3002 if (cmds[0] == "add-meta") {
3003 clobber = false;
3004 if (find(multiMetaWhitelist.begin(), multiMetaWhitelist.end(), kind) == multiMetaWhitelist.end() && kind.find("X-") != 0) {
3005 cerr<<"Refusing to add metadata to single-value metadata "<<kind<<endl;
3006 return 1;
3007 }
451ba512 3008 }
6995cfa7
PL
3009 vector<string> meta(cmds.begin() + 3, cmds.end());
3010 return addOrSetMeta(zone, kind, meta, clobber);
8daea594 3011 } else if (cmds[0]=="hsm") {
3c12a7e9 3012#ifdef HAVE_P11KIT1
8daea594 3013 UeberBackend B("default");
2be60de7
AT
3014 if (cmds.size() < 2) {
3015 cerr << "Missing sub-command for pdnsutil hsm"<< std::endl;
3016 return 0;
3017 } else if (cmds[1] == "assign") {
8daea594
AT
3018 DNSCryptoKeyEngine::storvector_t storvect;
3019 DomainInfo di;
629b6616 3020 std::vector<DNSBackend::KeyData> keys;
829035c1
AT
3021
3022 if (cmds.size() < 9) {
9ee32859 3023 std::cout << "Usage: pdnsutil hsm assign ZONE ALGORITHM {ksk|zsk} MODULE TOKEN PIN LABEL (PUBLABEL)" << std::endl;
829035c1
AT
3024 return 1;
3025 }
3026
e8afb726 3027 DNSName zone(cmds[2]);
829035c1 3028
8daea594
AT
3029 // verify zone
3030 if (!B.getDomainInfo(zone, di)) {
3031 cerr << "Unable to assign module to unknown zone '" << zone << "'" << std::endl;
3032 return 1;
3033 }
3034
b6bd795c 3035 int algorithm = DNSSECKeeper::shorthand2algorithm(cmds[3]);
5dce7548
AT
3036 if (algorithm<0) {
3037 cerr << "Unable to use unknown algorithm '" << cmds[3] << "'" << std::endl;
3038 return 1;
3039 }
3040
82cc0761 3041 int64_t id;
8daea594
AT
3042 bool keyOrZone = (cmds[4] == "ksk" ? true : false);
3043 string module = cmds[5];
3044 string slot = cmds[6];
3045 string pin = cmds[7];
3046 string label = cmds[8];
9ee32859
AT
3047 string pub_label;
3048 if (cmds.size() > 9)
3049 pub_label = cmds[9];
3050 else
3051 pub_label = label;
8daea594
AT
3052
3053 std::ostringstream iscString;
488bcb39
RG
3054 iscString << "Private-key-format: v1.2" << std::endl <<
3055 "Algorithm: " << algorithm << std::endl <<
8daea594
AT
3056 "Engine: " << module << std::endl <<
3057 "Slot: " << slot << std::endl <<
488bcb39 3058 "PIN: " << pin << std::endl <<
9ee32859
AT
3059 "Label: " << label << std::endl <<
3060 "PubLabel: " << pub_label << std::endl;
8daea594 3061
82cc0761
BZ
3062 DNSKEYRecordContent drc;
3063 DNSSECPrivateKey dpk;
3064 dpk.d_flags = (keyOrZone ? 257 : 256);
629b6616 3065
82cc0761
BZ
3066 shared_ptr<DNSCryptoKeyEngine> dke(DNSCryptoKeyEngine::makeFromISCString(drc, iscString.str()));
3067 if(!dke->checkKey()) {
3068 cerr << "Invalid DNS Private Key in engine " << module << " slot " << slot << std::endl;
3069 return 1;
3070 }
3071 dpk.setKey(dke);
629b6616 3072
82cc0761 3073 // make sure this key isn't being reused.
9c1c5d49 3074 B.getDomainKeys(zone, keys);
82cc0761 3075 id = -1;
8daea594 3076
82cc0761
BZ
3077 for(DNSBackend::KeyData& kd : keys) {
3078 if (kd.content == iscString.str()) {
3079 // it's this one, I guess...
3080 id = kd.id;
3081 break;
3082 }
3083 }
86c979f5 3084
82cc0761
BZ
3085 if (id > -1) {
3086 cerr << "You have already assigned this key with ID=" << id << std::endl;
3087 return 1;
3088 }
86c979f5 3089
82cc0761
BZ
3090 if (!dk.addKey(zone, dpk, id)) {
3091 cerr << "Unable to assign module slot to zone" << std::endl;
3092 return 1;
3093 }
86c979f5 3094
82cc0761 3095 cerr << "Module " << module << " slot " << slot << " assigned to " << zone << " with key id " << id << endl;
86c979f5 3096
82cc0761 3097 return 0;
8daea594 3098 } else if (cmds[1] == "create-key") {
70f0f8c4
AT
3099
3100 if (cmds.size() < 4) {
fd5076c8 3101 cerr << "Usage: pdnsutil hsm create-key ZONE KEY-ID [BITS]" << endl;
70f0f8c4
AT
3102 return 1;
3103 }
8daea594 3104 DomainInfo di;
e8afb726 3105 DNSName zone(cmds[2]);
8daea594 3106 unsigned int id;
70f0f8c4 3107 int bits = 2048;
8daea594
AT
3108 // verify zone
3109 if (!B.getDomainInfo(zone, di)) {
3110 cerr << "Unable to create key for unknown zone '" << zone << "'" << std::endl;
3111 return 1;
3112 }
488bcb39 3113
335da0ba 3114 id = pdns_stou(cmds[3]);
488bcb39 3115 std::vector<DNSBackend::KeyData> keys;
9c1c5d49 3116 if (!B.getDomainKeys(zone, keys)) {
8daea594
AT
3117 cerr << "No keys found for zone " << zone << std::endl;
3118 return 1;
488bcb39 3119 }
8daea594 3120
e69c2dac 3121 std::shared_ptr<DNSCryptoKeyEngine> dke = nullptr;
488bcb39 3122 // lookup correct key
ff05fd12 3123 for(DNSBackend::KeyData &kd : keys) {
8daea594 3124 if (kd.id == id) {
488bcb39 3125 // found our key.
8daea594
AT
3126 DNSKEYRecordContent dkrc;
3127 dke = DNSCryptoKeyEngine::makeFromISCString(dkrc, kd.content);
3128 }
3129 }
3130
3131 if (!dke) {
3132 cerr << "Could not find key with ID " << id << endl;
3133 return 1;
3134 }
70f0f8c4 3135 if (cmds.size() > 4) {
335da0ba 3136 bits = pdns_stou(cmds[4]);
70f0f8c4
AT
3137 }
3138 if (bits < 1) {
3139 cerr << "Invalid bit size " << bits << "given, must be positive integer";
3140 return 1;
3141 }
829035c1 3142 try {
70f0f8c4
AT
3143 dke->create(bits);
3144 } catch (PDNSException& e) {
3145 cerr << e.reason << endl;
829035c1
AT
3146 return 1;
3147 }
8daea594 3148
70f0f8c4 3149 cerr << "Key of size " << bits << " created" << std::endl;
8daea594
AT
3150 return 0;
3151 }
3c12a7e9
AT
3152#else
3153 cerr<<"PKCS#11 support not enabled"<<endl;
488bcb39 3154 return 1;
3c12a7e9 3155#endif
90c2c8e9
AT
3156 } else if (cmds[0] == "b2b-migrate") {
3157 if (cmds.size() < 3) {
ec53ae22 3158 cerr<<"Usage: b2b-migrate OLD NEW"<<endl;
90c2c8e9
AT
3159 return 1;
3160 }
3161
3162 DNSBackend *src,*tgt;
3163 src = tgt = NULL;
3164
3165 for(DNSBackend *b : BackendMakers().all()) {
3166 if (b->getPrefix() == cmds[1]) src = b;
3167 if (b->getPrefix() == cmds[2]) tgt = b;
3168 }
3169 if (!src) {
3170 cerr<<"Unknown source backend '"<<cmds[1]<<"'"<<endl;
3171 return 1;
3172 }
3173 if (!tgt) {
3174 cerr<<"Unknown target backend '"<<cmds[2]<<"'"<<endl;
3175 return 1;
3176 }
3177
3178 cout<<"Moving zone(s) from "<<src->getPrefix()<<" to "<<tgt->getPrefix()<<endl;
3179
3180 vector<DomainInfo> domains;
3181
3182 tgt->getAllDomains(&domains, true);
3183 if (domains.size()>0)
3184 throw PDNSException("Target backend has domain(s), please clean it first");
3185
3186 src->getAllDomains(&domains, true);
3187 // iterate zones
3188 for(const DomainInfo& di: domains) {
3189 size_t nr,nc,nm,nk;
604e9ac3 3190 DomainInfo di_new;
90c2c8e9 3191 DNSResourceRecord rr;
0b34684a 3192 cout<<"Processing '"<<di.zone<<"'"<<endl;
90c2c8e9
AT
3193 // create zone
3194 if (!tgt->createDomain(di.zone)) throw PDNSException("Failed to create zone");
604e9ac3
AT
3195 if (!tgt->getDomainInfo(di.zone, di_new)) throw PDNSException("Failed to create zone");
3196 tgt->setKind(di_new.zone, di.kind);
3197 tgt->setAccount(di_new.zone,di.account);
305cf6ab
PL
3198 string masters="";
3199 bool first = true;
d622042f 3200 for(const auto& master: di.masters) {
305cf6ab
PL
3201 if (!first)
3202 masters += ", ";
3203 first = false;
d622042f 3204 masters += master.toStringWithPortExcept(53);
90c2c8e9 3205 }
604e9ac3 3206 tgt->setMaster(di_new.zone, masters);
90c2c8e9
AT
3207 // move records
3208 if (!src->list(di.zone, di.id, true)) throw PDNSException("Failed to list records");
3209 nr=0;
3d47408f 3210
3211 tgt->startTransaction(di.zone, di_new.id);
3212
90c2c8e9 3213 while(src->get(rr)) {
604e9ac3 3214 rr.domain_id = di_new.id;
c9b43446 3215 if (!tgt->feedRecord(rr, DNSName())) throw PDNSException("Failed to feed record");
90c2c8e9
AT
3216 nr++;
3217 }
3d47408f 3218
90c2c8e9
AT
3219 // move comments
3220 nc=0;
3221 if (src->listComments(di.id)) {
3222 Comment c;
3223 while(src->getComment(c)) {
604e9ac3 3224 c.domain_id = di_new.id;
90c2c8e9
AT
3225 tgt->feedComment(c);
3226 nc++;
3227 }
3228 }
3229 // move metadata
3230 nm=0;
3231 std::map<std::string, std::vector<std::string> > meta;
3232 if (src->getAllDomainMetadata(di.zone, meta)) {
cb167afd
CHB
3233 for (const auto& i : meta) {
3234 if (!tgt->setDomainMetadata(di.zone, i.first, i.second)) throw PDNSException("Failed to feed domain metadata");
90c2c8e9
AT
3235 nm++;
3236 }
3237 }
3238 // move keys
3239 nk=0;
82cc0761
BZ
3240 // temp var for KeyID
3241 int64_t keyID;
90c2c8e9 3242 std::vector<DNSBackend::KeyData> keys;
9c1c5d49 3243 if (src->getDomainKeys(di.zone, keys)) {
90c2c8e9 3244 for(const DNSBackend::KeyData& k: keys) {
82cc0761 3245 tgt->addDomainKey(di.zone, k, keyID);
90c2c8e9
AT
3246 nk++;
3247 }
3248 }
3d47408f 3249 tgt->commitTransaction();
90c2c8e9
AT
3250 cout<<"Moved "<<nr<<" record(s), "<<nc<<" comment(s), "<<nm<<" metadata(s) and "<<nk<<" cryptokey(s)"<<endl;
3251 }
3252
3253 int ntk=0;
3254 // move tsig keys
3255 std::vector<struct TSIGKey> tkeys;
3256 if (src->getTSIGKeys(tkeys)) {
28c266da 3257 for(auto& tk: tkeys) {
90c2c8e9
AT
3258 if (!tgt->setTSIGKey(tk.name, tk.algorithm, tk.key)) throw PDNSException("Failed to feed TSIG key");
3259 ntk++;
3260 }
3261 }
3262 cout<<"Moved "<<ntk<<" TSIG key(s)"<<endl;
3263
3264 cout<<"Remember to drop the old backend and run rectify-all-zones"<<endl;
3265
f641c3b7
PD
3266 return 0;
3267 } else if (cmds[0] == "backend-cmd") {
3268 if (cmds.size() < 3) {
3269 cerr<<"Usage: backend-cmd BACKEND CMD [CMD..]"<<endl;
3270 return 1;
3271 }
3272
3273 DNSBackend *db;
3274 db = NULL;
3275
3276 for(DNSBackend *b : BackendMakers().all()) {
3277 if (b->getPrefix() == cmds[1]) db = b;
3278 }
3279
3280 if (!db) {
3281 cerr<<"Unknown backend '"<<cmds[1]<<"'"<<endl;
3282 return 1;
3283 }
3284
3285 for(auto i=next(begin(cmds),2); i != end(cmds); ++i) {
3286 cerr<<"== "<<*i<<endl;
3287 cout<<db->directBackendCmd(*i);
3288 }
3289
90c2c8e9 3290 return 0;
451ba512 3291 } else {
5cde65f4 3292 cerr<<"Unknown command '"<<cmds[0] <<"'"<< endl;
1d211b1b
BH
3293 return 1;
3294 }
3295 return 0;
3296}
3f81d239 3297catch(PDNSException& ae) {
20002664 3298 cerr<<"Error: "<<ae.reason<<endl;
0c4c552d 3299 return 1;
20002664 3300}
14133ba3
BH
3301catch(std::exception& e) {
3302 cerr<<"Error: "<<e.what()<<endl;
0c4c552d 3303 return 1;
14133ba3 3304}
38392ad7 3305catch(...)
3306{
3307 cerr<<"Caught an unknown exception"<<endl;
3308 return 1;
3309}