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