Coverage Report

Created: 2025-07-23 06:08

/src/openssl/crypto/pem/pem_pkey.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 1995-2024 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
/*
11
 * We need to use some deprecated APIs
12
 */
13
#include "internal/deprecated.h"
14
15
#include <stdio.h>
16
#include <openssl/buffer.h>
17
#include <openssl/objects.h>
18
#include <openssl/evp.h>
19
#include <openssl/x509.h>
20
#include <openssl/pkcs12.h>
21
#include <openssl/pem.h>
22
#include <openssl/engine.h>
23
#include <openssl/dh.h>
24
#include <openssl/decoder.h>
25
#include <openssl/ui.h>
26
#include "internal/cryptlib.h"
27
#include "internal/passphrase.h"
28
#include "crypto/asn1.h"
29
#include "crypto/x509.h"
30
#include "crypto/evp.h"
31
#include "pem_local.h"
32
33
int ossl_pem_check_suffix(const char *pem_str, const char *suffix);
34
35
static EVP_PKEY *pem_read_bio_key_decoder(BIO *bp, EVP_PKEY **x,
36
                                          pem_password_cb *cb, void *u,
37
                                          OSSL_LIB_CTX *libctx,
38
                                          const char *propq,
39
                                          int selection)
40
0
{
41
0
    EVP_PKEY *pkey = NULL;
42
0
    OSSL_DECODER_CTX *dctx = NULL;
43
0
    int pos, newpos;
44
45
0
    if ((pos = BIO_tell(bp)) < 0)
46
        /* We can depend on BIO_tell() thanks to the BIO_f_readbuffer() */
47
0
        return NULL;
48
49
0
    dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "PEM", NULL, NULL,
50
0
                                         selection, libctx, propq);
51
52
0
    if (dctx == NULL)
53
0
        return NULL;
54
55
0
    if (cb == NULL)
56
0
        cb = PEM_def_callback;
57
58
0
    if (!OSSL_DECODER_CTX_set_pem_password_cb(dctx, cb, u))
59
0
        goto err;
60
61
0
    ERR_set_mark();
62
0
    while (!OSSL_DECODER_from_bio(dctx, bp) || pkey == NULL)
63
0
        if (BIO_eof(bp) != 0 || (newpos = BIO_tell(bp)) < 0 || newpos <= pos) {
64
0
            ERR_clear_last_mark();
65
0
            goto err;
66
0
        } else {
67
0
            if (ERR_GET_REASON(ERR_peek_error()) == ERR_R_UNSUPPORTED) {
68
                /* unsupported PEM data, try again */
69
0
                ERR_pop_to_mark();
70
0
                ERR_set_mark();
71
0
            } else {
72
                /* other error, bail out */
73
0
                ERR_clear_last_mark();
74
0
                goto err;
75
0
            }
76
0
            pos = newpos;
77
0
        }
78
0
    ERR_pop_to_mark();
79
80
    /* if we were asked for private key, the public key is optional */
81
0
    if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
82
0
        selection = selection & ~OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
83
84
0
    if (!evp_keymgmt_util_has(pkey, selection)) {
85
0
        EVP_PKEY_free(pkey);
86
0
        pkey = NULL;
87
0
        ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
88
0
        goto err;
89
0
    }
90
91
0
    if (x != NULL) {
92
0
        EVP_PKEY_free(*x);
93
0
        *x = pkey;
94
0
    }
95
96
0
 err:
97
0
    OSSL_DECODER_CTX_free(dctx);
98
0
    return pkey;
99
0
}
100
101
static EVP_PKEY *pem_read_bio_key_legacy(BIO *bp, EVP_PKEY **x,
102
                                         pem_password_cb *cb, void *u,
103
                                         OSSL_LIB_CTX *libctx,
104
                                         const char *propq,
105
                                         int selection)
106
0
{
107
0
    char *nm = NULL;
108
0
    const unsigned char *p = NULL;
109
0
    unsigned char *data = NULL;
110
0
    long len;
111
0
    int slen;
112
0
    EVP_PKEY *ret = NULL;
113
114
0
    ERR_set_mark();  /* not interested in PEM read errors */
115
0
    if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
116
0
        if (!PEM_bytes_read_bio_secmem(&data, &len, &nm,
117
0
                                       PEM_STRING_EVP_PKEY,
118
0
                                       bp, cb, u)) {
119
0
            ERR_pop_to_mark();
120
0
            return NULL;
121
0
         }
122
0
    } else {
123
0
        const char *pem_string = PEM_STRING_PARAMETERS;
124
125
0
        if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
126
0
            pem_string = PEM_STRING_PUBLIC;
127
0
        if (!PEM_bytes_read_bio(&data, &len, &nm,
128
0
                                pem_string,
129
0
                                bp, cb, u)) {
130
0
            ERR_pop_to_mark();
131
0
            return NULL;
132
0
        }
133
0
    }
