root/trunk/pdns/pdns/pdnssec.cc @ 2130

Revision 2130, 24.5 KB (checked in by ahu, 2 years ago)

by popular demand, secure-zone now also rectifies it!

Line 
1#include "dnsseckeeper.hh"
2#include "dnssecinfra.hh"
3#include "statbag.hh"
4#include "base32.hh"
5#include "base64.hh"
6#include <boost/foreach.hpp>
7#include <boost/program_options.hpp>
8#include "dnsbackend.hh"
9#include "ueberbackend.hh"
10#include "arguments.hh"
11#include "packetcache.hh"
12#include "zoneparser-tng.hh"
13#include "signingpipe.hh"
14#include <boost/scoped_ptr.hpp>
15
16StatBag S;
17PacketCache PC;
18
19using namespace boost;
20namespace po = boost::program_options;
21po::variables_map g_vm;
22
23string s_programname="pdns";
24
25#if 0
26void launchSigningService(int fd)
27{
28  UeberBackend db("key-only");
29  DNSSECKeeper dk;
30  string str;
31  vector<DNSResourceRecord> chunk;
32  uint64_t signatures=0;
33  while(readLStringFromSocket(fd, str))
34  {
35    if(str.empty())
36      break;
37    chunk=convertDNSRRVectorFromPBString(str);
38 
39    addRRSigs(dk, db, "big.aa", chunk); // sucks
40 
41    ++signatures;
42    str=convertDNSRRVectorToPBString(chunk);
43    writeLStringToSocket(fd, str);   
44  }
45  cerr<<"Exiting after "<<signatures<<" signatures"<<endl;
46  char c;
47  //read(fd, &c, 1); // wait for EOF, signifies that the other side received everything
48  _exit(1);
49}
50
51void signingServer()
52{
53  ComboAddress local("::", 2000);
54  int sock = socket(AF_INET6, SOCK_STREAM, 0);
55 
56  setSocketReusable(sock);
57  if(::bind(sock, (struct sockaddr*)&local, local.getSocklen()) < 0)
58    unixDie("Binding signing server to socket");
59  listen(sock, 5);
60  for(;;) {
61    ComboAddress remote("::");
62    socklen_t remotelen = remote.getSocklen();
63    int client = accept(sock, (struct sockaddr*)&remote, &remotelen);
64   
65    if(client < 0)
66      break;
67    cerr<<"Got connection from "<<remote.toString()<<endl; 
68    if(fork())
69      continue;
70    launchSigningService(client);
71  }
72}
73#endif
74
75ArgvMap &arg()
76{
77  static ArgvMap arg;
78  return arg;
79}
80
81string humanTime(time_t t)
82{
83  char ret[256];
84  struct tm tm;
85  localtime_r(&t, &tm);
86  strftime(ret, sizeof(ret)-1, "%c", &tm);   // %h:%M %Y-%m-%d
87  return ret;
88}
89
90void loadMainConfig(const std::string& configdir)
91{
92  ::arg().set("config-dir","Location of configuration directory (pdns.conf)")=configdir;
93 
94  ::arg().set("launch","Which backends to launch");
95  ::arg().set("dnssec","if we should do dnssec")="true";
96  ::arg().set("config-name","Name of this virtual configuration - will rename the binary image")=g_vm["config-name"].as<string>();
97  ::arg().setCmd("help","Provide a helpful message");
98  //::arg().laxParse(argc,argv);
99
100  if(::arg().mustDo("help")) {
101    cerr<<"syntax:"<<endl<<endl;
102    cerr<<::arg().helpstring(::arg()["help"])<<endl;
103    exit(99);
104  }
105
106  if(::arg()["config-name"]!="") 
107    s_programname+="-"+::arg()["config-name"];
108
109  string configname=::arg()["config-dir"]+"/"+s_programname+".conf";
110  cleanSlashes(configname);
111 
112  ::arg().laxFile(configname.c_str());
113  ::arg().set("module-dir","Default directory for modules")=LIBDIR;
114  BackendMakers().launch(::arg()["launch"]); // vrooooom!
115  ::arg().laxFile(configname.c_str());   
116  //cerr<<"Backend: "<<::arg()["launch"]<<", '" << ::arg()["gmysql-dbname"] <<"'" <<endl;
117
118  S.declare("qsize-q","Number of questions waiting for database attention");
119   
120  S.declare("deferred-cache-inserts","Amount of cache inserts that were deferred because of maintenance");
121  S.declare("deferred-cache-lookup","Amount of cache lookups that were deferred because of maintenance");
122         
123  S.declare("query-cache-hit","Number of hits on the query cache");
124  S.declare("query-cache-miss","Number of misses on the query cache");
125  ::arg().set("max-cache-entries", "Maximum number of cache entries")="1000000";
126  ::arg().set("recursor","If recursion is desired, IP address of a recursing nameserver")="no"; 
127  ::arg().set("recursive-cache-ttl","Seconds to store packets in the PacketCache")="10";
128  ::arg().set("cache-ttl","Seconds to store packets in the PacketCache")="20";             
129  ::arg().set("negquery-cache-ttl","Seconds to store packets in the PacketCache")="60";
130  ::arg().set("query-cache-ttl","Seconds to store packets in the PacketCache")="20";             
131  ::arg().set("soa-refresh-default","Default SOA refresh")="10800";
132  ::arg().set("soa-retry-default","Default SOA retry")="3600";
133  ::arg().set("soa-expire-default","Default SOA expire")="604800";
134    ::arg().setSwitch("query-logging","Hint backends that queries should be logged")="no";
135  ::arg().set("soa-minimum-ttl","Default SOA mininum ttl")="3600";   
136 
137  UeberBackend::go();
138}
139
140// irritatingly enough, rectifyZone needs its own ueberbackend and can't therefore benefit from transactions outside its scope
141void rectifyZone(DNSSECKeeper& dk, const std::string& zone)
142{
143  scoped_ptr<UeberBackend> B(new UeberBackend("default"));
144  bool doTransaction=true; // but see above
145  SOAData sd;
146 
147  if(!B->getSOA(zone, sd)) {
148    cerr<<"No SOA known for '"<<zone<<"', is such a zone in the database?"<<endl;
149    return;
150  } 
151  sd.db->list(zone, sd.domain_id);
152  DNSResourceRecord rr;
153
154  set<string> qnames, nsset;
155 
156  while(sd.db->get(rr)) {
157    qnames.insert(rr.qname);
158    if(rr.qtype.getCode() == QType::NS && !pdns_iequals(rr.qname, zone)) 
159      nsset.insert(rr.qname);
160  }
161
162  NSEC3PARAMRecordContent ns3pr;
163  bool narrow;
164  bool haveNSEC3=dk.getNSEC3PARAM(zone, &ns3pr, &narrow);
165  string hashed;
166  if(!haveNSEC3) 
167    cerr<<"Adding NSEC ordering information"<<endl;
168  else if(!narrow)
169    cerr<<"Adding NSEC3 hashed ordering information for '"<<zone<<"'"<<endl;
170  else 
171    cerr<<"Erasing NSEC3 ordering since we are narrow, only setting 'auth' fields"<<endl;
172 
173  if(doTransaction)
174    sd.db->startTransaction("", -1);
175  BOOST_FOREACH(const string& qname, qnames)
176  {
177    string shorter(qname);
178    bool auth=true;
179    do {
180      if(nsset.count(shorter)) { 
181        auth=false;
182        break;
183      }
184    }while(chopOff(shorter));
185
186    if(!haveNSEC3) // NSEC
187      sd.db->updateDNSSECOrderAndAuth(sd.domain_id, zone, qname, auth);
188    else {
189      if(!narrow) {
190        hashed=toLower(toBase32Hex(hashQNameWithSalt(ns3pr.d_iterations, ns3pr.d_salt, qname)));
191        cerr<<"'"<<qname<<"' -> '"<< hashed <<"'"<<endl;
192      }
193      sd.db->updateDNSSECOrderAndAuthAbsolute(sd.domain_id, qname, hashed, auth);
194    }
195  }
196  if(doTransaction)
197    sd.db->commitTransaction();
198}
199
200void checkZone(DNSSECKeeper& dk, const std::string& zone)
201{
202  scoped_ptr<UeberBackend> B(new UeberBackend("default"));
203  SOAData sd;
204 
205  if(!B->getSOA(zone, sd)) {
206    cerr<<"No SOA!"<<endl;
207    return;
208  } 
209  sd.db->list(zone, sd.domain_id);
210  DNSResourceRecord rr;
211  uint64_t numrecords=0, numerrors=0;
212 
213  while(sd.db->get(rr)) {
214    if(rr.qtype.getCode() == QType::MX) 
215      rr.content = lexical_cast<string>(rr.priority)+" "+rr.content;
216    if(rr.auth == 0 && rr.qtype.getCode()!=QType::NS && rr.qtype.getCode()!=QType::A)
217    {
218      cerr<<"Following record is auth=0, run pdnssec rectify-zone?: "<<rr.qname<<" IN " <<rr.qtype.getName()<< " " << rr.content<<endl;
219    }
220    try {
221      shared_ptr<DNSRecordContent> drc(DNSRecordContent::mastermake(rr.qtype.getCode(), 1, rr.content));
222      string tmp=drc->serialize(rr.qname);
223    }
224    catch(std::exception& e) 
225    {
226      cerr<<"Following record had a problem: "<<rr.qname<<" IN " <<rr.qtype.getName()<< " " << rr.content<<endl;
227      cerr<<"Error was: "<<e.what()<<endl;
228      numerrors++;
229    }
230    numrecords++;
231  }
232  cerr<<"Checked "<<numrecords<<" records, "<<numerrors<<" errors"<<endl;
233}
234
235void testAlgorithms()
236{
237  DNSCryptoKeyEngine::testAll();
238}
239
240void testSpeed(DNSSECKeeper& dk, const string& zone, const string& remote, int cores)
241{
242  DNSResourceRecord rr;
243  rr.qname="blah."+zone;
244  rr.qtype=QType::A;
245  rr.ttl=3600;
246  rr.auth=1;
247  rr.qclass = 1;
248  rr.d_place=DNSResourceRecord::ANSWER;
249  rr.priority=0;
250 
251  UeberBackend db("key-only");
252 
253  ChunkedSigningPipe csp(zone, 1, remote, cores);
254 
255  vector<DNSResourceRecord> signatures;
256  uint32_t rnd;
257  unsigned char* octets = (unsigned char*)&rnd;
258  char tmp[25];
259  DTime dt;
260  dt.set();
261  for(unsigned int n=0; n < 100000; ++n) {
262    rnd = random();
263    snprintf(tmp, sizeof(tmp), "%d.%d.%d.%d", 
264      octets[0], octets[1], octets[2], octets[3]);
265    rr.content=tmp;
266   
267    snprintf(tmp, sizeof(tmp), "r-%u", rnd);
268    rr.qname=string(tmp)+"."+zone;
269   
270    if(csp.submit(rr))
271      while(signatures = csp.getChunk(), !signatures.empty())
272        ;
273  }
274  cerr<<"Flushing the pipe, "<<csp.d_signed<<" signed, "<<csp.d_queued<<" queued, "<<csp.d_outstanding<<" outstanding"<< endl;
275  cerr<<"Net speed: "<<csp.d_signed/ (dt.udiffNoReset()/1000000.0) << " sigs/s\n";
276  while(signatures = csp.getChunk(true), !signatures.empty())
277      ;
278  cerr<<"Done, "<<csp.d_signed<<" signed, "<<csp.d_queued<<" queued, "<<csp.d_outstanding<<" outstanding"<< endl;
279  cerr<<"Net speed: "<<csp.d_signed/ (dt.udiff()/1000000.0) << " sigs/s\n";
280}
281
282void verifyCrypto(const string& zone)
283{
284  ZoneParserTNG zpt(zone);
285  DNSResourceRecord rr;
286  DNSKEYRecordContent drc;
287  RRSIGRecordContent rrc;
288  DSRecordContent dsrc;
289  vector<shared_ptr<DNSRecordContent> > toSign;
290  unsigned int ttl;
291  string qname, apex;
292  dsrc.d_digesttype=0;
293  while(zpt.get(rr)) {
294    if(rr.qtype.getCode() == QType::DNSKEY) {
295      cerr<<"got DNSKEY!"<<endl;
296      apex=rr.qname;
297      drc = *dynamic_cast<DNSKEYRecordContent*>(DNSRecordContent::mastermake(QType::DNSKEY, 1, rr.content));
298    }
299    else if(rr.qtype.getCode() == QType::RRSIG) {
300      cerr<<"got RRSIG"<<endl;
301      rrc = *dynamic_cast<RRSIGRecordContent*>(DNSRecordContent::mastermake(QType::RRSIG, 1, rr.content));
302    }
303    else if(rr.qtype.getCode() == QType::DS) {
304      cerr<<"got DS"<<endl;
305      dsrc = *dynamic_cast<DSRecordContent*>(DNSRecordContent::mastermake(QType::DS, 1, rr.content));
306    }
307    else {
308      qname = rr.qname;
309      ttl = rr.ttl;
310      toSign.push_back(shared_ptr<DNSRecordContent>(DNSRecordContent::mastermake(rr.qtype.getCode(), 1, rr.content)));
311    }
312  }
313 
314  string msg = getMessageForRRSET(qname, rrc, toSign);       
315  cerr<<"Verify: "<<DNSCryptoKeyEngine::makeFromPublicKeyString(drc.d_algorithm, drc.d_key)->verify(msg, rrc.d_signature)<<endl;
316  if(dsrc.d_digesttype) {
317    cerr<<"Calculated DS: "<<apex<<" IN DS "<<makeDSFromDNSKey(apex, drc, dsrc.d_digesttype).getZoneRepresentation()<<endl;
318    cerr<<"Original DS:   "<<apex<<" IN DS "<<dsrc.getZoneRepresentation()<<endl;
319  }
320#if 0
321  DNSCryptoKeyEngine*key=DNSCryptoKeyEngine::makeFromISCString(drc, "Private-key-format: v1.2\n"
322      "Algorithm: 12 (ECC-GOST)\n"
323      "GostAsn1: MEUCAQAwHAYGKoUDAgITMBIGByqFAwICIwEGByqFAwICHgEEIgQg/9MiXtXKg9FDXDN/R9CmVhJDyuzRAIgh4tPwCu4NHIs=\n");
324  string resign=key->sign(hash);
325  cerr<<Base64Encode(resign)<<endl;
326  cerr<<"Verify: "<<DNSCryptoKeyEngine::makeFromPublicKeyString(drc.d_algorithm, drc.d_key)->verify(hash, resign)<<endl;
327#endif
328
329}
330
331void showZone(DNSSECKeeper& dk, const std::string& zone)
332{
333  if(!dk.isSecuredZone(zone)) {
334        cerr<<"Zone is not secured\n";
335        return;
336  }
337  NSEC3PARAMRecordContent ns3pr;
338  bool narrow;
339  bool haveNSEC3=dk.getNSEC3PARAM(zone, &ns3pr, &narrow);
340 
341  if(!haveNSEC3) 
342    cout<<"Zone has NSEC semantics"<<endl;
343  else
344    cout<<"Zone has " << (narrow ? "NARROW " : "") <<"hashed NSEC3 semantics, configuration: "<<ns3pr.getZoneRepresentation()<<endl;
345 
346  cout <<"Zone is " << (dk.isPresigned(zone) ? "" : "not ") << "presigned\n";
347 
348  DNSSECKeeper::keyset_t keyset=dk.getKeys(zone);
349
350  if(keyset.empty())  {
351    cerr << "No keys for zone '"<<zone<<"'."<<endl;
352  }
353  else { 
354    cout << "keys: "<<endl;
355    BOOST_FOREACH(DNSSECKeeper::keyset_t::value_type value, keyset) {
356      cout<<"ID = "<<value.second.id<<" ("<<(value.second.keyOrZone ? "KSK" : "ZSK")<<"), tag = "<<value.first.getDNSKEY().getTag();
357      cout<<", algo = "<<(int)value.first.d_algorithm<<", bits = "<<value.first.getKey()->getBits()<<"\tActive: "<<value.second.active<< endl; 
358      if(value.second.keyOrZone) {
359        cout<<"KSK DNSKEY = "<<zone<<" IN DNSKEY "<< value.first.getDNSKEY().getZoneRepresentation() << endl;
360        cout<<"DS = "<<zone<<" IN DS "<<makeDSFromDNSKey(zone, value.first.getDNSKEY(), 1).getZoneRepresentation() << endl;
361        cout<<"DS = "<<zone<<" IN DS "<<makeDSFromDNSKey(zone, value.first.getDNSKEY(), 2).getZoneRepresentation() << endl;
362        try {
363          string output=makeDSFromDNSKey(zone, value.first.getDNSKEY(), 3).getZoneRepresentation();
364          cout<<"DS = "<<zone<<" IN DS "<< output << endl;
365        }
366        catch(...)
367        {
368        }
369        cout<<endl; 
370      }
371    }
372  }
373}
374
375bool secureZone(DNSSECKeeper& dk, const std::string& zone)
376{
377        if(dk.isSecuredZone(zone)) {
378                cerr << "Zone '"<<zone<<"' already secure, remove keys with pdnssec remove-zone-key if needed"<<endl;
379                return false;
380        }
381
382        if(!dk.secureZone(zone, 8)) {
383                cerr<<"No backend was able to secure '"<<zone<<"', most likely because no DNSSEC\n";
384                cerr<<"capable backends are loaded, or because the backends have DNSSEC disabled.\n";
385                cerr<<"For the Generic SQL backends, set 'gsqlite3-dnssec' or 'gmysql-dnssec' or\n";
386                cerr<<"'gpgsql-dnssec' etc. Also make sure the schema has been updated for DNSSEC!\n";
387                return false;
388        }
389
390        if(!dk.isSecuredZone(zone)) {
391                cerr<<"Failed to secure zone. Is your backend dnssec enabled? (set \n";
392                cerr<<"sqlite3-dnssec, or gmysql-dnssec etc). Check this first.\n";
393                cerr<<"If you run with the BIND backend, make sure to also launch another\n";
394                cerr<<"backend which supports storage of DNSSEC settings.\n";
395                cerr<<"In addition, add '"<<zone<<"' to this backend, possibly like this: \n\n";
396                cerr<<"   insert into domains (name, type) values ('"<<zone<<"', 'NATIVE');\n\n";
397                cerr<<"And then rerun secure-zone"<<endl;
398                return false;
399        }
400
401        DNSSECKeeper::keyset_t zskset=dk.getKeys(zone, false);
402
403        if(!zskset.empty())  {
404                cerr<<"There were ZSKs already for zone '"<<zone<<"', no need to add more"<<endl;
405                return false;
406        }
407               
408        dk.addKey(zone, false, 8);
409        dk.addKey(zone, false, 8, 0, false); // not active
410        // rectifyZone(dk, zone);
411        // showZone(dk, zone);
412        cout<<"Zone "<<zone<<" secured"<<endl;
413  return true;
414}
415
416int main(int argc, char** argv)
417try
418{ 
419  po::options_description desc("Allowed options");
420  desc.add_options()
421    ("help,h", "produce help message")
422    ("verbose,v", po::value<bool>(), "be verbose")
423    ("force", "force an action")
424    ("config-name", po::value<string>()->default_value(""), "virtual configuration name")
425    ("config-dir", po::value<string>()->default_value(SYSCONFDIR), "location of pdns.conf")
426    ("commands", po::value<vector<string> >());
427
428  po::positional_options_description p;
429  p.add("commands", -1);
430  po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), g_vm);
431  po::notify(g_vm);
432
433  vector<string> cmds;
434
435  if(g_vm.count("commands")) 
436    cmds = g_vm["commands"].as<vector<string> >();
437
438  if(cmds.empty() || g_vm.count("help")) {
439    cerr<<"Usage: \npdnssec [options] [show-zone] [secure-zone] [rectify-zone] [add-zone-key] [deactivate-zone-key] [remove-zone-key] [activate-zone-key]\n";
440    cerr<<"         [import-zone-key] [export-zone-key] [set-nsec3] [set-presigned] [unset-nsec3] [unset-presigned] [export-zone-dnskey]\n\n";
441    cerr<<"activate-zone-key ZONE KEY-ID   Activate the key with key id KEY-ID in ZONE\n";
442    cerr<<"add-zone-key ZONE [zsk|ksk]     Add a ZSK or KSK to a zone\n";
443    cerr<<"  [bits] [rsasha1|rsasha256]    and specify algorithm & bits\n";
444    cerr<<"check-zone ZONE                 Check a zone for correctness\n";
445    cerr<<"deactivate-zone-key             Dectivate the key with key id KEY-ID in ZONE\n";
446    cerr<<"export-zone-dnskey ZONE KEY-ID  Export to stdout the public DNSKEY described\n";
447    cerr<<"export-zone-key ZONE KEY-ID     Export to stdout the private key described\n";
448    cerr<<"hash-zone-record ZONE RNAME     Calculate the NSEC3 hash for RNAME in ZONE\n";
449    cerr<<"import-zone-key ZONE FILE       Import from a file a private key, ZSK or KSK\n";           
450    cerr<<"                [ksk|zsk]       Defaults to KSK\n";
451    cerr<<"rectify-zone ZONE               Fix up DNSSEC fields (order, auth)\n";
452    cerr<<"remove-zone-key ZONE KEY-ID     Remove key with KEY-ID from ZONE\n";
453    cerr<<"secure-zone                     Add KSK and two ZSKs\n";
454    cerr<<"set-nsec3 ZONE 'params' [narrow]     Enable NSEC3 with PARAMs. Optionally narrow\n";
455    cerr<<"set-presigned ZONE              Use presigned RRSIGs from storage\n";
456    cerr<<"show-zone ZONE                  Show DNSSEC (public) key details about a zone\n";
457    cerr<<"unset-nsec3 ZONE                Switch back to NSEC\n";
458    cerr<<"unset-presigned ZONE            No longer use presigned RRSIGs\n\n";
459    cerr<<"Options:"<<endl;
460    cerr<<desc<<endl;
461    return 0;
462  }
463 
464  if(cmds[0] == "test-algorithms") {
465    testAlgorithms();
466    return 0;
467  }
468
469  loadMainConfig(g_vm["config-dir"].as<string>());
470  reportAllTypes();
471  DNSSECKeeper dk;
472
473  if(cmds[0] == "rectify-zone" || cmds[0] == "order-zone") {
474    if(cmds.size() != 2) {
475      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
476      return 0;
477    }
478    rectifyZone(dk, cmds[1]);
479  }
480  else if(cmds[0] == "check-zone") {
481    if(cmds.size() != 2) {
482      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
483      return 0;
484    }
485    checkZone(dk, cmds[1]);
486  }
487#if 0
488  else if(cmds[0] == "signing-server" )
489  {
490    signingServer();
491  }
492  else if(cmds[0] == "signing-slave")
493  {
494    launchSigningService(0);
495  }
496#endif
497  else if(cmds[0] == "test-speed") {
498    if(cmds.size() < 3) {
499      cerr << "Error: "<<cmds[0]<<" takes  2 or 3 parameters, zone numcores [signing-server]"<<endl;
500      return 0;
501    }
502    testSpeed(dk, cmds[1],  (cmds.size() > 3) ? cmds[3] : "", atoi(cmds[2].c_str()));
503  }
504  else if(cmds[0] == "verify-crypto") {
505    if(cmds.size() != 2) {
506      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
507      return 0;
508    }
509    verifyCrypto(cmds[1]);
510  }
511
512  else if(cmds[0] == "show-zone") {
513    if(cmds.size() != 2) {
514      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
515      return 0;
516    }
517    const string& zone=cmds[1];
518    showZone(dk, zone);
519  }
520  else if(cmds[0] == "activate-zone-key") {
521    const string& zone=cmds[1];
522    unsigned int id=atoi(cmds[2].c_str());
523    dk.activateKey(zone, id);
524  }
525  else if(cmds[0] == "deactivate-zone-key") {
526    const string& zone=cmds[1];
527    unsigned int id=atoi(cmds[2].c_str());
528    dk.deactivateKey(zone, id);
529  }
530  else if(cmds[0] == "add-zone-key") {
531    const string& zone=cmds[1];
532    // need to get algorithm, bits & ksk or zsk from commandline
533    bool keyOrZone=false;
534    int bits=0;
535    int algorithm=5;
536    for(unsigned int n=2; n < cmds.size(); ++n) {
537      if(pdns_iequals(cmds[n], "zsk"))
538        keyOrZone = false;
539      else if(pdns_iequals(cmds[n], "ksk"))
540        keyOrZone = true;
541      else if(pdns_iequals(cmds[n], "rsasha1"))
542        algorithm=5;
543      else if(pdns_iequals(cmds[n], "rsasha256"))
544        algorithm=8;
545      else if(pdns_iequals(cmds[n], "rsasha512"))
546        algorithm=10;
547      else if(pdns_iequals(cmds[n], "gost"))
548        algorithm=12;
549      else if(pdns_iequals(cmds[n], "ecdsa256"))
550        algorithm=13;
551      else if(pdns_iequals(cmds[n], "ecdsa384"))
552        algorithm=14;
553      else if(atoi(cmds[n].c_str()))
554        bits = atoi(cmds[n].c_str());
555      else { 
556        cerr<<"Unknown algorithm, key flag or size '"<<cmds[n]<<"'"<<endl;
557        return 0;
558      }
559    }
560    cerr<<"Adding a " << (keyOrZone ? "KSK" : "ZSK")<<" with algorithm = "<<algorithm<<endl;
561    if(bits)
562      cerr<<"Requesting specific key size of "<<bits<<" bits"<<endl;
563    dk.addKey(zone, keyOrZone, algorithm, bits); 
564  }
565  else if(cmds[0] == "remove-zone-key") {
566    if(cmds.size() < 3) {
567      cerr<<"Syntax: pdnssec remove-zone-key ZONE KEY-ID\n";
568      return 0;
569    }
570    const string& zone=cmds[1];
571    unsigned int id=atoi(cmds[2].c_str());
572    dk.removeKey(zone, id);
573  }
574 
575  else if(cmds[0] == "secure-zone") {
576    if(cmds.size() < 2) {
577      cerr << "Error: "<<cmds[0]<<" takes at least 1 parameter"<<endl;
578      return 0;
579    }
580    vector<string> mustRectify;
581    dk.startTransaction();   
582    for(unsigned int n = 1; n < cmds.size(); ++n) {
583                        const string& zone=cmds[n];
584                        if(secureZone(dk, zone)) {
585        mustRectify.push_back(zone);
586      }
587                }
588   
589    dk.commitTransaction();
590    BOOST_FOREACH(string& zone, mustRectify)
591      rectifyZone(dk, zone);
592  }
593  else if(cmds[0]=="set-nsec3") {
594    string nsec3params =  cmds.size() > 2 ? cmds[2] : "1 1 1 ab";
595    bool narrow = cmds.size() > 3 && cmds[3]=="narrow";
596    NSEC3PARAMRecordContent ns3pr(nsec3params);
597    if(!ns3pr.d_flags) {
598      cerr<<"PowerDNS only implements opt-out zones, please set the second parameter to '1' (example, '1 1 1 ab')"<<endl;
599      return 0;
600    }
601   
602    dk.setNSEC3PARAM(cmds[1], ns3pr, narrow);
603  }
604  else if(cmds[0]=="set-presigned") {
605        if(cmds.size() < 2) {
606                cerr<<"Wrong number of arguments, syntax: set-presigned DOMAIN"<<endl;
607        }
608    dk.setPresigned(cmds[1]);
609  }
610  else if(cmds[0]=="unset-presigned") {
611        if(cmds.size() < 2) {
612                cerr<<"Wrong number of arguments, syntax: unset-presigned DOMAIN"<<endl;
613        }
614    dk.unsetPresigned(cmds[1]);
615  }
616  else if(cmds[0]=="hash-zone-record") {
617    if(cmds.size() < 3) {
618      cerr<<"Wrong number of arguments, syntax: hash-zone-record ZONE RECORD"<<endl;
619      return 0;
620    }
621    string& zone=cmds[1];
622    string& record=cmds[2];
623    NSEC3PARAMRecordContent ns3pr;
624    bool narrow;
625    if(!dk.getNSEC3PARAM(zone, &ns3pr, &narrow)) {
626      cerr<<"The '"<<zone<<"' zone does not use NSEC3"<<endl;
627      return 0;
628    }
629    if(!narrow) {
630      cerr<<"The '"<<zone<<"' zone uses narrow NSEC3, but calculating hash anyhow"<<endl;
631    }
632     
633    cout<<toLower(toBase32Hex(hashQNameWithSalt(ns3pr.d_iterations, ns3pr.d_salt, record)))<<endl;
634  }
635  else if(cmds[0]=="unset-nsec3") {
636    dk.unsetNSEC3PARAM(cmds[1]);
637  }
638  else if(cmds[0]=="export-zone-key") {
639    if(cmds.size() < 3) {
640      cerr<<"Syntax: pdnssec export-zone-key zone-name id"<<endl;
641      cerr<<cmds.size()<<endl;
642      exit(1);
643    }
644
645    string zone=cmds[1];
646    unsigned int id=atoi(cmds[2].c_str());
647    DNSSECPrivateKey dpk=dk.getKeyById(zone, id);
648    cout << dpk.getKey()->convertToISC() <<endl;
649  } 
650  else if(cmds[0]=="import-zone-key-pem") {
651    if(cmds.size() < 4) {
652      cerr<<"Syntax: pdnssec import-zone-key zone-name filename.pem algorithm [zsk|ksk]"<<endl;
653      exit(1);
654    }
655    string zone=cmds[1];
656    string fname=cmds[2];
657    string line;
658    ifstream ifs(fname.c_str());
659    string tmp, interim, raw;
660    while(getline(ifs, line)) {
661      if(line[0]=='-')
662        continue;
663      trim(line);
664      interim += line;
665    }
666    B64Decode(interim, raw);
667    DNSSECPrivateKey dpk;
668    DNSKEYRecordContent drc;
669    shared_ptr<DNSCryptoKeyEngine> key(DNSCryptoKeyEngine::makeFromPEMString(drc, raw));
670    dpk.setKey(key);
671   
672    dpk.d_algorithm = atoi(cmds[3].c_str());
673   
674    if(dpk.d_algorithm == 7)
675      dpk.d_algorithm = 5;
676     
677    cerr<<(int)dpk.d_algorithm<<endl;
678   
679    if(cmds.size() > 4) {
680      if(pdns_iequals(cmds[4], "ZSK"))
681        dpk.d_flags = 256;
682      else if(pdns_iequals(cmds[4], "KSK"))
683        dpk.d_flags = 257;
684      else {
685        cerr<<"Unknown key flag '"<<cmds[4]<<"'\n";
686        exit(1);
687      }
688    }
689    else
690      dpk.d_flags = 257; // ksk
691     
692    dk.addKey(zone, dpk); 
693   
694  }
695  else if(cmds[0]=="import-zone-key") {
696    if(cmds.size() < 3) {
697      cerr<<"Syntax: pdnssec import-zone-key zone-name filename [zsk|ksk]"<<endl;
698      exit(1);
699    }
700    string zone=cmds[1];
701    string fname=cmds[2];
702    DNSSECPrivateKey dpk;
703    DNSKEYRecordContent drc;
704    shared_ptr<DNSCryptoKeyEngine> key(DNSCryptoKeyEngine::makeFromISCFile(drc, fname.c_str()));
705    dpk.setKey(key);
706    dpk.d_algorithm = drc.d_algorithm;
707   
708    if(dpk.d_algorithm == 7)
709      dpk.d_algorithm = 5;
710     
711    cerr<<(int)dpk.d_algorithm<<endl;
712   
713    if(cmds.size() > 3) {
714      if(pdns_iequals(cmds[3], "ZSK"))
715        dpk.d_flags = 256;
716      else if(pdns_iequals(cmds[3], "KSK"))
717        dpk.d_flags = 257;
718      else {
719        cerr<<"Unknown key flag '"<<cmds[3]<<"'\n";
720        exit(1);
721      }
722    }
723    else
724      dpk.d_flags = 257; 
725     
726    dk.addKey(zone, dpk); 
727  }
728  else if(cmds[0]=="export-zone-dnskey") {
729    if(cmds.size() < 3) {
730      cerr<<"Syntax: pdnssec export-zone-dnskey zone-name id"<<endl;
731      exit(1);
732    }
733
734    string zone=cmds[1];
735    unsigned int id=atoi(cmds[2].c_str());
736    DNSSECPrivateKey dpk=dk.getKeyById(zone, id);
737    cout << zone<<" IN DNSKEY "<<dpk.getDNSKEY().getZoneRepresentation() <<endl;
738    if(dpk.d_flags == 257) {
739      cout << zone << " IN DS "<<makeDSFromDNSKey(zone, dpk.getDNSKEY(), 1).getZoneRepresentation() << endl;
740      cout << zone << " IN DS "<<makeDSFromDNSKey(zone, dpk.getDNSKEY(), 2).getZoneRepresentation() << endl;
741    }
742  }
743  else {
744    cerr<<"Unknown command '"<<cmds[0]<<"'\n";
745    return 1;
746  }
747  return 0;
748}
749catch(AhuException& ae) {
750  cerr<<"Error: "<<ae.reason<<endl;
751}
752catch(std::exception& e) {
753  cerr<<"Error: "<<e.what()<<endl;
754}
Note: See TracBrowser for help on using the browser.