summaryrefslogtreecommitdiff
path: root/src/mongo/crypto/aead_encryption.cpp
blob: 030758850c108c222843898e37dd8aac2d225e7e (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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/**
 *    Copyright (C) 2019-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.
 */

#include "mongo/platform/basic.h"

#include "mongo/crypto/aead_encryption.h"

#include "mongo/base/data_view.h"
#include "mongo/crypto/sha512_block.h"
#include "mongo/crypto/symmetric_crypto.h"
#include "mongo/db/matcher/schema/encrypt_schema_gen.h"
#include "mongo/util/secure_compare_memory.h"

namespace mongo {
namespace crypto {

namespace {
constexpr size_t kHmacOutSize = 32;
constexpr size_t kIVSize = 16;

// AssociatedData can be 2^24 bytes but since there needs to be room for the ciphertext in the
// object, a value of 1<<16 was decided to cap the maximum size of AssociatedData.
constexpr int kMaxAssociatedDataLength = 1 << 16;

size_t aesCBCCipherOutputLength(size_t plainTextLen) {
    return aesBlockSize * (1 + plainTextLen / aesBlockSize);
}

std::pair<size_t, size_t> aesCBCExpectedPlaintextLen(size_t cipherTextLength) {
    return {cipherTextLength - aesCBCIVSize - aesBlockSize, cipherTextLength - aesCBCIVSize};
}

void aeadGenerateIV(const SymmetricKey* key, uint8_t* buffer, size_t bufferLen) {
    if (bufferLen < aesCBCIVSize) {
        fassert(51235, "IV buffer is too small for selected mode");
    }

    auto status = engineRandBytes(buffer, aesCBCIVSize);
    if (!status.isOK()) {
        fassert(51236, status);
    }
}

Status _aesEncrypt(const SymmetricKey& key,
                   const std::uint8_t* in,
                   std::size_t inLen,
                   std::uint8_t* out,
                   std::size_t outLen,
                   std::size_t* resultLen,
                   bool ivProvided) try {

    if (!ivProvided) {
        aeadGenerateIV(&key, out, aesCBCIVSize);
    }

    auto encryptor =
        uassertStatusOK(SymmetricEncryptor::create(key, aesMode::cbc, out, aesCBCIVSize));

    const size_t dataSize = outLen - aesCBCIVSize;
    uint8_t* data = out + aesCBCIVSize;

    const auto updateLen = uassertStatusOK(encryptor->update(in, inLen, data, dataSize));
    const auto finalLen =
        uassertStatusOK(encryptor->finalize(data + updateLen, dataSize - updateLen));
    const auto len = updateLen + finalLen;

    // Some cipher modes, such as GCM, will know in advance exactly how large their ciphertexts will
    // be. Others, like CBC, will have an upper bound. When this is true, we must allocate enough
    // memory to store the worst case. We must then set the actual size of the ciphertext so that
    // the buffer it has been written to may be serialized.
    invariant(len <= dataSize);
    *resultLen = aesCBCIVSize + len;

    // Check the returned length, including block size padding
    if (len != aesCBCCipherOutputLength(inLen)) {
        return {ErrorCodes::BadValue,
                str::stream() << "Encrypt error, expected cipher text of length "
                              << aesCBCCipherOutputLength(inLen)
                              << " but found "
                              << len};
    }

    return Status::OK();
} catch (const AssertionException& ex) {
    return ex.toStatus();
}

Status _aesDecrypt(const SymmetricKey& key,
                   ConstDataRange in,
                   std::uint8_t* out,
                   std::size_t outLen,
                   std::size_t* resultLen) try {
    // Check the plaintext buffer can fit the product of decryption
    auto[lowerBound, upperBound] = aesCBCExpectedPlaintextLen(in.length());
    if (upperBound > outLen) {
        return {ErrorCodes::BadValue,
                str::stream() << "Cleartext buffer of size " << outLen
                              << " too small for output which can be as large as "
                              << upperBound
                              << "]"};
    }

    const uint8_t* dataPtr = reinterpret_cast<const std::uint8_t*>(in.data());

    auto decryptor =
        uassertStatusOK(SymmetricDecryptor::create(key, aesMode::cbc, dataPtr, aesCBCIVSize));

    const size_t dataSize = in.length() - aesCBCIVSize;
    const uint8_t* data = dataPtr + aesCBCIVSize;

    const auto updateLen = uassertStatusOK(decryptor->update(data, dataSize, out, outLen));

    const auto finalLen = uassertStatusOK(decryptor->finalize(out + updateLen, outLen - updateLen));

    *resultLen = updateLen + finalLen;
    invariant(*resultLen <= outLen);

    // Check the returned length, excluding headers block padding
    if (*resultLen < lowerBound || *resultLen > upperBound) {
        return {ErrorCodes::BadValue,
                str::stream() << "Decrypt error, expected clear text length in interval"
                              << "["
                              << lowerBound
                              << ","
                              << upperBound
                              << "]"
                              << "but found "
                              << *resultLen};
    }

    /* Check that padding was removed.
     *
     * PKCS7 padding guarantees that the encrypted payload has
     * between 1 and blocksize bytes of padding which should be
     * removed during the decrypt process.
     *
     * If resultLen is the same as the payload len,
     * that means no padding was removed.
     *
     * macOS CommonCrypto will return such payloads when either the
     * key or ciphertext are corrupted and its unable to find any
     * expected padding.  It fails open by returning whatever it can.
     */
    if (*resultLen >= dataSize) {
        return {ErrorCodes::BadValue,
                "Decrypt error, plaintext is as large or larger than "
                "the ciphertext. This usually indicates an invalid key."};
    }

    return Status::OK();
} catch (const AssertionException& ex) {
    return ex.toStatus();
}

}  // namespace

size_t aeadCipherOutputLength(size_t plainTextLen) {
    // To calculate the size of the byte, we divide by the byte size and add 2 for padding
    // (1 for the attached IV, and 1 for the extra padding). The algorithm will add padding even
    // if the len is a multiple of the byte size, so if the len divides cleanly it will be
    // 32 bytes longer than the original, which is 16 bytes as padding and 16 bytes for the
    // IV. For things that don't divide cleanly, the cast takes care of floor dividing so it will
    // be 0 < x < 16 bytes added for padding and 16 bytes added for the IV.
    size_t aesOutLen = aesBlockSize * (plainTextLen / aesBlockSize + 2);
    return aesOutLen + kHmacOutSize;
}

StatusWith<size_t> aeadGetMaximumPlainTextLength(size_t cipherTextLen) {
    if (cipherTextLen > (aesCBCIVSize + kHmacOutSize)) {
        return cipherTextLen - aesCBCIVSize - kHmacOutSize;
    }

    return Status(ErrorCodes::BadValue, "Invalid cipher text length");
}

Status aeadEncrypt(const SymmetricKey& key,
                   const uint8_t* in,
                   const size_t inLen,
                   const uint8_t* associatedData,
                   const uint64_t associatedDataLen,
                   uint8_t* out,
                   size_t outLen) {

    if (associatedDataLen >= kMaxAssociatedDataLength) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "AssociatedData for encryption is too large. Cannot be larger than "
                          << kMaxAssociatedDataLength
                          << " bytes.");
    }

    // According to the rfc on AES encryption, the associatedDataLength is defined as the
    // number of bits in associatedData in BigEndian format. This is what the code segment
    // below describes.
    // RFC: (https://tools.ietf.org/html/draft-mcgrew-aead-aes-cbc-hmac-sha2-01#section-2.1)
    std::array<uint8_t, sizeof(uint64_t)> dataLenBitsEncodedStorage;
    DataRange dataLenBitsEncoded(dataLenBitsEncodedStorage);
    dataLenBitsEncoded.write<BigEndian<uint64_t>>(associatedDataLen * 8);

    ConstDataRange aeadKey(key.getKey(), kAeadAesHmacKeySize);

    if (key.getKeySize() != kFieldLevelEncryptionKeySize) {
        return Status(ErrorCodes::BadValue, "Invalid key size.");
    }

    if (in == nullptr || !in) {
        return Status(ErrorCodes::BadValue, "Invalid AEAD plaintext input.");
    }

    if (key.getAlgorithm() != aesAlgorithm) {
        return Status(ErrorCodes::BadValue, "Invalid algorithm for key.");
    }

    ConstDataRange hmacCDR(nullptr, 0);
    SHA512Block hmacOutput;
    if (associatedData != nullptr &&
        static_cast<int>(associatedData[0]) ==
            FleAlgorithmInt_serializer(FleAlgorithmInt::kDeterministic)) {
        const uint8_t* ivKey = key.getKey() + kAeadAesHmacKeySize;
        hmacOutput = SHA512Block::computeHmac(ivKey,
                                              sym256KeySize,
                                              {ConstDataRange(associatedData, associatedDataLen),
                                               dataLenBitsEncoded,
                                               ConstDataRange(in, inLen)});

        static_assert(SHA512Block::kHashLength >= kIVSize,
                      "Invalid AEAD parameters. Generated IV too short.");

        hmacCDR = ConstDataRange(hmacOutput.data(), kIVSize);
    }
    return aeadEncryptWithIV(aeadKey,
                             in,
                             inLen,
                             reinterpret_cast<const uint8_t*>(hmacCDR.data()),
                             hmacCDR.length(),
                             associatedData,
                             associatedDataLen,
                             dataLenBitsEncoded,
                             out,
                             outLen);
}

Status aeadEncryptWithIV(ConstDataRange key,
                         const uint8_t* in,
                         const size_t inLen,
                         const uint8_t* iv,
                         const size_t ivLen,
                         const uint8_t* associatedData,
                         const uint64_t associatedDataLen,
                         ConstDataRange dataLenBitsEncoded,
                         uint8_t* out,
                         size_t outLen) {
    if (key.length() != kAeadAesHmacKeySize) {
        return Status(ErrorCodes::BadValue, "Invalid key size.");
    }

    if (!(in && out)) {
        return Status(ErrorCodes::BadValue, "Invalid AEAD parameters.");
    }

    if (outLen != aeadCipherOutputLength(inLen)) {
        return Status(ErrorCodes::BadValue, "Invalid output buffer size.");
    }

    if (associatedDataLen >= kMaxAssociatedDataLength) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "AssociatedData for encryption is too large. Cannot be larger than "
                          << kMaxAssociatedDataLength
                          << " bytes.");
    }

    const uint8_t* macKey = reinterpret_cast<const uint8_t*>(key.data());
    const uint8_t* encKey = reinterpret_cast<const uint8_t*>(key.data() + sym256KeySize);

    size_t aesOutLen = outLen - kHmacOutSize;

    size_t cipherTextLen = 0;

    SymmetricKey symEncKey(encKey, sym256KeySize, aesAlgorithm, "aesKey", 1);

    bool ivProvided = false;
    if (ivLen != 0) {
        invariant(ivLen == 16);
        std::copy(iv, iv + ivLen, out);
        ivProvided = true;
    }

    auto sEncrypt = _aesEncrypt(symEncKey, in, inLen, out, aesOutLen, &cipherTextLen, ivProvided);

    if (!sEncrypt.isOK()) {
        return sEncrypt;
    }

    SHA512Block hmacOutput =
        SHA512Block::computeHmac(macKey,
                                 sym256KeySize,
                                 {ConstDataRange(associatedData, associatedDataLen),
                                  ConstDataRange(out, cipherTextLen),
                                  dataLenBitsEncoded});

    std::copy(hmacOutput.data(), hmacOutput.data() + kHmacOutSize, out + cipherTextLen);
    return Status::OK();
}

