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