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