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

Revision 1825, 13.9 KB (checked in by ahu, 2 years ago)

more documentation, plus add importing as zsk, ksk, plus adding a zsk or ksk and specifying bitsize

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]     Add a ZSK or KSK to a zone (ZSK only now)\n";
205    cerr<<"deactivate-zone-key             Dectivate the key with key id KEY-ID in ZONE\n";
206    cerr<<"export-zone-dnskey ZONE KEY-ID  Export to stdout the public DNSKEY described\n";
207    cerr<<"export-zone-key ZONE KEY-ID     Export to stdout the private key described\n";
208    cerr<<"import-zone-key ZONE FILE       Import from a file a private KSK\n";           
209    cerr<<"rectify-zone ZONE               Fix up DNSSEC fields (order, auth)\n";
210    cerr<<"remove-zone-key ZONE KEY-ID     Remove key with KEY-ID from ZONE\n";
211    cerr<<"secure-zone                     Add KSK and two ZSKs\n";
212    cerr<<"set-nsec3 'params' [narrow]     Enable NSEC3 with PARAMs. Optionally narrow\n";
213    cerr<<"show-zone ZONE                  Show DNSSEC (public) key details about a zone\n";
214    cerr<<"unset-nsec3 ZONE                Switch back to NSEC\n\n";
215
216    cerr<<"Options:"<<endl;
217    cerr<<desc<<endl;
218    return 0;
219  }
220 
221  loadMainConfig(g_vm["config-dir"].as<string>());
222  reportAllTypes();
223  DNSSECKeeper dk;
224
225  if(cmds[0] == "rectify-zone" || cmds[0] == "order-zone") {
226    if(cmds.size() != 2) {
227      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
228      return 0;
229    }
230    rectifyZone(dk, cmds[1]);
231  }
232  else if(cmds[0] == "check-zone") {
233    if(cmds.size() != 2) {
234      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
235      return 0;
236    }
237    checkZone(dk, cmds[1]);
238  }
239
240  else if(cmds[0] == "show-zone") {
241    if(cmds.size() != 2) {
242      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
243      return 0;
244    }
245    const string& zone=cmds[1];
246
247    NSEC3PARAMRecordContent ns3pr;
248    bool narrow;
249    dk.getNSEC3PARAM(zone, &ns3pr, &narrow);
250   
251    if(ns3pr.d_salt.empty()) 
252      cerr<<"Zone has NSEC semantics"<<endl;
253    else
254      cerr<<"Zone has " << (narrow ? "NARROW " : "") <<"hashed NSEC3 semantics, configuration: "<<ns3pr.getZoneRepresentation()<<endl;
255   
256    DNSSECKeeper::keyset_t keyset=dk.getKeys(zone);
257
258    if(keyset.empty())  {
259      cerr << "No keys for zone '"<<zone<<"'."<<endl;
260    }
261    else { 
262      cout << "keys: "<<endl;
263      BOOST_FOREACH(DNSSECKeeper::keyset_t::value_type value, keyset) {
264        cout<<"ID = "<<value.second.id<<" ("<<(value.second.keyOrZone ? "KSK" : "ZSK")<<"), tag = "<<value.first.getDNSKEY().getTag();
265        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;
266        if(value.second.keyOrZone) {
267          cout<<"KSK DNSKEY = "<<zone<<" IN DNSKEY "<< value.first.getDNSKEY().getZoneRepresentation() << endl;
268          cout<<"DS = "<<zone<<" IN DS "<<makeDSFromDNSKey(zone, value.first.getDNSKEY()).getZoneRepresentation() << endl << endl;
269        }
270      }
271    }
272  }
273  else if(cmds[0] == "activate-zone-key") {
274    const string& zone=cmds[1];
275    unsigned int id=atoi(cmds[2].c_str());
276    dk.activateKey(zone, id);
277  }
278  else if(cmds[0] == "deactivate-zone-key") {
279    const string& zone=cmds[1];
280    unsigned int id=atoi(cmds[2].c_str());
281    dk.deactivateKey(zone, id);
282  }
283  else if(cmds[0] == "add-zone-key") {
284    const string& zone=cmds[1];
285    // need to get algorithm, bits & ksk or zsk from commandline
286    bool keyOrZone=false;
287    int bits=0;
288    for(unsigned int n=2; n < cmds.size(); ++n) {
289      if(pdns_iequals(cmds[n], "zsk"))
290        keyOrZone = false;
291      else if(pdns_iequals(cmds[n], "ksk"))
292        keyOrZone = true;
293      else if(atoi(cmds[n].c_str()))
294        bits = atoi(cmds[n].c_str());
295      else { 
296        cerr<<"Unknown key flag or size '"<<cmds[n]<<"'"<<endl;
297      }
298    }
299    cerr<<"Adding a " << (keyOrZone ? "KSK" : "ZSK")<<endl;
300    if(bits)
301      cerr<<"Requesting specific key size of "<<bits<<" bits"<<endl;
302    dk.addKey(zone, keyOrZone, 5, bits); 
303  }
304  else if(cmds[0] == "remove-zone-key") {
305    const string& zone=cmds[1];
306    unsigned int id=atoi(cmds[2].c_str());
307    dk.removeKey(zone, id);
308  }
309 
310  else if(cmds[0] == "secure-zone") {
311    if(cmds.size() != 2) {
312      cerr << "Error: "<<cmds[0]<<" takes exactly 1 parameter"<<endl;
313      return 0;
314    }
315    const string& zone=cmds[1];
316    DNSSECPrivateKey dpk;
317   
318    if(dk.haveActiveKSKFor(zone, &dpk) && !g_vm.count("force")) {
319      cerr << "There is a key already for zone '"<<zone<<"', use --force to overwrite"<<endl;
320      return 0;
321    }
322     
323    dk.secureZone(zone, 5);
324
325    if(!dk.haveActiveKSKFor(zone, &dpk)) {
326      cerr << "This should not happen, still no key!" << endl;
327      return 0;
328    }
329    cout<<"Created KSK with tag "<<dpk.getDNSKEY().getTag()<<endl;
330 
331    DNSSECKeeper::keyset_t zskset=dk.getKeys(zone, false);
332
333    if(!zskset.empty() && !g_vm.count("force"))  {
334      cerr<<"There were ZSKs already for zone '"<<zone<<"'"<<endl;
335      return 0;
336    }
337     
338    dk.addKey(zone, false, 5);
339    dk.addKey(zone, false, 5, 0, false); // not active
340
341    zskset = dk.getKeys(zone, false);
342    if(zskset.empty()) {
343      cerr<<"This should not happen, still no ZSK!"<<endl;
344    }
345
346    cout<<"There are now "<<zskset.size()<<" ZSKs"<<endl;
347    BOOST_FOREACH(DNSSECKeeper::keyset_t::value_type value, zskset) {
348      cout<<"id = "<<value.second.id<<", tag = "<<value.first.getDNSKEY().getTag()<<", algo = "<<(int)value.first.d_algorithm<<
349        ", bits = "<<value.first.d_key.getContext().len*8;
350      cout<<"\tActive: "<<value.second.active<<endl;
351    }
352  }
353  else if(cmds[0]=="set-nsec3") {
354    string nsec3params =  cmds.size() > 2 ? cmds[2] : "1 0 1 ab";
355    bool narrow = cmds.size() > 3 && cmds[3]=="narrow";
356    NSEC3PARAMRecordContent ns3pr(nsec3params);
357    dk.setNSEC3PARAM(cmds[1], ns3pr, narrow);
358  }
359  else if(cmds[0]=="unset-nsec3") {
360    dk.unsetNSEC3PARAM(cmds[1]);
361  }
362  else if(cmds[0]=="export-zone-key") {
363    string zone=cmds[1];
364    unsigned int id=atoi(cmds[2].c_str());
365    DNSSECPrivateKey dpk=dk.getKeyById(zone, id);
366    cout << dpk.d_key.convertToISC(dpk.d_algorithm) <<endl;
367  } 
368  else if(cmds[0]=="import-zone-key") {
369    if(cmds.size() < 3) {
370      cerr<<"Syntax: pdnssec import-zone-key zone-name filename"<<endl;
371      exit(1);
372    }
373    string zone=cmds[1];
374    string fname=cmds[2];
375    DNSSECPrivateKey dpk;
376    getRSAKeyFromISC(&dpk.d_key.getContext(), fname.c_str());
377    dpk.d_algorithm = 5;
378   
379    if(cmds.size() > 3) {
380      if(pdns_iequals(cmds[3], "ZSK"))
381        dpk.d_flags = 256;
382      else if(pdns_iequals(cmds[3], "KSK"))
383        dpk.d_flags = 257;
384      else {
385        cerr<<"Unknown key flag '"<<cmds[3]<<"'\n";
386        exit(1);
387      }
388    }
389    else
390      dpk.d_flags = 257; 
391     
392    dk.addKey(zone, true, dpk); // add a KSK
393  }
394  else if(cmds[0]=="export-zone-dnskey") {
395    string zone=cmds[1];
396    unsigned int id=atoi(cmds[2].c_str());
397    DNSSECPrivateKey dpk=dk.getKeyById(zone, id);
398    cout << zone<<" IN DNSKEY "<<dpk.getDNSKEY().getZoneRepresentation() <<endl;
399    if(dpk.d_flags == 257)
400      cout << zone << " IN DS "<<makeDSFromDNSKey(zone, dpk.getDNSKEY()).getZoneRepresentation() << endl;
401  }
402  else {
403    cerr<<"Unknown command '"<<cmds[0]<<"'\n";
404    return 1;
405  }
406  return 0;
407}
408catch(AhuException& ae) {
409  cerr<<"Error: "<<ae.reason<<endl;
410}
411catch(std::exception& e) {
412  cerr<<"Error: "<<e.what()<<endl;
413}
Note: See TracBrowser for help on using the browser.