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

Revision 1884, 16.4 KB (checked in by ahu, 2 years ago)

implement 'pdnssec import-zone-key-pem' which is compatible with the default output of openssl genrsa.
This should aid interoperability with non-DNSSEC RSA key generators. Thanks to Martin van Hensbergen for helping us navigate the jungle of PEM/BER/DER/PKCS standards.

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
13StatBag S;
14PacketCache PC;
15
16using namespace boost;
17namespace po = boost::program_options;
18po::variables_map g_vm;
19
20string s_programname="pdns";
21
22ArgvMap &arg()
23{
24  static ArgvMap arg;
25  return arg;
26}
27
28string humanTime(time_t t)
29{
30  char ret[256];
31  struct tm tm;
32  localtime_r(&t, &tm);
33  strftime(ret, sizeof(ret)-1, "%c", &tm);   // %h:%M %Y-%m-%d
34  return ret;
35}
36
37void loadMainConfig(const std::string& configdir)
38{
39  ::arg().set("config-dir","Location of configuration directory (pdns.conf)")=configdir;
40 
41  ::arg().set("launch","Which backends to launch");
42  ::arg().set("dnssec","if we should do dnssec")="true";
43  ::arg().set("config-name","Name of this virtual configuration - will rename the binary image")=g_vm["config-name"].as<string>();
44  ::arg().setCmd("help","Provide a helpful message");
45  //::arg().laxParse(argc,argv);
46
47  if(::arg().mustDo("help")) {
48    cerr<<"syntax:"<<endl<<endl;
49    cerr<<::arg().helpstring(::arg()["help"])<<endl;
50    exit(99);
51  }
52
53  if(::arg()["config-name"]!="") 
54    s_programname+="-"+::arg()["config-name"];
55
56  string configname=::arg()["config-dir"]+"/"+s_programname+".conf";
57  cleanSlashes(configname);
58
59  cerr<<"configname: '"<<configname<<"'\n";
60 
61  ::arg().laxFile(configname.c_str());
62  ::arg().set("module-dir","Default directory for modules")=LIBDIR;
63  BackendMakers().launch(::arg()["launch"]); // vrooooom!
64  ::arg().laxFile(configname.c_str());   
65  //cerr<<"Backend: "<<::arg()["launch"]<<", '" << ::arg()["gmysql-dbname"] <<"'" <<endl;
66
67  S.declare("qsize-q","Number of questions waiting for database attention");
68   
69  S.declare("deferred-cache-inserts","Amount of cache inserts that were deferred because of maintenance");
70  S.declare("deferred-cache-lookup","Amount of cache lookups that were deferred because of maintenance");
71         
72  S.declare("query-cache-hit","Number of hits on the query cache");
73  S.declare("query-cache-miss","Number of misses on the query cache");
74  ::arg().set("max-cache-entries", "Maximum number of cache entries")="1000000";
75  ::arg().set("recursor","If recursion is desired, IP address of a recursing nameserver")="no"; 
76  ::arg().set("recursive-cache-ttl","Seconds to store packets in the PacketCache")="10";
77  ::arg().set("cache-ttl","Seconds to store packets in the PacketCache")="20";             
78  ::arg().set("negquery-cache-ttl","Seconds to store packets in the PacketCache")="60";
79  ::arg().set("query-cache-ttl","Seconds to store packets in the PacketCache")="20";             
80  ::arg().set("soa-refresh-default","Default SOA refresh")="10800";
81  ::arg().set("soa-retry-default","Default SOA retry")="3600";
82  ::arg().set("soa-expire-default","Default SOA expire")="604800";
83    ::arg().setSwitch("query-logging","Hint backends that queries should be logged")="no";
84  ::arg().set("soa-minimum-ttl","Default SOA mininum ttl")="3600";   
85 
86  UeberBackend::go();
87}
88
89void rectifyZone(DNSSECKeeper& dk, const std::string& zone)
90{
91  UeberBackend* B = new UeberBackend("default");
92  SOAData sd;
93 
94  if(!B->getSOA(zone, sd)) {
95    cerr<<"No SOA known for '"<<zone<<"', is such a zone in the database?"<<endl;
96    return;
97  } 
98  sd.db->list(zone, sd.domain_id);
99  DNSResourceRecord rr;
100
101  set<string> qnames, nsset;
102 
103  while(sd.db->get(rr)) {
104    qnames.insert(rr.qname);
105    if(rr.qtype.getCode() == QType::NS && !pdns_iequals(rr.qname, zone)) 
106      nsset.insert(rr.qname);
107  }
108
109  NSEC3PARAMRecordContent ns3pr;
110  bool narrow;
111  bool haveNSEC3=dk.getNSEC3PARAM(zone, &ns3pr, &narrow);
112  string hashed;
113  if(!haveNSEC3) 
114    cerr<<"Adding NSEC ordering information"<<endl;
115  else if(!narrow)
116    cerr<<"Adding NSEC3 hashed ordering information for '"<<zone<<"'"<<endl;
117  else 
118    cerr<<"Erasing NSEC3 ordering since we are narrow, only setting 'auth' fields"<<endl;
119 
120  BOOST_FOREACH(const string& qname, qnames)
121  {
122    string shorter(qname);
123    bool auth=true;
124    do {
125      if(nsset.count(shorter)) { 
126        auth=false;
127        break;
128      }
129    }while(chopOff(shorter));
130
131    if(!haveNSEC3) // NSEC
132      sd.db->updateDNSSECOrderAndAuth(sd.domain_id, zone, qname, auth);
133    else {
134      if(!narrow) {
135        hashed=toLower(toBase32Hex(hashQNameWithSalt(ns3pr.d_iterations, ns3pr.d_salt, qname)));
136        cerr<<"'"<<qname<<"' -> '"<< hashed <<"'"<<endl;
137      }
138      sd.db->updateDNSSECOrderAndAuthAbsolute(sd.domain_id, qname, hashed, auth);
139    }
140  }
141  cerr<<"Done listing"<<endl;
142}
143
144void checkZone(DNSSECKeeper& dk, const std::string& zone)
145{
146  UeberBackend* B = new UeberBackend("default");
147  SOAData sd;
148 
149  if(!B->getSOA(zone, sd)) {
150    cerr<<"No SOA!"<<endl;
151    return;
152  } 
153  sd.db->list(zone, sd.domain_id);
154  DNSResourceRecord rr;
155  uint64_t numrecords=0, numerrors=0;
156 
157  while(sd.db->get(rr)) {
158    if(rr.qtype.getCode() == QType::MX) 
159      rr.content = lexical_cast<string>(rr.priority)+" "+rr.content;
160    if(rr.auth == 0 && rr.qtype.getCode()!=QType::NS && rr.qtype.getCode()!=QType::A)
161    {
162      cerr<<"Following record is auth=0, run pdnssec rectify-zone?: "<<rr.qname<<" IN " <<rr.qtype.getName()<< " " << rr.content<<endl;
163    }
164    try {
165      shared_ptr<DNSRecordContent> drc(DNSRecordContent::mastermake(rr.qtype.getCode(), 1, rr.content));
166      string tmp=drc->serialize(rr.qname);
167    }
168    catch(std::exception& e) 
169    {
170      cerr<<"Following record had a problem: "<<rr.qname<<" IN " <<rr.qtype.getName()<< " " << rr.content<<endl;
171      cerr<<"Error was: "<<e.what()<<endl;
172      numerrors++;
173    }
174    numrecords++;
175  }
176  cerr<<"Checked "<<numrecords<<" records, "<<numerrors<<" errors"<<endl;
177}
178
179void showZone(DNSSECKeeper& dk, const std::string& zone)
180{
181  NSEC3PARAMRecordContent ns3pr;
182  bool narrow;
183  bool haveNSEC3=dk.getNSEC3PARAM(zone, &ns3pr, &narrow);
184 
185  if(!haveNSEC3) 
186    cout<<"Zone has NSEC semantics"<<endl;
187  else
188    cout<<"Zone has " << (narrow ? "NARROW " : "") <<"hashed NSEC3 semantics, configuration: "<<ns3pr.getZoneRepresentation()<<endl;
189 
190  DNSSECKeeper::keyset_t keyset=dk.getKeys(zone);
191
192  if(keyset.empty())  {
193    cerr << "No keys for zone '"<<zone<<"'."<<endl;
194  }
195  else { 
196    cout << "keys: "<<endl;
197    BOOST_FOREACH(DNSSECKeeper::keyset_t::value_type value, keyset) {
198      cout<<"ID = "<<value.second.id<<" ("<<(value.second.keyOrZone ? "KSK" : "ZSK")<<"), tag = "<<value.first.getDNSKEY().getTag();
199      cout<<", algo = "<<(int)value.first.d_algorithm<<", bits = "<<value.first.d_key.getConstContext().len*8<<"\tActive: "<<value.second.active<< endl; // humanTime(value.second.beginValidity)<<" - "<<humanTime(value.second.endValidity)<<endl;
200      if(value.second.keyOrZone) {
201        cout<<"KSK DNSKEY = "<<zone<<" IN DNSKEY "<< value.first.getDNSKEY().getZoneRepresentation() << endl;
202        cout<<"DS = "<<zone<<" IN DS "<<makeDSFromDNSKey(zone, value.first.getDNSKEY(), 1).getZoneRepresentation() << endl;
203        cout<<"DS = "<<zone<<" IN DS "<<makeDSFromDNSKey(zone, value.first.getDNSKEY(), 2).getZoneRepresentation() << endl << endl;
204      }
205    }
206  }
207}
208
209int main(int argc, char** argv)
210try
211{
212  po::options_description desc("Allowed options");
213  desc.add_options()
214    ("help,h", "produce help message")
215    ("verbose,v", po::value<bool>(), "be verbose")
216    ("force", "force an action")
217    ("config-name", po::value<string>()->default_value(""), "virtual configuration name")
218    ("config-dir", po::value<string>()->default_value(SYSCONFDIR), "location of pdns.conf")
219    ("commands", po::value<vector<string> >());
220
221  po::positional_options_description p;
222  p.add("commands", -1);
223  po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), g_vm);
224  po::notify(g_vm);
225
226  vector<string> cmds;
227
228  if(g_vm.count("commands")) 
229    cmds = g_vm["commands"].as<vector<string> >();
230
231  if(cmds.empty() || g_vm.count("help")) {
232    cerr<<"Usage: \npdnssec [options] [show-zone] [secure-zone] [rectify-zone] [add-zone-key] [deactivate-zone-key] [remove-zone-key] [activate-zone-key]\n";
233    cerr<<"         [import-zone-key] [export-zone-key] [set-nsec3] [unset-nsec3] [export-zone-dnskey]\n\n";
234    cerr<<"activate-zone-key ZONE KEY-ID   Activate the key with key id KEY-ID in ZONE\n";
235    cerr<<"add-zone-key ZONE [zsk|ksk]     Add a ZSK or KSK to a zone\n";
236    cerr<<"  [bits] [rsasha1|rsasha256]    and specify algorithm & bits\n";
237    cerr<<"check-zone ZONE                 Check a zone for correctness\n";
238    cerr<<"deactivate-zone-key             Dectivate the key with key id KEY-ID in ZONE\n";
239    cerr<<"export-zone-dnskey ZONE KEY-ID  Export to stdout the public DNSKEY described\n";
240    cerr<<"export-zone-key ZONE KEY-ID     Export to stdout the private key described\n";
241    cerr<<"import-zone-key ZONE FILE       Import from a file a private key, ZSK or KSK\n";           
242    cerr<<"                [ksk|zsk]       Defaults to KSK\n";
243    cerr<<"rectify-zone ZONE               Fix up DNSSEC fields (order, auth)\n";
244    cerr<<"remove-zone-key ZONE KEY-ID     Remove key with KEY-ID from ZONE\n";
245    cerr<<"secure-zone                     Add KSK and two ZSKs\n";
246    cerr<<"set-nsec3 'params' [narrow]     Enable NSEC3 with PARAMs. Optionally narrow\n";
247    cerr<<"show-zone ZONE                  Show DNSSEC (public) key details about a zone\n";
248    cerr<<"unset-nsec3 ZONE                Switch back to NSEC\n\n";
249
250    cerr<<"Options:"<<endl;
251    cerr<<desc<<endl;
252    return 0;
253  }
254 
255  loadMainConfig(g_vm["config-dir"].as<string>());
256  reportAllTypes();
257  DNSSECKeeper dk;
258
259  if(cmds[0] == "rectify-zone" || cmds[0] == "order-zone") {
260    if(cmds.size() != 2) {
261      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
262      return 0;
263    }
264    rectifyZone(dk, cmds[1]);
265  }
266  else if(cmds[0] == "check-zone") {
267    if(cmds.size() != 2) {
268      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
269      return 0;
270    }
271    checkZone(dk, cmds[1]);
272  }
273
274  else if(cmds[0] == "show-zone") {
275    if(cmds.size() != 2) {
276      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
277      return 0;
278    }
279    const string& zone=cmds[1];
280    showZone(dk, zone);
281  }
282  else if(cmds[0] == "activate-zone-key") {
283    const string& zone=cmds[1];
284    unsigned int id=atoi(cmds[2].c_str());
285    dk.activateKey(zone, id);
286  }
287  else if(cmds[0] == "deactivate-zone-key") {
288    const string& zone=cmds[1];
289    unsigned int id=atoi(cmds[2].c_str());
290    dk.deactivateKey(zone, id);
291  }
292  else if(cmds[0] == "add-zone-key") {
293    const string& zone=cmds[1];
294    // need to get algorithm, bits & ksk or zsk from commandline
295    bool keyOrZone=false;
296    int bits=0;
297    int algorithm=5;
298    for(unsigned int n=2; n < cmds.size(); ++n) {
299      if(pdns_iequals(cmds[n], "zsk"))
300        keyOrZone = false;
301      else if(pdns_iequals(cmds[n], "ksk"))
302        keyOrZone = true;
303      else if(pdns_iequals(cmds[n], "rsasha1"))
304        algorithm=5;
305      else if(pdns_iequals(cmds[n], "rsasha256"))
306        algorithm=8;
307      else if(atoi(cmds[n].c_str()))
308        bits = atoi(cmds[n].c_str());
309      else { 
310        cerr<<"Unknown algorithm, key flag or size '"<<cmds[n]<<"'"<<endl;
311        return 0;
312      }
313    }
314    cerr<<"Adding a " << (keyOrZone ? "KSK" : "ZSK")<<" with algorithm = "<<algorithm<<endl;
315    if(bits)
316      cerr<<"Requesting specific key size of "<<bits<<" bits"<<endl;
317    dk.addKey(zone, keyOrZone, algorithm, bits); 
318  }
319  else if(cmds[0] == "remove-zone-key") {
320    if(cmds.size() < 3) {
321      cerr<<"Syntax: pdnssec remove-zone-key ZONE KEY-ID\n";
322      return 0;
323    }
324    const string& zone=cmds[1];
325    unsigned int id=atoi(cmds[2].c_str());
326    dk.removeKey(zone, id);
327  }
328 
329  else if(cmds[0] == "secure-zone") {
330    if(cmds.size() != 2) {
331      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
332      return 0;
333    }
334    const string& zone=cmds[1];
335    DNSSECPrivateKey dpk;
336   
337    if(dk.haveActiveKSKFor(zone)) {
338      cerr << "There is a KSK already for zone '"<<zone<<"', remove with pdnssec remove-zone-key if needed"<<endl;
339      return 0;
340    }
341     
342    dk.secureZone(zone, 8);
343
344    if(!dk.haveActiveKSKFor(zone)) {
345      cerr << "This should not happen, still no key!" << endl;
346      return 0;
347    }
348 
349    DNSSECKeeper::keyset_t zskset=dk.getKeys(zone, false);
350
351    if(!zskset.empty())  {
352      cerr<<"There were ZSKs already for zone '"<<zone<<"', no need to add more"<<endl;
353      return 0;
354    }
355     
356    dk.addKey(zone, false, 8);
357    dk.addKey(zone, false, 8, 0, false); // not active
358    rectifyZone(dk, zone);
359    showZone(dk, zone);
360  }
361  else if(cmds[0]=="set-nsec3") {
362    string nsec3params =  cmds.size() > 2 ? cmds[2] : "1 0 1 ab";
363    bool narrow = cmds.size() > 3 && cmds[3]=="narrow";
364    NSEC3PARAMRecordContent ns3pr(nsec3params);
365    dk.setNSEC3PARAM(cmds[1], ns3pr, narrow);
366  }
367  else if(cmds[0]=="hash-zone-record") {
368    if(cmds.size() < 3) {
369      cerr<<"Wrong number of arguments, syntax: hash-zone-record ZONE RECORD"<<endl;
370      return 0;
371    }
372    string& zone=cmds[1];
373    string& record=cmds[2];
374    NSEC3PARAMRecordContent ns3pr;
375    bool narrow;
376    if(!dk.getNSEC3PARAM(zone, &ns3pr, &narrow)) {
377      cerr<<"The '"<<zone<<"' zone does not use NSEC3"<<endl;
378      return 0;
379    }
380    if(!narrow) {
381      cerr<<"The '"<<zone<<"' zone uses narrow NSEC3, but calculating hash anyhow"<<endl;
382    }
383     
384    cout<<toLower(toBase32Hex(hashQNameWithSalt(ns3pr.d_iterations, ns3pr.d_salt, record)))<<endl;
385  }
386  else if(cmds[0]=="unset-nsec3") {
387    dk.unsetNSEC3PARAM(cmds[1]);
388  }
389  else if(cmds[0]=="export-zone-key") {
390    if(cmds.size() < 3) {
391      cerr<<"Syntax: pdnssec export-zone-key zone-name id"<<endl;
392      cerr<<cmds.size()<<endl;
393      exit(1);
394    }
395
396    string zone=cmds[1];
397    unsigned int id=atoi(cmds[2].c_str());
398    DNSSECPrivateKey dpk=dk.getKeyById(zone, id);
399    cout << dpk.d_key.convertToISC(dpk.d_algorithm) <<endl;
400  } 
401  else if(cmds[0]=="import-zone-key-pem") {
402    if(cmds.size() < 4) {
403      cerr<<"Syntax: pdnssec import-zone-key zone-name filename.pem algorithm [zsk|ksk]"<<endl;
404      exit(1);
405    }
406    string zone=cmds[1];
407    string fname=cmds[2];
408    string line;
409    ifstream ifs(fname.c_str());
410    string tmp, interim, raw;
411    while(getline(ifs, line)) {
412      if(line[0]=='-')
413        continue;
414      trim(line);
415      interim += line;
416    }
417    B64Decode(interim, raw);
418    DNSSECPrivateKey dpk;
419    getRSAKeyFromPEMString(&dpk.d_key.getContext(), raw);
420   
421    dpk.d_algorithm = atoi(cmds[3].c_str());
422   
423    if(dpk.d_algorithm == 7)
424      dpk.d_algorithm = 5;
425     
426    cerr<<(int)dpk.d_algorithm<<endl;
427   
428    if(cmds.size() > 4) {
429      if(pdns_iequals(cmds[4], "ZSK"))
430        dpk.d_flags = 256;
431      else if(pdns_iequals(cmds[4], "KSK"))
432        dpk.d_flags = 257;
433      else {
434        cerr<<"Unknown key flag '"<<cmds[4]<<"'\n";
435        exit(1);
436      }
437    }
438    else
439      dpk.d_flags = 257; // ksk
440     
441    dk.addKey(zone, dpk); 
442   
443  }
444  else if(cmds[0]=="import-zone-key") {
445    if(cmds.size() < 3) {
446      cerr<<"Syntax: pdnssec import-zone-key zone-name filename [zsk|ksk]"<<endl;
447      exit(1);
448    }
449    string zone=cmds[1];
450    string fname=cmds[2];
451    DNSSECPrivateKey dpk;
452    DNSKEYRecordContent drc = getRSAKeyFromISC(&dpk.d_key.getContext(), fname.c_str());
453    dpk.d_algorithm = drc.d_algorithm;
454   
455    if(dpk.d_algorithm == 7)
456      dpk.d_algorithm = 5;
457     
458    cerr<<(int)dpk.d_algorithm<<endl;
459   
460    if(cmds.size() > 3) {
461      if(pdns_iequals(cmds[3], "ZSK"))
462        dpk.d_flags = 256;
463      else if(pdns_iequals(cmds[3], "KSK"))
464        dpk.d_flags = 257;
465      else {
466        cerr<<"Unknown key flag '"<<cmds[3]<<"'\n";
467        exit(1);
468      }
469    }
470    else
471      dpk.d_flags = 257; 
472     
473    dk.addKey(zone, dpk); 
474  }
475  else if(cmds[0]=="export-zone-dnskey") {
476    if(cmds.size() < 3) {
477      cerr<<"Syntax: pdnssec export-zone-dnskey zone-name id"<<endl;
478      exit(1);
479    }
480
481    string zone=cmds[1];
482    unsigned int id=atoi(cmds[2].c_str());
483    DNSSECPrivateKey dpk=dk.getKeyById(zone, id);
484    cout << zone<<" IN DNSKEY "<<dpk.getDNSKEY().getZoneRepresentation() <<endl;
485    if(dpk.d_flags == 257) {
486      cout << zone << " IN DS "<<makeDSFromDNSKey(zone, dpk.getDNSKEY(), 1).getZoneRepresentation() << endl;
487      cout << zone << " IN DS "<<makeDSFromDNSKey(zone, dpk.getDNSKEY(), 2).getZoneRepresentation() << endl;
488    }
489  }
490  else {
491    cerr<<"Unknown command '"<<cmds[0]<<"'\n";
492    return 1;
493  }
494  return 0;
495}
496catch(AhuException& ae) {
497  cerr<<"Error: "<<ae.reason<<endl;
498}
499catch(std::exception& e) {
500  cerr<<"Error: "<<e.what()<<endl;
501}
Note: See TracBrowser for help on using the browser.