134
0
    ERR_clear_last_mark();
135
0
    p = data;
136
137
0
    if (strcmp(nm, PEM_STRING_PKCS8INF) == 0) {
138
0
        PKCS8_PRIV_KEY_INFO *p8inf;
139
140
0
        if ((p8inf = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, len)) == NULL)
141
0
            goto p8err;
142
0
        ret = evp_pkcs82pkey_legacy(p8inf, libctx, propq);
143
0
        if (x != NULL) {
144
0
            EVP_PKEY_free(*x);
145
0
            *x = ret;
146
0
        }
147
0
        PKCS8_PRIV_KEY_INFO_free(p8inf);
148
0
    } else if (strcmp(nm, PEM_STRING_PKCS8) == 0) {
149
0
        PKCS8_PRIV_KEY_INFO *p8inf;
150
0
        X509_SIG *p8;
151
0
        int klen;
152
0
        char psbuf[PEM_BUFSIZE];
153
154
0
        if ((p8 = d2i_X509_SIG(NULL, &p, len)) == NULL)
155
0
            goto p8err;
156
0
        if (cb != NULL)
157
0
            klen = cb(psbuf, PEM_BUFSIZE, 0, u);
158
0
        else
159
0
            klen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u);
160
0
        if (klen < 0) {
161
0
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_PASSWORD_READ);
162
0
            X509_SIG_free(p8);
163
0
            goto err;
164
0
        }
165
0
        p8inf = PKCS8_decrypt(p8, psbuf, klen);
166
0
        X509_SIG_free(p8);
167
0
        OPENSSL_cleanse(psbuf, klen);
168
0
        if (p8inf == NULL)
169
0
            goto p8err;
170
0
        ret = evp_pkcs82pkey_legacy(p8inf, libctx, propq);
171
0
        if (x != NULL) {
172
0
            EVP_PKEY_free(*x);
173
0
            *x = ret;
174
0
        }
175
0
        PKCS8_PRIV_KEY_INFO_free(p8inf);
176
0
    } else if ((slen = ossl_pem_check_suffix(nm, "PRIVATE KEY")) > 0) {
177
0
        const EVP_PKEY_ASN1_METHOD *ameth;
178
0
        ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
179
0
        if (ameth == NULL || ameth->old_priv_decode == NULL)
180
0
            goto p8err;
181
0
        ret = ossl_d2i_PrivateKey_legacy(ameth->pkey_id, x, &p, len, libctx,
182
0
                                         propq);
183
0
    } else if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) == 0
184
0
               && (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
185
        /* Trying legacy PUBKEY decoding only if we do not want private key. */
186
0
        ret = ossl_d2i_PUBKEY_legacy(x, &p, len);
187
0
    } else if ((selection & EVP_PKEY_KEYPAIR) == 0
188
0
               && (slen = ossl_pem_check_suffix(nm, "PARAMETERS")) > 0) {
189
        /* Trying legacy params decoding only if we do not want a key. */
190
0
        ret = EVP_PKEY_new();
191
0
        if (ret == NULL)
192
0
            goto err;
193
0
        if (!EVP_PKEY_set_type_str(ret, nm, slen)
194
0
            || !ret->ameth->param_decode
195
0
            || !ret->ameth->param_decode(ret, &p, len)) {
196
0
            EVP_PKEY_free(ret);
197
0
            ret = NULL;
198
0
            goto err;
199
0
        }
200
0
        if (x) {
201
0
            EVP_PKEY_free(*x);
202
0
            *x = ret;
203
0
        }
204
0
    }
205
206
0
 p8err:
207
0
    if (ret == NULL && ERR_peek_last_error() == 0)
208
        /* ensure some error is reported but do not hide the real one */
209
0
        ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB);
210
0
 err:
211
0
    OPENSSL_secure_free(nm);
212
0
    OPENSSL_secure_clear_free(data, len);
213
0
    return ret;
214
0
}
215
216
static EVP_PKEY *pem_read_bio_key(BIO *bp, EVP_PKEY **x,
217
                                  pem_password_cb *cb, void *u,
218
                                  OSSL_LIB_CTX *libctx,
219
                                  const char *propq,
220
                                  int selection)
