1 | /* |
2 | * Copyright (C) 2017 Apple Inc. All rights reserved. |
3 | * Copyright (C) 2017 Metrological Group B.V. |
4 | * Copyright (C) 2017 Igalia S.L. |
5 | * |
6 | * Redistribution and use in source and binary forms, with or without |
7 | * modification, are permitted provided that the following conditions |
8 | * are met: |
9 | * 1. Redistributions of source code must retain the above copyright |
10 | * notice, this list of conditions and the following disclaimer. |
11 | * 2. Redistributions in binary form must reproduce the above copyright |
12 | * notice, this list of conditions and the following disclaimer in the |
13 | * documentation and/or other materials provided with the distribution. |
14 | * |
15 | * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' |
16 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, |
17 | * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR |
18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS |
19 | * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
20 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
21 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
22 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
23 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
24 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF |
25 | * THE POSSIBILITY OF SUCH DAMAGE. |
26 | */ |
27 | |
28 | #include "config.h" |
29 | #include "CryptoAlgorithmAES_CTR.h" |
30 | |
31 | #if ENABLE(WEB_CRYPTO) |
32 | |
33 | #include "CryptoAlgorithmAesCtrParams.h" |
34 | #include "CryptoKeyAES.h" |
35 | #include <pal/crypto/gcrypt/Handle.h> |
36 | #include <pal/crypto/gcrypt/Utilities.h> |
37 | |
38 | namespace WebCore { |
39 | |
40 | // This is a helper function that resets the cipher object, sets the provided counter data, |
41 | // and executes the encrypt or decrypt operation, retrieving and returning the output data. |
42 | static 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) |
43 | { |
44 | gcry_error_t error = gcry_cipher_reset(handle); |
45 | if (error != GPG_ERR_NO_ERROR) { |
46 | PAL::GCrypt::logError(error); |
47 | return WTF::nullopt; |
48 | } |
49 | |
50 | error = gcry_cipher_setctr(handle, counter.data(), counter.size()); |
51 | if (error != GPG_ERR_NO_ERROR) { |
52 | PAL::GCrypt::logError(error); |
53 | return WTF::nullopt; |
54 | } |
55 | |
56 | error = gcry_cipher_final(handle); |
57 | if (error != GPG_ERR_NO_ERROR) { |
58 | PAL::GCrypt::logError(error); |
59 | return WTF::nullopt; |
60 | } |
61 | |
62 | Vector<uint8_t> output(size); |
63 | error = operation(handle, output.data(), output.size(), data, size); |
64 | if (error != GPG_ERR_NO_ERROR) { |
65 | PAL::GCrypt::logError(error); |
66 | return WTF::nullopt; |
67 | } |
68 | |
69 | return output; |
70 | } |
71 | |
72 | static Optional<Vector<uint8_t>> gcryptAES_CTR(PAL::GCrypt::CipherOperation operation, const Vector<uint8_t>& key, const Vector<uint8_t>& counter, size_t counterLength, const Vector<uint8_t>& inputText) |
73 | { |
74 | constexpr size_t blockSize = 16; |
75 | auto algorithm = PAL::GCrypt::aesAlgorithmForKeySize(key.size() * 8); |
76 | if (!algorithm) |
77 | return WTF::nullopt; |
78 | |
79 | // Construct the libgcrypt cipher object and attach the key to it. Key information on this |
80 | // cipher object will live through any gcry_cipher_reset() calls. |
81 | PAL::GCrypt::Handle<gcry_cipher_hd_t> handle; |
82 | gcry_error_t error = gcry_cipher_open(&handle, *algorithm, GCRY_CIPHER_MODE_CTR, 0); |
83 | if (error != GPG_ERR_NO_ERROR) { |
84 | PAL::GCrypt::logError(error); |
85 | return WTF::nullopt; |
86 | } |
87 | |
88 | error = gcry_cipher_setkey(handle, key.data(), key.size()); |
89 | if (error != GPG_ERR_NO_ERROR) { |
90 | PAL::GCrypt::logError(error); |
91 | return WTF::nullopt; |
92 | } |
93 | |
94 | // Calculate the block count: ((inputText.size() + blockSize - 1) / blockSize), remainder discarded. |
95 | PAL::GCrypt::Handle<gcry_mpi_t> blockCountMPI(gcry_mpi_new(0)); |
96 | { |
97 | PAL::GCrypt::Handle<gcry_mpi_t> blockSizeMPI(gcry_mpi_set_ui(nullptr, blockSize)); |
98 | PAL::GCrypt::Handle<gcry_mpi_t> roundedUpSize(gcry_mpi_set_ui(nullptr, inputText.size())); |
99 | |
100 | gcry_mpi_add_ui(roundedUpSize, roundedUpSize, blockSize - 1); |
101 | gcry_mpi_div(blockCountMPI, nullptr, roundedUpSize, blockSizeMPI, 0); |
102 | } |
103 | |
104 | // Calculate the counter limit for the specified counter length: (2 << counterLength). |
105 | // (counterLimitMPI - 1) is the maximum value the counter can hold -- essentially it's |
106 | // a bit-mask for valid counter values. |
107 | PAL::GCrypt::Handle<gcry_mpi_t> counterLimitMPI(gcry_mpi_set_ui(nullptr, 1)); |
108 | gcry_mpi_mul_2exp(counterLimitMPI, counterLimitMPI, counterLength); |
109 | |
110 | // Counter values must not repeat for a given cipher text. If the counter limit (i.e. |
111 | // the number of unique counter values we could produce for the specified counter |
112 | // length) is lower than the deduced block count, we bail. |
113 | if (gcry_mpi_cmp(counterLimitMPI, blockCountMPI) < 0) |
114 | return WTF::nullopt; |
115 | |
116 | // If the counter length, in bits, matches the size of the counter data, we don't have to |
117 | // use any part of the counter Vector<> as nonce. This allows us to directly encrypt or |
118 | // decrypt all the provided data in a single step. |
119 | if (counterLength == counter.size() * 8) |
120 | return callOperation(operation, handle, counter, inputText.data(), inputText.size()); |
121 | |
122 | // Scan the counter data into the MPI format. We'll do all the counter computations with |
123 | // the MPI API. |
124 | PAL::GCrypt::Handle<gcry_mpi_t> counterDataMPI; |
125 | error = gcry_mpi_scan(&counterDataMPI, GCRYMPI_FMT_USG, counter.data(), counter.size(), nullptr); |
126 | if (error != GPG_ERR_NO_ERROR) { |
127 | PAL::GCrypt::logError(error); |
128 | return WTF::nullopt; |
129 | } |
130 | |
131 | // Extract the counter MPI from the counterDataMPI: (counterDataMPI % counterLimitMPI). |
132 | // This MPI represents solely the counter value, as initially provided. |
133 | PAL::GCrypt::Handle<gcry_mpi_t> counterMPI(gcry_mpi_new(0)); |
134 | gcry_mpi_mod(counterMPI, counterDataMPI, counterLimitMPI); |
135 | |
136 | { |
137 | // Calculate the leeway of the initially-provided counter: counterLimitMPI - counterMPI. |
138 | // This is essentially the number of blocks we can encrypt/decrypt with that counter |
139 | // (incrementing it after each operation) before the counter wraps around to 0. |
140 | PAL::GCrypt::Handle<gcry_mpi_t> counterLeewayMPI(gcry_mpi_new(0)); |
141 | gcry_mpi_sub(counterLeewayMPI, counterLimitMPI, counterMPI); |
142 | |
143 | // If counterLeewayMPI is larger or equal to the deduced block count, we can directly |
144 | // encrypt or decrypt the provided data in a single step since it's ensured that the |
145 | // counter won't overflow. |
146 | if (gcry_mpi_cmp(counterLeewayMPI, blockCountMPI) >= 0) |
147 | return callOperation(operation, handle, counter, inputText.data(), inputText.size()); |
148 | } |
149 | |
150 | // From here onwards we're dealing with a counter of which the length doesn't match the |
151 | // provided data, meaning we'll also have to manage the nonce data. The counter will also |
152 | // wrap around, so we'll have to address that too. |
153 | |
154 | // Determine the nonce MPI that we'll use to reconstruct the counter data for each block: |
155 | // (counterDataMPI - counterMPI). This is equivalent to counterDataMPI with the lowest |
156 | // counterLength bits cleared. |
157 | PAL::GCrypt::Handle<gcry_mpi_t> nonceMPI(gcry_mpi_new(0)); |
158 | gcry_mpi_sub(nonceMPI, counterDataMPI, counterMPI); |
159 | |
160 | // FIXME: This should be optimized further by first encrypting the amount of blocks for |
161 | // which the counter won't yet wrap around, and then encrypting the rest of the blocks |
162 | // starting from the counter set to 0. |
163 | |
164 | Vector<uint8_t> output; |
165 | Vector<uint8_t> blockCounterData(16); |
166 | size_t inputTextSize = inputText.size(); |
167 | |
168 | for (size_t i = 0; i < inputTextSize; i += 16) { |
169 | size_t blockInputSize = std::min<size_t>(16, inputTextSize - i); |
170 | |
171 | // Construct the block-specific counter: (nonceMPI + counterMPI). |
172 | PAL::GCrypt::Handle<gcry_mpi_t> blockCounterMPI(gcry_mpi_new(0)); |
173 | gcry_mpi_add(blockCounterMPI, nonceMPI, counterMPI); |
174 | |
175 | error = gcry_mpi_print(GCRYMPI_FMT_USG, blockCounterData.data(), blockCounterData.size(), nullptr, blockCounterMPI); |
176 | if (error != GPG_ERR_NO_ERROR) { |
177 | PAL::GCrypt::logError(error); |
178 | return WTF::nullopt; |
179 | } |
180 | |
181 | // Encrypt/decrypt this single block with the block-specific counter. Output for this |
182 | // single block is appended to the general output vector. |
183 | auto blockOutput = callOperation(operation, handle, blockCounterData, inputText.data() + i, blockInputSize); |
184 | if (!blockOutput) |
185 | return WTF::nullopt; |
186 | |
187 | output.appendVector(*blockOutput); |
188 | |
189 | // Increment the counter. The modulus operation takes care of any wrap-around. |
190 | PAL::GCrypt::Handle<gcry_mpi_t> counterIncrementMPI(gcry_mpi_new(0)); |
191 | gcry_mpi_add_ui(counterIncrementMPI, counterMPI, 1); |
192 | gcry_mpi_mod(counterMPI, counterIncrementMPI, counterLimitMPI); |
193 | } |
194 | |
195 | return output; |
196 | } |
197 | |
198 | ExceptionOr<Vector<uint8_t>> CryptoAlgorithmAES_CTR::platformEncrypt(const CryptoAlgorithmAesCtrParams& parameters, const CryptoKeyAES& key, const Vector<uint8_t>& plainText) |
199 | { |
200 | auto output = gcryptAES_CTR(gcry_cipher_encrypt, key.key(), parameters.counterVector(), parameters.length, plainText); |
201 | if (!output) |
202 | return Exception { OperationError }; |
203 | return WTFMove(*output); |
204 | } |
205 | |
206 | ExceptionOr<Vector<uint8_t>> CryptoAlgorithmAES_CTR::platformDecrypt(const CryptoAlgorithmAesCtrParams& parameters, const CryptoKeyAES& key, const Vector<uint8_t>& cipherText) |
207 | { |
208 | auto output = gcryptAES_CTR(gcry_cipher_decrypt, key.key(), parameters.counterVector(), parameters.length, cipherText); |
209 | if (!output) |
210 | return Exception { OperationError }; |
211 | return WTFMove(*output); |
212 | } |
213 | |
214 | } // namespace WebCore |
215 | |
216 | #endif // ENABLE(WEB_CRYPTO) |
217 | |