botan_hmac.cc 7.82 KB
Newer Older
1
// Copyright (C) 2011-2016 Internet Systems Consortium, Inc. ("ISC")
2
//
3
4
5
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7
8
9
10
11
12
13
14
15
16
17

#include <cryptolink.h>
#include <cryptolink/crypto_hmac.h>

#include <boost/scoped_ptr.hpp>

#include <botan/version.h>
#include <botan/botan.h>
#include <botan/hmac.h>
#include <botan/hash.h>
#include <botan/types.h>

18
#include <cryptolink/botan_common.h>
19

20
#include <cstring>
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

namespace isc {
namespace cryptolink {

/// @brief Botan implementation of HMAC. Each method is the counterpart
/// of the HMAC corresponding method.
class HMACImpl {
public:
    /// @brief Constructor from a secret and a hash algorithm
    ///
    /// See constructor of the @ref isc::cryptolink::HMAC class for details.
    ///
    /// @param secret The secret to sign with
    /// @param secret_len The length of the secret
    /// @param hash_algorithm The hash algorithm
    explicit HMACImpl(const void* secret, size_t secret_len,
37
38
                      const HashAlgorithm hash_algorithm)
    : hash_algorithm_(hash_algorithm), hmac_() {
39
40
        Botan::HashFunction* hash;
        try {
41
            hash = Botan::get_hash(btn::getHashAlgorithmName(hash_algorithm));
42
        } catch (const Botan::Algorithm_Not_Found&) {
43
            isc_throw(UnsupportedAlgorithm,
44
45
46
                      "Unknown hash algorithm: " <<
                      static_cast<int>(hash_algorithm));
        } catch (const Botan::Exception& exc) {
47
            isc_throw(LibraryError, exc.what());
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
        }

        hmac_.reset(new Botan::HMAC(hash));

        // If the key length is larger than the block size, we hash the
        // key itself first.
        try {
            // use a temp var so we don't have blocks spanning
            // preprocessor directives
#if BOTAN_VERSION_CODE >= BOTAN_VERSION_CODE_FOR(1,9,0)
            size_t block_length = hash->hash_block_size();
#elif BOTAN_VERSION_CODE >= BOTAN_VERSION_CODE_FOR(1,8,0)
            size_t block_length = hash->HASH_BLOCK_SIZE;
#else
#error "Unsupported Botan version (need 1.8 or higher)"
            // added to suppress irrelevant compiler errors
            size_t block_length = 0;
#endif
            if (secret_len > block_length) {
                Botan::SecureVector<Botan::byte> hashed_key =
                    hash->process(static_cast<const Botan::byte*>(secret),
                                  secret_len);
                hmac_->set_key(hashed_key.begin(), hashed_key.size());
            } else {
                // Botan 1.8 considers len 0 a bad key. 1.9 does not,
                // but we won't accept it anyway, and fail early
                if (secret_len == 0) {
                    isc_throw(BadKey, "Bad HMAC secret length: 0");
                }
                hmac_->set_key(static_cast<const Botan::byte*>(secret),
                               secret_len);
            }
        } catch (const Botan::Invalid_Key_Length& ikl) {
            isc_throw(BadKey, ikl.what());
        } catch (const Botan::Exception& exc) {
83
            isc_throw(LibraryError, exc.what());
84
85
86
87
88
89
90
        }
    }

    /// @brief Destructor
    ~HMACImpl() {
    }

91
92
93
94
95
    /// @brief Returns the HashAlgorithm of the object
    HashAlgorithm getHashAlgorithm() const {
        return (hash_algorithm_);
    }

96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    /// @brief Returns the output size of the digest
    ///
    /// @return output size of the digest
    size_t getOutputLength() const {
#if BOTAN_VERSION_CODE >= BOTAN_VERSION_CODE_FOR(1,9,0)
        return (hmac_->output_length());
#elif BOTAN_VERSION_CODE >= BOTAN_VERSION_CODE_FOR(1,8,0)
        return (hmac_->OUTPUT_LENGTH);
#else
#error "Unsupported Botan version (need 1.8 or higher)"
        // added to suppress irrelevant compiler errors
        return 0;
#endif
    }

