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