Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl30/crypto/pem/pvkfmt.c
Line
Count
Source
1
/*
2
 * Copyright 2005-2021 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
 * Support for PVK format keys and related structures (such a PUBLICKEYBLOB
12
 * and PRIVATEKEYBLOB).
13
 */
14
15
/*
16
 * RSA and DSA low level APIs are deprecated for public use, but still ok for
17
 * internal use.
18
 */
19
#include "internal/deprecated.h"
20
21
#include <openssl/pem.h>
22
#include <openssl/rand.h>
23
#include <openssl/bn.h>
24
#include <openssl/dsa.h>
25
#include <openssl/rsa.h>
26
#include "internal/cryptlib.h"
27
#include "crypto/pem.h"
28
#include "crypto/evp.h"
29
30
/*
31
 * Utility function: read a DWORD (4 byte unsigned integer) in little endian
32
 * format
33
 */
34
35
static unsigned int read_ledword(const unsigned char **in)
36
53.9k
{
37
53.9k
    const unsigned char *p = *in;
38
53.9k
    unsigned int ret;
39
40
53.9k
    ret = (unsigned int)*p++;
41
53.9k
    ret |= (unsigned int)*p++ << 8;
42
53.9k
    ret |= (unsigned int)*p++ << 16;
43
53.9k
    ret |= (unsigned int)*p++ << 24;
44
53.9k
    *in = p;
45
53.9k
    return ret;
46
53.9k
}
47
48
/*
49
 * Read a BIGNUM in little endian format. The docs say that this should take
50
 * up bitlen/8 bytes.
51
 */
52
53
static int read_lebn(const unsigned char **in, unsigned int nbyte, BIGNUM **r)
54
18.0k
{
55
18.0k
    *r = BN_lebin2bn(*in, nbyte, NULL);
56
18.0k
    if (*r == NULL)
57
0
        return 0;
58
18.0k
    *in += nbyte;
59
18.0k
    return 1;
60
18.0k
}
61
62
/*
63
 * Create an EVP_PKEY from a type specific key.
64
 * This takes ownership of |key|, as long as the |evp_type| is acceptable
65
 * (EVP_PKEY_RSA or EVP_PKEY_DSA), even if the resulting EVP_PKEY wasn't
66
 * created.
67
 */
68
#define isdss_to_evp_type(isdss)                           \
69
0
    (isdss == 0 ? EVP_PKEY_RSA : isdss == 1 ? EVP_PKEY_DSA \
70
0
                                            : EVP_PKEY_NONE)
71
static EVP_PKEY *evp_pkey_new0_key(void *key, int evp_type)
72
0
{
73
0
    EVP_PKEY *pkey = NULL;
74
75
    /*
76
     * It's assumed that if |key| is NULL, something went wrong elsewhere
77
     * and suitable errors are already reported.
78
     */
79
0
    if (key == NULL)
80
0
        return NULL;
81
82
0
    if (!ossl_assert(evp_type == EVP_PKEY_RSA || evp_type == EVP_PKEY_DSA)) {
83
0
        ERR_raise(ERR_LIB_PEM, ERR_R_INTERNAL_ERROR);
84
0
        return NULL;
85
0
    }
86
87
0
    if ((pkey = EVP_PKEY_new()) != NULL) {
88
0
        switch (evp_type) {
89
0
        case EVP_PKEY_RSA:
90
0
            if (EVP_PKEY_set1_RSA(pkey, key))
91
0
                break;
92
0
            EVP_PKEY_free(pkey);
93
0
            pkey = NULL;
94
0
            break;
95
0
#ifndef OPENSSL_NO_DSA
96
0
        case EVP_PKEY_DSA:
97
0
            if (EVP_PKEY_set1_DSA(pkey, key))
98
0
                break;
99
0
            EVP_PKEY_free(pkey);
100
0
            pkey = NULL;
101
0
            break;
102
0
#endif
103
0
        }
104
0
    }
105
106
0
    switch (evp_type) {
107
0
    case EVP_PKEY_RSA:
108
0
        RSA_free(key);
109
0
        break;
110
0
#ifndef OPENSSL_NO_DSA
111
0
    case EVP_PKEY_DSA:
112
0
        DSA_free(key);
113
0
        break;
114
0
#endif
115
0
    }
116
117
0
    if (pkey == NULL)
118
0
        ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
119
0
    return pkey;
120
0
}
121
122
/* Convert private key blob to EVP_PKEY: RSA and DSA keys supported */
123
124
6.18k
#define MS_PUBLICKEYBLOB 0x6
125
4.45k
#define MS_PRIVATEKEYBLOB 0x7
126
8.92k
#define MS_RSA1MAGIC 0x31415352L
127
10.0k
#define MS_RSA2MAGIC 0x32415352L
128
1.92k
#define MS_DSS1MAGIC 0x31535344L
129
3.75k
#define MS_DSS2MAGIC 0x32535344L
130
131
0
#define MS_KEYALG_RSA_KEYX 0xa400
132
0
#define MS_KEYALG_DSS_SIGN 0x2200
133
134
0
#define MS_KEYTYPE_KEYX 0x1
135
0
#define MS_KEYTYPE_SIGN 0x2
136
137
/* The PVK file magic number: seems to spell out "bobsfile", who is Bob? */
138
9.27k
#define MS_PVKMAGIC 0xb0b5f11eL
139
/* Salt length for PVK files */
140
0
#define PVK_SALTLEN 0x10
141
/* Maximum length in PVK header */
142
990
#define PVK_MAX_KEYLEN 102400
143
/* Maximum salt length */
144
421
#define PVK_MAX_SALTLEN 10240
145
146
/*
147
 * Read the MSBLOB header and get relevant data from it.
148
 *
149
 * |pisdss| and |pispub| have a double role, as they can be used for
150
 * discovery as well as to check the the blob meets expectations.
151
 * |*pisdss| is the indicator for whether the key is a DSA key or not.
152
 * |*pispub| is the indicator for whether the key is public or not.
153
 * In both cases, the following input values apply:
154
 *
155
 * 0    Expected to not be what the variable indicates.
156
 * 1    Expected to be what the variable indicates.
157
 * -1   No expectations, this function will assign 0 or 1 depending on
158
 *      header data.
159
 */
