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