summaryrefslogtreecommitdiff
path: root/src/mongo/crypto/hash_block.h
blob: e16d6301d41a6a02380e0f96e519e4f59a6d7972 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#pragma once

#include <MurmurHash3.h>
#include <array>
#include <cstddef>
#include <string>
#include <vector>

#include "mongo/base/data_range.h"
#include "mongo/base/secure_allocator.h"
#include "mongo/base/status_with.h"
#include "mongo/bson/bsonmisc.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/bson/util/builder.h"
#include "mongo/util/base64.h"
#include "mongo/util/hex.h"
#include "mongo/util/secure_compare_memory.h"

namespace mongo {

struct BSONBinData;
class BSONObjBuilder;

/**
 * Secure allocator wrapper for HashBlock Traits.
 *
 * Usage:
 *   HashBlock<SecureTraits<SHA256BlockTraits>> secureBlock;
 * or as a convenience:
 *   SHA256Block::Secure secureBlock;
 */
template <typename Traits>
class SecureTraits {
public:
    using HashType = typename Traits::HashType;
    static constexpr auto name = Traits::name;

    SecureTraits() = default;
    SecureTraits(const SecureTraits& hash) : _hash(hash) {}
    SecureTraits(const Traits& hash) : _hash(hash) {}

    static void computeHash(std::initializer_list<ConstDataRange> input, HashType* const output) {
        Traits::computeHash(input, output);
    }

    static void computeHmac(const uint8_t* key,
                            size_t keyLen,
                            std::initializer_list<ConstDataRange> input,
                            HashType* const output) {
        Traits::computeHmac(key, keyLen, input, output);
    }

    auto data() {
        return _hash->data();
    }

    auto size() const {
        return _hash->size();
    }

private:
    using SecureHashType = SecureAllocatorDefaultDomain::SecureHandle<HashType>;

    SecureHashType _hash;
};

/**
 * Data structure with fixed sized byte array that can be used as HMAC key or result of a SHA
 * computation.
 */
template <typename Traits>
class HashBlock {
public:
    using Secure = HashBlock<SecureTraits<Traits>>;
    using HashType = typename Traits::HashType;
    static constexpr size_t kHashLength = sizeof(HashType);
    static constexpr auto kName = Traits::name;

    HashBlock() = default;

    HashBlock(HashType rawHash) : _hash(rawHash) {}

    /**
     * Constructs a HashBlock from a buffer of specified size.
     */
    static StatusWith<HashBlock> fromBuffer(const uint8_t* input, size_t inputLen) {
        if (inputLen != kHashLength) {
            return {ErrorCodes::InvalidLength,
                    str::stream() << "Unsupported " << Traits::name
                                  << " hash length: " << inputLen};
        }

        HashType newHash;
        memcpy(newHash.data(), input, inputLen);
        return HashBlock(newHash);
    }

    static StatusWith<HashBlock> fromHexStringNoThrow(StringData hex) {
        if (!hexblob::validate(hex)) {
            return {ErrorCodes::BadValue, "Hash input is not a hex string"};
        }

        BufBuilder buf;
        hexblob::decode(hex, &buf);
        return fromBuffer(reinterpret_cast<const uint8_t*>(buf.buf()), buf.len());
    }

    static HashBlock fromHexString(StringData hex) {
        return uassertStatusOK(fromHexStringNoThrow(hex));
    }

    static void computeHash(std::initializer_list<ConstDataRange> input, HashBlock* const output) {
        Traits::computeHash(input, &(output->_hash));
    }

    /**
     * Computes a hash of 'input' from multiple contigous buffers.
     */
    static HashBlock computeHash(std::initializer_list<ConstDataRange> input) {
        HashBlock ret;
        computeHash(input, &ret);
        return ret;
    }

    /**
     * Computes a hash of 'input' from one buffer.
     */
    static HashBlock computeHash(const uint8_t* input, size_t inputLen) {
        return computeHash({ConstDataRange(input, inputLen)});
    }

    /**
     * Computes a HMAC keyed hash of 'input' using the key 'key'.
     */
    static HashBlock computeHmac(const uint8_t* key,
                                 size_t keyLen,
                                 const uint8_t* input,
                                 size_t inputLen) {
        HashBlock output;
        HashBlock::computeHmac(key, keyLen, {ConstDataRange(input, inputLen)}, &output);
        return output;
    }