160
int ossl_do_blob_header(const unsigned char **in, unsigned int length,
161
    unsigned int *pmagic, unsigned int *pbitlen,
162
    int *pisdss, int *pispub)
163
32.7k
{
164
32.7k
    const unsigned char *p = *in;
165
166
32.7k
    if (length < 16)
167
13
        return 0;
168
    /* bType */
169
32.6k
    switch (*p) {
170
6.18k
    case MS_PUBLICKEYBLOB:
171
6.18k
        if (*pispub == 0) {
172
7
            ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_PRIVATE_KEY_BLOB);
173
7
            return 0;
174
7
        }
175
6.17k
        *pispub = 1;
176
6.17k
        break;
177
178
4.45k
    case MS_PRIVATEKEYBLOB:
179
4.45k
        if (*pispub == 1) {
180
0
            ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_PUBLIC_KEY_BLOB);
181
0
            return 0;
182
0
        }
183
4.45k
        *pispub = 0;
184
4.45k
        break;
185
186
22.0k
    default:
187
22.0k
        return 0;
188
32.6k
    }
189
10.6k
    p++;
190
    /* Version */
191
10.6k
    if (*p++ != 0x2) {
192
243
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_VERSION_NUMBER);
193
243
        return 0;
194
243
    }
195
    /* Ignore reserved, aiKeyAlg */
196
10.3k
    p += 6;
197
10.3k
    *pmagic = read_ledword(&p);
198
10.3k
    *pbitlen = read_ledword(&p);
199
200
    /* Consistency check for private vs public */
201
10.3k
    switch (*pmagic) {
202
966
    case MS_DSS1MAGIC:
203
4.94k
    case MS_RSA1MAGIC:
204
4.94k
        if (*pispub == 0) {
205
14
            ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_PRIVATE_KEY_BLOB);
206
14
            return 0;
207
14
        }
208
4.93k
        break;
209
210
4.93k
    case MS_DSS2MAGIC:
211
3.73k
    case MS_RSA2MAGIC:
212
3.73k
        if (*pispub == 1) {
213
10
            ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_PUBLIC_KEY_BLOB);
214
10
            return 0;
215
10
        }
216
3.72k
        break;
217
218
3.72k
    default:
219
1.70k
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_MAGIC_NUMBER);
220
1.70k
        return -1;
221
10.3k
    }
222
223
    /* Check that we got the expected type */
224
8.65k
    switch (*pmagic) {
225
962
    case MS_DSS1MAGIC:
226
2.35k
    case MS_DSS2MAGIC:
227
2.35k
        if (*pisdss == 0) {
228
14
            ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_DSS_KEY_BLOB);
229
14
            return 0;
230
14
        }
231
2.34k
        *pisdss = 1;
232
2.34k
        break;
233
3.97k
    case MS_RSA1MAGIC:
234
6.30k
    case MS_RSA2MAGIC:
235
6.30k
        if (*pisdss == 1) {
236
30
            ERR_raise(ERR_LIB_PEM, PEM_R_EXPECTING_RSA_KEY_BLOB);
237
30
            return 0;
238
30
        }
239
6.27k
        *pisdss = 0;
240
6.27k
        break;
241
242
0
    default:
243
0
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_MAGIC_NUMBER);
244
0
        return -1;
245
8.65k
    }
246
8.61k
    *in = p;
247
8.61k
    return 1;
248
8.65k
}
249
250
unsigned int ossl_blob_length(unsigned bitlen, int isdss, int ispub)
251
5.40k
{
252
5.40k
    unsigned int nbyte = (bitlen + 7) >> 3;
253
5.40k
    unsigned int hnbyte = (bitlen + 15) >> 4;
254
255
5.40k
    if (isdss) {
256
257
        /*
258
         * Expected length: 20 for q + 3 components bitlen each + 24 for seed
259
         * structure.
260
         */
261
2.24k
        if (ispub)
262
911
            return 44 + 3 * nbyte;
263
        /*
264
         * Expected length: 20 for q, priv, 2 bitlen components + 24 for seed
265
         * structure.
266
         */
267
1.33k
        else
268
1.33k
            return 64 + 2 * nbyte;
269
3.16k
    } else {
270
        /* Expected length: 4 for 'e' + 'n' */
271
3.16k
        if (ispub)
272
1.98k
            return 4 + nbyte;
273
1.17k
        else
274
            /*
275
             * Expected length: 4 for 'e' and 7 other components. 2
276
             * components are bitlen size, 5 are bitlen/2
277
             */
278
1.17k
            return 4 + 2 * nbyte + 5 * hnbyte;
279
3.16k
    }
280
5.40k
}
281
282
static void *do_b2i_key(const unsigned char **in, unsigned int length,
283
    int *isdss, int *ispub)
