summaryrefslogtreecommitdiff
path: root/src/mongo/crypto/sha_block.h
blob: 45be68dc7536b0f372c5fa93e538a614cc80053e (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

/**
 *    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 <array>
#include <cstddef>
#include <string>
#include <third_party/murmurhash3/MurmurHash3.h>
#include <vector>

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

namespace mongo {

struct BSONBinData;
class BSONObjBuilder;

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

    SHABlock() = default;

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

    /**
     * Constructs a SHABlock from a buffer of specified size.
     */
    static StatusWith<SHABlock> 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 SHABlock(newHash);
    }

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

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

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

    /**
     * Computes a HMAC keyed hash of 'input' using the key 'key'. Writes the results into
     * a pre-allocated SHABlock. This lets us allocate SHABlocks with the SecureAllocator.
     */
    static void computeHmac(const uint8_t* key,
                            size_t keyLen,
                            const uint8_t* input,
                            size_t inputLen,
                            SHABlock* const output) {
        return Traits::computeHmac(key, keyLen, input, inputLen, &(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 SHABlock from a BSON BinData value.
     */
    static StatusWith<SHABlock> 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 SHABlock(newHash);
    }

    /**
     * Make a new SHABlock from a vector of bytes representing bindata. For IDL.
     */
    static SHABlock 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 SHABlock(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 SHABlock and replace the current contents of this block
     * with the result.
     */
    void xorInline(const SHABlock& 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(reinterpret_cast<const char*>(_hash.data()), _hash.size());
    }

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

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

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

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

template <typename T>
constexpr size_t SHABlock<T>::kHashLength;

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

}  // namespace mongo