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

Revision 1835, 14.4 KB (checked in by ahu, 2 years ago)

make dnsseckeeper & dnssecinfra code, plus pdnssec, aware of non-RSASHA1 algorithms, specifically RSASHA256. Rest of PowerDNSSEC has no clue yet.

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