284
172
{
285
172
    const unsigned char *p = *in;
286
172
    unsigned int bitlen, magic;
287
172
    void *key = NULL;
288
289
172
    if (ossl_do_blob_header(&p, length, &magic, &bitlen, isdss, ispub) <= 0) {
290
85
        ERR_raise(ERR_LIB_PEM, PEM_R_KEYBLOB_HEADER_PARSE_ERROR);
291
85
        return NULL;
292
85
    }
293
87
    length -= 16;
294
87
    if (length < ossl_blob_length(bitlen, *isdss, *ispub)) {
295
67
        ERR_raise(ERR_LIB_PEM, PEM_R_KEYBLOB_TOO_SHORT);
296
67
        return NULL;
297
67
    }
298
20
    if (!*isdss)
299
12
        key = ossl_b2i_RSA_after_header(&p, bitlen, *ispub);
300
8
#ifndef OPENSSL_NO_DSA
301
8
    else
302
8
        key = ossl_b2i_DSA_after_header(&p, bitlen, *ispub);
303
20
#endif
304
305
20
    if (key == NULL) {
306
4
        ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
307
4
        return NULL;
308
4
    }
309
310
16
    return key;
311
20
}
312
313
EVP_PKEY *ossl_b2i(const unsigned char **in, unsigned int length, int *ispub)
314
0
{
315
0
    int isdss = -1;
316
0
    void *key = do_b2i_key(in, length, &isdss, ispub);
317
318
0
    return evp_pkey_new0_key(key, isdss_to_evp_type(isdss));
319
0
}
320
321
EVP_PKEY *ossl_b2i_bio(BIO *in, int *ispub)
322
0
{
323
0
    const unsigned char *p;
324
0
    unsigned char hdr_buf[16], *buf = NULL;
325
0
    unsigned int bitlen, magic, length;
326
0
    int isdss = -1;
327
0
    void *key = NULL;
328
0
    EVP_PKEY *pkey = NULL;
329
330
0
    if (BIO_read(in, hdr_buf, 16) != 16) {
331
0
        ERR_raise(ERR_LIB_PEM, PEM_R_KEYBLOB_TOO_SHORT);
332
0
        return NULL;
333
0
    }
334
0
    p = hdr_buf;
335
0
    if (ossl_do_blob_header(&p, 16, &magic, &bitlen, &isdss, ispub) <= 0)
336
0
        return NULL;
337
338
0
    length = ossl_blob_length(bitlen, isdss, *ispub);
339
0
    if (length > BLOB_MAX_LENGTH) {
340
0
        ERR_raise(ERR_LIB_PEM, PEM_R_HEADER_TOO_LONG);
341
0
        return NULL;
342
0
    }
343
0
    buf = OPENSSL_malloc(length);
344
0
    if (buf == NULL) {
345
0
        ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
346
0
        goto err;
347
0
    }
348
0
    p = buf;
349
0
    if (BIO_read(in, buf, length) != (int)length) {
350
0
        ERR_raise(ERR_LIB_PEM, PEM_R_KEYBLOB_TOO_SHORT);
351
0
        goto err;
352
0
    }
353
354
0
    if (!isdss)
355
0
        key = ossl_b2i_RSA_after_header(&p, bitlen, *ispub);
356
0
#ifndef OPENSSL_NO_DSA
357
0
    else
358
0
        key = ossl_b2i_DSA_after_header(&p, bitlen, *ispub);
359
0
#endif
360
361
0
    if (key == NULL) {
362
0
        ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_PUBLIC_KEY_TYPE);
363
0
        goto err;
364
0
    }
365
366
0
    pkey = evp_pkey_new0_key(key, isdss_to_evp_type(isdss));
367
0
err:
368
0
    OPENSSL_free(buf);
369
0
    return pkey;
370
0
}
371
372
#ifndef OPENSSL_NO_DSA
373
DSA *ossl_b2i_DSA_after_header(const unsigned char **in, unsigned int bitlen,
374
    int ispub)
375
0
{
376
0
    const unsigned char *p = *in;
377
0
    DSA *dsa = NULL;
378
0
    BN_CTX *ctx = NULL;
379
0
    BIGNUM *pbn = NULL, *qbn = NULL, *gbn = NULL, *priv_key = NULL;
380
0
    BIGNUM *pub_key = NULL;
381
0
    unsigned int nbyte = (bitlen + 7) >> 3;
382
383
0
    dsa = DSA_new();
384
0
    if (dsa == NULL)
385
0
        goto memerr;
386
0
    if (!read_lebn(&p, nbyte, &pbn))
387
0
        goto memerr;
388
389
0
    if (!read_lebn(&p, 20, &qbn))
390
0
        goto memerr;
391
392
0
    if (!read_lebn(&p, nbyte, &gbn))
393
0
        goto memerr;
394
395
0
    if (ispub) {
396
0
        if (!read_lebn(&p, nbyte, &pub_key))
397
0
            goto memerr;
398
0
    } else {
399
0
        if (!read_lebn(&p, 20, &priv_key))
400
0
            goto memerr;
401
402
        /* Set constant time flag before public key calculation */
403
0
        BN_set_flags(priv_key, BN_FLG_CONSTTIME);
404
405
        /* Calculate public key */
406
0
        pub_key = BN_new();
407
0
        if (pub_key == NULL)
408
0
            goto memerr;
409
0
        if ((ctx = BN_CTX_new()) == NULL)
410
0
            goto memerr;
411
412
0
        if (!BN_mod_exp(pub_key, gbn, priv_key, pbn, ctx))
413
0
            goto memerr;
414
415
0
        BN_CTX_free(ctx);
416
0
        ctx = NULL;
417
0
    }
418
0
    if (!DSA_set0_pqg(dsa, pbn, qbn, gbn))
419
0
        goto memerr;
420
0
    pbn = qbn = gbn = NULL;
421
0
    if (!DSA_set0_key(dsa, pub_key, priv_key))
422
0
        goto memerr;
423
0
    pub_key = priv_key = NULL;
424
425
0
    *in = p;
426
0
    return dsa;
427
428
0
memerr:
429
0
    ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
430
0
    DSA_free(dsa);
431
0
    BN_free(pbn);
432
0
    BN_free(qbn);
433
0
    BN_free(gbn);
434
0
    BN_free(pub_key);
435
0
    BN_free(priv_key);
436
0
    BN_CTX_free(ctx);
437
0
    return NULL;
438
0
}
439
#endif
440
441
RSA *ossl_b2i_RSA_after_header(const unsigned char **in, unsigned int bitlen,
442
    int ispub)
