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 <stdlib.h>
55 #include <string.h>
56 
57 #include <string>
58 #include <vector>
59 
60 #include <openssl/cipher.h>
61 #include <openssl/crypto.h>
62 #include <openssl/err.h>
63 
64 #include "../test/file_test.h"
65 
66 
GetCipher(const std::string & name)67 static const EVP_CIPHER *GetCipher(const std::string &name) {
68   if (name == "DES-CBC") {
69     return EVP_des_cbc();
70   } else if (name == "DES-ECB") {
71     return EVP_des_ecb();
72   } else if (name == "DES-EDE") {
73     return EVP_des_ede();
74   } else if (name == "DES-EDE-CBC") {
75     return EVP_des_ede_cbc();
76   } else if (name == "DES-EDE3-CBC") {
77     return EVP_des_ede3_cbc();
78   } else if (name == "RC4") {
79     return EVP_rc4();
80   } else if (name == "AES-128-ECB") {
81     return EVP_aes_128_ecb();
82   } else if (name == "AES-256-ECB") {
83     return EVP_aes_256_ecb();
84   } else if (name == "AES-128-CBC") {
85     return EVP_aes_128_cbc();
86   } else if (name == "AES-128-GCM") {
87     return EVP_aes_128_gcm();
88   } else if (name == "AES-128-OFB") {
89     return EVP_aes_128_ofb();
90   } else if (name == "AES-192-CBC") {
91     return EVP_aes_192_cbc();
92   } else if (name == "AES-192-ECB") {
93     return EVP_aes_192_ecb();
94   } else if (name == "AES-256-CBC") {
95     return EVP_aes_256_cbc();
96   } else if (name == "AES-128-CTR") {
97     return EVP_aes_128_ctr();
98   } else if (name == "AES-256-CTR") {
99     return EVP_aes_256_ctr();
100   } else if (name == "AES-256-GCM") {
101     return EVP_aes_256_gcm();
102   } else if (name == "AES-256-OFB") {
103     return EVP_aes_256_ofb();
104   }
105   return nullptr;
106 }
107 
TestOperation(FileTest * t,const EVP_CIPHER * cipher,bool encrypt,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)108 static bool TestOperation(FileTest *t,
109                           const EVP_CIPHER *cipher,
110                           bool encrypt,
111                           size_t chunk_size,
112                           const std::vector<uint8_t> &key,
113                           const std::vector<uint8_t> &iv,
114                           const std::vector<uint8_t> &plaintext,
115                           const std::vector<uint8_t> &ciphertext,
116                           const std::vector<uint8_t> &aad,
117                           const std::vector<uint8_t> &tag) {
118   const std::vector<uint8_t> *in, *out;
119   if (encrypt) {
120     in = &plaintext;
121     out = &ciphertext;
122   } else {
123     in = &ciphertext;
124     out = &plaintext;
125   }
126 
127   bool is_aead = EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE;
128 
129   bssl::ScopedEVP_CIPHER_CTX ctx;
130   if (!EVP_CipherInit_ex(ctx.get(), cipher, nullptr, nullptr, nullptr,
131                          encrypt ? 1 : 0)) {
132     return false;
133   }
134   if (t->HasAttribute("IV")) {
135     if (is_aead) {
136       if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN,
137                                iv.size(), 0)) {
138         return false;
139       }
140     } else if (iv.size() != EVP_CIPHER_CTX_iv_length(ctx.get())) {
141       t->PrintLine("Bad IV length.");
142       return false;
143     }
144   }
145   if (is_aead && !encrypt &&
146       !EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, tag.size(),
147                            const_cast<uint8_t*>(tag.data()))) {
148     return false;
149   }
150   // The ciphers are run with no padding. For each of the ciphers we test, the
151   // output size matches the input size.
152   std::vector<uint8_t> result(in->size());
153   if (in->size() != out->size()) {
154     t->PrintLine("Input/output size mismatch (%u vs %u).", (unsigned)in->size(),
155                  (unsigned)out->size());
156     return false;
157   }
158   // Note: the deprecated |EVP_CIPHER|-based AES-GCM API is sensitive to whether
159   // parameters are NULL, so it is important to skip the |in| and |aad|
160   // |EVP_CipherUpdate| calls when empty.
161   int unused, result_len1 = 0, result_len2;
162   if (!EVP_CIPHER_CTX_set_key_length(ctx.get(), key.size()) ||
163       !EVP_CipherInit_ex(ctx.get(), nullptr, nullptr, key.data(), iv.data(),
164                          -1) ||
165       (!aad.empty() &&
166        !EVP_CipherUpdate(ctx.get(), nullptr, &unused, aad.data(),
167                          aad.size())) ||
168       !EVP_CIPHER_CTX_set_padding(ctx.get(), 0)) {
169     t->PrintLine("Operation failed.");
170     return false;
171   }
172   if (chunk_size != 0) {
173     for (size_t i = 0; i < in->size();) {
174       size_t todo = chunk_size;
175       if (i + todo > in->size()) {
176         todo = in->size() - i;
177       }
178 
179       int len;
180       if (!EVP_CipherUpdate(ctx.get(), result.data() + result_len1, &len,
181                             in->data() + i, todo)) {
182         t->PrintLine("Operation failed.");
183         return false;
184       }
185       result_len1 += len;
186       i += todo;
187     }
188   } else if (!in->empty() &&
189              !EVP_CipherUpdate(ctx.get(), result.data(), &result_len1,
190                                in->data(), in->size())) {
191     t->PrintLine("Operation failed.");
192     return false;
193   }
194   if (!EVP_CipherFinal_ex(ctx.get(), result.data() + result_len1,
195                           &result_len2)) {
196     t->PrintLine("Operation failed.");
197     return false;
198   }
199   result.resize(result_len1 + result_len2);
200   if (!t->ExpectBytesEqual(out->data(), out->size(), result.data(),
201                            result.size())) {
202     return false;
203   }
204   if (encrypt && is_aead) {
205     uint8_t rtag[16];
206     if (tag.size() > sizeof(rtag)) {
207       t->PrintLine("Bad tag length.");
208       return false;
209     }
210     if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, tag.size(),
211                              rtag) ||
212         !t->ExpectBytesEqual(tag.data(), tag.size(), rtag,
213                              tag.size())) {
214       return false;
215     }
216   }
217   return true;
218 }
219 
TestCipher(FileTest * t,void * arg)220 static bool TestCipher(FileTest *t, void *arg) {
221   std::string cipher_str;
222   if (!t->GetAttribute(&cipher_str, "Cipher")) {
223     return false;
224   }
225   const EVP_CIPHER *cipher = GetCipher(cipher_str);
226   if (cipher == nullptr) {
227     t->PrintLine("Unknown cipher: '%s'.", cipher_str.c_str());
228     return false;
229   }
230 
231   std::vector<uint8_t> key, iv, plaintext, ciphertext, aad, tag;
232   if (!t->GetBytes(&key, "Key") ||
233       !t->GetBytes(&plaintext, "Plaintext") ||
234       !t->GetBytes(&ciphertext, "Ciphertext")) {
235     return false;
236   }
237   if (EVP_CIPHER_iv_length(cipher) > 0 &&
238       !t->GetBytes(&iv, "IV")) {
239     return false;
240   }
241   if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE) {
242     if (!t->GetBytes(&aad, "AAD") ||
243         !t->GetBytes(&tag, "Tag")) {
244       return false;
245     }
246   }
247 
248   enum {
249     kEncrypt,
250     kDecrypt,
251     kBoth,
252   } operation = kBoth;
253   if (t->HasAttribute("Operation")) {
254     const std::string &str = t->GetAttributeOrDie("Operation");
255     if (str == "ENCRYPT") {
256       operation = kEncrypt;
257     } else if (str == "DECRYPT") {
258       operation = kDecrypt;
259     } else {
260       t->PrintLine("Unknown operation: '%s'.", str.c_str());
261       return false;
262     }
263   }
264 
265   const std::vector<size_t> chunk_sizes = {0,  1,  2,  5,  7,  8,  9,  15, 16,
266                                            17, 31, 32, 33, 63, 64, 65, 512};
267 
268   for (size_t chunk_size : chunk_sizes) {
269     // By default, both directions are run, unless overridden by the operation.
270     if (operation != kDecrypt &&
271         !TestOperation(t, cipher, true /* encrypt */, chunk_size, key, iv,
272                        plaintext, ciphertext, aad, tag)) {
273       return false;
274     }
275 
276     if (operation != kEncrypt &&
277         !TestOperation(t, cipher, false /* decrypt */, chunk_size, key, iv,
278                        plaintext, ciphertext, aad, tag)) {
279       return false;
280     }
281   }
282 
283   return true;
284 }
285 
main(int argc,char ** argv)286 int main(int argc, char **argv) {
287   CRYPTO_library_init();
288 
289   if (argc != 2) {
290     fprintf(stderr, "%s <test file>\n", argv[0]);
291     return 1;
292   }
293 
294   return FileTestMain(TestCipher, nullptr, argv[1]);
295 }
296