Status aeadDecrypt(const SymmetricKey& key,
                   const uint8_t* cipherText,
                   const size_t cipherLen,
                   const uint8_t* associatedData,
                   const uint64_t associatedDataLen,
                   uint8_t* out,
                   size_t* outLen) {
    if (key.getKeySize() < kAeadAesHmacKeySize) {
        return Status(ErrorCodes::BadValue, "Invalid key size.");
    }

    if (!(cipherText && out)) {
        return Status(ErrorCodes::BadValue, "Invalid AEAD parameters.");
    }

    if (cipherLen < kHmacOutSize) {
        return Status(ErrorCodes::BadValue, "Ciphertext is not long enough.");
    }

    size_t expectedMaximumPlainTextSize = uassertStatusOK(aeadGetMaximumPlainTextLength(cipherLen));
    if ((*outLen) != expectedMaximumPlainTextSize) {
        return Status(ErrorCodes::BadValue, "Output buffer must be as long as the cipherText.");
    }

    if (associatedDataLen >= kMaxAssociatedDataLength) {
        return Status(ErrorCodes::BadValue,
                      str::stream()
                          << "AssociatedData for encryption is too large. Cannot be larger than "
                          << kMaxAssociatedDataLength
                          << " bytes.");
    }

    const uint8_t* macKey = key.getKey();
    const uint8_t* encKey = key.getKey() + sym256KeySize;

    size_t aesLen = cipherLen - kHmacOutSize;

    // According to the rfc on AES encryption, the associatedDataLength is defined as the
    // number of bits in associatedData in BigEndian format. This is what the code segment
    // below describes.
    std::array<uint8_t, sizeof(uint64_t)> dataLenBitsEncodedStorage;
    DataRange dataLenBitsEncoded(dataLenBitsEncodedStorage);
    dataLenBitsEncoded.write<BigEndian<uint64_t>>(associatedDataLen * 8);

    SHA512Block hmacOutput =
        SHA512Block::computeHmac(macKey,
                                 sym256KeySize,
                                 {ConstDataRange(associatedData, associatedDataLen),
                                  ConstDataRange(cipherText, aesLen),
                                  dataLenBitsEncoded});

    if (consttimeMemEqual(reinterpret_cast<const unsigned char*>(hmacOutput.data()),
                          reinterpret_cast<const unsigned char*>(cipherText + aesLen),
                          kHmacOutSize) == false) {
        return Status(ErrorCodes::BadValue, "HMAC data authentication failed.");
    }

    SymmetricKey symEncKey(encKey, sym256KeySize, aesAlgorithm, key.getKeyId(), 1);

    auto sDecrypt =
        _aesDecrypt(symEncKey, ConstDataRange(cipherText, aesLen), out, *outLen, outLen);
    if (!sDecrypt.isOK()) {
        return sDecrypt;
    }

    return Status::OK();
}

}  // namespace crypto
}  // namespace mongo