443
0
{
444
0
    const unsigned char *pin = *in;
445
0
    BIGNUM *e = NULL, *n = NULL, *d = NULL;
446
0
    BIGNUM *p = NULL, *q = NULL, *dmp1 = NULL, *dmq1 = NULL, *iqmp = NULL;
447
0
    RSA *rsa = NULL;
448
0
    unsigned int nbyte = (bitlen + 7) >> 3;
449
0
    unsigned int hnbyte = (bitlen + 15) >> 4;
450
451
0
    rsa = RSA_new();
452
0
    if (rsa == NULL)
453
0
        goto memerr;
454
0
    e = BN_new();
455
0
    if (e == NULL)
456
0
        goto memerr;
457
0
    if (!BN_set_word(e, read_ledword(&pin)))
458
0
        goto memerr;
459
0
    if (!read_lebn(&pin, nbyte, &n))
460
0
        goto memerr;
461
0
    if (!ispub) {
462
0
        if (!read_lebn(&pin, hnbyte, &p))
463
0
            goto memerr;
464
0
        if (!read_lebn(&pin, hnbyte, &q))
465
0
            goto memerr;
466
0
        if (!read_lebn(&pin, hnbyte, &dmp1))
467
0
            goto memerr;
468
0
        if (!read_lebn(&pin, hnbyte, &dmq1))
469
0
            goto memerr;
470
0
        if (!read_lebn(&pin, hnbyte, &iqmp))
471
0
            goto memerr;
472
0
        if (!read_lebn(&pin, nbyte, &d))
473
0
            goto memerr;
474
0
        if (!RSA_set0_factors(rsa, p, q))
475
0
            goto memerr;
476
0
        p = q = NULL;
477
0
        if (!RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp))
478
0
            goto memerr;
479
0
        dmp1 = dmq1 = iqmp = NULL;
480
0
    }
481
0
    if (!RSA_set0_key(rsa, n, e, d))
482
0
        goto memerr;
483
0
    n = e = d = NULL;
484
485
0
    *in = pin;
486
0
    return rsa;
487
0
memerr:
488
0
    ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
489
0
    BN_free(e);
490
0
    BN_free(n);
491
0
    BN_free(p);
492
0
    BN_free(q);
493
0
    BN_free(dmp1);
494
0
    BN_free(dmq1);
495
0
    BN_free(iqmp);
496
0
    BN_free(d);
497
0
    RSA_free(rsa);
498
0
    return NULL;
