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