1 /*
2 * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3 * project.
4 */
5 /* ====================================================================
6 * Copyright (c) 2015 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * licensing@OpenSSL.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 */
53
54 #include <limits.h>
55 #include <stdlib.h>
56 #include <string.h>
57
58 #include <algorithm>
59 #include <string>
60 #include <vector>
61
62 #include <gtest/gtest.h>
63
64 #include <openssl/cipher.h>
65 #include <openssl/err.h>
66 #include <openssl/span.h>
67
68 #include "../test/file_test.h"
69 #include "../test/test_util.h"
70 #include "../test/wycheproof_util.h"
71
72
GetCipher(const std::string & name)73 static const EVP_CIPHER *GetCipher(const std::string &name) {
74 if (name == "DES-CBC") {
75 return EVP_des_cbc();
76 } else if (name == "DES-ECB") {
77 return EVP_des_ecb();
78 } else if (name == "DES-EDE") {
79 return EVP_des_ede();
80 } else if (name == "DES-EDE3") {
81 return EVP_des_ede3();
82 } else if (name == "DES-EDE-CBC") {
83 return EVP_des_ede_cbc();
84 } else if (name == "DES-EDE3-CBC") {
85 return EVP_des_ede3_cbc();
86 } else if (name == "RC4") {
87 return EVP_rc4();
88 } else if (name == "AES-128-ECB") {
89 return EVP_aes_128_ecb();
90 } else if (name == "AES-256-ECB") {
91 return EVP_aes_256_ecb();
92 } else if (name == "AES-128-CBC") {
93 return EVP_aes_128_cbc();
94 } else if (name == "AES-128-GCM") {
95 return EVP_aes_128_gcm();
96 } else if (name == "AES-128-OFB") {
97 return EVP_aes_128_ofb();
98 } else if (name == "AES-192-CBC") {
99 return EVP_aes_192_cbc();
100 } else if (name == "AES-192-CTR") {
101 return EVP_aes_192_ctr();
102 } else if (name == "AES-192-ECB") {
103 return EVP_aes_192_ecb();
104 } else if (name == "AES-192-OFB") {
105 return EVP_aes_192_ofb();
106 } else if (name == "AES-256-CBC") {
107 return EVP_aes_256_cbc();
108 } else if (name == "AES-128-CTR") {
109 return EVP_aes_128_ctr();
110 } else if (name == "AES-256-CTR") {
111 return EVP_aes_256_ctr();
112 } else if (name == "AES-256-GCM") {
113 return EVP_aes_256_gcm();
114 } else if (name == "AES-256-OFB") {
115 return EVP_aes_256_ofb();
116 }
117 return nullptr;
118 }
119
DoCipher(EVP_CIPHER_CTX * ctx,std::vector<uint8_t> * out,bssl::Span<const uint8_t> in,size_t chunk)120 static bool DoCipher(EVP_CIPHER_CTX *ctx, std::vector<uint8_t> *out,
121 bssl::Span<const uint8_t> in, size_t chunk) {
122 size_t max_out = in.size();
123 if ((EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_NO_PADDING) == 0 &&
124 EVP_CIPHER_CTX_encrypting(ctx)) {
125 unsigned block_size = EVP_CIPHER_CTX_block_size(ctx);
126 max_out += block_size - (max_out % block_size);
127 }
128 out->resize(max_out);
129
130 size_t total = 0;
131 int len;
132 while (!in.empty()) {
133 size_t todo = chunk == 0 ? in.size() : std::min(in.size(), chunk);
134 EXPECT_LE(todo, static_cast<size_t>(INT_MAX));
135 if (!EVP_CipherUpdate(ctx, out->data() + total, &len, in.data(),
136 static_cast<int>(todo))) {
137 return false;
138 }
139 EXPECT_GE(len, 0);
140 total += static_cast<size_t>(len);
141 in = in.subspan(todo);
142 }
143 if (!EVP_CipherFinal_ex(ctx, out->data() + total, &len)) {
144 return false;
145 }
146 EXPECT_GE(len, 0);
147 total += static_cast<size_t>(len);
148 out->resize(total);
149 return true;
150 }
151
TestOperation(FileTest * t,const EVP_CIPHER * cipher,bool encrypt,bool copy,size_t chunk_size,const std::vector<uint8_t> & key,const std::vector<uint8_t> & iv,const std::vector<uint8_t> & plaintext,const std::vector<uint8_t> & ciphertext,const std::vector<uint8_t> & aad,const std::vector<uint8_t> & tag)152 static void TestOperation(FileTest *t, const EVP_CIPHER *cipher, bool encrypt,
153 bool copy, size_t chunk_size,
154 const std::vector<uint8_t> &key,
155 const std::vector<uint8_t> &iv,
156 const std::vector<uint8_t> &plaintext,
157 const std::vector<uint8_t> &ciphertext,
158 const std::vector<uint8_t> &aad,
159 const std::vector<uint8_t> &tag) {
160 const std::vector<uint8_t> *in, *out;
161 if (encrypt) {
162 in = &plaintext;
163 out = &ciphertext;
164 } else {
165 in = &ciphertext;
166 out = &plaintext;
167 }
168
169 bool is_aead = EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE;
170
171 bssl::ScopedEVP_CIPHER_CTX ctx1;
172 ASSERT_TRUE(EVP_CipherInit_ex(ctx1.get(), cipher, nullptr, nullptr, nullptr,
173 encrypt ? 1 : 0));
174 if (t->HasAttribute("IV")) {
175 if (is_aead) {
176 ASSERT_TRUE(EVP_CIPHER_CTX_ctrl(ctx1.get(), EVP_CTRL_AEAD_SET_IVLEN,
177 iv.size(), 0));
178 } else {
179 ASSERT_EQ(iv.size(), EVP_CIPHER_CTX_iv_length(ctx1.get()));
180 }
181 }
182
183 bssl::ScopedEVP_CIPHER_CTX ctx2;
184 EVP_CIPHER_CTX *ctx = ctx1.get();
185 if (copy) {
186 ASSERT_TRUE(EVP_CIPHER_CTX_copy(ctx2.get(), ctx1.get()));
187 ctx = ctx2.get();
188 }
189
190 if (is_aead && !encrypt) {
191 ASSERT_TRUE(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag.size(),
192 const_cast<uint8_t *>(tag.data())));
193 }
194 // The ciphers are run with no padding. For each of the ciphers we test, the
195 // output size matches the input size.
196 ASSERT_EQ(in->size(), out->size());
197 ASSERT_TRUE(EVP_CIPHER_CTX_set_key_length(ctx, key.size()));
198 ASSERT_TRUE(
199 EVP_CipherInit_ex(ctx, nullptr, nullptr, key.data(), iv.data(), -1));
200 // Note: the deprecated |EVP_CIPHER|-based AEAD API is sensitive to whether
201 // parameters are NULL, so it is important to skip the |in| and |aad|
202 // |EVP_CipherUpdate| calls when empty.
203 if (!aad.empty()) {
204 int unused;
205 ASSERT_TRUE(
206 EVP_CipherUpdate(ctx, nullptr, &unused, aad.data(), aad.size()));
207 }
208 ASSERT_TRUE(EVP_CIPHER_CTX_set_padding(ctx, 0));
209 std::vector<uint8_t> result;
210 ASSERT_TRUE(DoCipher(ctx, &result, *in, chunk_size));
211 EXPECT_EQ(Bytes(*out), Bytes(result));
212 if (encrypt && is_aead) {
213 uint8_t rtag[16];
214 ASSERT_LE(tag.size(), sizeof(rtag));
215 ASSERT_TRUE(
216 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, tag.size(), rtag));
217 EXPECT_EQ(Bytes(tag), Bytes(rtag, tag.size()));
218 }
219 }
220
TestCipher(FileTest * t)221 static void TestCipher(FileTest *t) {
222 std::string cipher_str;
223 ASSERT_TRUE(t->GetAttribute(&cipher_str, "Cipher"));
224 const EVP_CIPHER *cipher = GetCipher(cipher_str);
225 ASSERT_TRUE(cipher);
226
227 std::vector<uint8_t> key, iv, plaintext, ciphertext, aad, tag;
228 ASSERT_TRUE(t->GetBytes(&key, "Key"));
229 ASSERT_TRUE(t->GetBytes(&plaintext, "Plaintext"));
230 ASSERT_TRUE(t->GetBytes(&ciphertext, "Ciphertext"));
231 if (EVP_CIPHER_iv_length(cipher) > 0) {
232 ASSERT_TRUE(t->GetBytes(&iv, "IV"));
233 }
234 if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE) {
235 ASSERT_TRUE(t->GetBytes(&aad, "AAD"));
236 ASSERT_TRUE(t->GetBytes(&tag, "Tag"));
237 }
238
239 enum {
240 kEncrypt,
241 kDecrypt,
242 kBoth,
243 } operation = kBoth;
244 if (t->HasAttribute("Operation")) {
245 const std::string &str = t->GetAttributeOrDie("Operation");
246 if (str == "ENCRYPT") {
247 operation = kEncrypt;
248 } else if (str == "DECRYPT") {
249 operation = kDecrypt;
250 } else {
251 FAIL() << "Unknown operation: " << str;
252 }
253 }
254
255 const std::vector<size_t> chunk_sizes = {0, 1, 2, 5, 7, 8, 9, 15, 16,
256 17, 31, 32, 33, 63, 64, 65, 512};
257
258 for (size_t chunk_size : chunk_sizes) {
259 SCOPED_TRACE(chunk_size);
260 // By default, both directions are run, unless overridden by the operation.
261 if (operation != kDecrypt) {
262 SCOPED_TRACE("encrypt");
263 TestOperation(t, cipher, true /* encrypt */, false /* no copy */,
264 chunk_size, key, iv, plaintext, ciphertext, aad, tag);
265 TestOperation(t, cipher, true /* encrypt */, true /* copy */, chunk_size,
266 key, iv, plaintext, ciphertext, aad, tag);
267 }
268
269 if (operation != kEncrypt) {
270 SCOPED_TRACE("decrypt");
271 TestOperation(t, cipher, false /* decrypt */, false /* no copy */,
272 chunk_size, key, iv, plaintext, ciphertext, aad, tag);
273 TestOperation(t, cipher, false /* decrypt */, true /* copy */, chunk_size,
274 key, iv, plaintext, ciphertext, aad, tag);
275 }
276 }
277 }
278
TEST(CipherTest,TestVectors)279 TEST(CipherTest, TestVectors) {
280 FileTestGTest("crypto/cipher_extra/test/cipher_tests.txt", TestCipher);
281 }
282
TEST(CipherTest,CAVP_AES_128_CBC)283 TEST(CipherTest, CAVP_AES_128_CBC) {
284 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_128_cbc.txt",
285 TestCipher);
286 }
287
TEST(CipherTest,CAVP_AES_128_CTR)288 TEST(CipherTest, CAVP_AES_128_CTR) {
289 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_128_ctr.txt",
290 TestCipher);
291 }
292
TEST(CipherTest,CAVP_AES_192_CBC)293 TEST(CipherTest, CAVP_AES_192_CBC) {
294 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_192_cbc.txt",
295 TestCipher);
296 }
297
TEST(CipherTest,CAVP_AES_192_CTR)298 TEST(CipherTest, CAVP_AES_192_CTR) {
299 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_192_ctr.txt",
300 TestCipher);
301 }
302
TEST(CipherTest,CAVP_AES_256_CBC)303 TEST(CipherTest, CAVP_AES_256_CBC) {
304 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_256_cbc.txt",
305 TestCipher);
306 }
307
TEST(CipherTest,CAVP_AES_256_CTR)308 TEST(CipherTest, CAVP_AES_256_CTR) {
309 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_256_ctr.txt",
310 TestCipher);
311 }
312
TEST(CipherTest,CAVP_TDES_CBC)313 TEST(CipherTest, CAVP_TDES_CBC) {
314 FileTestGTest("crypto/cipher_extra/test/nist_cavp/tdes_cbc.txt", TestCipher);
315 }
316
TEST(CipherTest,CAVP_TDES_ECB)317 TEST(CipherTest, CAVP_TDES_ECB) {
318 FileTestGTest("crypto/cipher_extra/test/nist_cavp/tdes_ecb.txt", TestCipher);
319 }
320
TEST(CipherTest,WycheproofAESCBC)321 TEST(CipherTest, WycheproofAESCBC) {
322 FileTestGTest("third_party/wycheproof_testvectors/aes_cbc_pkcs5_test.txt",
323 [](FileTest *t) {
324 t->IgnoreInstruction("type");
325 t->IgnoreInstruction("ivSize");
326
327 std::string key_size;
328 ASSERT_TRUE(t->GetInstruction(&key_size, "keySize"));
329 const EVP_CIPHER *cipher;
330 switch (atoi(key_size.c_str())) {
331 case 128:
332 cipher = EVP_aes_128_cbc();
333 break;
334 case 192:
335 cipher = EVP_aes_192_cbc();
336 break;
337 case 256:
338 cipher = EVP_aes_256_cbc();
339 break;
340 default:
341 FAIL() << "Unsupported key size: " << key_size;
342 }
343
344 std::vector<uint8_t> key, iv, msg, ct;
345 ASSERT_TRUE(t->GetBytes(&key, "key"));
346 ASSERT_TRUE(t->GetBytes(&iv, "iv"));
347 ASSERT_TRUE(t->GetBytes(&msg, "msg"));
348 ASSERT_TRUE(t->GetBytes(&ct, "ct"));
349 ASSERT_EQ(EVP_CIPHER_key_length(cipher), key.size());
350 ASSERT_EQ(EVP_CIPHER_iv_length(cipher), iv.size());
351 WycheproofResult result;
352 ASSERT_TRUE(GetWycheproofResult(t, &result));
353
354 bssl::ScopedEVP_CIPHER_CTX ctx;
355 std::vector<uint8_t> out;
356 const std::vector<size_t> chunk_sizes = {0, 1, 2, 5, 7, 8, 9, 15, 16,
357 17, 31, 32, 33, 63, 64, 65, 512};
358 for (size_t chunk : chunk_sizes) {
359 SCOPED_TRACE(chunk);
360 if (result == WycheproofResult::kValid) {
361 ASSERT_TRUE(EVP_DecryptInit_ex(ctx.get(), cipher, nullptr, key.data(),
362 iv.data()));
363 ASSERT_TRUE(DoCipher(ctx.get(), &out, ct, chunk));
364 EXPECT_EQ(Bytes(msg), Bytes(out));
365
366 ASSERT_TRUE(EVP_EncryptInit_ex(ctx.get(), cipher, nullptr, key.data(),
367 iv.data()));
368 ASSERT_TRUE(DoCipher(ctx.get(), &out, msg, chunk));
369 EXPECT_EQ(Bytes(ct), Bytes(out));
370 } else {
371 ASSERT_TRUE(EVP_DecryptInit_ex(ctx.get(), cipher, nullptr, key.data(),
372 iv.data()));
373 EXPECT_FALSE(DoCipher(ctx.get(), &out, ct, chunk));
374 }
375 }
376 });
377 }
378