499
0
}
500
501
EVP_PKEY *b2i_PrivateKey(const unsigned char **in, long length)
502
0
{
503
0
    int ispub = 0;
504
505
0
    return ossl_b2i(in, length, &ispub);
506
0
}
507
508
EVP_PKEY *b2i_PublicKey(const unsigned char **in, long length)
509
0
{
510
0
    int ispub = 1;
511
512
0
    return ossl_b2i(in, length, &ispub);
513
0
}
514
515
EVP_PKEY *b2i_PrivateKey_bio(BIO *in)
516
0
{
517
0
    int ispub = 0;
518
519
0
    return ossl_b2i_bio(in, &ispub);
520
0
}
521
522
EVP_PKEY *b2i_PublicKey_bio(BIO *in)
523
0
{
524
0
    int ispub = 1;
525
526
0
    return ossl_b2i_bio(in, &ispub);
527
0
}
528
529
static void write_ledword(unsigned char **out, unsigned int dw)
530
0
{
531
0
    unsigned char *p = *out;
532
533
0
    *p++ = dw & 0xff;
534
0
    *p++ = (dw >> 8) & 0xff;
535
0
    *p++ = (dw >> 16) & 0xff;
536
0
    *p++ = (dw >> 24) & 0xff;
537
0
    *out = p;
538
0
}
539
540
static void write_lebn(unsigned char **out, const BIGNUM *bn, int len)
541
0
{
542
0
    BN_bn2lebinpad(bn, *out, len);
543
0
    *out += len;
544
0
}
545
546
static int check_bitlen_rsa(const RSA *rsa, int ispub, unsigned int *magic);
547
static void write_rsa(unsigned char **out, const RSA *rsa, int ispub);
548
549
#ifndef OPENSSL_NO_DSA
550
static int check_bitlen_dsa(const DSA *dsa, int ispub, unsigned int *magic);
551
static void write_dsa(unsigned char **out, const DSA *dsa, int ispub);
552
#endif
553
554
static int do_i2b(unsigned char **out, const EVP_PKEY *pk, int ispub)
555
0
{
556
0
    unsigned char *p;
557
0
    unsigned int bitlen = 0, magic = 0, keyalg = 0;
558
0
    int outlen = -1, noinc = 0;
559
560
0
    if (EVP_PKEY_is_a(pk, "RSA")) {
561
0
        bitlen = check_bitlen_rsa(EVP_PKEY_get0_RSA(pk), ispub, &magic);
562
0
        keyalg = MS_KEYALG_RSA_KEYX;
563
0
#ifndef OPENSSL_NO_DSA
564
0
    } else if (EVP_PKEY_is_a(pk, "DSA")) {
565
0
        bitlen = check_bitlen_dsa(EVP_PKEY_get0_DSA(pk), ispub, &magic);
566
0
        keyalg = MS_KEYALG_DSS_SIGN;
567
0
#endif
568
0
    }
569
0
    if (bitlen == 0) {
570
0
        goto end;
571
0
    }
572
0
    outlen = 16
573
0
        + ossl_blob_length(bitlen, keyalg == MS_KEYALG_DSS_SIGN ? 1 : 0, ispub);
574
0
    if (out == NULL)
575
0
        goto end;
576
0
    if (*out)
577
0
        p = *out;
578
0
    else {
579
0
        if ((p = OPENSSL_malloc(outlen)) == NULL) {
580
0
            ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
581
0
            outlen = -1;
582
0
            goto end;
583
0
        }
584
0
        *out = p;
585
0
        noinc = 1;
586
0
    }
587
0
    if (ispub)
588
0
        *p++ = MS_PUBLICKEYBLOB;
589
0
    else
590
0
        *p++ = MS_PRIVATEKEYBLOB;
591
0
    *p++ = 0x2;
592
0
    *p++ = 0;
593
0
    *p++ = 0;
594
0
    write_ledword(&p, keyalg);
595
0
    write_ledword(&p, magic);
596
0
    write_ledword(&p, bitlen);
597
0
    if (keyalg == MS_KEYALG_RSA_KEYX)
598
0
        write_rsa(&p, EVP_PKEY_get0_RSA(pk), ispub);
599
0
#ifndef OPENSSL_NO_DSA
600
0
    else
601
0
        write_dsa(&p, EVP_PKEY_get0_DSA(pk), ispub);
602
0
#endif
603
0
    if (!noinc)
604
0
        *out += outlen;
605
0
end:
606
0
    return outlen;
607
0
}
608
609
static int do_i2b_bio(BIO *out, const EVP_PKEY *pk, int ispub)
610
0
{
611
0
    unsigned char *tmp = NULL;
612
0
    int outlen, wrlen;
613
614
0
    outlen = do_i2b(&tmp, pk, ispub);
615
0
    if (outlen < 0)
616
0
        return -1;
617
0
    wrlen = BIO_write(out, tmp, outlen);
618
0
    OPENSSL_free(tmp);
619
0
    if (wrlen == outlen)
620
0
        return outlen;
621
0
    return -1;
622
0
}
623
624
static int check_bitlen_rsa(const RSA *rsa, int ispub, unsigned int *pmagic)
625
0
{
626
0
    int nbyte, hnbyte, bitlen;
627
0
    const BIGNUM *e;
628
629
0
    RSA_get0_key(rsa, NULL, &e, NULL);
630
0
    if (BN_num_bits(e) > 32)
631
0
        goto badkey;
632
0
    bitlen = RSA_bits(rsa);
633
0
    nbyte = RSA_size(rsa);
634
0
    hnbyte = (bitlen + 15) >> 4;
635
0
    if (ispub) {
636
0
        *pmagic = MS_RSA1MAGIC;
637
0
        return bitlen;
638
0
    } else {
639
0
        const BIGNUM *d, *p, *q, *iqmp, *dmp1, *dmq1;
640
641
0
        *pmagic = MS_RSA2MAGIC;
642
643
        /*
644
         * For private key each component must fit within nbyte or hnbyte.
645
         */
646
0
        RSA_get0_key(rsa, NULL, NULL, &d);
647
0
        if (BN_num_bytes(d) > nbyte)
648
0
            goto badkey;
649
0
        RSA_get0_factors(rsa, &p, &q);
650
0
        RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
651
0
        if ((BN_num_bytes(iqmp) > hnbyte)
652
0
            || (BN_num_bytes(p) > hnbyte)
653
0
            || (BN_num_bytes(q) > hnbyte)
654
0
            || (BN_num_bytes(dmp1) > hnbyte)
655
0
            || (BN_num_bytes(dmq1) > hnbyte))
656
0
            goto badkey;
657
0
    }
658
0
    return bitlen;
659
0
badkey:
660
0
    ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
661
0
    return 0;
662
0
}
663
664
static void write_rsa(unsigned char **out, const RSA *rsa, int ispub)
665
0
{
666
0
    int nbyte, hnbyte;
667
0
    const BIGNUM *n, *d, *e, *p, *q, *iqmp, *dmp1, *dmq1;
668
669
0
    nbyte = RSA_size(rsa);
670
0
    hnbyte = (RSA_bits(rsa) + 15) >> 4;
671
0
    RSA_get0_key(rsa, &n, &e, &d);
672
0
    write_lebn(out, e, 4);
673
0
    write_lebn(out, n, nbyte);
674
0
    if (ispub)
675
0
        return;
676
0
    RSA_get0_factors(rsa, &p, &q);
677
0
    RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
678
0
    write_lebn(out, p, hnbyte);
679
0
    write_lebn(out, q, hnbyte);
680
0
    write_lebn(out, dmp1, hnbyte);
681
0
    write_lebn(out, dmq1, hnbyte);
682
0
    write_lebn(out, iqmp, hnbyte);
683
0
    write_lebn(out, d, nbyte);
684
0
}
685
686
#ifndef OPENSSL_NO_DSA
687
static int check_bitlen_dsa(const DSA *dsa, int ispub, unsigned int *pmagic)
688
0
{
689
0
    int bitlen;
690
0
    const BIGNUM *p = NULL, *q = NULL, *g = NULL;
691
0
    const BIGNUM *pub_key = NULL, *priv_key = NULL;
692
693
0
    DSA_get0_pqg(dsa, &p, &q, &g);
694
0
    DSA_get0_key(dsa, &pub_key, &priv_key);
695
0
    bitlen = BN_num_bits(p);
696
0
    if ((bitlen & 7) || (BN_num_bits(q) != 160)
697
0
        || (BN_num_bits(g) > bitlen))
698
0
        goto badkey;
699
0
    if (ispub) {
700
0
        if (BN_num_bits(pub_key) > bitlen)
701
0
            goto badkey;
702
0
        *pmagic = MS_DSS1MAGIC;
703
0
    } else {
704
0
        if (BN_num_bits(priv_key) > 160)
705
0
            goto badkey;
706
0
        *pmagic = MS_DSS2MAGIC;
707
0
    }
708
709
0
    return bitlen;
710
0
badkey:
711
0
    ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_KEY_COMPONENTS);
712
0
    return 0;