221
0
{
222
0
    EVP_PKEY *ret = NULL;
223
0
    BIO *new_bio = NULL;
224
0
    int pos;
225
0
    struct ossl_passphrase_data_st pwdata = { 0 };
226
227
0
    if ((pos = BIO_tell(bp)) < 0) {
228
0
        new_bio = BIO_new(BIO_f_readbuffer());
229
0
        if (new_bio == NULL)
230
0
            return NULL;
231
0
        bp = BIO_push(new_bio, bp);
232
0
        pos = BIO_tell(bp);
233
0
    }
234
235
0
    if (cb == NULL)
236
0
        cb = PEM_def_callback;
237
238
0
    if (!ossl_pw_set_pem_password_cb(&pwdata, cb, u)
239
0
        || !ossl_pw_enable_passphrase_caching(&pwdata))
240
0
        goto err;
241
242
0
    ERR_set_mark();
243
0
    ret = pem_read_bio_key_decoder(bp, x, ossl_pw_pem_password, &pwdata,
244
0
                                   libctx, propq, selection);
245
0
    if (ret == NULL
246
0
        && (BIO_seek(bp, pos) < 0
247
0
            || (ret = pem_read_bio_key_legacy(bp, x,
248
0
                                              ossl_pw_pem_password, &pwdata,
249
0
                                              libctx, propq,
250
0
                                              selection)) == NULL))
251
0
        ERR_clear_last_mark();
252
0
    else
253
0
        ERR_pop_to_mark();
254
255
0
 err:
256
0
    ossl_pw_clear_passphrase_data(&pwdata);
257
0
    if (new_bio != NULL) {
258
0
        BIO_pop(new_bio);
259
0
        BIO_free(new_bio);
260
0
    }
261
0
    return ret;
262
0
}
263
264
EVP_PKEY *PEM_read_bio_PUBKEY_ex(BIO *bp, EVP_PKEY **x,
265
                                 pem_password_cb *cb, void *u,
266
                                 OSSL_LIB_CTX *libctx, const char *propq)
267
0
{
268
0
    return pem_read_bio_key(bp, x, cb, u, libctx, propq,
269
0
                            EVP_PKEY_PUBLIC_KEY);
270
0
}
271
272
EVP_PKEY *PEM_read_bio_PUBKEY(BIO *bp, EVP_PKEY **x, pem_password_cb *cb,
273
                              void *u)
274
0
{
275
0
    return PEM_read_bio_PUBKEY_ex(bp, x, cb, u, NULL, NULL);
276
0
}
277
278
#ifndef OPENSSL_NO_STDIO
279
EVP_PKEY *PEM_read_PUBKEY_ex(FILE *fp, EVP_PKEY **x,
280
                             pem_password_cb *cb, void *u,
281
                             OSSL_LIB_CTX *libctx, const char *propq)
282
0
{
283
0
    BIO *b;
284
0
    EVP_PKEY *ret;
285
286
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
287
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
288
0
        return 0;
289
0
    }
290
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
291
0
    ret = PEM_read_bio_PUBKEY_ex(b, x, cb, u, libctx, propq);
292
0
    BIO_free(b);
293
0
    return ret;
294
0
}
295
296
EVP_PKEY *PEM_read_PUBKEY(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u)
297
0
{
298
0
    return PEM_read_PUBKEY_ex(fp, x, cb, u, NULL, NULL);
299
0
}
300
#endif
301
302
EVP_PKEY *PEM_read_bio_PrivateKey_ex(BIO *bp, EVP_PKEY **x,
303
                                     pem_password_cb *cb, void *u,
304
                                     OSSL_LIB_CTX *libctx, const char *propq)
305
0
{
306
0
    return pem_read_bio_key(bp, x, cb, u, libctx, propq,
307
                            /* we also want the public key, if available */
308
0
                            EVP_PKEY_KEYPAIR);
309
0
}
310
311
EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb,
312
                                  void *u)
313
0
{
314
0
    return PEM_read_bio_PrivateKey_ex(bp, x, cb, u, NULL, NULL);
315
0
}
316
317
PEM_write_cb_ex_fnsig(PrivateKey, EVP_PKEY, BIO, write_bio)
318
0
{
319
0
    IMPLEMENT_PEM_provided_write_body_vars(pkey, PrivateKey, propq);
320
321
0
    IMPLEMENT_PEM_provided_write_body_pass();
322
0
    IMPLEMENT_PEM_provided_write_body_main(pkey, bio);
323
324
0
 legacy:
325
0
    if (x != NULL && (x->ameth == NULL || x->ameth->priv_encode != NULL))
326
0
        return PEM_write_bio_PKCS8PrivateKey(out, x, enc,
327
0
                                             (const char *)kstr, klen, cb, u);
328
0
    return PEM_write_bio_PrivateKey_traditional(out, x, enc, kstr, klen, cb, u);
329
0
}
330
331
PEM_write_cb_fnsig(PrivateKey, EVP_PKEY, BIO, write_bio)
332
0
{
333
0
    return PEM_write_bio_PrivateKey_ex(out, x, enc, kstr, klen, cb, u,
334
0
                                       NULL, NULL);
335
0
}
336
337
/*
338
 * Note: there is no way to tell a provided pkey encoder to use "traditional"
339
 * encoding.  Therefore, if the pkey is provided, we try to take a copy
340
 */
