ENCODER: Refactor the OSSL_ENCODER API to be more like OSSL_DECODER
[openssl.git] / crypto / encode_decode / encoder_pkey.c
1 /*
2  * Copyright 2019-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "e_os.h"                /* strcasecmp on Windows */
11 #include <openssl/err.h>
12 #include <openssl/ui.h>
13 #include <openssl/params.h>
14 #include <openssl/encoder.h>
15 #include <openssl/core_names.h>
16 #include <openssl/safestack.h>
17 #include "internal/provider.h"
18 #include "internal/property.h"
19 #include "crypto/evp.h"
20 #include "encoder_local.h"
21
22 DEFINE_STACK_OF(OSSL_ENCODER)
23
24 int OSSL_ENCODER_CTX_set_cipher(OSSL_ENCODER_CTX *ctx,
25                                 const char *cipher_name,
26                                 const char *propquery)
27 {
28     OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END };
29
30     params[0] =
31         OSSL_PARAM_construct_utf8_string(OSSL_ENCODER_PARAM_CIPHER,
32                                          (void *)cipher_name, 0);
33     params[1] =
34         OSSL_PARAM_construct_utf8_string(OSSL_ENCODER_PARAM_PROPERTIES,
35                                          (void *)propquery, 0);
36
37     return OSSL_ENCODER_CTX_set_params(ctx, params);
38 }
39
40 int OSSL_ENCODER_CTX_set_passphrase(OSSL_ENCODER_CTX *ctx,
41                                     const unsigned char *kstr,
42                                     size_t klen)
43 {
44     return ossl_pw_set_passphrase(&ctx->pwdata, kstr, klen);
45 }
46
47 int OSSL_ENCODER_CTX_set_passphrase_ui(OSSL_ENCODER_CTX *ctx,
48                                        const UI_METHOD *ui_method,
49                                        void *ui_data)
50 {
51     return ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data);
52 }
53
54 int OSSL_ENCODER_CTX_set_pem_password_cb(OSSL_ENCODER_CTX *ctx,
55                                          pem_password_cb *cb, void *cbarg)
56 {
57     return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg);
58 }
59
60 int OSSL_ENCODER_CTX_set_passphrase_cb(OSSL_ENCODER_CTX *ctx,
61                                        OSSL_PASSPHRASE_CALLBACK *cb,
62                                        void *cbarg)
63 {
64     return ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg);
65 }
66
67 /*
68  * Support for OSSL_ENCODER_CTX_new_by_TYPE:
69  * finding a suitable encoder
70  */
71
72 struct collected_encoder_st {
73     const char *output_type;
74     STACK_OF(OSSL_ENCODER) *encoders;
75     int error_occured;
76 };
77
78 static void collect_encoder(OSSL_ENCODER *encoder, void *arg)
79 {
80     struct collected_encoder_st *data = arg;
81     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
82     const char *output_type = NULL;
83
84     if (data->error_occured)
85         return;
86
87     /*
88      * Ask for the output type.  If the encoder doesn't answer to that,
89      * we refuse it.
90      */
91     params[0] =
92         OSSL_PARAM_construct_utf8_ptr(OSSL_ENCODER_PARAM_OUTPUT_TYPE,
93                                       (char **)&output_type, 0);
94     if (!encoder->get_params(params)
95         || !OSSL_PARAM_modified(&params[0])
96         || output_type == NULL
97         || strcasecmp(output_type, data->output_type) != 0)
98         return;
99
100     data->error_occured = 1;         /* Assume the worst */
101
102     if (!OSSL_ENCODER_up_ref(encoder) /* ref++ */)
103         return;
104     if (sk_OSSL_ENCODER_push(data->encoders, encoder) <= 0) {
105         OSSL_ENCODER_free(encoder);  /* ref-- */
106         return;
107     }
108
109     data->error_occured = 0;         /* All is good now */
110 }
111
112 struct collected_names_st {
113     STACK_OF(OPENSSL_CSTRING) *names;
114     unsigned int error_occured:1;
115 };
116
117 static void collect_name(const char *name, void *arg)
118 {
119     struct collected_names_st *data = arg;
120
121     if (data->error_occured)
122         return;
123
124     data->error_occured = 1;         /* Assume the worst */
125
126     if (sk_OPENSSL_CSTRING_push(data->names, name) <= 0)
127         return;
128
129     data->error_occured = 0;         /* All is good now */
130 }
131
132 /*
133  * Support for OSSL_ENCODER_to_bio:
134  * writing callback for the OSSL_PARAM (the implementation doesn't have
135  * intimate knowledge of the provider side object)
136  */
137
138 struct construct_data_st {
139     const EVP_PKEY *pk;
140     int selection;
141
142     OSSL_ENCODER_INSTANCE *encoder_inst;
143     const void *obj;
144     void *constructed_obj;
145 };
146
147 static int encoder_import_cb(const OSSL_PARAM params[], void *arg)
148 {
149     struct construct_data_st *construct_data = arg;
150     OSSL_ENCODER_INSTANCE *encoder_inst = construct_data->encoder_inst;
151     OSSL_ENCODER *encoder = OSSL_ENCODER_INSTANCE_get_encoder(encoder_inst);
152     void *encoderctx = OSSL_ENCODER_INSTANCE_get_encoder_ctx(encoder_inst);
153
154     construct_data->constructed_obj =
155         encoder->import_object(encoderctx, construct_data->selection, params);
156
157     return (construct_data->constructed_obj != NULL);
158 }
159
160 static const void *
161 encoder_construct_EVP_PKEY(OSSL_ENCODER_INSTANCE *encoder_inst, void *arg)
162 {
163     struct construct_data_st *data = arg;
164
165     if (data->obj == NULL) {
166         OSSL_ENCODER *encoder =
167             OSSL_ENCODER_INSTANCE_get_encoder(encoder_inst);
168         const EVP_PKEY *pk = data->pk;
169         const OSSL_PROVIDER *k_prov = EVP_KEYMGMT_provider(pk->keymgmt);
170         const OSSL_PROVIDER *e_prov = OSSL_ENCODER_provider(encoder);
171
172         if (k_prov != e_prov) {
173             data->encoder_inst = encoder_inst;
174
175             if (!evp_keymgmt_export(pk->keymgmt, pk->keydata, data->selection,
176                                     &encoder_import_cb, data))
177                 return NULL;
178             data->obj = data->constructed_obj;
179         } else {
180             data->obj = pk->keydata;
181         }
182     }
183
184     return data->obj;
185 }
186
187 static void encoder_destruct_EVP_PKEY(void *arg)
188 {
189     struct construct_data_st *data = arg;
190
191     if (data->encoder_inst != NULL) {
192         OSSL_ENCODER *encoder =
193             OSSL_ENCODER_INSTANCE_get_encoder(data->encoder_inst);
194
195         encoder->free_object(data->constructed_obj);
196     }
197     data->constructed_obj = NULL;
198 }
199
200 /*
201  * OSSL_ENCODER_CTX_new_by_EVP_PKEY() returns a ctx with no encoder if
202  * it couldn't find a suitable encoder.  This allows a caller to detect if
203  * a suitable encoder was found, with OSSL_ENCODER_CTX_get_num_encoder(),
204  * and to use fallback methods if the result is NULL.
205  */
206 static int ossl_encoder_ctx_setup_for_EVP_PKEY(OSSL_ENCODER_CTX *ctx,
207                                                const EVP_PKEY *pkey,
208                                                int selection,
209                                                OPENSSL_CTX *libctx,
210                                                const char *propquery)
211 {
212     struct construct_data_st *data = NULL;
213     int ok = 0;
214
215     if (!ossl_assert(ctx != NULL) || !ossl_assert(pkey != NULL)) {
216         ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
217         return 0;
218     }
219
220     if (pkey->keymgmt != NULL) {
221         OSSL_ENCODER *found = NULL;
222         const OSSL_PROVIDER *desired_prov = EVP_KEYMGMT_provider(pkey->keymgmt);
223         struct collected_encoder_st encoder_data;
224         struct collected_names_st keymgmt_data;
225         int i;
226
227         if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL) {
228             ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_MALLOC_FAILURE);
229             goto err;
230         }
231
232         /*
233          * Select the encoder in two steps.  First, collect all encoders
234          * that have the correct output type, as well as all keymgmt names.
235          */
236         encoder_data.output_type = ctx->output_type;
237         encoder_data.encoders = sk_OSSL_ENCODER_new_null();
238         encoder_data.error_occured = 0;
239         keymgmt_data.names = sk_OPENSSL_CSTRING_new_null();
240         keymgmt_data.error_occured = 0;
241         if (encoder_data.encoders == NULL || keymgmt_data.names == NULL) {
242             sk_OSSL_ENCODER_free(encoder_data.encoders);
243             sk_OPENSSL_CSTRING_free(keymgmt_data.names);
244             return 0;
245         }
246         OSSL_ENCODER_do_all_provided(libctx, collect_encoder, &encoder_data);
247         EVP_KEYMGMT_names_do_all(pkey->keymgmt, collect_name, &keymgmt_data);
248
249         /*-
250          * Now we look for the most desirable encoder for our |pkey|.
251          *
252          * Encoders offer two functions:
253          *
254          * - one ('encode') that encodes a given provider-native object that
255          *   it knows intimately, so it must be from the same provider.
256          * - one ('import_object') that imports the parameters of an object
257          *   of the same type from a different provider, which is used to
258          *   create a temporary object that 'encode' can handle.
259          *
260          * It is, of course, more desirable to be able to use 'encode'
261          * directly without having to go through an export/import maneuver,
262          * but the latter allows us to have generic encoders.
263          *
264          * Of course, if |libctx| is different from |pkey|'s library context,
265          * we're going to have to do an export/import maneuvre no matter what.
266          */
267         for (i = 0; i < sk_OSSL_ENCODER_num(encoder_data.encoders); i++) {
268             OSSL_ENCODER *encoder =
269                 sk_OSSL_ENCODER_value(encoder_data.encoders, i);
270             int j;
271
272             /* Check that any of the |keymgmt| names match */
273             for (j = 0; j < sk_OPENSSL_CSTRING_num(keymgmt_data.names); j++) {
274                 const char *name =
275                     sk_OPENSSL_CSTRING_value(keymgmt_data.names, j);
276
277                 if (OSSL_ENCODER_is_a(encoder, name))
278                     break;
279             }
280
281             if (j == sk_OPENSSL_CSTRING_num(keymgmt_data.names))
282                 continue;
283
284             /* We found one!  Process it */
285             if (OSSL_ENCODER_provider(encoder) == desired_prov) {
286                 /*
287                  * We found one in the same provider as the keymgmt.  Choose
288                  * it and stop looking.
289                  */
290                 found = encoder;
291                 break;
292             }
293             if (found == NULL && encoder->import_object != NULL) {
294                 /*
295                  * We found one that's good enough.  Choose it for now, but
296                  * keep looking.
297                  */
298                 found = encoder;
299             }
300         }
301
302         if (found != NULL) {
303             (void)OSSL_ENCODER_CTX_add_encoder(ctx, found);
304         } else {
305             if (encoder_data.error_occured)
306                 ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_MALLOC_FAILURE);
307             else
308                 ERR_raise(ERR_LIB_OSSL_ENCODER,
309                           OSSL_ENCODER_R_ENCODER_NOT_FOUND);
310         }
311
312         sk_OPENSSL_CSTRING_free(keymgmt_data.names);
313         sk_OSSL_ENCODER_pop_free(encoder_data.encoders, OSSL_ENCODER_free);
314     }
315
316     if (OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0) {
317         if (!OSSL_ENCODER_CTX_set_construct(ctx, encoder_construct_EVP_PKEY)
318             || !OSSL_ENCODER_CTX_set_construct_data(ctx, data)
319             || !OSSL_ENCODER_CTX_set_cleanup(ctx, encoder_destruct_EVP_PKEY))
320             goto err;
321
322         data->pk = pkey;
323         data->selection = selection;
324
325         data = NULL;             /* Avoid it being freed */
326     }
327
328     ok = 1;
329  err:
330     if (data != NULL) {
331         OSSL_ENCODER_CTX_set_construct_data(ctx, NULL);
332         OPENSSL_free(data);
333     }
334     return ok;
335 }
336
337 OSSL_ENCODER_CTX *OSSL_ENCODER_CTX_new_by_EVP_PKEY(const EVP_PKEY *pkey,
338                                                    const char *output_type,
339                                                    int selection,
340                                                    OPENSSL_CTX *libctx,
341                                                    const char *propquery)
342 {
343     OSSL_ENCODER_CTX *ctx = NULL;
344
345     if ((ctx = OSSL_ENCODER_CTX_new()) == NULL) {
346         ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_MALLOC_FAILURE);
347         return NULL;
348     }
349     if (OSSL_ENCODER_CTX_set_output_type(ctx, output_type)
350         && OSSL_ENCODER_CTX_set_selection(ctx, selection)
351         && ossl_encoder_ctx_setup_for_EVP_PKEY(ctx, pkey, selection,
352                                                libctx, propquery)
353         && OSSL_ENCODER_CTX_add_extra(ctx, libctx, propquery))
354         return ctx;
355
356     OSSL_ENCODER_CTX_free(ctx);
357     return NULL;
358 }