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 <stdio.h>
55 #include <stdint.h>
56 #include <stdlib.h>
57 #include <string.h>
58 
59 #include <map>
60 #include <string>
61 #include <vector>
62 
63 #include <openssl/bio.h>
64 #include <openssl/crypto.h>
65 #include <openssl/digest.h>
66 #include <openssl/err.h>
67 #include <openssl/evp.h>
68 #include <openssl/pem.h>
69 
70 #include "../test/file_test.h"
71 #include "../test/scoped_types.h"
72 #include "../test/stl_compat.h"
73 
74 
75 // evp_test dispatches between multiple test types. HMAC tests test the legacy
76 // EVP_PKEY_HMAC API. PrivateKey tests take a key name parameter and single
77 // block, decode it as a PEM private key, and save it under that key name.
78 // Decrypt, Sign, and Verify tests take a previously imported key name as
79 // parameter and test their respective operations.
80 
GetDigest(FileTest * t,const std::string & name)81 static const EVP_MD *GetDigest(FileTest *t, const std::string &name) {
82   if (name == "MD5") {
83     return EVP_md5();
84   } else if (name == "SHA1") {
85     return EVP_sha1();
86   } else if (name == "SHA224") {
87     return EVP_sha224();
88   } else if (name == "SHA256") {
89     return EVP_sha256();
90   } else if (name == "SHA384") {
91     return EVP_sha384();
92   } else if (name == "SHA512") {
93     return EVP_sha512();
94   }
95   t->PrintLine("Unknown digest: '%s'", name.c_str());
96   return nullptr;
97 }
98 
99 using KeyMap = std::map<std::string, EVP_PKEY*>;
100 
101 // ImportPrivateKey evaluates a PrivateKey test in |t| and writes the resulting
102 // private key to |key_map|.
ImportPrivateKey(FileTest * t,KeyMap * key_map)103 static bool ImportPrivateKey(FileTest *t, KeyMap *key_map) {
104   const std::string &key_name = t->GetParameter();
105   if (key_map->count(key_name) > 0) {
106     t->PrintLine("Duplicate key '%s'.", key_name.c_str());
107     return false;
108   }
109   const std::string &block = t->GetBlock();
110   ScopedBIO bio(BIO_new_mem_buf(const_cast<char*>(block.data()), block.size()));
111   if (!bio) {
112     return false;
113   }
114   ScopedEVP_PKEY pkey(PEM_read_bio_PrivateKey(bio.get(), nullptr, 0, nullptr));
115   if (!pkey) {
116     t->PrintLine("Error reading private key.");
117     return false;
118   }
119   (*key_map)[key_name] = pkey.release();
120   return true;
121 }
122 
TestHMAC(FileTest * t)123 static bool TestHMAC(FileTest *t) {
124   std::string digest_str;
125   if (!t->GetAttribute(&digest_str, "HMAC")) {
126     return false;
127   }
128   const EVP_MD *digest = GetDigest(t, digest_str);
129   if (digest == nullptr) {
130     return false;
131   }
132 
133   std::vector<uint8_t> key, input, output;
134   if (!t->GetBytes(&key, "Key") ||
135       !t->GetBytes(&input, "Input") ||
136       !t->GetBytes(&output, "Output")) {
137     return false;
138   }
139 
140   ScopedEVP_PKEY pkey(EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, nullptr,
141                                            bssl::vector_data(&key),
142                                            key.size()));
143   ScopedEVP_MD_CTX mctx;
144   if (!pkey ||
145       !EVP_DigestSignInit(mctx.get(), nullptr, digest, nullptr, pkey.get()) ||
146       !EVP_DigestSignUpdate(mctx.get(), bssl::vector_data(&input),
147                             input.size())) {
148     return false;
149   }
150 
151   size_t len;
152   std::vector<uint8_t> actual;
153   if (!EVP_DigestSignFinal(mctx.get(), nullptr, &len)) {
154     return false;
155   }
156   actual.resize(len);
157   if (!EVP_DigestSignFinal(mctx.get(), bssl::vector_data(&actual), &len)) {
158     return false;
159   }
160   actual.resize(len);
161   return t->ExpectBytesEqual(bssl::vector_data(&output), output.size(),
162                              bssl::vector_data(&actual), actual.size());
163 }
164 
TestEVP(FileTest * t,void * arg)165 static bool TestEVP(FileTest *t, void *arg) {
166   KeyMap *key_map = reinterpret_cast<KeyMap*>(arg);
167   if (t->GetType() == "PrivateKey") {
168     return ImportPrivateKey(t, key_map);
169   } else if (t->GetType() == "HMAC") {
170     return TestHMAC(t);
171   }
172 
173   int (*key_op_init)(EVP_PKEY_CTX *ctx);
174   int (*key_op)(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len,
175                 const uint8_t *in, size_t in_len);
176   if (t->GetType() == "Decrypt") {
177     key_op_init = EVP_PKEY_decrypt_init;
178     key_op = EVP_PKEY_decrypt;
179   } else if (t->GetType() == "Sign") {
180     key_op_init = EVP_PKEY_sign_init;
181     key_op = EVP_PKEY_sign;
182   } else if (t->GetType() == "Verify") {
183     key_op_init = EVP_PKEY_verify_init;
184     key_op = nullptr;  // EVP_PKEY_verify is handled differently.
185   } else {
186     t->PrintLine("Unknown test '%s'", t->GetType().c_str());
187     return false;
188   }
189 
190   // Load the key.
191   const std::string &key_name = t->GetParameter();
192   if (key_map->count(key_name) == 0) {
193     t->PrintLine("Could not find key '%s'.", key_name.c_str());
194     return false;
195   }
196   EVP_PKEY *key = (*key_map)[key_name];
197 
198   std::vector<uint8_t> input, output;
199   if (!t->GetBytes(&input, "Input") ||
200       !t->GetBytes(&output, "Output")) {
201     return false;
202   }
203 
204   // Set up the EVP_PKEY_CTX.
205   ScopedEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(key, nullptr));
206   if (!ctx || !key_op_init(ctx.get())) {
207     return false;
208   }
209   if (t->HasAttribute("Digest")) {
210     const EVP_MD *digest = GetDigest(t, t->GetAttributeOrDie("Digest"));
211     if (digest == nullptr ||
212         !EVP_PKEY_CTX_set_signature_md(ctx.get(), digest)) {
213       return false;
214     }
215   }
216 
217   if (t->GetType() == "Verify") {
218     if (!EVP_PKEY_verify(ctx.get(), bssl::vector_data(&output), output.size(),
219                          bssl::vector_data(&input), input.size())) {
220       // ECDSA sometimes doesn't push an error code. Push one on the error queue
221       // so it's distinguishable from other errors.
222       ERR_put_error(ERR_LIB_USER, 0, ERR_R_EVP_LIB, __FILE__, __LINE__);
223       return false;
224     }
225     return true;
226   }
227 
228   size_t len;
229   std::vector<uint8_t> actual;
230   if (!key_op(ctx.get(), nullptr, &len, bssl::vector_data(&input),
231               input.size())) {
232     return false;
233   }
234   actual.resize(len);
235   if (!key_op(ctx.get(), bssl::vector_data(&actual), &len,
236               bssl::vector_data(&input), input.size())) {
237     return false;
238   }
239   actual.resize(len);
240   if (!t->ExpectBytesEqual(bssl::vector_data(&output), output.size(),
241                            bssl::vector_data(&actual), len)) {
242     return false;
243   }
244   return true;
245 }
246 
main(int argc,char ** argv)247 int main(int argc, char **argv) {
248   CRYPTO_library_init();
249   if (argc != 2) {
250     fprintf(stderr, "%s <test file.txt>\n", argv[0]);
251     return 1;
252   }
253 
254   KeyMap map;
255   int ret = FileTestMain(TestEVP, &map, argv[1]);
256   // TODO(davidben): When we can rely on a move-aware std::map, make KeyMap a
257   // map of ScopedEVP_PKEY instead.
258   for (const auto &pair : map) {
259     EVP_PKEY_free(pair.second);
260   }
261   return ret;
262 }
263