713
0
}
714
715
static void write_dsa(unsigned char **out, const DSA *dsa, int ispub)
716
0
{
717
0
    int nbyte;
718
0
    const BIGNUM *p = NULL, *q = NULL, *g = NULL;
719
0
    const BIGNUM *pub_key = NULL, *priv_key = NULL;
720
721
0
    DSA_get0_pqg(dsa, &p, &q, &g);
722
0
    DSA_get0_key(dsa, &pub_key, &priv_key);
723
0
    nbyte = BN_num_bytes(p);
724
0
    write_lebn(out, p, nbyte);
725
0
    write_lebn(out, q, 20);
726
0
    write_lebn(out, g, nbyte);
727
0
    if (ispub)
728
0
        write_lebn(out, pub_key, nbyte);
729
0
    else
730
0
        write_lebn(out, priv_key, 20);
731
    /* Set "invalid" for seed structure values */
732
0
    memset(*out, 0xff, 24);
733
0
    *out += 24;
734
0
    return;
735
0
}
736
#endif
737
738
int i2b_PrivateKey_bio(BIO *out, const EVP_PKEY *pk)
739
0
{
740
0
    return do_i2b_bio(out, pk, 0);
741
0
}
742
743
int i2b_PublicKey_bio(BIO *out, const EVP_PKEY *pk)
744
0
{
745
0
    return do_i2b_bio(out, pk, 1);
746
0
}
747
748
int ossl_do_PVK_header(const unsigned char **in, unsigned int length,
749
    int skip_magic,
750
    unsigned int *psaltlen, unsigned int *pkeylen)
751
9.27k
{
752
9.27k
    const unsigned char *p = *in;
753
9.27k
    unsigned int pvk_magic, is_encrypted;
754
755
9.27k
    if (skip_magic) {
756
0
        if (length < 20) {
757
0
            ERR_raise(ERR_LIB_PEM, PEM_R_PVK_TOO_SHORT);
758
0
            return 0;
759
0
        }
760
9.27k
    } else {
761
9.27k
        if (length < 24) {
762
0
            ERR_raise(ERR_LIB_PEM, PEM_R_PVK_TOO_SHORT);
763
0
            return 0;
764
0
        }
765
9.27k
        pvk_magic = read_ledword(&p);
766
9.27k
        if (pvk_magic != MS_PVKMAGIC) {
767
8.78k
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_MAGIC_NUMBER);
768
8.78k
            return 0;
769
8.78k
        }
770
9.27k
    }
771
    /* Skip reserved */
772
495
    p += 4;
773
    /*
774
     * keytype =
775
     */
776
495
    read_ledword(&p);
777
495
    is_encrypted = read_ledword(&p);
778
495
    *psaltlen = read_ledword(&p);
779
495
    *pkeylen = read_ledword(&p);
780
781
495
    if (*pkeylen > PVK_MAX_KEYLEN || *psaltlen > PVK_MAX_SALTLEN)
782
184
        return 0;
783
784
311
    if (is_encrypted && *psaltlen == 0) {
785
46
        ERR_raise(ERR_LIB_PEM, PEM_R_INCONSISTENT_HEADER);
786
46
        return 0;
787
46
    }
788
789
265
    *in = p;
790
265
    return 1;
791
311
}
792
793
#ifndef OPENSSL_NO_RC4
794
static int derive_pvk_key(unsigned char *key,
795
    const unsigned char *salt, unsigned int saltlen,
796
    const unsigned char *pass, int passlen,
797
    OSSL_LIB_CTX *libctx, const char *propq)
798
0
{
799
0
    EVP_MD_CTX *mctx = EVP_MD_CTX_new();
800
0
    int rv = 0;
801
0
    EVP_MD *sha1 = NULL;
802
803
0
    if ((sha1 = EVP_MD_fetch(libctx, SN_sha1, propq)) == NULL)
804
0
        goto err;
805
806
0
    if (mctx == NULL
807
0
        || !EVP_DigestInit_ex(mctx, sha1, NULL)
808
0
        || !EVP_DigestUpdate(mctx, salt, saltlen)
809
0
        || !EVP_DigestUpdate(mctx, pass, passlen)
810
0
        || !EVP_DigestFinal_ex(mctx, key, NULL))
811
0
        goto err;
812
813
0
    rv = 1;
814
0
err:
815
0
    EVP_MD_CTX_free(mctx);
816
0
    EVP_MD_free(sha1);
817
0
    return rv;
818
0
}
819
#endif
820
821
static void *do_PVK_body_key(const unsigned char **in,
822
    unsigned int saltlen, unsigned int keylen,
823
    pem_password_cb *cb, void *u,
824
    int *isdss, int *ispub,
825
    OSSL_LIB_CTX *libctx, const char *propq)
826
193
{
827
193
    const unsigned char *p = *in;
828
193
    unsigned char *enctmp = NULL;
829
193
    unsigned char keybuf[20];
830
193
    void *key = NULL;
831
193
#ifndef OPENSSL_NO_RC4
832
193
    EVP_CIPHER *rc4 = NULL;
833
193
#endif
834
193
    EVP_CIPHER_CTX *cctx = EVP_CIPHER_CTX_new();
835
836
193
    if (cctx == NULL) {
837
0
        ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
838
0
        goto err;
839
0
    }
840
841
193
    if (saltlen) {
842
21
#ifndef OPENSSL_NO_RC4
843
21
        unsigned int magic;
844
21
        char psbuf[PEM_BUFSIZE];
845
21
        int enctmplen, inlen;
846
21
        unsigned char *q;
847
848
21
        if (cb)
849
21
            inlen = cb(psbuf, PEM_BUFSIZE, 0, u);
850
0
        else
851
0
            inlen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u);
852
21
        if (inlen < 0) {
853
21
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_PASSWORD_READ);
854
21
            goto err;
855
21
        }
856
0
        enctmp = OPENSSL_malloc(keylen + 8);
857
0
        if (enctmp == NULL) {
858
0
            ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
859
0
            goto err;
860
0
        }
861
0
        if (!derive_pvk_key(keybuf, p, saltlen,
862
0
                (unsigned char *)psbuf, inlen, libctx, propq))
863
0
            goto err;
864
0
        p += saltlen;
865
        /* Copy BLOBHEADER across, decrypt rest */
866
0
        memcpy(enctmp, p, 8);
867
0
        p += 8;
868
0
        if (keylen < 8) {
869
0
            ERR_raise(ERR_LIB_PEM, PEM_R_PVK_TOO_SHORT);
870
0
            goto err;
871
0
        }
872
0
        inlen = keylen - 8;
873
0
        q = enctmp + 8;
