]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/dnssecinfra.cc
Merge pull request #7067 from klaus3000/soa-check-reject-nxdomain-response
[thirdparty/pdns.git] / pdns / dnssecinfra.cc
CommitLineData
12471842
PL
1/*
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
870a0fe4
AT
22#ifdef HAVE_CONFIG_H
23#include "config.h"
24#endif
4691b2df
BH
25#include "dnsparser.hh"
26#include "sstuff.hh"
27#include "misc.hh"
28#include "dnswriter.hh"
29#include "dnsrecords.hh"
acbfb1c1 30#ifndef RECURSOR
4691b2df 31#include "statbag.hh"
acbfb1c1 32#endif
4691b2df 33#include "iputils.hh"
fa8fd4d2 34
4691b2df 35#include <boost/algorithm/string.hpp>
4691b2df
BH
36#include "dnssecinfra.hh"
37#include "dnsseckeeper.hh"
5e8e902d
CH
38#include <openssl/hmac.h>
39#include <openssl/sha.h>
673208a2
BH
40#include <boost/assign/std/vector.hpp> // for 'operator+=()'
41#include <boost/assign/list_inserter.hpp>
f309dacd 42#include "base64.hh"
9e04108d 43#include "namespaces.hh"
8daea594
AT
44#ifdef HAVE_P11KIT1
45#include "pkcs11signers.hh"
46#endif
7f9ac49b 47#include "gss_context.hh"
da15912b 48#include "misc.hh"
8daea594 49
673208a2
BH
50using namespace boost::assign;
51
e69c2dac 52shared_ptr<DNSCryptoKeyEngine> DNSCryptoKeyEngine::makeFromISCFile(DNSKEYRecordContent& drc, const char* fname)
4691b2df 53{
f309dacd 54 string sline, isc;
4691b2df 55 FILE *fp=fopen(fname, "r");
699e6e37
BH
56 if(!fp) {
57 throw runtime_error("Unable to read file '"+string(fname)+"' for generating DNS Private Key");
58 }
f309dacd 59
699e6e37 60 while(stringfgets(fp, sline)) {
f309dacd 61 isc += sline;
699e6e37
BH
62 }
63 fclose(fp);
e69c2dac 64 shared_ptr<DNSCryptoKeyEngine> dke = makeFromISCString(drc, isc);
45c2bc60 65 if(!dke->checkKey()) {
8ca3ea33
RG
66 throw runtime_error("Invalid DNS Private Key in file '"+string(fname));
67 }
68 return dke;
f309dacd 69}
4691b2df 70
e69c2dac 71shared_ptr<DNSCryptoKeyEngine> DNSCryptoKeyEngine::makeFromISCString(DNSKEYRecordContent& drc, const std::string& content)
f309dacd 72{
8daea594 73 bool pkcs11=false;
f309dacd
BH
74 int algorithm = 0;
75 string sline, key, value, raw;
9e04108d 76 std::istringstream str(content);
f309dacd 77 map<string, string> stormap;
495155bf 78
9e04108d 79 while(std::getline(str, sline)) {
f309dacd
BH
80 tie(key,value)=splitField(sline, ':');
81 trim(value);
82 if(pdns_iequals(key,"algorithm")) {
335da0ba
AT
83 algorithm = pdns_stou(value);
84 stormap["algorithm"]=std::to_string(algorithm);
f309dacd 85 continue;
8daea594
AT
86 } else if (pdns_iequals(key,"pin")) {
87 stormap["pin"]=value;
88 continue;
89 } else if (pdns_iequals(key,"engine")) {
90 stormap["engine"]=value;
91 pkcs11=true;
92 continue;
93 } else if (pdns_iequals(key,"slot")) {
248d701f 94 stormap["slot"]=value;
8daea594
AT
95 continue;
96 } else if (pdns_iequals(key,"label")) {
97 stormap["label"]=value;
98 continue;
9ee32859
AT
99 } else if (pdns_iequals(key,"publabel")) {
100 stormap["publabel"]=value;
101 continue;
f309dacd
BH
102 }
103 else if(pdns_iequals(key, "Private-key-format"))
104 continue;
105 raw.clear();
106 B64Decode(value, raw);
107 stormap[toLower(key)]=raw;
108 }
e69c2dac 109 shared_ptr<DNSCryptoKeyEngine> dpk;
8daea594
AT
110
111 if (pkcs11) {
112#ifdef HAVE_P11KIT1
f0a0745b
AT
113 if (stormap.find("slot") == stormap.end())
114 throw PDNSException("Cannot load PKCS#11 key, no Slot specified");
115 // we need PIN to be at least empty
116 if (stormap.find("pin") == stormap.end()) stormap["pin"] = "";
8daea594
AT
117 dpk = PKCS11DNSCryptoKeyEngine::maker(algorithm);
118#else
70f0f8c4 119 throw PDNSException("Cannot load PKCS#11 key without support for it");
8daea594
AT
120#endif
121 } else {
122 dpk=make(algorithm);
123 }
f309dacd 124 dpk->fromISCMap(drc, stormap);
022e5e0b
BH
125 return dpk;
126}
127
189bb9d2
BH
128std::string DNSCryptoKeyEngine::convertToISC() const
129{
c99573a5 130 storvector_t stormap = this->convertToISCVector();
189bb9d2 131 ostringstream ret;
c99573a5 132 ret<<"Private-key-format: v1.2\n";
ef7cd021 133 for(const stormap_t::value_type& value : stormap) {
8daea594
AT
134 if(value.first != "Algorithm" && value.first != "PIN" &&
135 value.first != "Slot" && value.first != "Engine" &&
9ee32859 136 value.first != "Label" && value.first != "PubLabel")
c99573a5
BH
137 ret<<value.first<<": "<<Base64Encode(value.second)<<"\n";
138 else
139 ret<<value.first<<": "<<value.second<<"\n";
189bb9d2
BH
140 }
141 return ret.str();
142}
f309dacd 143
e69c2dac 144shared_ptr<DNSCryptoKeyEngine> DNSCryptoKeyEngine::make(unsigned int algo)
022e5e0b 145{
8455425c 146 const makers_t& makers = getMakers();
022e5e0b 147 makers_t::const_iterator iter = makers.find(algo);
8455425c 148 if(iter != makers.cend())
022e5e0b
BH
149 return (iter->second)(algo);
150 else {
335da0ba 151 throw runtime_error("Request to create key object for unknown algorithm number "+std::to_string(algo));
699e6e37 152 }
699e6e37 153}
4691b2df 154
98d13a90
PL
155/**
156 * Returns the supported DNSSEC algorithms with the name of the Crypto Backend used
157 *
158 * @return A vector with pairs of (algorithm-number (int), backend-name (string))
159 */
160vector<pair<uint8_t, string>> DNSCryptoKeyEngine::listAllAlgosWithBackend()
161{
162 vector<pair<uint8_t, string>> ret;
163 for (auto const& value : getMakers()) {
164 shared_ptr<DNSCryptoKeyEngine> dcke(value.second(value.first));
165 ret.push_back(make_pair(value.first, dcke->getName()));
166 }
167 return ret;
168}
169
8d9f38f2 170void DNSCryptoKeyEngine::report(unsigned int algo, maker_t* maker, bool fallback)
022e5e0b 171{
189bb9d2 172 getAllMakers()[algo].push_back(maker);
f309dacd
BH
173 if(getMakers().count(algo) && fallback) {
174 return;
4691b2df 175 }
f309dacd 176 getMakers()[algo]=maker;
699e6e37
BH
177}
178
166d8647 179bool DNSCryptoKeyEngine::testAll()
189bb9d2 180{
166d8647
KM
181 bool ret=true;
182
ef7cd021 183 for(const allmakers_t::value_type& value : getAllMakers())
189bb9d2 184 {
ef7cd021 185 for(maker_t* creator : value.second) {
530b4335 186
ef7cd021 187 for(maker_t* signer : value.second) {
530b4335
PD
188 // multi_map<unsigned int, maker_t*> bestSigner, bestVerifier;
189
ef7cd021 190 for(maker_t* verifier : value.second) {
530b4335 191 try {
12184d68 192 /* pair<unsigned int, unsigned int> res=*/ testMakers(value.first, creator, signer, verifier);
530b4335
PD
193 }
194 catch(std::exception& e)
195 {
196 cerr<<e.what()<<endl;
166d8647 197 ret=false;
530b4335 198 }
189bb9d2
BH
199 }
200 }
201 }
202 }
166d8647 203 return ret;
189bb9d2
BH
204}
205
166d8647 206bool DNSCryptoKeyEngine::testOne(int algo)
cbb0025b 207{
166d8647
KM
208 bool ret=true;
209
ef7cd021 210 for(maker_t* creator : getAllMakers()[algo]) {
530b4335 211
ef7cd021 212 for(maker_t* signer : getAllMakers()[algo]) {
cbb0025b
PD
213 // multi_map<unsigned int, maker_t*> bestSigner, bestVerifier;
214
ef7cd021 215 for(maker_t* verifier : getAllMakers()[algo]) {
cbb0025b 216 try {
12184d68 217 /* pair<unsigned int, unsigned int> res=*/testMakers(algo, creator, signer, verifier);
cbb0025b
PD
218 }
219 catch(std::exception& e)
220 {
221 cerr<<e.what()<<endl;
166d8647 222 ret=false;
cbb0025b
PD
223 }
224 }
225 }
530b4335 226 }
166d8647 227 return ret;
cbb0025b 228}
12184d68 229// returns times it took to sign and verify
530b4335 230pair<unsigned int, unsigned int> DNSCryptoKeyEngine::testMakers(unsigned int algo, maker_t* creator, maker_t* signer, maker_t* verifier)
189bb9d2 231{
530b4335 232 shared_ptr<DNSCryptoKeyEngine> dckeCreate(creator(algo));
189bb9d2
BH
233 shared_ptr<DNSCryptoKeyEngine> dckeSign(signer(algo));
234 shared_ptr<DNSCryptoKeyEngine> dckeVerify(verifier(algo));
530b4335
PD
235
236 cerr<<"Testing algorithm "<<algo<<": '"<<dckeCreate->getName()<<"' ->'"<<dckeSign->getName()<<"' -> '"<<dckeVerify->getName()<<"' ";
189bb9d2
BH
237 unsigned int bits;
238 if(algo <= 10)
239 bits=1024;
902c4e9c
CH
240 else if(algo == DNSSECKeeper::ECCGOST || algo == DNSSECKeeper::ECDSA256 || algo == DNSSECKeeper::ED25519)
241 bits = 256;
242 else if(algo == DNSSECKeeper::ECDSA384)
45826dd7 243 bits = 384;
902c4e9c 244 else if(algo == DNSSECKeeper::ED448)
21a8834a 245 bits = 456;
45826dd7 246 else
335da0ba 247 throw runtime_error("Can't guess key size for algorithm "+std::to_string(algo));
45826dd7 248
530b4335
PD
249 dckeCreate->create(bits);
250
251 { // FIXME: this block copy/pasted from makeFromISCString
252 DNSKEYRecordContent dkrc;
253 int algorithm = 0;
254 string sline, key, value, raw;
255 std::istringstream str(dckeCreate->convertToISC());
256 map<string, string> stormap;
257
258 while(std::getline(str, sline)) {
259 tie(key,value)=splitField(sline, ':');
260 trim(value);
261 if(pdns_iequals(key,"algorithm")) {
335da0ba
AT
262 algorithm = pdns_stou(value);
263 stormap["algorithm"]=std::to_string(algorithm);
530b4335 264 continue;
8daea594
AT
265 } else if (pdns_iequals(key,"pin")) {
266 stormap["pin"]=value;
267 continue;
268 } else if (pdns_iequals(key,"engine")) {
269 stormap["engine"]=value;
270 continue;
271 } else if (pdns_iequals(key,"slot")) {
335da0ba
AT
272 int slot = std::stoi(value);
273 stormap["slot"]=std::to_string(slot);
8daea594
AT
274 continue;
275 } else if (pdns_iequals(key,"label")) {
276 stormap["label"]=value;
277 continue;
530b4335
PD
278 }
279 else if(pdns_iequals(key, "Private-key-format"))
280 continue;
281 raw.clear();
282 B64Decode(value, raw);
283 stormap[toLower(key)]=raw;
284 }
285 dckeSign->fromISCMap(dkrc, stormap);
45c2bc60
RG
286 if(!dckeSign->checkKey()) {
287 throw runtime_error("Verification of key with creator "+dckeCreate->getName()+" with signer "+dckeSign->getName()+" and verifier "+dckeVerify->getName()+" failed");
8ca3ea33 288 }
530b4335
PD
289 }
290
189bb9d2
BH
291 string message("Hi! How is life?");
292
293 string signature;
294 DTime dt; dt.set();
f011d0ad
BH
295 for(unsigned int n = 0; n < 100; ++n)
296 signature = dckeSign->sign(message);
297 unsigned int udiffSign= dt.udiff()/100, udiffVerify;
189bb9d2
BH
298
299 dckeVerify->fromPublicKeyString(dckeSign->getPublicKeyString());
7fbe4163
CH
300 if (dckeVerify->getPublicKeyString().compare(dckeSign->getPublicKeyString())) {
301 throw runtime_error("Comparison of public key loaded into verifier produced by signer failed");
302 }
189bb9d2
BH
303 dt.set();
304 if(dckeVerify->verify(message, signature)) {
305 udiffVerify = dt.udiff();
306 cerr<<"Signature & verify ok, signature "<<udiffSign<<"usec, verify "<<udiffVerify<<"usec"<<endl;
307 }
308 else {
530b4335 309 throw runtime_error("Verification of creator "+dckeCreate->getName()+" with signer "+dckeSign->getName()+" and verifier "+dckeVerify->getName()+" failed");
189bb9d2
BH
310 }
311 return make_pair(udiffSign, udiffVerify);
312}
313
e69c2dac 314shared_ptr<DNSCryptoKeyEngine> DNSCryptoKeyEngine::makeFromPublicKeyString(unsigned int algorithm, const std::string& content)
aa65a832 315{
e69c2dac 316 shared_ptr<DNSCryptoKeyEngine> dpk=make(algorithm);
189bb9d2 317 dpk->fromPublicKeyString(content);
aa65a832
BH
318 return dpk;
319}
320
f0397b95 321
e69c2dac 322shared_ptr<DNSCryptoKeyEngine> DNSCryptoKeyEngine::makeFromPEMString(DNSKEYRecordContent& drc, const std::string& raw)
ed3f8559 323{
ed3f8559 324
8455425c 325 for(const makers_t::value_type& val : getMakers())
022e5e0b 326 {
e69c2dac 327 shared_ptr<DNSCryptoKeyEngine> ret=nullptr;
022e5e0b
BH
328 try {
329 ret = val.second(val.first);
330 ret->fromPEMString(drc, raw);
331 return ret;
332 }
333 catch(...)
334 {
ed3f8559
BH
335 }
336 }
022e5e0b 337 return 0;
ed3f8559 338}
f0397b95 339
4691b2df 340
8455425c 341static bool sharedDNSSECCompare(const shared_ptr<DNSRecordContent>& a, const shared_ptr<DNSRecordContent>& b)
4691b2df 342{
12c06211 343 return a->serialize(g_rootdnsname, true, true) < b->serialize(g_rootdnsname, true, true);
4691b2df
BH
344}
345
125058a0
PL
346/**
347 * Returns the string that should be hashed to create/verify the RRSIG content
348 *
349 * @param qname DNSName of the RRSIG's owner name.
350 * @param rrc The RRSIGRecordContent we take the Type Covered and
351 * original TTL fields from.
352 * @param signRecords A vector of DNSRecordContent shared_ptr's that are covered
353 * by the RRSIG, where we get the RDATA from.
354 * @param processRRSIGLabels A boolean to trigger processing the RRSIG's "Labels"
355 * field. This is usually only needed for validation
356 * purposes, as the authoritative server correctly
357 * sets qname to the wildcard.
358 */
359string getMessageForRRSET(const DNSName& qname, const RRSIGRecordContent& rrc, vector<shared_ptr<DNSRecordContent> >& signRecords, bool processRRSIGLabels)
4691b2df
BH
360{
361 sort(signRecords.begin(), signRecords.end(), sharedDNSSECCompare);
362
363 string toHash;
12c06211 364 toHash.append(const_cast<RRSIGRecordContent&>(rrc).serialize(g_rootdnsname, true, true));
ade1b1e9 365 toHash.resize(toHash.size() - rrc.d_signature.length()); // chop off the end, don't sign the signature!
4691b2df 366
125058a0
PL
367 string nameToHash(qname.toDNSStringLC());
368
369 if (processRRSIGLabels) {
370 unsigned int rrsig_labels = rrc.d_labels;
371 unsigned int fqdn_labels = qname.countLabels();
372
373 if (rrsig_labels < fqdn_labels) {
374 DNSName choppedQname(qname);
375 while (choppedQname.countLabels() > rrsig_labels)
376 choppedQname.chopOff();
377 nameToHash = "\x01*" + choppedQname.toDNSStringLC();
378 } else if (rrsig_labels > fqdn_labels) {
379 // The RRSIG Labels field is a lie (or the qname is wrong) and the RRSIG
380 // can never be valid
381 return "";
382 }
383 }
384
ef7cd021 385 for(shared_ptr<DNSRecordContent>& add : signRecords) {
125058a0 386 toHash.append(nameToHash);
4691b2df
BH
387 uint16_t tmp=htons(rrc.d_type);
388 toHash.append((char*)&tmp, 2);
389 tmp=htons(1); // class
390 toHash.append((char*)&tmp, 2);
391 uint32_t ttl=htonl(rrc.d_originalttl);
392 toHash.append((char*)&ttl, 4);
feb53a77 393 // for NSEC signatures, we should not lowercase the rdata section
12c06211 394 string rdata=add->serialize(g_rootdnsname, true, (add->getType() == QType::NSEC) ? false : true); // RFC 6840, 5.1
4691b2df
BH
395 tmp=htons(rdata.length());
396 toHash.append((char*)&tmp, 2);
397 toHash.append(rdata);
398 }
f96192e3 399
f309dacd 400 return toHash;
4691b2df
BH
401}
402
8455425c
RG
403bool DNSCryptoKeyEngine::isAlgorithmSupported(unsigned int algo)
404{
405 const makers_t& makers = getMakers();
406 makers_t::const_iterator iter = makers.find(algo);
407 return iter != makers.cend();
408}
409
410static unsigned int digestToAlgorithmNumber(uint8_t digest)
411{
412 switch(digest) {
413 case DNSSECKeeper::SHA1:
414 return DNSSECKeeper::RSASHA1;
415 case DNSSECKeeper::SHA256:
416 return DNSSECKeeper::RSASHA256;
417 case DNSSECKeeper::GOST:
418 return DNSSECKeeper::ECCGOST;
419 case DNSSECKeeper::SHA384:
420 return DNSSECKeeper::ECDSA384;
421 default:
422 throw std::runtime_error("Unknown digest type " + std::to_string(digest));
423 }
424 return 0;
425}
426
427bool DNSCryptoKeyEngine::isDigestSupported(uint8_t digest)
428{
429 try {
430 unsigned int algo = digestToAlgorithmNumber(digest);
431 return isAlgorithmSupported(algo);
432 }
433 catch(const std::exception& e) {
434 return false;
435 }
436}
437
438DSRecordContent makeDSFromDNSKey(const DNSName& qname, const DNSKEYRecordContent& drc, uint8_t digest)
4691b2df
BH
439{
440 string toHash;
0ba4e1ee 441 toHash.assign(qname.toDNSStringLC());
290a083d 442 toHash.append(const_cast<DNSKEYRecordContent&>(drc).serialize(DNSName(), true, true));
224778b0 443
4691b2df 444 DSRecordContent dsrc;
8455425c
RG
445 try {
446 unsigned int algo = digestToAlgorithmNumber(digest);
447 shared_ptr<DNSCryptoKeyEngine> dpk(DNSCryptoKeyEngine::make(algo));
39315b97
BH
448 dsrc.d_digest = dpk->hash(toHash);
449 }
8455425c 450 catch(const std::exception& e) {
73c9bf8c 451 throw std::runtime_error("Asked to create (C)DS record of unknown digest type " + std::to_string(digest));
8455425c 452 }
224778b0 453
8455425c
RG
454 dsrc.d_algorithm = drc.d_algorithm;
455 dsrc.d_digesttype = digest;
456 dsrc.d_tag = const_cast<DNSKEYRecordContent&>(drc).getTag();
8daea594 457
4691b2df
BH
458 return dsrc;
459}
460
4691b2df 461
7afd3f74 462static DNSKEYRecordContent makeDNSKEYFromDNSCryptoKeyEngine(const std::shared_ptr<DNSCryptoKeyEngine>& pk, uint8_t algorithm, uint16_t flags)
699e6e37
BH
463{
464 DNSKEYRecordContent drc;
8daea594 465
4691b2df 466 drc.d_protocol=3;
c3c89361 467 drc.d_algorithm = algorithm;
4691b2df 468
4c1474f3 469 drc.d_flags=flags;
699e6e37 470 drc.d_key = pk->getPublicKeyString();
8daea594 471
4691b2df
BH
472 return drc;
473}
474
b61e407d 475uint32_t getStartOfWeek()
4691b2df 476{
b61e407d 477 uint32_t now = time(0);
4691b2df
BH
478 now -= (now % (7*86400));
479 return now;
480}
481
28e2e78e 482string hashQNameWithSalt(const NSEC3PARAMRecordContent& ns3prc, const DNSName& qname)
4691b2df 483{
e4805005 484 return hashQNameWithSalt(ns3prc.d_salt, ns3prc.d_iterations, qname);
485}
486
487string hashQNameWithSalt(const std::string& salt, unsigned int iterations, const DNSName& qname)
488{
489 unsigned int times = iterations;
4691b2df 490 unsigned char hash[20];
0ba4e1ee 491 string toHash(qname.toDNSStringLC());
28e2e78e 492
4691b2df 493 for(;;) {
e4805005 494 toHash.append(salt);
5e8e902d 495 SHA1((unsigned char*)toHash.c_str(), toHash.length(), hash);
f96192e3 496 toHash.assign((char*)hash, sizeof(hash));
28e2e78e
KM
497 if(!times--)
498 break;
4691b2df 499 }
28e2e78e 500 return toHash;
4691b2df 501}
28e2e78e 502
95823c07
RG
503void incrementHash(std::string& raw) // I wonder if this is correct, cmouse? ;-)
504{
505 if(raw.empty())
506 return;
507
508 for(string::size_type pos=raw.size(); pos; ) {
509 --pos;
510 unsigned char c = (unsigned char)raw[pos];
511 ++c;
512 raw[pos] = (char) c;
513 if(c)
514 break;
515 }
516}
517
518void decrementHash(std::string& raw) // I wonder if this is correct, cmouse? ;-)
519{
520 if(raw.empty())
521 return;
522
523 for(string::size_type pos=raw.size(); pos; ) {
524 --pos;
525 unsigned char c = (unsigned char)raw[pos];
526 --c;
527 raw[pos] = (char) c;
528 if(c != 0xff)
529 break;
530 }
531}
532
673208a2
BH
533DNSKEYRecordContent DNSSECPrivateKey::getDNSKEY() const
534{
8d9f38f2 535 return makeDNSKEYFromDNSCryptoKeyEngine(getKey(), d_algorithm, d_flags);
673208a2 536}
ed3f8559
BH
537
538class DEREater
539{
540public:
541 DEREater(const std::string& str) : d_str(str), d_pos(0)
542 {}
543
544 struct eof{};
545
546 uint8_t getByte()
547 {
548 if(d_pos >= d_str.length()) {
549 throw eof();
550 }
551 return (uint8_t) d_str[d_pos++];
552 }
553
554 uint32_t getLength()
555 {
556 uint8_t first = getByte();
557 if(first < 0x80) {
558 return first;
559 }
560 first &= ~0x80;
561
562 uint32_t len=0;
563 for(int n=0; n < first; ++n) {
564 len *= 0x100;
565 len += getByte();
566 }
567 return len;
568 }
569
570 std::string getBytes(unsigned int len)
571 {
572 std::string ret;
573 for(unsigned int n=0; n < len; ++n)
574 ret.append(1, (char)getByte());
575 return ret;
576 }
577
578 std::string::size_type getOffset()
579 {
580 return d_pos;
581 }
582private:
583 const std::string& d_str;
584 std::string::size_type d_pos;
585};
586
ea3816cf 587static string calculateHMAC(const std::string& key, const std::string& text, TSIGHashEnum hasher) {
78bcb858 588
5e8e902d
CH
589 const EVP_MD* md_type;
590 unsigned int outlen;
591 unsigned char hash[EVP_MAX_MD_SIZE];
592 switch(hasher) {
593 case TSIG_MD5:
594 md_type = EVP_md5();
595 break;
596 case TSIG_SHA1:
597 md_type = EVP_sha1();
598 break;
599 case TSIG_SHA224:
600 md_type = EVP_sha224();
601 break;
602 case TSIG_SHA256:
603 md_type = EVP_sha256();
604 break;
605 case TSIG_SHA384:
606 md_type = EVP_sha384();
607 break;
608 case TSIG_SHA512:
609 md_type = EVP_sha512();
610 break;
611 default:
60a1c204 612 throw PDNSException("Unknown hash algorithm requested from calculateHMAC()");
5e8e902d
CH
613 }
614
615 unsigned char* out = HMAC(md_type, reinterpret_cast<const unsigned char*>(key.c_str()), key.size(), reinterpret_cast<const unsigned char*>(text.c_str()), text.size(), hash, &outlen);
60a1c204
RG
616 if (out == NULL || outlen == 0) {
617 throw PDNSException("HMAC computation failed");
5e8e902d 618 }
5e8e902d 619
60a1c204
RG
620 return string((char*) hash, outlen);
621}
622
ea3816cf 623static bool constantTimeStringEquals(const std::string& a, const std::string& b)
60a1c204
RG
624{
625 if (a.size() != b.size()) {
626 return false;
627 }
628 const size_t size = a.size();
629#if OPENSSL_VERSION_NUMBER >= 0x0090819fL
630 return CRYPTO_memcmp(a.c_str(), b.c_str(), size) == 0;
631#else
632 const volatile unsigned char *_a = (const volatile unsigned char *) a.c_str();
633 const volatile unsigned char *_b = (const volatile unsigned char *) b.c_str();
634 unsigned char res = 0;
635
636 for (size_t idx = 0; idx < size; idx++) {
637 res |= _a[idx] ^ _b[idx];
638 }
639
640 return res == 0;
641#endif
3213be1e
AT
642}
643
ea3816cf 644static string makeTSIGPayload(const string& previous, const char* packetBegin, size_t packetSize, const DNSName& tsigKeyName, const TSIGRecordContent& trc, bool timersonly)
01cb2fe2
BH
645{
646 string message;
c48dec72 647
01cb2fe2
BH
648 if(!previous.empty()) {
649 uint16_t len = htons(previous.length());
ea3816cf 650 message.append(reinterpret_cast<const char*>(&len), sizeof(len));
01cb2fe2
BH
651 message.append(previous);
652 }
ea3816cf
RG
653
654 message.append(packetBegin, packetSize);
01cb2fe2
BH
655
656 vector<uint8_t> signVect;
290a083d 657 DNSPacketWriter dw(signVect, DNSName(), 0);
57ddc8ba 658 auto pos=signVect.size();
01cb2fe2 659 if(!timersonly) {
ea3816cf 660 dw.xfrName(tsigKeyName, false);
f4d26b4f 661 dw.xfr16BitInt(QClass::ANY); // class
01cb2fe2 662 dw.xfr32BitInt(0); // TTL
68e9d647 663 dw.xfrName(trc.d_algoName.makeLowerCase(), false);
01cb2fe2
BH
664 }
665
666 uint32_t now = trc.d_time;
667 dw.xfr48BitInt(now);
668 dw.xfr16BitInt(trc.d_fudge); // fudge
669 if(!timersonly) {
670 dw.xfr16BitInt(trc.d_eRcode); // extended rcode
671 dw.xfr16BitInt(trc.d_otherData.length()); // length of 'other' data
672 // dw.xfrBlob(trc->d_otherData);
673 }
57ddc8ba 674 message.append(signVect.begin()+pos, signVect.end());
01cb2fe2
BH
675 return message;
676}
677
ea3816cf 678static string makeTSIGMessageFromTSIGPacket(const string& opacket, unsigned int tsigOffset, const DNSName& keyname, const TSIGRecordContent& trc, const string& previous, bool timersonly, unsigned int dnsHeaderOffset=0)
01cb2fe2 679{
ea3816cf
RG
680 string message;
681 string packet(opacket);
981fa489 682
ea3816cf
RG
683 packet.resize(tsigOffset); // remove the TSIG record at the end as per RFC2845 3.4.1
684 packet[(dnsHeaderOffset + sizeof(struct dnsheader))-1]--; // Decrease ARCOUNT because we removed the TSIG RR in the previous line.
01cb2fe2 685
ea3816cf
RG
686
687 // Replace the message ID with the original message ID from the TSIG record.
688 // This is needed for forwarded DNS Update as they get a new ID when forwarding (section 6.1 of RFC2136). The TSIG record stores the original ID and the
689 // signature was created with the original ID, so we replace it here to get the originally signed message.
690 // If the message is not forwarded, we simply override it with the same id.
691 uint16_t origID = htons(trc.d_origID);
692 packet.replace(0, 2, (char*)&origID, 2);
693
694 return makeTSIGPayload(previous, packet.data(), packet.size(), keyname, trc, timersonly);
695}
696
697void addTSIG(DNSPacketWriter& pw, TSIGRecordContent& trc, const DNSName& tsigkeyname, const string& tsigsecret, const string& tsigprevious, bool timersonly)
698{
699 TSIGHashEnum algo;
700 if (!getTSIGHashEnum(trc.d_algoName, algo)) {
86f1af1c 701 throw PDNSException(string("Unsupported TSIG HMAC algorithm ") + trc.d_algoName.toLogString());
01cb2fe2 702 }
ea3816cf
RG
703
704 string toSign = makeTSIGPayload(tsigprevious, reinterpret_cast<const char*>(pw.getContent().data()), pw.getContent().size(), tsigkeyname, trc, timersonly);
01cb2fe2 705
7f9ac49b 706 if (algo == TSIG_GSS) {
ea3816cf 707 if (!gss_add_signature(tsigkeyname, toSign, trc.d_mac)) {
86f1af1c 708 throw PDNSException(string("Could not add TSIG signature with algorithm 'gss-tsig' and key name '")+tsigkeyname.toLogString()+string("'"));
7f9ac49b
AT
709 }
710 } else {
ea3816cf
RG
711 trc.d_mac = calculateHMAC(tsigsecret, toSign, algo);
712 // trc.d_mac[0]++; // sabotage
7f9ac49b 713 }
e693ff5a 714 pw.startRecord(tsigkeyname, QType::TSIG, 0, QClass::ANY, DNSResourceRecord::ADDITIONAL, false);
ea3816cf 715 trc.toPacket(pw);
01cb2fe2
BH
716 pw.commit();
717}
8daea594 718
ea3816cf
RG
719bool validateTSIG(const std::string& packet, size_t sigPos, const TSIGTriplet& tt, const TSIGRecordContent& trc, const std::string& previousMAC, const std::string& theirMAC, bool timersOnly, unsigned int dnsHeaderOffset)
720{
721 uint64_t delta = std::abs((int64_t)trc.d_time - (int64_t)time(nullptr));
722 if(delta > trc.d_fudge) {
723 throw std::runtime_error("Invalid TSIG time delta " + std::to_string(delta) + " > fudge " + std::to_string(trc.d_fudge));
724 }
725
726 TSIGHashEnum algo;
727 if (!getTSIGHashEnum(trc.d_algoName, algo)) {
86f1af1c 728 throw std::runtime_error("Unsupported TSIG HMAC algorithm " + trc.d_algoName.toLogString());
ea3816cf
RG
729 }
730
731 TSIGHashEnum expectedAlgo;
732 if (!getTSIGHashEnum(tt.algo, expectedAlgo)) {
86f1af1c 733 throw std::runtime_error("Unsupported TSIG HMAC algorithm expected " + tt.algo.toLogString());
ea3816cf
RG
734 }
735
736 if (algo != expectedAlgo) {
86f1af1c 737 throw std::runtime_error("Signature with TSIG key '"+tt.name.toLogString()+"' does not match the expected algorithm (" + tt.algo.toLogString() + " / " + trc.d_algoName.toLogString() + ")");
ea3816cf
RG
738 }
739
740 string tsigMsg;
741 tsigMsg = makeTSIGMessageFromTSIGPacket(packet, sigPos, tt.name, trc, previousMAC, timersOnly, dnsHeaderOffset);
742
743 if (algo == TSIG_GSS) {
744 GssContext gssctx(tt.name);
745 if (!gss_verify_signature(tt.name, tsigMsg, theirMAC)) {
86f1af1c 746 throw std::runtime_error("Signature with TSIG key '"+tt.name.toLogString()+"' failed to validate");
ea3816cf
RG
747 }
748 } else {
749 string ourMac = calculateHMAC(tt.secret, tsigMsg, algo);
750
751 if(!constantTimeStringEquals(ourMac, theirMAC)) {
86f1af1c 752 throw std::runtime_error("Signature with TSIG key '"+tt.name.toLogString()+"' failed to validate");
ea3816cf
RG
753 }
754 }
755
756 return true;
757}