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