    /// @brief Add data to digest
    ///
    /// See @ref isc::cryptolink::HMAC::update() for details.
    void update(const void* data, const size_t len) {
        try {
            hmac_->update(static_cast<const Botan::byte*>(data), len);
        } catch (const Botan::Exception& exc) {
118
            isc_throw(LibraryError, exc.what());
119
120
121
122
123
124
125
126
127
128
        }
    }

    /// @brief Calculate the final signature
    ///
    /// See @ref isc::cryptolink::HMAC::sign() for details.
    void sign(isc::util::OutputBuffer& result, size_t len) {
        try {
            Botan::SecureVector<Botan::byte> b_result(hmac_->final());

129
            if (len > b_result.size()) {
130
131
132
133
                len = b_result.size();
            }
            result.writeData(b_result.begin(), len);
        } catch (const Botan::Exception& exc) {
134
            isc_throw(LibraryError, exc.what());
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
        }
    }

    /// @brief Calculate the final signature
    ///
    /// See @ref isc::cryptolink::HMAC::sign() for details.
    void sign(void* result, size_t len) {
        try {
            Botan::SecureVector<Botan::byte> b_result(hmac_->final());
            size_t output_size = getOutputLength();
            if (output_size > len) {
                output_size = len;
            }
            std::memcpy(result, b_result.begin(), output_size);
        } catch (const Botan::Exception& exc) {
150
            isc_throw(LibraryError, exc.what());
151
152
153
154
155
156
157
158
159
        }
    }

    /// @brief Calculate the final signature
    ///
    /// See @ref isc::cryptolink::HMAC::sign() for details.
    std::vector<uint8_t> sign(size_t len) {
        try {
            Botan::SecureVector<Botan::byte> b_result(hmac_->final());
160
            if (len > b_result.size()) {
161
162
163
164
165
                return (std::vector<uint8_t>(b_result.begin(), b_result.end()));
            } else {
                return (std::vector<uint8_t>(b_result.begin(), &b_result[len]));
            }
        } catch (const Botan::Exception& exc) {
166
            isc_throw(LibraryError, exc.what());
167
168
169
170
171
172
173
174
        }
    }


    /// @brief Verify an existing signature
    ///
    /// See @ref isc::cryptolink::HMAC::verify() for details.
    bool verify(const void* sig, size_t len) {
175
176
177
        // Botan's verify_mac checks if len matches the output_length,
        // which causes it to fail for truncated signatures, so we do
        // the check ourselves
178
        try {
179
            size_t size = getOutputLength();
180
            if (len < 10 || len < size / 2) {
181
182
                return (false);
            }
183
            if (len > size) {
184
                len = size;
185
            }
186
            if (digest_.size() == 0) {
187
188
189
                digest_ = hmac_->final();
            }
            return (Botan::same_mem(&digest_[0],
190
191
192
                                    static_cast<const unsigned char*>(sig),
                                    len));
        } catch (const Botan::Exception& exc) {
193
            isc_throw(LibraryError, exc.what());
194
195
196
197
        }
    }

private:
198
199
200
201
    /// @brief The hash algorithm
    HashAlgorithm hash_algorithm_;

    /// @brief The protected pointer to the Botan HMAC object
202
    boost::scoped_ptr<Botan::HMAC> hmac_;
203
204
205

    /// @brief The digest cache for multiple verify
    Botan::SecureVector<Botan::byte> digest_;
206
207
208
209
210
211
212
213
214
215
216
217
};

HMAC::HMAC(const void* secret, size_t secret_length,
           const HashAlgorithm hash_algorithm)
{
    impl_ = new HMACImpl(secret, secret_length, hash_algorithm);
}

HMAC::~HMAC() {
    delete impl_;
}

218
219
220
221
222
HashAlgorithm
HMAC::getHashAlgorithm() const {
    return (impl_->getHashAlgorithm());
}

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
size_t
HMAC::getOutputLength() const {
    return (impl_->getOutputLength());
}

void
HMAC::update(const void* data, const size_t len) {
    impl_->update(data, len);
}

void
HMAC::sign(isc::util::OutputBuffer& result, size_t len) {
    impl_->sign(result, len);
}

void
HMAC::sign(void* result, size_t len) {
    impl_->sign(result, len);
}

std::vector<uint8_t>
HMAC::sign(size_t len) {
    return impl_->sign(len);
}

bool
HMAC::verify(const void* sig, const size_t len) {
    return (impl_->verify(sig, len));
}

} // namespace cryptolink
} // namespace isc