    /**
     * Computes a HMAC keyed hash of 'input' using the key 'key'. Writes the results into
     * a pre-allocated HashBlock. This lets us allocate HashBlocks with the SecureAllocator.
     */
    static void computeHmac(const uint8_t* key,
                            size_t keyLen,
                            const uint8_t* input,
                            size_t inputLen,
                            HashBlock* const output) {
        HashBlock::computeHmac(key, keyLen, {ConstDataRange(input, inputLen)}, output);
    }

    static HashBlock computeHmac(const uint8_t* key,
                                 size_t keyLen,
                                 std::initializer_list<ConstDataRange> input) {
        HashBlock output;
        HashBlock::computeHmac(key, keyLen, input, &output);
        return output;
    }

    static void computeHmac(const uint8_t* key,
                            size_t keyLen,
                            std::initializer_list<ConstDataRange> input,
                            HashBlock* const output) {
        Traits::computeHmac(key, keyLen, input, &(output->_hash));
    }

    const uint8_t* data() const& {
        return _hash.data();
    }

    uint8_t* data() && = delete;

    ConstDataRange toCDR() && = delete;

    ConstDataRange toCDR() const& {
        return ConstDataRange(reinterpret_cast<const char*>(_hash.data()), kHashLength);
    }

    size_t size() const {
        return _hash.size();
    }

    /**
     * Make a new HashBlock from a BSON BinData value.
     */
    static StatusWith<HashBlock> fromBinData(const BSONBinData& binData) {
        if (binData.type != BinDataGeneral) {
            return {ErrorCodes::UnsupportedFormat,
                    str::stream() << Traits::name << " only accepts BinDataGeneral type"};
        }

        if (binData.length != kHashLength) {
            return {ErrorCodes::UnsupportedFormat,
                    str::stream() << "Unsupported " << Traits::name
                                  << " hash length: " << binData.length};
        }

        HashType newHash;
        memcpy(newHash.data(), binData.data, binData.length);
        return HashBlock(newHash);
    }

    /**
     * Make a new HashBlock from a vector of bytes representing bindata. For IDL.
     */
    static HashBlock fromBinData(const std::vector<unsigned char>& bytes) {
        HashType newHash;
        uassert(ErrorCodes::UnsupportedFormat,
                str::stream() << "Unsupported " << Traits::name << " hash length: " << bytes.size(),
                bytes.size() == kHashLength);
        memcpy(newHash.data(), bytes.data(), bytes.size());
        return HashBlock(newHash);
    }

    /**
     * Append this to a builder using the given name as a BSON BinData type value.
     */
    void appendAsBinData(BSONObjBuilder& builder, StringData fieldName) const {
        builder.appendBinData(fieldName, _hash.size(), BinDataGeneral, _hash.data());
    }

    /**
     * Do a bitwise xor against another HashBlock and replace the current contents of this block
     * with the result.
     */
    void xorInline(const HashBlock& other) {
        for (size_t x = 0; x < _hash.size(); x++) {
            _hash[x] ^= other._hash[x];
        }
    }

    /**
     * Base64 encoding of the sha block as a string.
     */
    std::string toString() const {
        return base64::encode(
            StringData(reinterpret_cast<const char*>(_hash.data()), _hash.size()));
    }

    /**
     * Hex encoded hash block.
     */
    std::string toHexString() const {
        return hexblob::encode(_hash.data(), _hash.size());
    }

    bool operator==(const HashBlock& other) const {
        return consttimeMemEqual(this->_hash.data(), other._hash.data(), kHashLength);
    }

    bool operator!=(const HashBlock& other) const {
        return !(*this == other);
    }

    bool operator<(const HashBlock& other) const {
        return this->_hash < other._hash;
    }

    bool operator==(const HashBlock::Secure& other) const {
        return consttimeMemEqual(this->_hash.data(), other.data(), kHashLength);
    }

    bool operator!=(const HashBlock::Secure& other) const {
        return !(*this == other);
    }

    /**
     * Custom hasher so HashBlocks can be used in unordered data structures.
     *
     * ex: std::unordered_set<HashBlock, HashBlock::Hash> shaSet;
     */
    struct Hash {
        std::size_t operator()(const HashBlock& HashBlock) const {
            uint32_t hash;
            MurmurHash3_x86_32(HashBlock.data(), HashBlock::kHashLength, 0, &hash);
            return hash;
        }
    };

private:
    // The backing array of bytes for the sha block
    HashType _hash;
};


template <typename Traits>
std::ostream& operator<<(std::ostream& os, const HashBlock<Traits>& sha) {
    return os << sha.toString();
}

}  // namespace mongo