341
int PEM_write_bio_PrivateKey_traditional(BIO *bp, const EVP_PKEY *x,
342
                                         const EVP_CIPHER *enc,
343
                                         const unsigned char *kstr, int klen,
344
                                         pem_password_cb *cb, void *u)
345
0
{
346
0
    char pem_str[80];
347
0
    EVP_PKEY *copy = NULL;
348
0
    int ret;
349
350
0
    if (x == NULL)
351
0
        return 0;
352
353
0
    if (evp_pkey_is_assigned(x)
354
0
        && evp_pkey_is_provided(x)
355
0
        && evp_pkey_copy_downgraded(&copy, x))
356
0
        x = copy;
357
358
0
    if (x->ameth == NULL || x->ameth->old_priv_encode == NULL) {
359
0
        ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
360
0
        EVP_PKEY_free(copy);
361
0
        return 0;
362
0
    }
363
0
    BIO_snprintf(pem_str, 80, "%s PRIVATE KEY", x->ameth->pem_str);
364
0
    ret = PEM_ASN1_write_bio((i2d_of_void *)i2d_PrivateKey,
365
0
                             pem_str, bp, x, enc, kstr, klen, cb, u);
366
367
0
    EVP_PKEY_free(copy);
368
0
    return ret;
369
0
}
370
371
static int no_password_cb(char *buf, int num, int rwflag, void *userdata)
372
0
{
373
0
    return -1;
374
0
}
375
376
EVP_PKEY *PEM_read_bio_Parameters_ex(BIO *bp, EVP_PKEY **x,
377
                                     OSSL_LIB_CTX *libctx, const char *propq)
378
0
{
379
    /*
380
     * PEM_read_bio_Parameters(_ex) should never ask for a password. Any attempt
381
     * to get a password just fails.
382
     */
383
0
    return pem_read_bio_key(bp, x, no_password_cb, NULL, libctx, propq,
384
0
                            EVP_PKEY_KEY_PARAMETERS);
385
0
}
386
387
EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x)
388
0
{
389
0
    return PEM_read_bio_Parameters_ex(bp, x, NULL, NULL);
390
0
}
391
392
PEM_write_fnsig(Parameters, EVP_PKEY, BIO, write_bio)
393
0
{
394
0
    char pem_str[80];
395
0
    IMPLEMENT_PEM_provided_write_body_vars(pkey, Parameters, NULL);
396
397
0
    IMPLEMENT_PEM_provided_write_body_main(pkey, bio);
398
399
0
 legacy:
400
0
    if (!x->ameth || !x->ameth->param_encode)
401
0
        return 0;
402
403
0
    BIO_snprintf(pem_str, 80, "%s PARAMETERS", x->ameth->pem_str);
404
0
    return PEM_ASN1_write_bio((i2d_of_void *)x->ameth->param_encode,
405
0
                              pem_str, out, x, NULL, NULL, 0, 0, NULL);
406
0
}
407
408
#ifndef OPENSSL_NO_STDIO
409
EVP_PKEY *PEM_read_PrivateKey_ex(FILE *fp, EVP_PKEY **x, pem_password_cb *cb,
410
                                 void *u, OSSL_LIB_CTX *libctx,
411
                                 const char *propq)
412
0
{
413
0
    BIO *b;
414
0
    EVP_PKEY *ret;
415
416
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
417
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
418
0
        return 0;
419
0
    }
420
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
421
0
    ret = PEM_read_bio_PrivateKey_ex(b, x, cb, u, libctx, propq);
422
0
    BIO_free(b);
423
0
    return ret;
424
0
}
425
426
EVP_PKEY *PEM_read_PrivateKey(FILE *fp, EVP_PKEY **x, pem_password_cb *cb,
427
                              void *u)
428
0
{
429
0
    return PEM_read_PrivateKey_ex(fp, x, cb, u, NULL, NULL);
430
0
}
431
432
PEM_write_cb_ex_fnsig(PrivateKey, EVP_PKEY, FILE, write)
433
0
{
434
0
    BIO *b;
435
0
    int ret;
436
437
0
    if ((b = BIO_new_fp(out, BIO_NOCLOSE)) == NULL) {
438
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
439
0
        return 0;
440
0
    }
441
0
    ret = PEM_write_bio_PrivateKey_ex(b, x, enc, kstr, klen, cb, u,
442
0
                                      libctx, propq);
443
0
    BIO_free(b);
444
0
    return ret;
445
0
}
446
447
PEM_write_cb_fnsig(PrivateKey, EVP_PKEY, FILE, write)
448
0
{
449
0
    return PEM_write_PrivateKey_ex(out, x, enc, kstr, klen, cb, u, NULL, NULL);
450
0
}
451
#endif