1/*
2 * Copyright 2019-2022 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 <openssl/err.h>
11#include <openssl/ui.h>
12#include <openssl/params.h>
13#include <openssl/encoder.h>
14#include <openssl/core_names.h>
15#include <openssl/provider.h>
16#include <openssl/safestack.h>
17#include <openssl/trace.h>
18#include "internal/provider.h"
19#include "internal/property.h"
20#include "crypto/evp.h"
21#include "encoder_local.h"
22
23DEFINE_STACK_OF(OSSL_ENCODER)
24
25int OSSL_ENCODER_CTX_set_cipher(OSSL_ENCODER_CTX *ctx,
26                                const char *cipher_name,
27                                const char *propquery)
28{
29    OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END };
30
31    params[0] =
32        OSSL_PARAM_construct_utf8_string(OSSL_ENCODER_PARAM_CIPHER,
33                                         (void *)cipher_name, 0);
34    params[1] =
35        OSSL_PARAM_construct_utf8_string(OSSL_ENCODER_PARAM_PROPERTIES,
36                                         (void *)propquery, 0);
37
38    return OSSL_ENCODER_CTX_set_params(ctx, params);
39}
40
41int OSSL_ENCODER_CTX_set_passphrase(OSSL_ENCODER_CTX *ctx,
42                                    const unsigned char *kstr,
43                                    size_t klen)
44{
45    return ossl_pw_set_passphrase(&ctx->pwdata, kstr, klen);
46}
47
48int OSSL_ENCODER_CTX_set_passphrase_ui(OSSL_ENCODER_CTX *ctx,
49                                       const UI_METHOD *ui_method,
50                                       void *ui_data)
51{
52    return ossl_pw_set_ui_method(&ctx->pwdata, ui_method, ui_data);
53}
54
55int OSSL_ENCODER_CTX_set_pem_password_cb(OSSL_ENCODER_CTX *ctx,
56                                         pem_password_cb *cb, void *cbarg)
57{
58    return ossl_pw_set_pem_password_cb(&ctx->pwdata, cb, cbarg);
59}
60
61int OSSL_ENCODER_CTX_set_passphrase_cb(OSSL_ENCODER_CTX *ctx,
62                                       OSSL_PASSPHRASE_CALLBACK *cb,
63                                       void *cbarg)
64{
65    return ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg);
66}
67
68/*
69 * Support for OSSL_ENCODER_CTX_new_for_type:
70 * finding a suitable encoder
71 */
72
73struct collected_encoder_st {
74    STACK_OF(OPENSSL_CSTRING) *names;
75    const char *output_structure;
76    const char *output_type;
77
78    const OSSL_PROVIDER *keymgmt_prov;
79    OSSL_ENCODER_CTX *ctx;
80    unsigned int flag_find_same_provider:1;
81
82    int error_occurred;
83};
84
85static void collect_encoder(OSSL_ENCODER *encoder, void *arg)
86{
87    struct collected_encoder_st *data = arg;
88    size_t i, end_i;
89
90    if (data->error_occurred)
91        return;
92
93    data->error_occurred = 1;     /* Assume the worst */
94
95    if (data->names == NULL)
96        return;
97
98    end_i = sk_OPENSSL_CSTRING_num(data->names);
99    for (i = 0; i < end_i; i++) {
100        const char *name = sk_OPENSSL_CSTRING_value(data->names, i);
101        const OSSL_PROVIDER *prov = OSSL_ENCODER_get0_provider(encoder);
102        void *provctx = OSSL_PROVIDER_get0_provider_ctx(prov);
103
104        /*
105         * collect_encoder() is called in two passes, one where the encoders
106         * from the same provider as the keymgmt are looked up, and one where
107         * the other encoders are looked up.  |data->flag_find_same_provider|
108         * tells us which pass we're in.
109         */
110        if ((data->keymgmt_prov == prov) != data->flag_find_same_provider)
111            continue;
112
113        if (!OSSL_ENCODER_is_a(encoder, name)
114            || (encoder->does_selection != NULL
115                && !encoder->does_selection(provctx, data->ctx->selection))
116            || (data->keymgmt_prov != prov
117                && encoder->import_object == NULL))
118            continue;
119
120        /* Only add each encoder implementation once */
121        if (OSSL_ENCODER_CTX_add_encoder(data->ctx, encoder))
122            break;
123    }
124
125    data->error_occurred = 0;         /* All is good now */
126}
127
128struct collected_names_st {
129    STACK_OF(OPENSSL_CSTRING) *names;
130    unsigned int error_occurred:1;
131};
132
133static void collect_name(const char *name, void *arg)
134{
135    struct collected_names_st *data = arg;
136
137    if (data->error_occurred)
138        return;
139
140    data->error_occurred = 1;         /* Assume the worst */
141
142    if (sk_OPENSSL_CSTRING_push(data->names, name) <= 0)
143        return;
144
145    data->error_occurred = 0;         /* All is good now */
146}
147
148/*
149 * Support for OSSL_ENCODER_to_bio:
150 * writing callback for the OSSL_PARAM (the implementation doesn't have
151 * intimate knowledge of the provider side object)
152 */
153
154struct construct_data_st {
155    const EVP_PKEY *pk;
156    int selection;
157
158    OSSL_ENCODER_INSTANCE *encoder_inst;
159    const void *obj;
160    void *constructed_obj;
161};
162
163static int encoder_import_cb(const OSSL_PARAM params[], void *arg)
164{
165    struct construct_data_st *construct_data = arg;
166    OSSL_ENCODER_INSTANCE *encoder_inst = construct_data->encoder_inst;
167    OSSL_ENCODER *encoder = OSSL_ENCODER_INSTANCE_get_encoder(encoder_inst);
168    void *encoderctx = OSSL_ENCODER_INSTANCE_get_encoder_ctx(encoder_inst);
169
170    construct_data->constructed_obj =
171        encoder->import_object(encoderctx, construct_data->selection, params);
172
173    return (construct_data->constructed_obj != NULL);
174}
175
176static const void *
177encoder_construct_pkey(OSSL_ENCODER_INSTANCE *encoder_inst, void *arg)
178{
179    struct construct_data_st *data = arg;
180
181    if (data->obj == NULL) {
182        OSSL_ENCODER *encoder =
183            OSSL_ENCODER_INSTANCE_get_encoder(encoder_inst);
184        const EVP_PKEY *pk = data->pk;
185        const OSSL_PROVIDER *k_prov = EVP_KEYMGMT_get0_provider(pk->keymgmt);
186        const OSSL_PROVIDER *e_prov = OSSL_ENCODER_get0_provider(encoder);
187
188        if (k_prov != e_prov) {
189            data->encoder_inst = encoder_inst;
190
191            if (!evp_keymgmt_export(pk->keymgmt, pk->keydata, data->selection,
192                                    &encoder_import_cb, data))
193                return NULL;
194            data->obj = data->constructed_obj;
195        } else {
196            data->obj = pk->keydata;
197        }
198    }
199
200    return data->obj;
201}
202
203static void encoder_destruct_pkey(void *arg)
204{
205    struct construct_data_st *data = arg;
206
207    if (data->encoder_inst != NULL) {
208        OSSL_ENCODER *encoder =
209            OSSL_ENCODER_INSTANCE_get_encoder(data->encoder_inst);
210
211        encoder->free_object(data->constructed_obj);
212    }
213    data->constructed_obj = NULL;
214}
215
216/*
217 * OSSL_ENCODER_CTX_new_for_pkey() returns a ctx with no encoder if
218 * it couldn't find a suitable encoder.  This allows a caller to detect if
219 * a suitable encoder was found, with OSSL_ENCODER_CTX_get_num_encoder(),
220 * and to use fallback methods if the result is NULL.
221 */
222static int ossl_encoder_ctx_setup_for_pkey(OSSL_ENCODER_CTX *ctx,
223                                           const EVP_PKEY *pkey,
224                                           int selection,
225                                           const char *propquery)
226{
227    struct construct_data_st *data = NULL;
228    const OSSL_PROVIDER *prov = NULL;
229    OSSL_LIB_CTX *libctx = NULL;
230    int ok = 0;
231
232    if (!ossl_assert(ctx != NULL) || !ossl_assert(pkey != NULL)) {
233        ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
234        return 0;
235    }
236
237    if (evp_pkey_is_provided(pkey)) {
238        prov = EVP_KEYMGMT_get0_provider(pkey->keymgmt);
239        libctx = ossl_provider_libctx(prov);
240    }
241
242    if (pkey->keymgmt != NULL) {
243        struct collected_encoder_st encoder_data;
244        struct collected_names_st keymgmt_data;
245
246        if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL) {
247            ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_MALLOC_FAILURE);
248            goto err;
249        }
250
251        /*
252         * Select the first encoder implementations in two steps.
253         * First, collect the keymgmt names, then the encoders that match.
254         */
255        keymgmt_data.names = sk_OPENSSL_CSTRING_new_null();
256        if (keymgmt_data.names == NULL) {
257            ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_MALLOC_FAILURE);
258            goto err;
259        }
260
261        keymgmt_data.error_occurred = 0;
262        EVP_KEYMGMT_names_do_all(pkey->keymgmt, collect_name, &keymgmt_data);
263        if (keymgmt_data.error_occurred) {
264            sk_OPENSSL_CSTRING_free(keymgmt_data.names);
265            goto err;
266        }
267
268        encoder_data.names = keymgmt_data.names;
269        encoder_data.output_type = ctx->output_type;
270        encoder_data.output_structure = ctx->output_structure;
271        encoder_data.error_occurred = 0;
272        encoder_data.keymgmt_prov = prov;
273        encoder_data.ctx = ctx;
274
275        /*
276         * Place the encoders with the a different provider as the keymgmt
277         * last (the chain is processed in reverse order)
278         */
279        encoder_data.flag_find_same_provider = 0;
280        OSSL_ENCODER_do_all_provided(libctx, collect_encoder, &encoder_data);
281
282        /*
283         * Place the encoders with the same provider as the keymgmt first
284         * (the chain is processed in reverse order)
285         */
286        encoder_data.flag_find_same_provider = 1;
287        OSSL_ENCODER_do_all_provided(libctx, collect_encoder, &encoder_data);
288
289        sk_OPENSSL_CSTRING_free(keymgmt_data.names);
290        if (encoder_data.error_occurred) {
291            ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_MALLOC_FAILURE);
292            goto err;
293        }
294    }
295
296    if (data != NULL && OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0) {
297        if (!OSSL_ENCODER_CTX_set_construct(ctx, encoder_construct_pkey)
298            || !OSSL_ENCODER_CTX_set_construct_data(ctx, data)
299            || !OSSL_ENCODER_CTX_set_cleanup(ctx, encoder_destruct_pkey))
300            goto err;
301
302        data->pk = pkey;
303        data->selection = selection;
304
305        data = NULL;             /* Avoid it being freed */
306    }
307
308    ok = 1;
309 err:
310    if (data != NULL) {
311        OSSL_ENCODER_CTX_set_construct_data(ctx, NULL);
312        OPENSSL_free(data);
313    }
314    return ok;
315}
316
317OSSL_ENCODER_CTX *OSSL_ENCODER_CTX_new_for_pkey(const EVP_PKEY *pkey,
318                                                int selection,
319                                                const char *output_type,
320                                                const char *output_struct,
321                                                const char *propquery)
322{
323    OSSL_ENCODER_CTX *ctx = NULL;
324    OSSL_LIB_CTX *libctx = NULL;
325
326    if (pkey == NULL) {
327        ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_NULL_PARAMETER);
328        return NULL;
329    }
330
331    if (!evp_pkey_is_assigned(pkey)) {
332        ERR_raise_data(ERR_LIB_OSSL_ENCODER, ERR_R_PASSED_INVALID_ARGUMENT,
333                       "The passed EVP_PKEY must be assigned a key");
334        return NULL;
335    }
336
337    if ((ctx = OSSL_ENCODER_CTX_new()) == NULL) {
338        ERR_raise(ERR_LIB_OSSL_ENCODER, ERR_R_MALLOC_FAILURE);
339        return NULL;
340    }
341
342    if (evp_pkey_is_provided(pkey)) {
343        const OSSL_PROVIDER *prov = EVP_KEYMGMT_get0_provider(pkey->keymgmt);
344
345        libctx = ossl_provider_libctx(prov);
346    }
347
348    OSSL_TRACE_BEGIN(ENCODER) {
349        BIO_printf(trc_out,
350                   "(ctx %p) Looking for %s encoders with selection %d\n",
351                   (void *)ctx, EVP_PKEY_get0_type_name(pkey), selection);
352        BIO_printf(trc_out, "    output type: %s, output structure: %s\n",
353                   output_type, output_struct);
354    } OSSL_TRACE_END(ENCODER);
355
356    if (OSSL_ENCODER_CTX_set_output_type(ctx, output_type)
357        && (output_struct == NULL
358            || OSSL_ENCODER_CTX_set_output_structure(ctx, output_struct))
359        && OSSL_ENCODER_CTX_set_selection(ctx, selection)
360        && ossl_encoder_ctx_setup_for_pkey(ctx, pkey, selection, propquery)
361        && OSSL_ENCODER_CTX_add_extra(ctx, libctx, propquery)) {
362        OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
363        int save_parameters = pkey->save_parameters;
364
365        params[0] = OSSL_PARAM_construct_int(OSSL_ENCODER_PARAM_SAVE_PARAMETERS,
366                                             &save_parameters);
367        /* ignoring error as this is only auxiliary parameter */
368        (void)OSSL_ENCODER_CTX_set_params(ctx, params);
369
370        OSSL_TRACE_BEGIN(ENCODER) {
371            BIO_printf(trc_out, "(ctx %p) Got %d encoders\n",
372                       (void *)ctx, OSSL_ENCODER_CTX_get_num_encoders(ctx));
373        } OSSL_TRACE_END(ENCODER);
374        return ctx;
375    }
376
377    OSSL_ENCODER_CTX_free(ctx);
378    return NULL;
379}
380