874
0
        if ((rc4 = EVP_CIPHER_fetch(libctx, "RC4", propq)) == NULL)
875
0
            goto err;
876
0
        if (!EVP_DecryptInit_ex(cctx, rc4, NULL, keybuf, NULL))
877
0
            goto err;
878
0
        if (!EVP_DecryptUpdate(cctx, q, &enctmplen, p, inlen))
879
0
            goto err;
880
0
        if (!EVP_DecryptFinal_ex(cctx, q + enctmplen, &enctmplen))
881
0
            goto err;
882
0
        magic = read_ledword((const unsigned char **)&q);
883
0
        if (magic != MS_RSA2MAGIC && magic != MS_DSS2MAGIC) {
884
0
            q = enctmp + 8;
885
0
            memset(keybuf + 5, 0, 11);
886
0
            if (!EVP_DecryptInit_ex(cctx, rc4, NULL, keybuf, NULL))
887
0
                goto err;
888
0
            if (!EVP_DecryptUpdate(cctx, q, &enctmplen, p, inlen))
889
0
                goto err;
890
0
            if (!EVP_DecryptFinal_ex(cctx, q + enctmplen, &enctmplen))
891
0
                goto err;
892
0
            magic = read_ledword((const unsigned char **)&q);
893
0
            if (magic != MS_RSA2MAGIC && magic != MS_DSS2MAGIC) {
894
0
                ERR_raise(ERR_LIB_PEM, PEM_R_BAD_DECRYPT);
895
0
                goto err;
896
0
            }
897
0
        }
898
0
        p = enctmp;
899
#else
900
        ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_CIPHER);
901
        goto err;
902
#endif
903
0
    }
904
905
172
    key = do_b2i_key(&p, keylen, isdss, ispub);
906
193
err:
907
193
    EVP_CIPHER_CTX_free(cctx);
908
193
#ifndef OPENSSL_NO_RC4
909
193
    EVP_CIPHER_free(rc4);
910
193
#endif
911
193
    if (enctmp != NULL) {
912
0
        OPENSSL_cleanse(keybuf, sizeof(keybuf));
913
0
        OPENSSL_free(enctmp);
914
0
    }
915
193
    return key;
916
172
}
917
918
static void *do_PVK_key_bio(BIO *in, pem_password_cb *cb, void *u,
919
    int *isdss, int *ispub,
920
    OSSL_LIB_CTX *libctx, const char *propq)
921
43.6k
{
922
43.6k
    unsigned char pvk_hdr[24], *buf = NULL;
923
43.6k
    const unsigned char *p;
924
43.6k
    int buflen;
925
43.6k
    void *key = NULL;
926
43.6k
    unsigned int saltlen, keylen;
927
928
43.6k
    if (BIO_read(in, pvk_hdr, 24) != 24) {
929
17.1k
        ERR_raise(ERR_LIB_PEM, PEM_R_PVK_DATA_TOO_SHORT);
930
17.1k
        return NULL;
931
17.1k
    }
932
26.4k
    p = pvk_hdr;
933
934
26.4k
    if (!ossl_do_PVK_header(&p, 24, 0, &saltlen, &keylen))
935
26.0k
        return 0;
936
452
    buflen = (int)keylen + saltlen;
937
452
    buf = OPENSSL_malloc(buflen);
938
452
    if (buf == NULL) {
939
7
        ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
940
7
        return 0;
941
7
    }
942
445
    p = buf;
943
445
    if (BIO_read(in, buf, buflen) != buflen) {
944
252
        ERR_raise(ERR_LIB_PEM, PEM_R_PVK_DATA_TOO_SHORT);
945
252
        goto err;
946
252
    }
947
193
    key = do_PVK_body_key(&p, saltlen, keylen, cb, u, isdss, ispub, libctx, propq);
948
949
445
err:
950
445
    OPENSSL_clear_free(buf, buflen);
951
445
    return key;
952
193
}
953
954
#ifndef OPENSSL_NO_DSA
955
DSA *b2i_DSA_PVK_bio_ex(BIO *in, pem_password_cb *cb, void *u,
956
    OSSL_LIB_CTX *libctx, const char *propq)
957
24.9k
{
958
24.9k
    int isdss = 1;
959
24.9k
    int ispub = 0; /* PVK keys are always private */
960
961
24.9k
    return do_PVK_key_bio(in, cb, u, &isdss, &ispub, libctx, propq);
962
24.9k
}
963
964
DSA *b2i_DSA_PVK_bio(BIO *in, pem_password_cb *cb, void *u)
965
0
{
966
0
    return b2i_DSA_PVK_bio_ex(in, cb, u, NULL, NULL);
967
0
}
968
#endif
969
970
RSA *b2i_RSA_PVK_bio_ex(BIO *in, pem_password_cb *cb, void *u,
971
    OSSL_LIB_CTX *libctx, const char *propq)
972
18.7k
{
973
18.7k
    int isdss = 0;
974
18.7k
    int ispub = 0; /* PVK keys are always private */
975
976
18.7k
    return do_PVK_key_bio(in, cb, u, &isdss, &ispub, libctx, propq);
977
18.7k
}
978
979
RSA *b2i_RSA_PVK_bio(BIO *in, pem_password_cb *cb, void *u)
980
0
{
981
0
    return b2i_RSA_PVK_bio_ex(in, cb, u, NULL, NULL);
982
0
}
983
984
EVP_PKEY *b2i_PVK_bio_ex(BIO *in, pem_password_cb *cb, void *u,
985
    OSSL_LIB_CTX *libctx, const char *propq)
986
0
{
987
0
    int isdss = -1;
988
0
    int ispub = -1;
989
0
    void *key = do_PVK_key_bio(in, cb, u, &isdss, &ispub, NULL, NULL);
990
991
0
    return evp_pkey_new0_key(key, isdss_to_evp_type(isdss));
992
0
}
993
994
EVP_PKEY *b2i_PVK_bio(BIO *in, pem_password_cb *cb, void *u)
995
0
{
996
0
    return b2i_PVK_bio_ex(in, cb, u, NULL, NULL);
997
0
}
998
999
static int i2b_PVK(unsigned char **out, const EVP_PKEY *pk, int enclevel,
1000
    pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx,
1001
    const char *propq)
