File: CryptoAlgorithmAESCTRGCrypt.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (212 lines) | stat: -rw-r--r-- 9,908 bytes parent folder | download | duplicates (6)
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
/*
 * Copyright (C) 2017 Apple Inc. All rights reserved.
 * Copyright (C) 2017 Metrological Group B.V.
 * Copyright (C) 2017 Igalia S.L.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "CryptoAlgorithmAESCTR.h"

#include "CryptoAlgorithmAesCtrParams.h"
#include "CryptoKeyAES.h"
#include <pal/crypto/gcrypt/Handle.h>
#include <pal/crypto/gcrypt/Utilities.h>

namespace WebCore {

// This is a helper function that resets the cipher object, sets the provided counter data,
// and executes the encrypt or decrypt operation, retrieving and returning the output data.
static std::optional<Vector<uint8_t>> callOperation(PAL::GCrypt::CipherOperation operation, gcry_cipher_hd_t handle, const Vector<uint8_t>& counter, const uint8_t* data, const size_t size)
{
    gcry_error_t error = gcry_cipher_reset(handle);
    if (error != GPG_ERR_NO_ERROR) {
        PAL::GCrypt::logError(error);
        return std::nullopt;
    }

    error = gcry_cipher_setctr(handle, counter.data(), counter.size());
    if (error != GPG_ERR_NO_ERROR) {
        PAL::GCrypt::logError(error);
        return std::nullopt;
    }

    error = gcry_cipher_final(handle);
    if (error != GPG_ERR_NO_ERROR) {
        PAL::GCrypt::logError(error);
        return std::nullopt;
    }

    Vector<uint8_t> output(size);
    error = operation(handle, output.data(), output.size(), data, size);
    if (error != GPG_ERR_NO_ERROR) {
        PAL::GCrypt::logError(error);
        return std::nullopt;
    }

    return output;
}

static std::optional<Vector<uint8_t>> gcryptAESCTR(PAL::GCrypt::CipherOperation operation, const Vector<uint8_t>& key, const Vector<uint8_t>& counter, size_t counterLength, const Vector<uint8_t>& inputText)
{
    constexpr size_t blockSize = 16;
    auto algorithm = PAL::GCrypt::aesAlgorithmForKeySize(key.size() * 8);
    if (!algorithm)
        return std::nullopt;

    // Construct the libgcrypt cipher object and attach the key to it. Key information on this
    // cipher object will live through any gcry_cipher_reset() calls.
    PAL::GCrypt::Handle<gcry_cipher_hd_t> handle;
    gcry_error_t error = gcry_cipher_open(&handle, *algorithm, GCRY_CIPHER_MODE_CTR, 0);
    if (error != GPG_ERR_NO_ERROR) {
        PAL::GCrypt::logError(error);
        return std::nullopt;
    }

    error = gcry_cipher_setkey(handle, key.data(), key.size());
    if (error != GPG_ERR_NO_ERROR) {
        PAL::GCrypt::logError(error);
        return std::nullopt;
    }

    // Calculate the block count: ((inputText.size() + blockSize - 1) / blockSize), remainder discarded.
    PAL::GCrypt::Handle<gcry_mpi_t> blockCountMPI(gcry_mpi_new(0));
    {
        PAL::GCrypt::Handle<gcry_mpi_t> blockSizeMPI(gcry_mpi_set_ui(nullptr, blockSize));
        PAL::GCrypt::Handle<gcry_mpi_t> roundedUpSize(gcry_mpi_set_ui(nullptr, inputText.size()));

        gcry_mpi_add_ui(roundedUpSize, roundedUpSize, blockSize - 1);
        gcry_mpi_div(blockCountMPI, nullptr, roundedUpSize, blockSizeMPI, 0);
    }

    // Calculate the counter limit for the specified counter length: (2 << counterLength).
    // (counterLimitMPI - 1) is the maximum value the counter can hold -- essentially it's
    // a bit-mask for valid counter values.
    PAL::GCrypt::Handle<gcry_mpi_t> counterLimitMPI(gcry_mpi_set_ui(nullptr, 1));
    gcry_mpi_mul_2exp(counterLimitMPI, counterLimitMPI, counterLength);

    // Counter values must not repeat for a given cipher text. If the counter limit (i.e.
    // the number of unique counter values we could produce for the specified counter
    // length) is lower than the deduced block count, we bail.
    if (gcry_mpi_cmp(counterLimitMPI, blockCountMPI) < 0)
        return std::nullopt;

    // If the counter length, in bits, matches the size of the counter data, we don't have to
    // use any part of the counter Vector<> as nonce. This allows us to directly encrypt or
    // decrypt all the provided data in a single step.
    if (counterLength == counter.size() * 8)
        return callOperation(operation, handle, counter, inputText.data(), inputText.size());

    // Scan the counter data into the MPI format. We'll do all the counter computations with
    // the MPI API.
    PAL::GCrypt::Handle<gcry_mpi_t> counterDataMPI;
    error = gcry_mpi_scan(&counterDataMPI, GCRYMPI_FMT_USG, counter.data(), counter.size(), nullptr);
    if (error != GPG_ERR_NO_ERROR) {
        PAL::GCrypt::logError(error);
        return std::nullopt;
    }

    // Extract the counter MPI from the counterDataMPI: (counterDataMPI % counterLimitMPI).
    // This MPI represents solely the counter value, as initially provided.
    PAL::GCrypt::Handle<gcry_mpi_t> counterMPI(gcry_mpi_new(0));
    gcry_mpi_mod(counterMPI, counterDataMPI, counterLimitMPI);

    {
        // Calculate the leeway of the initially-provided counter: counterLimitMPI - counterMPI.
        // This is essentially the number of blocks we can encrypt/decrypt with that counter
        // (incrementing it after each operation) before the counter wraps around to 0.
        PAL::GCrypt::Handle<gcry_mpi_t> counterLeewayMPI(gcry_mpi_new(0));
        gcry_mpi_sub(counterLeewayMPI, counterLimitMPI, counterMPI);

        // If counterLeewayMPI is larger or equal to the deduced block count, we can directly
        // encrypt or decrypt the provided data in a single step since it's ensured that the
        // counter won't overflow.
        if (gcry_mpi_cmp(counterLeewayMPI, blockCountMPI) >= 0)
            return callOperation(operation, handle, counter, inputText.data(), inputText.size());
    }

    // From here onwards we're dealing with a counter of which the length doesn't match the
    // provided data, meaning we'll also have to manage the nonce data. The counter will also
    // wrap around, so we'll have to address that too.

    // Determine the nonce MPI that we'll use to reconstruct the counter data for each block:
    // (counterDataMPI - counterMPI). This is equivalent to counterDataMPI with the lowest
    // counterLength bits cleared.
    PAL::GCrypt::Handle<gcry_mpi_t> nonceMPI(gcry_mpi_new(0));
    gcry_mpi_sub(nonceMPI, counterDataMPI, counterMPI);

    // FIXME: This should be optimized further by first encrypting the amount of blocks for
    // which the counter won't yet wrap around, and then encrypting the rest of the blocks
    // starting from the counter set to 0.

    Vector<uint8_t> output;
    Vector<uint8_t> blockCounterData(16);
    size_t inputTextSize = inputText.size();

    for (size_t i = 0; i < inputTextSize; i += 16) {
        size_t blockInputSize = std::min<size_t>(16, inputTextSize - i);

        // Construct the block-specific counter: (nonceMPI + counterMPI).
        PAL::GCrypt::Handle<gcry_mpi_t> blockCounterMPI(gcry_mpi_new(0));
        gcry_mpi_add(blockCounterMPI, nonceMPI, counterMPI);

        error = gcry_mpi_print(GCRYMPI_FMT_USG, blockCounterData.data(), blockCounterData.size(), nullptr, blockCounterMPI);
        if (error != GPG_ERR_NO_ERROR) {
            PAL::GCrypt::logError(error);
            return std::nullopt;
        }

        // Encrypt/decrypt this single block with the block-specific counter. Output for this
        // single block is appended to the general output vector.
        auto blockOutput = callOperation(operation, handle, blockCounterData, inputText.subspan(i).data(), blockInputSize);
        if (!blockOutput)
            return std::nullopt;

        output.appendVector(*blockOutput);

        // Increment the counter. The modulus operation takes care of any wrap-around.
        PAL::GCrypt::Handle<gcry_mpi_t> counterIncrementMPI(gcry_mpi_new(0));
        gcry_mpi_add_ui(counterIncrementMPI, counterMPI, 1);
        gcry_mpi_mod(counterMPI, counterIncrementMPI, counterLimitMPI);
    }

    return output;
}

ExceptionOr<Vector<uint8_t>> CryptoAlgorithmAESCTR::platformEncrypt(const CryptoAlgorithmAesCtrParams& parameters, const CryptoKeyAES& key, const Vector<uint8_t>& plainText)
{
    auto output = gcryptAESCTR(gcry_cipher_encrypt, key.key(), parameters.counterVector(), parameters.length, plainText);
    if (!output)
        return Exception { ExceptionCode::OperationError };
    return WTFMove(*output);
}

ExceptionOr<Vector<uint8_t>> CryptoAlgorithmAESCTR::platformDecrypt(const CryptoAlgorithmAesCtrParams& parameters, const CryptoKeyAES& key, const Vector<uint8_t>& cipherText)
{
    auto output = gcryptAESCTR(gcry_cipher_decrypt, key.key(), parameters.counterVector(), parameters.length, cipherText);
    if (!output)
        return Exception { ExceptionCode::OperationError };
    return WTFMove(*output);
}

} // namespace WebCore