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/aes.h>
65 #include <openssl/cipher.h>
66 #include <openssl/err.h>
67 #include <openssl/nid.h>
68 #include <openssl/rand.h>
69 #include <openssl/sha.h>
70 #include <openssl/span.h>
71
72 #include "../test/file_test.h"
73 #include "../test/test_util.h"
74 #include "../test/wycheproof_util.h"
75 #include "./internal.h"
76
77
GetCipher(const std::string & name)78 static const EVP_CIPHER *GetCipher(const std::string &name) {
79 if (name == "DES-CBC") {
80 return EVP_des_cbc();
81 } else if (name == "DES-ECB") {
82 return EVP_des_ecb();
83 } else if (name == "DES-EDE") {
84 return EVP_des_ede();
85 } else if (name == "DES-EDE3") {
86 return EVP_des_ede3();
87 } else if (name == "DES-EDE-CBC") {
88 return EVP_des_ede_cbc();
89 } else if (name == "DES-EDE3-CBC") {
90 return EVP_des_ede3_cbc();
91 } else if (name == "RC4") {
92 return EVP_rc4();
93 } else if (name == "AES-128-ECB") {
94 return EVP_aes_128_ecb();
95 } else if (name == "AES-256-ECB") {
96 return EVP_aes_256_ecb();
97 } else if (name == "AES-128-CBC") {
98 return EVP_aes_128_cbc();
99 } else if (name == "AES-128-GCM") {
100 return EVP_aes_128_gcm();
101 } else if (name == "AES-128-OFB") {
102 return EVP_aes_128_ofb();
103 } else if (name == "AES-192-CBC") {
104 return EVP_aes_192_cbc();
105 } else if (name == "AES-192-CTR") {
106 return EVP_aes_192_ctr();
107 } else if (name == "AES-192-ECB") {
108 return EVP_aes_192_ecb();
109 } else if (name == "AES-192-OFB") {
110 return EVP_aes_192_ofb();
111 } else if (name == "AES-256-CBC") {
112 return EVP_aes_256_cbc();
113 } else if (name == "AES-128-CTR") {
114 return EVP_aes_128_ctr();
115 } else if (name == "AES-256-CTR") {
116 return EVP_aes_256_ctr();
117 } else if (name == "AES-256-GCM") {
118 return EVP_aes_256_gcm();
119 } else if (name == "AES-256-OFB") {
120 return EVP_aes_256_ofb();
121 }
122 return nullptr;
123 }
124
DoCipher(EVP_CIPHER_CTX * ctx,std::vector<uint8_t> * out,bssl::Span<const uint8_t> in,size_t chunk,bool in_place)125 static bool DoCipher(EVP_CIPHER_CTX *ctx, std::vector<uint8_t> *out,
126 bssl::Span<const uint8_t> in, size_t chunk,
127 bool in_place) {
128 size_t max_out = in.size();
129 if ((EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_NO_PADDING) == 0 &&
130 EVP_CIPHER_CTX_encrypting(ctx)) {
131 unsigned block_size = EVP_CIPHER_CTX_block_size(ctx);
132 max_out += block_size - (max_out % block_size);
133 }
134 out->resize(max_out);
135 if (in_place) {
136 std::copy(in.begin(), in.end(), out->begin());
137 in = bssl::MakeConstSpan(out->data(), in.size());
138 }
139
140 size_t total = 0;
141 int len;
142 while (!in.empty()) {
143 size_t todo = chunk == 0 ? in.size() : std::min(in.size(), chunk);
144 EXPECT_LE(todo, static_cast<size_t>(INT_MAX));
145 if (!EVP_CipherUpdate(ctx, out->data() + total, &len, in.data(),
146 static_cast<int>(todo))) {
147 return false;
148 }
149 EXPECT_GE(len, 0);
150 total += static_cast<size_t>(len);
151 in = in.subspan(todo);
152 }
153 if (!EVP_CipherFinal_ex(ctx, out->data() + total, &len)) {
154 return false;
155 }
156 EXPECT_GE(len, 0);
157 total += static_cast<size_t>(len);
158 out->resize(total);
159 return true;
160 }
161
TestOperation(FileTest * t,const EVP_CIPHER * cipher,bool encrypt,bool copy,bool in_place,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)162 static void TestOperation(FileTest *t, const EVP_CIPHER *cipher, bool encrypt,
163 bool copy, bool in_place, size_t chunk_size,
164 const std::vector<uint8_t> &key,
165 const std::vector<uint8_t> &iv,
166 const std::vector<uint8_t> &plaintext,
167 const std::vector<uint8_t> &ciphertext,
168 const std::vector<uint8_t> &aad,
169 const std::vector<uint8_t> &tag) {
170 const std::vector<uint8_t> *in, *out;
171 if (encrypt) {
172 in = &plaintext;
173 out = &ciphertext;
174 } else {
175 in = &ciphertext;
176 out = &plaintext;
177 }
178
179 bool is_aead = EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE;
180
181 bssl::ScopedEVP_CIPHER_CTX ctx1;
182 ASSERT_TRUE(EVP_CipherInit_ex(ctx1.get(), cipher, nullptr, nullptr, nullptr,
183 encrypt ? 1 : 0));
184 if (t->HasAttribute("IV")) {
185 if (is_aead) {
186 ASSERT_TRUE(EVP_CIPHER_CTX_ctrl(ctx1.get(), EVP_CTRL_AEAD_SET_IVLEN,
187 iv.size(), 0));
188 } else {
189 ASSERT_EQ(iv.size(), EVP_CIPHER_CTX_iv_length(ctx1.get()));
190 }
191 }
192
193 bssl::ScopedEVP_CIPHER_CTX ctx2;
194 EVP_CIPHER_CTX *ctx = ctx1.get();
195 if (copy) {
196 ASSERT_TRUE(EVP_CIPHER_CTX_copy(ctx2.get(), ctx1.get()));
197 ctx = ctx2.get();
198 }
199
200 if (is_aead && !encrypt) {
201 ASSERT_TRUE(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag.size(),
202 const_cast<uint8_t *>(tag.data())));
203 }
204 // The ciphers are run with no padding. For each of the ciphers we test, the
205 // output size matches the input size.
206 ASSERT_EQ(in->size(), out->size());
207 ASSERT_TRUE(EVP_CIPHER_CTX_set_key_length(ctx, key.size()));
208 ASSERT_TRUE(
209 EVP_CipherInit_ex(ctx, nullptr, nullptr, key.data(), iv.data(), -1));
210 // Note: the deprecated |EVP_CIPHER|-based AEAD API is sensitive to whether
211 // parameters are NULL, so it is important to skip the |in| and |aad|
212 // |EVP_CipherUpdate| calls when empty.
213 if (!aad.empty()) {
214 int unused;
215 ASSERT_TRUE(
216 EVP_CipherUpdate(ctx, nullptr, &unused, aad.data(), aad.size()));
217 }
218 ASSERT_TRUE(EVP_CIPHER_CTX_set_padding(ctx, 0));
219 std::vector<uint8_t> result;
220 ASSERT_TRUE(DoCipher(ctx, &result, *in, chunk_size, in_place));
221 EXPECT_EQ(Bytes(*out), Bytes(result));
222 if (encrypt && is_aead) {
223 uint8_t rtag[16];
224 ASSERT_LE(tag.size(), sizeof(rtag));
225 ASSERT_TRUE(
226 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, tag.size(), rtag));
227 EXPECT_EQ(Bytes(tag), Bytes(rtag, tag.size()));
228 }
229
230 // Additionally test low-level AES mode APIs. Skip runs where |copy| because
231 // it does not apply.
232 if (!copy) {
233 int nid = EVP_CIPHER_nid(cipher);
234 bool is_ctr = nid == NID_aes_128_ctr || nid == NID_aes_192_ctr ||
235 nid == NID_aes_256_ctr;
236 bool is_cbc = nid == NID_aes_128_cbc || nid == NID_aes_192_cbc ||
237 nid == NID_aes_256_cbc;
238 bool is_ofb = nid == NID_aes_128_ofb128 || nid == NID_aes_192_ofb128 ||
239 nid == NID_aes_256_ofb128;
240 if (is_ctr || is_cbc || is_ofb) {
241 AES_KEY aes;
242 if (encrypt || !is_cbc) {
243 ASSERT_EQ(0, AES_set_encrypt_key(key.data(), key.size() * 8, &aes));
244 } else {
245 ASSERT_EQ(0, AES_set_decrypt_key(key.data(), key.size() * 8, &aes));
246 }
247
248 // The low-level APIs all work in-place.
249 bssl::Span<const uint8_t> input = *in;
250 result.clear();
251 if (in_place) {
252 result = *in;
253 input = result;
254 } else {
255 result.resize(out->size());
256 }
257 bssl::Span<uint8_t> output = bssl::MakeSpan(result);
258 ASSERT_EQ(input.size(), output.size());
259
260 // The low-level APIs all use block-size IVs.
261 ASSERT_EQ(iv.size(), size_t{AES_BLOCK_SIZE});
262 uint8_t ivec[AES_BLOCK_SIZE];
263 OPENSSL_memcpy(ivec, iv.data(), iv.size());
264
265 if (is_ctr) {
266 unsigned num = 0;
267 uint8_t ecount_buf[AES_BLOCK_SIZE];
268 if (chunk_size == 0) {
269 AES_ctr128_encrypt(input.data(), output.data(), input.size(), &aes,
270 ivec, ecount_buf, &num);
271 } else {
272 do {
273 size_t todo = std::min(input.size(), chunk_size);
274 AES_ctr128_encrypt(input.data(), output.data(), todo, &aes, ivec,
275 ecount_buf, &num);
276 input = input.subspan(todo);
277 output = output.subspan(todo);
278 } while (!input.empty());
279 }
280 EXPECT_EQ(Bytes(*out), Bytes(result));
281 } else if (is_cbc && chunk_size % AES_BLOCK_SIZE == 0) {
282 // Note |AES_cbc_encrypt| requires block-aligned chunks.
283 if (chunk_size == 0) {
284 AES_cbc_encrypt(input.data(), output.data(), input.size(), &aes, ivec,
285 encrypt);
286 } else {
287 do {
288 size_t todo = std::min(input.size(), chunk_size);
289 AES_cbc_encrypt(input.data(), output.data(), todo, &aes, ivec,
290 encrypt);
291 input = input.subspan(todo);
292 output = output.subspan(todo);
293 } while (!input.empty());
294 }
295 EXPECT_EQ(Bytes(*out), Bytes(result));
296 } else if (is_ofb) {
297 int num = 0;
298 if (chunk_size == 0) {
299 AES_ofb128_encrypt(input.data(), output.data(), input.size(), &aes,
300 ivec, &num);
301 } else {
302 do {
303 size_t todo = std::min(input.size(), chunk_size);
304 AES_ofb128_encrypt(input.data(), output.data(), todo, &aes, ivec,
305 &num);
306 input = input.subspan(todo);
307 output = output.subspan(todo);
308 } while (!input.empty());
309 }
310 EXPECT_EQ(Bytes(*out), Bytes(result));
311 }
312 }
313 }
314 }
315
TestCipher(FileTest * t)316 static void TestCipher(FileTest *t) {
317 std::string cipher_str;
318 ASSERT_TRUE(t->GetAttribute(&cipher_str, "Cipher"));
319 const EVP_CIPHER *cipher = GetCipher(cipher_str);
320 ASSERT_TRUE(cipher);
321
322 std::vector<uint8_t> key, iv, plaintext, ciphertext, aad, tag;
323 ASSERT_TRUE(t->GetBytes(&key, "Key"));
324 ASSERT_TRUE(t->GetBytes(&plaintext, "Plaintext"));
325 ASSERT_TRUE(t->GetBytes(&ciphertext, "Ciphertext"));
326 if (EVP_CIPHER_iv_length(cipher) > 0) {
327 ASSERT_TRUE(t->GetBytes(&iv, "IV"));
328 }
329 if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE) {
330 ASSERT_TRUE(t->GetBytes(&aad, "AAD"));
331 ASSERT_TRUE(t->GetBytes(&tag, "Tag"));
332 }
333
334 enum {
335 kEncrypt,
336 kDecrypt,
337 kBoth,
338 } operation = kBoth;
339 if (t->HasAttribute("Operation")) {
340 const std::string &str = t->GetAttributeOrDie("Operation");
341 if (str == "ENCRYPT") {
342 operation = kEncrypt;
343 } else if (str == "DECRYPT") {
344 operation = kDecrypt;
345 } else {
346 FAIL() << "Unknown operation: " << str;
347 }
348 }
349
350 const std::vector<size_t> chunk_sizes = {0, 1, 2, 5, 7, 8, 9, 15, 16,
351 17, 31, 32, 33, 63, 64, 65, 512};
352
353 for (size_t chunk_size : chunk_sizes) {
354 SCOPED_TRACE(chunk_size);
355 for (bool copy : {false, true}) {
356 SCOPED_TRACE(copy);
357 for (bool in_place : {false, true}) {
358 SCOPED_TRACE(in_place);
359 // By default, both directions are run, unless overridden by the
360 // operation.
361 if (operation != kDecrypt) {
362 SCOPED_TRACE("encrypt");
363 TestOperation(t, cipher, true /* encrypt */, copy, in_place,
364 chunk_size, key, iv, plaintext, ciphertext, aad, tag);
365 }
366
367 if (operation != kEncrypt) {
368 SCOPED_TRACE("decrypt");
369 TestOperation(t, cipher, false /* decrypt */, copy, in_place,
370 chunk_size, key, iv, plaintext, ciphertext, aad, tag);
371 }
372 }
373 }
374 }
375 }
376
TEST(CipherTest,TestVectors)377 TEST(CipherTest, TestVectors) {
378 FileTestGTest("crypto/cipher_extra/test/cipher_tests.txt", TestCipher);
379 }
380
TEST(CipherTest,CAVP_AES_128_CBC)381 TEST(CipherTest, CAVP_AES_128_CBC) {
382 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_128_cbc.txt",
383 TestCipher);
384 }
385
TEST(CipherTest,CAVP_AES_128_CTR)386 TEST(CipherTest, CAVP_AES_128_CTR) {
387 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_128_ctr.txt",
388 TestCipher);
389 }
390
TEST(CipherTest,CAVP_AES_192_CBC)391 TEST(CipherTest, CAVP_AES_192_CBC) {
392 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_192_cbc.txt",
393 TestCipher);
394 }
395
TEST(CipherTest,CAVP_AES_192_CTR)396 TEST(CipherTest, CAVP_AES_192_CTR) {
397 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_192_ctr.txt",
398 TestCipher);
399 }
400
TEST(CipherTest,CAVP_AES_256_CBC)401 TEST(CipherTest, CAVP_AES_256_CBC) {
402 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_256_cbc.txt",
403 TestCipher);
404 }
405
TEST(CipherTest,CAVP_AES_256_CTR)406 TEST(CipherTest, CAVP_AES_256_CTR) {
407 FileTestGTest("crypto/cipher_extra/test/nist_cavp/aes_256_ctr.txt",
408 TestCipher);
409 }
410
TEST(CipherTest,CAVP_TDES_CBC)411 TEST(CipherTest, CAVP_TDES_CBC) {
412 FileTestGTest("crypto/cipher_extra/test/nist_cavp/tdes_cbc.txt", TestCipher);
413 }
414
TEST(CipherTest,CAVP_TDES_ECB)415 TEST(CipherTest, CAVP_TDES_ECB) {
416 FileTestGTest("crypto/cipher_extra/test/nist_cavp/tdes_ecb.txt", TestCipher);
417 }
418
TEST(CipherTest,WycheproofAESCBC)419 TEST(CipherTest, WycheproofAESCBC) {
420 FileTestGTest(
421 "third_party/wycheproof_testvectors/aes_cbc_pkcs5_test.txt",
422 [](FileTest *t) {
423 t->IgnoreInstruction("type");
424 t->IgnoreInstruction("ivSize");
425
426 std::string key_size;
427 ASSERT_TRUE(t->GetInstruction(&key_size, "keySize"));
428 const EVP_CIPHER *cipher;
429 switch (atoi(key_size.c_str())) {
430 case 128:
431 cipher = EVP_aes_128_cbc();
432 break;
433 case 192:
434 cipher = EVP_aes_192_cbc();
435 break;
436 case 256:
437 cipher = EVP_aes_256_cbc();
438 break;
439 default:
440 FAIL() << "Unsupported key size: " << key_size;
441 }
442
443 std::vector<uint8_t> key, iv, msg, ct;
444 ASSERT_TRUE(t->GetBytes(&key, "key"));
445 ASSERT_TRUE(t->GetBytes(&iv, "iv"));
446 ASSERT_TRUE(t->GetBytes(&msg, "msg"));
447 ASSERT_TRUE(t->GetBytes(&ct, "ct"));
448 ASSERT_EQ(EVP_CIPHER_key_length(cipher), key.size());
449 ASSERT_EQ(EVP_CIPHER_iv_length(cipher), iv.size());
450 WycheproofResult result;
451 ASSERT_TRUE(GetWycheproofResult(t, &result));
452
453 bssl::ScopedEVP_CIPHER_CTX ctx;
454 std::vector<uint8_t> out;
455 const std::vector<size_t> chunk_sizes = {
456 0, 1, 2, 5, 7, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65, 512};
457 for (size_t chunk : chunk_sizes) {
458 SCOPED_TRACE(chunk);
459 for (bool in_place : {false, true}) {
460 SCOPED_TRACE(in_place);
461 if (result.IsValid()) {
462 ASSERT_TRUE(EVP_DecryptInit_ex(ctx.get(), cipher, nullptr,
463 key.data(), iv.data()));
464 ASSERT_TRUE(DoCipher(ctx.get(), &out, ct, chunk, in_place));
465 EXPECT_EQ(Bytes(msg), Bytes(out));
466
467 ASSERT_TRUE(EVP_EncryptInit_ex(ctx.get(), cipher, nullptr,
468 key.data(), iv.data()));
469 ASSERT_TRUE(DoCipher(ctx.get(), &out, msg, chunk, in_place));
470 EXPECT_EQ(Bytes(ct), Bytes(out));
471 } else {
472 ASSERT_TRUE(EVP_DecryptInit_ex(ctx.get(), cipher, nullptr,
473 key.data(), iv.data()));
474 EXPECT_FALSE(DoCipher(ctx.get(), &out, ct, chunk, in_place));
475 }
476 }
477 }
478 });
479 }
480
TEST(CipherTest,SHA1WithSecretSuffix)481 TEST(CipherTest, SHA1WithSecretSuffix) {
482 uint8_t buf[SHA_CBLOCK * 4];
483 RAND_bytes(buf, sizeof(buf));
484 // Hashing should run in time independent of the bytes.
485 CONSTTIME_SECRET(buf, sizeof(buf));
486
487 // Exhaustively testing interesting cases in this function is cubic in the
488 // block size, so we test in 3-byte increments.
489 constexpr size_t kSkip = 3;
490 // This value should be less than 8 to test the edge case when the 8-byte
491 // length wraps to the next block.
492 static_assert(kSkip < 8, "kSkip is too large");
493
494 // |EVP_sha1_final_with_secret_suffix| is sensitive to the public length of
495 // the partial block previously hashed. In TLS, this is the HMAC prefix, the
496 // header, and the public minimum padding length.
497 for (size_t prefix = 0; prefix < SHA_CBLOCK; prefix += kSkip) {
498 SCOPED_TRACE(prefix);
499 // The first block is treated differently, so we run with up to three
500 // blocks of length variability.
501 for (size_t max_len = 0; max_len < 3 * SHA_CBLOCK; max_len += kSkip) {
502 SCOPED_TRACE(max_len);
503 for (size_t len = 0; len <= max_len; len += kSkip) {
504 SCOPED_TRACE(len);
505
506 uint8_t expected[SHA_DIGEST_LENGTH];
507 SHA1(buf, prefix + len, expected);
508 CONSTTIME_DECLASSIFY(expected, sizeof(expected));
509
510 // Make a copy of the secret length to avoid interfering with the loop.
511 size_t secret_len = len;
512 CONSTTIME_SECRET(&secret_len, sizeof(secret_len));
513
514 SHA_CTX ctx;
515 SHA1_Init(&ctx);
516 SHA1_Update(&ctx, buf, prefix);
517 uint8_t computed[SHA_DIGEST_LENGTH];
518 ASSERT_TRUE(EVP_sha1_final_with_secret_suffix(
519 &ctx, computed, buf + prefix, secret_len, max_len));
520
521 CONSTTIME_DECLASSIFY(computed, sizeof(computed));
522 EXPECT_EQ(Bytes(expected), Bytes(computed));
523 }
524 }
525 }
526 }
527