1002
0
{
1003
0
    int ret = -1;
1004
0
    int outlen = 24, pklen;
1005
0
    unsigned char *p = NULL, *start = NULL;
1006
0
    EVP_CIPHER_CTX *cctx = NULL;
1007
0
#ifndef OPENSSL_NO_RC4
1008
0
    unsigned char *salt = NULL;
1009
0
    EVP_CIPHER *rc4 = NULL;
1010
0
#endif
1011
1012
0
    if (enclevel)
1013
0
        outlen += PVK_SALTLEN;
1014
0
    pklen = do_i2b(NULL, pk, 0);
1015
0
    if (pklen < 0)
1016
0
        return -1;
1017
0
    outlen += pklen;
1018
0
    if (out == NULL)
1019
0
        return outlen;
1020
0
    if (*out != NULL) {
1021
0
        p = *out;
1022
0
    } else {
1023
0
        start = p = OPENSSL_malloc(outlen);
1024
0
        if (p == NULL) {
1025
0
            ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
1026
0
            return -1;
1027
0
        }
1028
0
    }
1029
1030
0
    cctx = EVP_CIPHER_CTX_new();
1031
0
    if (cctx == NULL)
1032
0
        goto error;
1033
1034
0
    write_ledword(&p, MS_PVKMAGIC);
1035
0
    write_ledword(&p, 0);
1036
0
    if (EVP_PKEY_get_id(pk) == EVP_PKEY_RSA)
1037
0
        write_ledword(&p, MS_KEYTYPE_KEYX);
1038
0
#ifndef OPENSSL_NO_DSA
1039
0
    else
1040
0
        write_ledword(&p, MS_KEYTYPE_SIGN);
1041
0
#endif
1042
0
    write_ledword(&p, enclevel ? 1 : 0);
1043
0
    write_ledword(&p, enclevel ? PVK_SALTLEN : 0);
1044
0
    write_ledword(&p, pklen);
1045
0
    if (enclevel) {
1046
0
#ifndef OPENSSL_NO_RC4
1047
0
        if (RAND_bytes_ex(libctx, p, PVK_SALTLEN, 0) <= 0)
1048
0
            goto error;
1049
0
        salt = p;
1050
0
        p += PVK_SALTLEN;
1051
0
#endif
1052
0
    }
1053
0
    do_i2b(&p, pk, 0);
1054
0
    if (enclevel != 0) {
1055
0
#ifndef OPENSSL_NO_RC4
1056
0
        char psbuf[PEM_BUFSIZE];
1057
0
        unsigned char keybuf[20];
1058
0
        int enctmplen, inlen;
1059
0
        if (cb)
1060
0
            inlen = cb(psbuf, PEM_BUFSIZE, 1, u);
1061
0
        else
1062
0
            inlen = PEM_def_callback(psbuf, PEM_BUFSIZE, 1, u);
1063
0
        if (inlen <= 0) {
1064
0
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_PASSWORD_READ);
1065
0
            goto error;
1066
0
        }
1067
0
        if (!derive_pvk_key(keybuf, salt, PVK_SALTLEN,
1068
0
                (unsigned char *)psbuf, inlen, libctx, propq))
1069
0
            goto error;
1070
0
        if ((rc4 = EVP_CIPHER_fetch(libctx, "RC4", propq)) == NULL)
1071
0
            goto error;
1072
0
        if (enclevel == 1)
1073
0
            memset(keybuf + 5, 0, 11);
1074
0
        p = salt + PVK_SALTLEN + 8;
1075
0
        if (!EVP_EncryptInit_ex(cctx, rc4, NULL, keybuf, NULL))
1076
0
            goto error;
1077
0
        OPENSSL_cleanse(keybuf, 20);
1078
0
        if (!EVP_EncryptUpdate(cctx, p, &enctmplen, p, pklen - 8))
1079
0
            goto error;
1080
0
        if (!EVP_EncryptFinal_ex(cctx, p + enctmplen, &enctmplen))
1081
0
            goto error;
1082
#else
1083
        ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_CIPHER);
1084
        goto error;
1085
#endif
1086
0
    }
1087
1088
0
    if (*out == NULL)
1089
0
        *out = start;
1090
0
    ret = outlen;
1091
0
error:
1092
0
    EVP_CIPHER_CTX_free(cctx);
1093
0
#ifndef OPENSSL_NO_RC4
1094
0
    EVP_CIPHER_free(rc4);
1095
0
#endif
1096
0
    if (*out == NULL)
1097
0
        OPENSSL_free(start);
1098
1099
0
    return ret;
1100
0
}
1101
1102
int i2b_PVK_bio_ex(BIO *out, const EVP_PKEY *pk, int enclevel,
1103
    pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx,
1104
    const char *propq)
1105
0
{
1106
0
    unsigned char *tmp = NULL;
1107
0
    int outlen, wrlen;
1108
1109
0
    outlen = i2b_PVK(&tmp, pk, enclevel, cb, u, libctx, propq);
1110
0
    if (outlen < 0)
1111
0
        return -1;
1112
0
    wrlen = BIO_write(out, tmp, outlen);
1113
0
    OPENSSL_free(tmp);
1114
0
    if (wrlen == outlen) {
1115
0
        return outlen;
1116
0
    }
1117
0
    ERR_raise(ERR_LIB_PEM, PEM_R_BIO_WRITE_FAILURE);
1118
0
    return -1;
1119
0
}
1120
1121
int i2b_PVK_bio(BIO *out, const EVP_PKEY *pk, int enclevel,
1122
    pem_password_cb *cb, void *u)
1123
0
{
1124
0
    return i2b_PVK_bio_ex(out, pk, enclevel, cb, u, NULL, NULL);
1125
0
}