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