From 2880bfe62698b36a01c75f71a17256f6f0ac6e4a Mon Sep 17 00:00:00 2001 From: Remi Gacogne Date: Fri, 11 Dec 2020 16:47:51 +0100 Subject: [PATCH] Don't copy the same salt for all iterations in hashQNameWithSalt() The salt does not change between iterations, and the hash size is constant, so we can just overwrite the hash instead. --- pdns/dnssecinfra.cc | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/pdns/dnssecinfra.cc b/pdns/dnssecinfra.cc index 502c10bbc9..152fd3bf80 100644 --- a/pdns/dnssecinfra.cc +++ b/pdns/dnssecinfra.cc @@ -492,16 +492,34 @@ string hashQNameWithSalt(const NSEC3PARAMRecordContent& ns3prc, const DNSName& q string hashQNameWithSalt(const std::string& salt, unsigned int iterations, const DNSName& qname) { unsigned int times = iterations; - unsigned char hash[20]; - string toHash(qname.toDNSStringLC()); - - for(;;) { - toHash.append(salt); - SHA1((unsigned char*)toHash.c_str(), toHash.length(), hash); - toHash.assign((char*)hash, sizeof(hash)); - if(!times--) + unsigned char hash[SHA_DIGEST_LENGTH]; + string toHash(qname.toDNSStringLC() + salt); + if (toHash.capacity() < (salt.size() + sizeof(hash))) { + toHash.reserve(salt.size() + sizeof(hash)); + } + + for (;;) { + /* so the first time we hash the (lowercased) qname plus the salt, + then the result of the last iteration plus the salt */ + SHA1(reinterpret_cast(toHash.c_str()), toHash.length(), hash); + if (!times--) { + /* we are done, just copy the result and return it */ + toHash.assign(reinterpret_cast(hash), sizeof(hash)); break; + } + if (times == (iterations-1)) { + /* first time, we need to replace the qname + salt with + the hash plus salt, since the qname will not likely + match the size of the hash */ + toHash.assign(reinterpret_cast(hash), sizeof(hash)); + toHash.append(salt); + } + else { + /* starting with the second iteration, the hash size does not change, so we don't need to copy the salt again */ + std::copy(reinterpret_cast(hash), reinterpret_cast(hash) + sizeof(hash), toHash.begin()); + } } + return toHash; } -- 2.47.2