Coverage Report

Created: 2026-10-31 07:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-openssl-api/src/ssl_p7p12.c
Line
Count
Source
1
/* ssl_p7p12.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
23
24
#if defined(OPENSSL_EXTRA) && (defined(HAVE_FIPS) || defined(HAVE_SELFTEST))
25
    #include <wolfssl/wolfcrypt/pkcs7.h>
26
#endif
27
#if defined(OPENSSL_ALL) && defined(HAVE_PKCS7)
28
    #include <wolfssl/openssl/pkcs7.h>
29
#endif
30
31
#if !defined(WOLFSSL_SSL_P7P12_INCLUDED)
32
    #ifndef WOLFSSL_IGNORE_FILE_WARN
33
        #warning ssl_p7p12.c does not need to be compiled separately from ssl.c
34
    #endif
35
#else
36
37
#if !defined(WOLFCRYPT_ONLY) && !defined(NO_CERTS)
38
39
/*******************************************************************************
40
 * START OF PKCS7 APIs
41
 ******************************************************************************/
42
#ifdef HAVE_PKCS7
43
44
#ifdef OPENSSL_ALL
45
PKCS7* wolfSSL_PKCS7_new(void)
46
{
47
    WOLFSSL_PKCS7* pkcs7;
48
    int ret = 0;
49
50
    pkcs7 = (WOLFSSL_PKCS7*)XMALLOC(sizeof(WOLFSSL_PKCS7), NULL,
51
                                    DYNAMIC_TYPE_PKCS7);
52
    if (pkcs7 != NULL) {
53
        XMEMSET(pkcs7, 0, sizeof(WOLFSSL_PKCS7));
54
        ret = wc_PKCS7_Init(&pkcs7->pkcs7, NULL, INVALID_DEVID);
55
    }
56
57
    if (ret != 0 && pkcs7 != NULL) {
58
        XFREE(pkcs7, NULL, DYNAMIC_TYPE_PKCS7);
59
        pkcs7 = NULL;
60
    }
61
62
    return (PKCS7*)pkcs7;
63
}
64
65
/******************************************************************************
66
* wolfSSL_PKCS7_SIGNED_new - allocates PKCS7 and initialize it for a signed data
67
*
68
* RETURNS:
69
* returns pointer to the PKCS7 structure on success, otherwise returns NULL
70
*/
71
PKCS7_SIGNED* wolfSSL_PKCS7_SIGNED_new(void)
72
{
73
    byte signedData[]= { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02};
74
    PKCS7* pkcs7 = NULL;
75
76
    if ((pkcs7 = wolfSSL_PKCS7_new()) == NULL)
77
        return NULL;
78
    pkcs7->contentOID = SIGNED_DATA;
79
    if ((wc_PKCS7_SetContentType(pkcs7, signedData, sizeof(signedData))) < 0) {
80
        if (pkcs7) {
81
            wolfSSL_PKCS7_free(pkcs7);
82
            return NULL;
83
        }
84
    }
85
    return pkcs7;
86
}
87
88
void wolfSSL_PKCS7_free(PKCS7* pkcs7)
89
{
90
    WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
91
92
    if (p7 != NULL) {
93
        XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7);
94
        wc_PKCS7_Free(&p7->pkcs7);
95
        if (p7->certs)
96
            wolfSSL_sk_pop_free(p7->certs, NULL);
97
        XFREE(p7, NULL, DYNAMIC_TYPE_PKCS7);
98
    }
99
}
100
101
void wolfSSL_PKCS7_SIGNED_free(PKCS7_SIGNED* p7)
102
{
103
    wolfSSL_PKCS7_free(p7);
104
    return;
105
}
106
107
/**
108
 * Convert DER/ASN.1 encoded signedData structure to internal PKCS7
109
 * structure. Note, does not support detached content.
110
 *
111
 * p7 - pointer to set to address of newly created PKCS7 structure on return
112
 * in - pointer to pointer of DER/ASN.1 data
113
 * len - length of input data, bytes
114
 *
115
 * Returns newly allocated and populated PKCS7 structure or NULL on error.
116
 */
117
PKCS7* wolfSSL_d2i_PKCS7(PKCS7** p7, const unsigned char** in, int len)
118
{
119
    return wolfSSL_d2i_PKCS7_ex(p7, in, len, NULL, 0);
120
}
121
122
/* This internal function is only decoding and setting up the PKCS7 struct. It
123
* does not verify the PKCS7 signature.
124
*
125
* RETURNS:
126
* returns pointer to a PKCS7 structure on success, otherwise returns NULL
127
*/
128
static PKCS7* wolfSSL_d2i_PKCS7_only(PKCS7** p7, const unsigned char** in,
129
    int len, byte* content, word32 contentSz)
130
{
131
    WOLFSSL_PKCS7* pkcs7 = NULL;
132
133
    WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_ex");
134
135
    if (in == NULL || *in == NULL || len < 0)
136
        return NULL;
137
138
    if ((pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL)
139
        return NULL;
140
141
    pkcs7->len = len;
142
    pkcs7->data = (byte*)XMALLOC(pkcs7->len, NULL, DYNAMIC_TYPE_PKCS7);
143
    if (pkcs7->data == NULL) {
144
        wolfSSL_PKCS7_free((PKCS7*)pkcs7);
145
        return NULL;
146
    }
147
    XMEMCPY(pkcs7->data, *in, pkcs7->len);
148
149
    if (content != NULL) {
150
        pkcs7->pkcs7.content = content;
151
        pkcs7->pkcs7.contentSz = contentSz;
152
    }
153
154
    if (p7 != NULL)
155
        *p7 = (PKCS7*)pkcs7;
156
    *in += pkcs7->len;
157
    return (PKCS7*)pkcs7;
158
}
159
160
161
/*****************************************************************************
162
* wolfSSL_d2i_PKCS7_ex - Converts the given unsigned char buffer of size len
163
* into a PKCS7 object.  Optionally, accepts a byte buffer of content which
164
* is stored as the PKCS7 object's content, to support detached signatures.
165
* @param content The content which is signed, in case the signature is
166
*                detached.  Ignored if NULL.
167
* @param contentSz The size of the passed in content.
168
*
169
* RETURNS:
170
* returns pointer to a PKCS7 structure on success, otherwise returns NULL
171
*/
172
PKCS7* wolfSSL_d2i_PKCS7_ex(PKCS7** p7, const unsigned char** in, int len,
173
        byte* content, word32 contentSz)
174
{
175
    WOLFSSL_PKCS7* pkcs7 = NULL;
176
177
    WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_ex");
178
179
    if (in == NULL || *in == NULL || len < 0)
180
        return NULL;
181
182
    pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_d2i_PKCS7_only(p7, in, len, content,
183
            contentSz);
184
    if (pkcs7 != NULL) {
185
        if (wc_PKCS7_VerifySignedData(&pkcs7->pkcs7, pkcs7->data, pkcs7->len)
186
                                                                         != 0) {
187
            WOLFSSL_MSG("wc_PKCS7_VerifySignedData failed");
188
            wolfSSL_PKCS7_free((PKCS7*)pkcs7);
189
            if (p7 != NULL) {
190
                *p7 = NULL;
191
            }
192
            return NULL;
193
        }
194
    }
195
196
    return (PKCS7*)pkcs7;
197
}
198
199
200
/**
201
 * This API was added as a helper function for libest. It
202
 * extracts a stack of certificates from the pkcs7 object.
203
 * @param pkcs7 PKCS7 parameter object
204
 * @return WOLFSSL_STACK_OF(WOLFSSL_X509)*
205
 */
206
WOLFSSL_STACK* wolfSSL_PKCS7_to_stack(PKCS7* pkcs7)
207
{
208
    int i;
209
    WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
210
    WOLF_STACK_OF(WOLFSSL_X509)* ret = NULL;
211
212
    WOLFSSL_ENTER("wolfSSL_PKCS7_to_stack");
213
214
    if (!p7) {
215
        WOLFSSL_MSG("Bad parameter");
216
        return NULL;
217
    }
218
219
    if (p7->certs)
220
        return p7->certs;
221
222
    for (i = 0; i < MAX_PKCS7_CERTS && p7->pkcs7.cert[i]; i++) {
223
        WOLFSSL_X509* x509 = wolfSSL_X509_d2i_ex(NULL, p7->pkcs7.cert[i],
224
            p7->pkcs7.certSz[i], pkcs7->heap);
225
        if (!ret)
226
            ret = wolfSSL_sk_X509_new_null();
227
        if (x509) {
228
            if (wolfSSL_sk_X509_push(ret, x509) <= 0) {
229
                wolfSSL_X509_free(x509);
230
                x509 = NULL;
231
                WOLFSSL_MSG("wolfSSL_sk_X509_push error");
232
                goto error;
233
            }
234
        }
235
        else {
236
            WOLFSSL_MSG("wolfSSL_X509_d2i error");
237
            goto error;
238
        }
239
    }
240
241
    /* Save stack to free later */
242
    if (p7->certs)
243
        wolfSSL_sk_pop_free(p7->certs, NULL);
244
    p7->certs = ret;
245
246
    return ret;
247
error:
248
    if (ret) {
249
        wolfSSL_sk_pop_free(ret, NULL);
250
    }
251
    return NULL;
252
}
253
254
/**
255
 * Return stack of signers contained in PKCS7 cert.
256
 * Notes:
257
 * - Currently only PKCS#7 messages with a single signer cert is supported.
258
 * - Returned WOLFSSL_STACK must be freed by caller.
259
 *
260
 * pkcs7 - PKCS7 struct to retrieve signer certs from.
261
 * certs - currently unused
262
 * flags - flags to control function behavior.
263
 *
264
 * Return WOLFSSL_STACK of signers on success, NULL on error.
265
 */
266
WOLFSSL_STACK* wolfSSL_PKCS7_get0_signers(PKCS7* pkcs7, WOLFSSL_STACK* certs,
267
                                          int flags)
268
{
269
    WOLFSSL_X509* x509 = NULL;
270
    WOLFSSL_STACK* signers = NULL;
271
    WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
272
    byte* signerCert;
273
    word32 signerCertSz;
274
275
    if (p7 == NULL)
276
        return NULL;
277
278
    if (flags & PKCS7_NOINTERN) {
279
        WOLFSSL_MSG("PKCS7_NOINTERN flag not supported");
280
        return NULL;
281
    }
282
283
    /* Prefer the certificate that actually verified the signature. Falling
284
     * back to singleCert (cert[0]) would let an attacker that bundles a
285
     * trusted cert ahead of their own attacker cert have the trusted cert
286
     * reported as the signer even though it did not produce the signature.
287
     *
288
     * Copy the chosen pointer into a local before passing its address to
289
     * wolfSSL_d2i_X509; d2i_X509 advances *in by the DER length, and if
290
     * we handed it the address of the struct field directly it would
291
     * permanently corrupt the field, producing a heap-OOB read on the
292
     * next use (pointer advanced, singleCertSz unchanged). */
293
    if (p7->pkcs7.verifyCert != NULL && p7->pkcs7.verifyCertSz > 0) {
294
        signerCert   = p7->pkcs7.verifyCert;
295
        signerCertSz = p7->pkcs7.verifyCertSz;
296
    }
297
    else {
298
        signerCert   = p7->pkcs7.singleCert;
299
        signerCertSz = p7->pkcs7.singleCertSz;
300
    }
301
302
    signers = wolfSSL_sk_X509_new_null();
303
    if (signers == NULL)
304
        return NULL;
305
306
    if (wolfSSL_d2i_X509(&x509, (const byte**)&signerCert,
307
                         signerCertSz) == NULL) {
308
        wolfSSL_sk_X509_pop_free(signers, NULL);
309
        return NULL;
310
    }
311
312
    if (wolfSSL_sk_X509_push(signers, x509) <= 0) {
313
        wolfSSL_X509_free(x509);
314
        wolfSSL_sk_X509_pop_free(signers, NULL);
315
        return NULL;
316
    }
317
318
    (void)certs;
319
320
    return signers;
321
}
322
323
#ifndef NO_BIO
324
325
PKCS7* wolfSSL_d2i_PKCS7_bio(WOLFSSL_BIO* bio, PKCS7** p7)
326
{
327
    WOLFSSL_PKCS7* pkcs7;
328
    int ret;
329
330
    WOLFSSL_ENTER("wolfSSL_d2i_PKCS7_bio");
331
332
    if (bio == NULL)
333
        return NULL;
334
335
    if ((pkcs7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL)
336
        return NULL;
337
338
    pkcs7->len = wolfSSL_BIO_get_len(bio);
339
    if (pkcs7->len < 0){
340
        wolfSSL_PKCS7_free((PKCS7*)pkcs7);
341
        return NULL;
342
    }
343
    pkcs7->data = (byte*)XMALLOC(pkcs7->len, NULL, DYNAMIC_TYPE_PKCS7);
344
    if (pkcs7->data == NULL) {
345
        wolfSSL_PKCS7_free((PKCS7*)pkcs7);
346
        return NULL;
347
    }
348
349
    if ((ret = wolfSSL_BIO_read(bio, pkcs7->data, pkcs7->len)) <= 0) {
350
        wolfSSL_PKCS7_free((PKCS7*)pkcs7);
351
        return NULL;
352
    }
353
    /* pkcs7->len may change if using b64 for example */
354
    pkcs7->len = ret;
355
356
    if (wc_PKCS7_VerifySignedData(&pkcs7->pkcs7, pkcs7->data, pkcs7->len)
357
                                                                         != 0) {
358
        WOLFSSL_MSG("wc_PKCS7_VerifySignedData failed");
359
        wolfSSL_PKCS7_free((PKCS7*)pkcs7);
360
        return NULL;
361
    }
362
363
    if (p7 != NULL)
364
        *p7 = (PKCS7*)pkcs7;
365
    return (PKCS7*)pkcs7;
366
}
367
368
int wolfSSL_i2d_PKCS7(PKCS7 *p7, unsigned char **out)
369
{
370
    byte* output = NULL;
371
    int localBuf = 0;
372
    int len;
373
    WC_RNG rng;
374
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
375
    WOLFSSL_ENTER("wolfSSL_i2d_PKCS7");
376
377
    if (!out || !p7) {
378
        WOLFSSL_MSG("Bad parameter");
379
        return WOLFSSL_FAILURE;
380
    }
381
382
    if (!p7->rng) {
383
        if (wc_InitRng(&rng) != 0) {
384
            WOLFSSL_MSG("wc_InitRng error");
385
            return WOLFSSL_FAILURE;
386
        }
387
        p7->rng = &rng; /* cppcheck-suppress autoVariables
388
                         */
389
    }
390
391
    if ((len = wc_PKCS7_EncodeSignedData(p7, NULL, 0)) < 0) {
392
        WOLFSSL_MSG("wc_PKCS7_EncodeSignedData error");
393
        goto cleanup;
394
    }
395
396
    if (*out == NULL) {
397
        output = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
398
        if (!output) {
399
            WOLFSSL_MSG("malloc error");
400
            goto cleanup;
401
        }
402
        localBuf = 1;
403
    }
404
    else {
405
        output = *out;
406
    }
407
408
    if ((len = wc_PKCS7_EncodeSignedData(p7, output, (word32)len)) < 0) {
409
        WOLFSSL_MSG("wc_PKCS7_EncodeSignedData error");
410
        goto cleanup;
411
    }
412
413
    ret = len;
414
cleanup:
415
    if (p7->rng == &rng) {
416
        wc_FreeRng(&rng);
417
        p7->rng = NULL;
418
    }
419
    if (ret == WC_NO_ERR_TRACE(WOLFSSL_FAILURE) && localBuf)
420
        XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER);
421
    if (ret != WC_NO_ERR_TRACE(WOLFSSL_FAILURE))
422
        *out = output;
423
    return ret;
424
}
425
426
int wolfSSL_i2d_PKCS7_bio(WOLFSSL_BIO *bio, PKCS7 *p7)
427
{
428
    byte* output = NULL;
429
    int len;
430
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
431
    WOLFSSL_ENTER("wolfSSL_i2d_PKCS7_bio");
432
433
    if (!bio || !p7) {
434
        WOLFSSL_MSG("Bad parameter");
435
        return WOLFSSL_FAILURE;
436
    }
437
438
    if ((len = wolfSSL_i2d_PKCS7(p7, &output)) ==
439
        WC_NO_ERR_TRACE(WOLFSSL_FAILURE))
440
    {
441
        WOLFSSL_MSG("wolfSSL_i2d_PKCS7 error");
442
        goto cleanup;
443
    }
444
445
    if (wolfSSL_BIO_write(bio, output, len) <= 0) {
446
        WOLFSSL_MSG("wolfSSL_BIO_write error");
447
        goto cleanup;
448
    }
449
450
    ret = WOLFSSL_SUCCESS;
451
cleanup:
452
    XFREE(output, NULL, DYNAMIC_TYPE_TMP_BUFFER);
453
    return ret;
454
}
455
456
/**
457
 * Creates and returns a PKCS7 signedData structure.
458
 *
459
 * Inner content type is set to DATA to match OpenSSL behavior.
460
 *
461
 * signer   - certificate to sign bundle with
462
 * pkey     - private key matching signer
463
 * certs    - optional additional set of certificates to include
464
 * in       - input data to be signed
465
 * flags    - optional set of flags to control sign behavior
466
 *
467
 *    PKCS7_BINARY   - Do not translate input data to MIME canonical
468
 *                     format (\r\n line endings), thus preventing corruption of
469
 *                     binary content.
470
 *    PKCS7_TEXT     - Prepend MIME headers for text/plain to content.
471
 *    PKCS7_DETACHED - Set signature detached, omit content from output bundle.
472
 *    PKCS7_STREAM   - initialize PKCS7 struct for signing, do not read data.
473
 *
474
 * Flags not currently supported:
475
 *    PKCS7_NOCERTS  - Do not include the signer cert in the output bundle.
476
 *    PKCS7_PARTIAL  - Allow for PKCS7_sign() to be only partially set up,
477
 *                     then signers etc to be added separately before
478
 *                     calling PKCS7_final().
479
 *
480
 * Returns valid PKCS7 structure pointer, or NULL if an error occurred.
481
 */
482
PKCS7* wolfSSL_PKCS7_sign(WOLFSSL_X509* signer, WOLFSSL_EVP_PKEY* pkey,
483
        WOLFSSL_STACK* certs, WOLFSSL_BIO* in, int flags)
484
{
485
    int err = 0;
486
    WOLFSSL_PKCS7* p7 = NULL;
487
    WOLFSSL_STACK* cert = certs;
488
489
    WOLFSSL_ENTER("wolfSSL_PKCS7_sign");
490
491
    if (flags & PKCS7_NOCERTS) {
492
        WOLFSSL_MSG("PKCS7_NOCERTS flag not yet supported");
493
        err = 1;
494
    }
495
496
    if (flags & PKCS7_PARTIAL) {
497
        WOLFSSL_MSG("PKCS7_PARTIAL flag not yet supported");
498
        err = 1;
499
    }
500
501
    if ((err == 0) && (signer == NULL || signer->derCert == NULL ||
502
                       signer->derCert->length == 0)) {
503
        WOLFSSL_MSG("Bad function arg, signer is NULL or incomplete");
504
        err = 1;
505
    }
506
507
    if ((err == 0) && (pkey == NULL || pkey->pkey.ptr == NULL ||
508
                       pkey->pkey_sz <= 0)) {
509
        WOLFSSL_MSG("Bad function arg, pkey is NULL or incomplete");
510
        err = 1;
511
    }
512
513
    if ((err == 0) && (in == NULL) && !(flags & PKCS7_STREAM)) {
514
        WOLFSSL_MSG("input data required unless PKCS7_STREAM used");
515
        err = 1;
516
    }
517
518
    if ((err == 0) && ((p7 = (WOLFSSL_PKCS7*)wolfSSL_PKCS7_new()) == NULL)) {
519
        WOLFSSL_MSG("Error allocating new WOLFSSL_PKCS7");
520
        err = 1;
521
    }
522
523
    /* load signer certificate */
524
    if (err == 0) {
525
        if (wc_PKCS7_InitWithCert(&p7->pkcs7, signer->derCert->buffer,
526
                                  signer->derCert->length) != 0) {
527
            WOLFSSL_MSG("Failed to load signer certificate");
528
            err = 1;
529
        }
530
    }
531
532
    /* set signer private key, data types, defaults */
533
    if (err == 0) {
534
        p7->pkcs7.privateKey = (byte*)pkey->pkey.ptr;
535
        p7->pkcs7.privateKeySz = (word32)pkey->pkey_sz;
536
        p7->pkcs7.contentOID = DATA;  /* inner content default is DATA */
537
        p7->pkcs7.hashOID = SHA256h;  /* default to SHA-256 hash type */
538
        p7->type = SIGNED_DATA;       /* PKCS7_final switches on type */
539
    }
540
541
    /* add additional chain certs if provided */
542
    while (cert && (err == 0)) {
543
        if (cert->data.x509 != NULL && cert->data.x509->derCert != NULL) {
544
            if (wc_PKCS7_AddCertificate(&p7->pkcs7,
545
                                cert->data.x509->derCert->buffer,
546
                                cert->data.x509->derCert->length) != 0) {
547
                WOLFSSL_MSG("Error in wc_PKCS7_AddCertificate");
548
                err = 1;
549
            }
550
        }
551
        cert = cert->next;
552
    }
553
554
    if ((err == 0) && (flags & PKCS7_DETACHED)) {
555
        if (wc_PKCS7_SetDetached(&p7->pkcs7, 1) != 0) {
556
            WOLFSSL_MSG("Failed to set signature detached");
557
            err = 1;
558
        }
559
    }
560
561
    if ((err == 0) && (flags & PKCS7_STREAM)) {
562
        /* if streaming, return before finalizing */
563
        return (PKCS7*)p7;
564
    }
565
566
    if ((err == 0) && (wolfSSL_PKCS7_final((PKCS7*)p7, in, flags) != 1)) {
567
        WOLFSSL_MSG("Error calling wolfSSL_PKCS7_final");
568
        err = 1;
569
    }
570
571
    if ((err != 0) && (p7 != NULL)) {
572
        wolfSSL_PKCS7_free((PKCS7*)p7);
573
        p7 = NULL;
574
    }
575
576
    return (PKCS7*)p7;
577
}
578
579
#ifdef HAVE_SMIME
580
581
#ifndef MAX_MIME_LINE_LEN
582
    #define MAX_MIME_LINE_LEN 1024
583
#endif
584
585
/**
586
 * Copy input BIO to output BIO, but convert all line endings to CRLF (\r\n),
587
 * used by PKCS7_final().
588
 *
589
 * in  - input WOLFSSL_BIO to be converted
590
 * out - output WOLFSSL_BIO to hold copy of in, with line endings adjusted
591
 *
592
 * Return 0 on success, negative on error
593
 */
594
static int wolfSSL_BIO_to_MIME_crlf(WOLFSSL_BIO* in, WOLFSSL_BIO* out)
595
{
596
    int ret = 0;
597
    int lineLen = 0;
598
    word32 canonLineLen = 0;
599
    char* canonLine = NULL;
600
    WC_DECLARE_VAR(line, char, MAX_MIME_LINE_LEN, 0);
601
602
    if (in == NULL || out == NULL) {
603
        return BAD_FUNC_ARG;
604
    }
605
606
#ifdef WOLFSSL_SMALL_STACK
607
    line = (char*)XMALLOC(MAX_MIME_LINE_LEN, in->heap,
608
                          DYNAMIC_TYPE_TMP_BUFFER);
609
    if (line == NULL) {
610
        return MEMORY_E;
611
    }
612
#endif
613
    XMEMSET(line, 0, MAX_MIME_LINE_LEN);
614
615
    while ((lineLen = wolfSSL_BIO_gets(in, line, MAX_MIME_LINE_LEN)) > 0) {
616
617
        if (line[lineLen - 1] == '\r' || line[lineLen - 1] == '\n') {
618
            canonLineLen = (word32)lineLen;
619
            if ((canonLine = wc_MIME_single_canonicalize(
620
                                line, &canonLineLen)) == NULL) {
621
                ret = WOLFSSL_FATAL_ERROR;
622
                break;
623
            }
624
625
            /* remove trailing null */
626
            if (canonLineLen >= 1 && canonLine[canonLineLen-1] == '\0') {
627
                canonLineLen--;
628
            }
629
630
            if (wolfSSL_BIO_write(out, canonLine, (int)canonLineLen) < 0) {
631
                ret = WOLFSSL_FATAL_ERROR;
632
                break;
633
            }
634
            XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7);
635
            canonLine = NULL;
636
        }
637
        else {
638
            /* no line ending in current line, write direct to out */
639
            if (wolfSSL_BIO_write(out, line, lineLen) < 0) {
640
                ret = WOLFSSL_FATAL_ERROR;
641
                break;
642
            }
643
        }
644
    }
645
646
    XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7);
647
    WC_FREE_VAR_EX(line, in->heap, DYNAMIC_TYPE_TMP_BUFFER);
648
649
    return ret;
650
}
651
652
#endif /* HAVE_SMIME */
653
654
/* Used by both PKCS7_final() and PKCS7_verify() */
655
static const char contTypeText[] = "Content-Type: text/plain\r\n\r\n";
656
657
/**
658
 * Finalize PKCS7 structure, currently supports signedData only.
659
 *
660
 * Does not generate final bundle (ie: signedData), but finalizes
661
 * the PKCS7 structure in preparation for a output function to be called next.
662
 *
663
 * pkcs7 - initialized PKCS7 structure, populated with signer, etc
664
 * in    - input data
665
 * flags - flags to control PKCS7 behavior. Other flags except those noted
666
 *         below are ignored:
667
 *
668
 *    PKCS7_BINARY - Do not translate input data to MIME canonical
669
 *                   format (\r\n line endings), thus preventing corruption of
670
 *                   binary content.
671
 *    PKCS7_TEXT   - Prepend MIME headers for text/plain to content.
672
 *
673
 * Returns 1 on success, 0 on error
674
 */
675
int wolfSSL_PKCS7_final(PKCS7* pkcs7, WOLFSSL_BIO* in, int flags)
676
{
677
    int ret = 1;
678
    int memSz = 0;
679
    unsigned char* mem = NULL;
680
    WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
681
    WOLFSSL_BIO* data = NULL;
682
683
    WOLFSSL_ENTER("wolfSSL_PKCS7_final");
684
685
    if (p7 == NULL || in == NULL) {
686
        WOLFSSL_MSG("Bad input args to PKCS7_final");
687
        ret = 0;
688
    }
689
690
    if (ret == 1) {
691
        if ((data = wolfSSL_BIO_new(wolfSSL_BIO_s_mem())) == NULL) {
692
            WOLFSSL_MSG("Error in wolfSSL_BIO_new");
693
            ret = 0;
694
        }
695
    }
696
697
    /* prepend Content-Type header if PKCS7_TEXT */
698
    if ((ret == 1) && (flags & PKCS7_TEXT)) {
699
        if (wolfSSL_BIO_write(data, contTypeText,
700
                              (int)XSTR_SIZEOF(contTypeText)) < 0) {
701
            WOLFSSL_MSG("Error prepending Content-Type header");
702
            ret = 0;
703
        }
704
    }
705
706
    /* convert line endings to CRLF if !PKCS7_BINARY */
707
    if (ret == 1) {
708
        if (flags & PKCS7_BINARY) {
709
710
            /* no CRLF conversion, direct copy content */
711
            if ((memSz = wolfSSL_BIO_get_len(in)) <= 0) {
712
                ret = 0;
713
            }
714
            if (ret == 1) {
715
                mem = (unsigned char*)XMALLOC(memSz, in->heap,
716
                                              DYNAMIC_TYPE_TMP_BUFFER);
717
                if (mem == NULL) {
718
                    WOLFSSL_MSG("Failed to allocate memory for input data");
719
                    ret = 0;
720
                }
721
            }
722
723
            if (ret == 1) {
724
                if (wolfSSL_BIO_read(in, mem, memSz) != memSz) {
725
                    WOLFSSL_MSG("Error reading from input BIO");
726
                    ret = 0;
727
                }
728
                else if (wolfSSL_BIO_write(data, mem, memSz) < 0) {
729
                    ret = 0;
730
                }
731
            }
732
733
            XFREE(mem, in->heap, DYNAMIC_TYPE_TMP_BUFFER);
734
        }
735
        else {
736
    #ifdef HAVE_SMIME
737
            /* convert content line endings to CRLF */
738
            if (wolfSSL_BIO_to_MIME_crlf(in, data) != 0) {
739
                WOLFSSL_MSG("Error converting line endings to CRLF");
740
                ret = 0;
741
            }
742
            else {
743
                p7->pkcs7.contentCRLF = 1;
744
            }
745
    #else
746
            WOLFSSL_MSG("Without PKCS7_BINARY requires wolfSSL to be built "
747
                        "with HAVE_SMIME");
748
            ret = 0;
749
    #endif
750
        }
751
    }
752
753
    if ((ret == 1) && ((memSz = wolfSSL_BIO_get_mem_data(data, &mem)) < 0)) {
754
        WOLFSSL_MSG("Error in wolfSSL_BIO_get_mem_data");
755
        ret = 0;
756
    }
757
758
    if (ret == 1) {
759
        XFREE(p7->data, NULL, DYNAMIC_TYPE_PKCS7);
760
        p7->data = (byte*)XMALLOC(memSz, NULL, DYNAMIC_TYPE_PKCS7);
761
        if (p7->data == NULL) {
762
            ret = 0;
763
        }
764
        else {
765
            XMEMCPY(p7->data, mem, memSz);
766
            p7->len = memSz;
767
        }
768
    }
769
770
    if (ret == 1) {
771
        p7->pkcs7.content = p7->data;
772
        p7->pkcs7.contentSz = (word32)p7->len;
773
    }
774
775
    if (data != NULL) {
776
        wolfSSL_BIO_free(data);
777
    }
778
779
    return ret;
780
}
781
782
int wolfSSL_PKCS7_verify(PKCS7* pkcs7, WOLFSSL_STACK* certs,
783
        WOLFSSL_X509_STORE* store, WOLFSSL_BIO* in, WOLFSSL_BIO* out, int flags)
784
{
785
    int i, ret = 0;
786
    unsigned char* mem = NULL;
787
    int memSz = 0;
788
    WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
789
    int contTypeLen;
790
    WOLFSSL_X509* signer = NULL;
791
    WOLFSSL_STACK* signers = NULL;
792
    X509_STORE_CTX* ctx = NULL;
793
794
795
    WOLFSSL_ENTER("wolfSSL_PKCS7_verify");
796
797
    if (pkcs7 == NULL)
798
        return WOLFSSL_FAILURE;
799
800
    if (in != NULL) {
801
        if ((memSz = wolfSSL_BIO_get_mem_data(in, &mem)) < 0)
802
            return WOLFSSL_FAILURE;
803
804
        p7->pkcs7.content = mem;
805
        p7->pkcs7.contentSz = (word32)memSz;
806
    }
807
808
    /* certs is the list of certificates to find the cert with issuer/serial. */
809
    (void)certs;
810
    /* store is the certificate store to use to verify signer certificate
811
     * associated with the signers.
812
     */
813
    (void)store;
814
815
    ret = wc_PKCS7_VerifySignedData(&p7->pkcs7, p7->data, p7->len);
816
    if (ret != 0)
817
        return WOLFSSL_FAILURE;
818
819
    /* Reject a degenerate (certs-only) PKCS#7 with no verified signer. Such an
820
     * object has empty signerInfos, so wc_PKCS7_VerifySignedData() succeeds
821
     * without authenticating the content. pkcs7.verifyCert is only set once a
822
     * signer's signature has actually been verified, so a NULL value here means
823
     * the content carries no valid signature and must not be reported as
824
     * verified - regardless of PKCS7_NOVERIFY, which only suppresses signer
825
     * certificate chain validation, not the requirement that a signature exist.
826
     */
827
    if (p7->pkcs7.verifyCert == NULL) {
828
        WOLFSSL_MSG("PKCS7 has no verified signer (degenerate/certs-only)");
829
        return WOLFSSL_FAILURE;
830
    }
831
832
    if ((flags & PKCS7_NOVERIFY) != PKCS7_NOVERIFY) {
833
        /* Verify signer certificates */
834
        if (store == NULL || store->cm == NULL) {
835
            WOLFSSL_MSG("No store or store certs, but PKCS7_NOVERIFY not set");
836
            return WOLFSSL_FAILURE;
837
        }
838
839
        ctx = X509_STORE_CTX_new();
840
        if (ctx == NULL) {
841
            WOLFSSL_MSG("Error allocating X509 Store Context");
842
            return WOLFSSL_FAILURE;
843
        }
844
845
        signers = wolfSSL_PKCS7_get0_signers(pkcs7, certs, flags);
846
        if (signers == NULL) {
847
            WOLFSSL_MSG("No signers found to verify");
848
            wolfSSL_X509_STORE_CTX_free(ctx);
849
            return WOLFSSL_FAILURE;
850
        }
851
852
        for (i = 0; i < wolfSSL_sk_X509_num(signers); i++) {
853
            signer = wolfSSL_sk_X509_value(signers, i);
854
            if (wolfSSL_X509_STORE_CTX_init(ctx, store, signer, NULL)
855
                        != WOLFSSL_SUCCESS) {
856
                WOLFSSL_MSG("Failed to initialize X509 STORE CTX");
857
                wolfSSL_sk_X509_pop_free(signers, NULL);
858
                wolfSSL_X509_STORE_CTX_free(ctx);
859
                return WOLFSSL_FAILURE;
860
            }
861
            if (wolfSSL_X509_verify_cert(ctx) != WOLFSSL_SUCCESS) {
862
                WOLFSSL_MSG("Failed to verify signer certificate");
863
                wolfSSL_sk_X509_pop_free(signers, NULL);
864
                wolfSSL_X509_STORE_CTX_free(ctx);
865
                return WOLFSSL_FAILURE;
866
            }
867
        }
868
        wolfSSL_sk_X509_pop_free(signers, NULL);
869
        wolfSSL_X509_STORE_CTX_free(ctx);
870
    }
871
872
    if (flags & PKCS7_TEXT) {
873
        /* strip MIME header for text/plain, otherwise error */
874
        contTypeLen = XSTR_SIZEOF(contTypeText);
875
        if ((p7->pkcs7.contentSz < (word32)contTypeLen) ||
876
            (XMEMCMP(p7->pkcs7.content, contTypeText, contTypeLen) != 0)) {
877
            WOLFSSL_MSG("Error PKCS7 Content-Type not found with PKCS7_TEXT");
878
            return WOLFSSL_FAILURE;
879
        }
880
        p7->pkcs7.content += contTypeLen;
881
        p7->pkcs7.contentSz -= contTypeLen;
882
    }
883
884
    if (out != NULL) {
885
        wolfSSL_BIO_write(out, p7->pkcs7.content, p7->pkcs7.contentSz);
886
    }
887
888
    WOLFSSL_LEAVE("wolfSSL_PKCS7_verify", WOLFSSL_SUCCESS);
889
890
    return WOLFSSL_SUCCESS;
891
}
892
893
/**
894
 * This API was added as a helper function for libest. It
895
 * encodes a stack of certificates to pkcs7 format.
896
 * @param pkcs7 PKCS7 parameter object
897
 * @param certs WOLFSSL_STACK_OF(WOLFSSL_X509)*
898
 * @param out   Output bio
899
 * @return WOLFSSL_SUCCESS on success and WOLFSSL_FAILURE on failure
900
 */
901
int wolfSSL_PKCS7_encode_certs(PKCS7* pkcs7, WOLFSSL_STACK* certs,
902
        WOLFSSL_BIO* out)
903
{
904
    int ret;
905
    WOLFSSL_PKCS7* p7;
906
    WOLFSSL_STACK* certHead = certs;
907
    WOLFSSL_ENTER("wolfSSL_PKCS7_encode_certs");
908
909
    if (!pkcs7 || !certs || !out) {
910
        WOLFSSL_MSG("Bad parameter");
911
        return WOLFSSL_FAILURE;
912
    }
913
914
    p7 = (WOLFSSL_PKCS7*)pkcs7;
915
916
    if (pkcs7->certList) {
917
        WOLFSSL_MSG("wolfSSL_PKCS7_encode_certs called multiple times on same "
918
                    "struct");
919
        return WOLFSSL_FAILURE;
920
    }
921
922
    if (certs) {
923
        /* Save some of the values */
924
        int hashOID = pkcs7->hashOID;
925
        byte version = pkcs7->version;
926
927
        if (!certs->data.x509 || !certs->data.x509->derCert) {
928
            WOLFSSL_MSG("Missing cert");
929
            return WOLFSSL_FAILURE;
930
        }
931
932
        if (wc_PKCS7_InitWithCert(pkcs7, certs->data.x509->derCert->buffer,
933
                                      certs->data.x509->derCert->length) != 0) {
934
            WOLFSSL_MSG("wc_PKCS7_InitWithCert error");
935
            return WOLFSSL_FAILURE;
936
        }
937
        certs = certs->next;
938
939
        pkcs7->hashOID = hashOID;
940
        pkcs7->version = version;
941
    }
942
943
    /* Add the certs to the PKCS7 struct */
944
    while (certs) {
945
        if (!certs->data.x509 || !certs->data.x509->derCert) {
946
            WOLFSSL_MSG("Missing cert");
947
            return WOLFSSL_FAILURE;
948
        }
949
        if (wc_PKCS7_AddCertificate(pkcs7, certs->data.x509->derCert->buffer,
950
                                      certs->data.x509->derCert->length) != 0) {
951
            WOLFSSL_MSG("wc_PKCS7_AddCertificate error");
952
            return WOLFSSL_FAILURE;
953
        }
954
        certs = certs->next;
955
    }
956
957
    if (wc_PKCS7_SetSignerIdentifierType(pkcs7, DEGENERATE_SID) != 0) {
958
        WOLFSSL_MSG("wc_PKCS7_SetSignerIdentifierType error");
959
        return WOLFSSL_FAILURE;
960
    }
961
962
    ret = wolfSSL_i2d_PKCS7_bio(out, pkcs7);
963
964
    /* Transfer stack ownership only on full success; every failure path leaves
965
     * p7->certs NULL so the caller still owns certs and cannot double-free. */
966
    if (ret == WOLFSSL_SUCCESS) {
967
        p7->certs = certHead;
968
    }
969
970
    return ret;
971
}
972
973
/******************************************************************************
974
* wolfSSL_PEM_write_bio_PKCS7 - writes the PKCS7 data to BIO
975
*
976
* RETURNS:
977
* returns WOLFSSL_SUCCESS on success, otherwise returns WOLFSSL_FAILURE
978
*/
979
int wolfSSL_PEM_write_bio_PKCS7(WOLFSSL_BIO* bio, PKCS7* p7)
980
{
981
#ifdef WOLFSSL_SMALL_STACK
982
    byte* outputHead;
983
    byte* outputFoot;
984
#else
985
    byte outputHead[2048];
986
    byte outputFoot[2048];
987
#endif
988
    word32 outputHeadSz = 2048;
989
    word32 outputFootSz = 2048;
990
    word32 outputSz = 0;
991
    byte*  output = NULL;
992
    byte*  pem = NULL;
993
    int    pemSz = -1;
994
    enum wc_HashType hashType;
995
    byte hashBuf[WC_MAX_DIGEST_SIZE];
996
    word32 hashSz = 0;
997
998
    WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PKCS7");
999
1000
    if (bio == NULL || p7 == NULL)
1001
        return WOLFSSL_FAILURE;
1002
1003
#ifdef WOLFSSL_SMALL_STACK
1004
    outputHead = (byte*)XMALLOC(outputHeadSz, bio->heap,
1005
        DYNAMIC_TYPE_TMP_BUFFER);
1006
    if (outputHead == NULL)
1007
        return WOLFSSL_FAILURE;
1008
1009
    outputFoot = (byte*)XMALLOC(outputFootSz, bio->heap,
1010
        DYNAMIC_TYPE_TMP_BUFFER);
1011
    if (outputFoot == NULL)
1012
        goto error;
1013
1014
#endif
1015
1016
    XMEMSET(hashBuf, 0, WC_MAX_DIGEST_SIZE);
1017
    XMEMSET(outputHead, 0, outputHeadSz);
1018
    XMEMSET(outputFoot, 0, outputFootSz);
1019
1020
    hashType = wc_OidGetHash(p7->hashOID);
1021
    hashSz = (word32)wc_HashGetDigestSize(hashType);
1022
    if (hashSz > WC_MAX_DIGEST_SIZE)
1023
        goto error;
1024
1025
    /* only SIGNED_DATA is supported */
1026
    switch (p7->contentOID) {
1027
        case SIGNED_DATA:
1028
            break;
1029
        default:
1030
            WOLFSSL_MSG("Unknown PKCS#7 Type");
1031
            goto error;
1032
    };
1033
1034
    if ((wc_PKCS7_EncodeSignedData_ex(p7, hashBuf, hashSz,
1035
        outputHead, &outputHeadSz, outputFoot, &outputFootSz)) != 0)
1036
        goto error;
1037
1038
    outputSz = outputHeadSz + p7->contentSz + outputFootSz;
1039
    output = (byte*)XMALLOC(outputSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1040
1041
    if (!output)
1042
        goto error;
1043
1044
    XMEMSET(output, 0, outputSz);
1045
    outputSz = 0;
1046
    XMEMCPY(&output[outputSz], outputHead, outputHeadSz);
1047
    outputSz += outputHeadSz;
1048
    XMEMCPY(&output[outputSz], p7->content, p7->contentSz);
1049
    outputSz += p7->contentSz;
1050
    XMEMCPY(&output[outputSz], outputFoot, outputFootSz);
1051
    outputSz += outputFootSz;
1052
1053
    /* get PEM size */
1054
    pemSz = wc_DerToPemEx(output, outputSz, NULL, 0, NULL, CERT_TYPE);
1055
    if (pemSz < 0)
1056
        goto error;
1057
1058
    pemSz++; /* for '\0'*/
1059
1060
    /* create PEM buffer and convert from DER to PEM*/
1061
    if ((pem = (byte*)XMALLOC(pemSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER))
1062
                                                                        == NULL)
1063
        goto error;
1064
1065
    XMEMSET(pem, 0, pemSz);
1066
1067
    if (wc_DerToPemEx(output, outputSz, pem, (word32)pemSz, NULL,CERT_TYPE)
1068
                                                                          < 0) {
1069
        goto error;
1070
    }
1071
    if ((wolfSSL_BIO_write(bio, pem, pemSz) == pemSz)) {
1072
        XFREE(output, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1073
        XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1074
        WC_FREE_VAR_EX(outputHead, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1075
        WC_FREE_VAR_EX(outputFoot, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1076
        return WOLFSSL_SUCCESS;
1077
    }
1078
1079
error:
1080
    WC_FREE_VAR_EX(outputHead, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1081
    WC_FREE_VAR_EX(outputFoot, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1082
    XFREE(output, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1083
    XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1084
    return WOLFSSL_FAILURE;
1085
}
1086
1087
#ifdef HAVE_SMIME
1088
/*****************************************************************************
1089
* wolfSSL_SMIME_read_PKCS7 - Reads the given S/MIME message and parses it into
1090
* a PKCS7 object. In case of a multipart message, stores the signed data in
1091
* bcont.
1092
*
1093
* RETURNS:
1094
* returns pointer to a PKCS7 structure on success, otherwise returns NULL
1095
*/
1096
PKCS7* wolfSSL_SMIME_read_PKCS7(WOLFSSL_BIO* in, WOLFSSL_BIO** bcont)
1097
{
1098
    MimeHdr* allHdrs = NULL;
1099
    MimeHdr* curHdr = NULL;
1100
    MimeParam* curParam = NULL;
1101
    int inLen = 0;
1102
    byte* bcontMem = NULL;
1103
    int bcontMemSz = 0;
1104
    int sectionLen = 0;
1105
    int ret = -1;
1106
    char* section = NULL;
1107
    char* canonLine = NULL;
1108
    char* canonSection = NULL;
1109
    PKCS7* pkcs7 = NULL;
1110
    word32 outLen = 0;
1111
    word32 canonLineLen = 0;
1112
    byte* out = NULL;
1113
    byte* outHead = NULL;
1114
1115
    int canonPos = 0;
1116
    int lineLen = 0;
1117
    int remainLen = 0;
1118
    byte isEnd = 0;
1119
    size_t canonSize = 0;
1120
    size_t boundLen = 0;
1121
    char* boundary = NULL;
1122
1123
    static const char kContType[] = "Content-Type";
1124
    static const char kCTE[] = "Content-Transfer-Encoding";
1125
    static const char kMultSigned[] = "multipart/signed";
1126
    static const char kAppPkcsSign[] = "application/pkcs7-signature";
1127
    static const char kAppXPkcsSign[] = "application/x-pkcs7-signature";
1128
    static const char kAppPkcs7Mime[] = "application/pkcs7-mime";
1129
    static const char kAppXPkcs7Mime[] = "application/x-pkcs7-mime";
1130
1131
    WOLFSSL_ENTER("wolfSSL_SMIME_read_PKCS7");
1132
1133
    if (in == NULL || bcont == NULL) {
1134
        goto error;
1135
    }
1136
    inLen = wolfSSL_BIO_get_len(in);
1137
    if (inLen <= 0) {
1138
        goto error;
1139
    }
1140
    remainLen = wolfSSL_BIO_get_len(in);
1141
    if (remainLen <= 0) {
1142
        goto error;
1143
    }
1144
1145
    section = (char*)XMALLOC(remainLen+1, NULL, DYNAMIC_TYPE_PKCS7);
1146
    if (section == NULL) {
1147
        goto error;
1148
    }
1149
    lineLen = wolfSSL_BIO_gets(in, section, remainLen);
1150
    if (lineLen <= 0) {
1151
        goto error;
1152
    }
1153
    while (isEnd == 0 && remainLen > 0) {
1154
        sectionLen += lineLen;
1155
        remainLen -= lineLen;
1156
        lineLen = wolfSSL_BIO_gets(in, &section[sectionLen], remainLen);
1157
        if (lineLen <= 0) {
1158
            goto error;
1159
        }
1160
        /* Line with just newline signals end of headers. */
1161
        if ((lineLen==2 && !XSTRNCMP(&section[sectionLen],
1162
                                     "\r\n", 2)) ||
1163
            (lineLen==1 && (section[sectionLen] == '\r' ||
1164
                            section[sectionLen] == '\n'))) {
1165
            isEnd = 1;
1166
        }
1167
    }
1168
    section[sectionLen] = '\0';
1169
    ret = wc_MIME_parse_headers(section, sectionLen, &allHdrs);
1170
    if (ret < 0) {
1171
        WOLFSSL_MSG("Parsing MIME headers failed.");
1172
        goto error;
1173
    }
1174
    isEnd = 0;
1175
    section[0] = '\0';
1176
    sectionLen = 0;
1177
1178
    curHdr = wc_MIME_find_header_name(kContType, allHdrs);
1179
    if (curHdr && !XSTRNCMP(curHdr->body, kMultSigned,
1180
                            XSTR_SIZEOF(kMultSigned))) {
1181
        curParam = wc_MIME_find_param_attr("protocol", curHdr->params);
1182
        if (curParam && (!XSTRNCMP(curParam->value, kAppPkcsSign,
1183
                                   XSTR_SIZEOF(kAppPkcsSign)) ||
1184
                         !XSTRNCMP(curParam->value, kAppXPkcsSign,
1185
                                   XSTR_SIZEOF(kAppXPkcsSign)))) {
1186
            curParam = wc_MIME_find_param_attr("boundary", curHdr->params);
1187
            if (curParam == NULL) {
1188
                goto error;
1189
            }
1190
1191
            boundLen = XSTRLEN(curParam->value) + 2;
1192
            boundary = (char*)XMALLOC(boundLen+1, NULL, DYNAMIC_TYPE_PKCS7);
1193
            if (boundary == NULL) {
1194
                goto error;
1195
            }
1196
            XMEMSET(boundary, 0, (word32)(boundLen+1));
1197
            boundary[0] = boundary[1] = '-';
1198
            /* analyzers have issues with using strncpy and strcpy here */
1199
            XMEMCPY(&boundary[2], curParam->value, boundLen - 2);
1200
1201
            /* Parse up to first boundary, ignore everything here. */
1202
            lineLen = wolfSSL_BIO_gets(in, section, remainLen);
1203
            if (lineLen <= 0) {
1204
                goto error;
1205
            }
1206
            while (XSTRNCMP(&section[sectionLen], boundary, boundLen) &&
1207
                   remainLen > 0) {
1208
                sectionLen += lineLen;
1209
                remainLen -= lineLen;
1210
                lineLen = wolfSSL_BIO_gets(in, &section[sectionLen],
1211
                                           remainLen);
1212
                if (lineLen <= 0) {
1213
                    goto error;
1214
                }
1215
            }
1216
1217
            section[0] = '\0';
1218
            sectionLen = 0;
1219
            canonSize = (size_t)remainLen + 1;
1220
            canonSection = (char*)XMALLOC(canonSize, NULL,
1221
                                          DYNAMIC_TYPE_PKCS7);
1222
            if (canonSection == NULL) {
1223
                goto error;
1224
            } else {
1225
                XMEMSET(canonSection, 0, (word32)canonSize);
1226
            }
1227
1228
            lineLen = wolfSSL_BIO_gets(in, section, remainLen);
1229
            if (lineLen < 0) {
1230
                goto error;
1231
            }
1232
            while (XSTRNCMP(&section[sectionLen], boundary, boundLen) &&
1233
                            remainLen > 0) {
1234
                canonLineLen = (word32)lineLen;
1235
                canonLine = wc_MIME_single_canonicalize(&section[sectionLen],
1236
                                                        &canonLineLen);
1237
                if (canonLine == NULL) {
1238
                    goto error;
1239
                }
1240
                /* If line endings were added, the initial length may be
1241
                 * exceeded. */
1242
                if ((canonPos + canonLineLen) >= canonSize) {
1243
                    char* newCanonSection;
1244
                    canonSize = canonPos + canonLineLen;
1245
                    newCanonSection = (char*)XREALLOC(canonSection, canonSize,
1246
                                                   NULL, DYNAMIC_TYPE_PKCS7);
1247
                    if (newCanonSection == NULL) {
1248
                        goto error;
1249
                    }
1250
                    canonSection = newCanonSection;
1251
                }
1252
                XMEMCPY(&canonSection[canonPos], canonLine,
1253
                        (int)canonLineLen - 1);
1254
                canonPos += canonLineLen - 1;
1255
                XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7);
1256
                canonLine = NULL;
1257
1258
                sectionLen += lineLen;
1259
                remainLen -= lineLen;
1260
1261
                lineLen = wolfSSL_BIO_gets(in, &section[sectionLen],
1262
                                           remainLen);
1263
                if (lineLen <= 0) {
1264
                    goto error;
1265
                }
1266
            }
1267
1268
            if (canonPos > 0) {
1269
                canonPos--;
1270
            }
1271
1272
            /* Strip the final trailing newline.  Support \r, \n or \r\n. */
1273
            if (canonSection[canonPos] == '\n') {
1274
                if (canonPos > 0) {
1275
                    canonPos--;
1276
                }
1277
            }
1278
1279
            if (canonSection[canonPos] == '\r') {
1280
                if (canonPos > 0) {
1281
                    canonPos--;
1282
                }
1283
            }
1284
1285
            canonSection[canonPos+1] = '\0';
1286
1287
            *bcont = wolfSSL_BIO_new(wolfSSL_BIO_s_mem());
1288
            ret = wolfSSL_BIO_write(*bcont, canonSection,
1289
                                    canonPos + 1);
1290
            if (ret != (canonPos+1)) {
1291
                goto error;
1292
            }
1293
            if ((bcontMemSz = wolfSSL_BIO_get_mem_data(*bcont, &bcontMem))
1294
                                                                          < 0) {
1295
                goto error;
1296
            }
1297
            XFREE(canonSection, NULL, DYNAMIC_TYPE_PKCS7);
1298
            canonSection = NULL;
1299
1300
            wc_MIME_free_hdrs(allHdrs);
1301
            allHdrs = NULL;
1302
            section[0] = '\0';
1303
            sectionLen = 0;
1304
            lineLen = wolfSSL_BIO_gets(in, section, remainLen);
1305
            if (lineLen <= 0) {
1306
                goto error;
1307
            }
1308
            while (isEnd == 0 && remainLen > 0) {
1309
                sectionLen += lineLen;
1310
                remainLen -= lineLen;
1311
                lineLen = wolfSSL_BIO_gets(in, &section[sectionLen],
1312
                                           remainLen);
1313
                if (lineLen <= 0) {
1314
                    goto error;
1315
                }
1316
                /* Line with just newline signals end of headers. */
1317
                if ((lineLen==2 && !XSTRNCMP(&section[sectionLen],
1318
                                             "\r\n", 2)) ||
1319
                    (lineLen==1 && (section[sectionLen] == '\r' ||
1320
                                    section[sectionLen] == '\n'))) {
1321
                    isEnd = 1;
1322
                }
1323
            }
1324
            section[sectionLen] = '\0';
1325
            ret = wc_MIME_parse_headers(section, sectionLen, &allHdrs);
1326
            if (ret < 0) {
1327
                WOLFSSL_MSG("Parsing MIME headers failed.");
1328
                goto error;
1329
            }
1330
            curHdr = wc_MIME_find_header_name(kContType, allHdrs);
1331
            if (curHdr == NULL || (XSTRNCMP(curHdr->body, kAppPkcsSign,
1332
                                   XSTR_SIZEOF(kAppPkcsSign)) &&
1333
                                   XSTRNCMP(curHdr->body, kAppXPkcsSign,
1334
                                   XSTR_SIZEOF(kAppXPkcsSign)))) {
1335
                WOLFSSL_MSG("S/MIME headers not found inside "
1336
                            "multipart message.\n");
1337
                goto error;
1338
            }
1339
1340
            section[0] = '\0';
1341
            sectionLen = 0;
1342
            lineLen = wolfSSL_BIO_gets(in, section, remainLen);
1343
            while (XSTRNCMP(&section[sectionLen], boundary, boundLen) &&
1344
                   remainLen > 0) {
1345
                sectionLen += lineLen;
1346
                remainLen -= lineLen;
1347
                lineLen = wolfSSL_BIO_gets(in, &section[sectionLen],
1348
                                           remainLen);
1349
                if (lineLen <= 0) {
1350
                    goto error;
1351
                }
1352
            }
1353
1354
            XFREE(boundary, NULL, DYNAMIC_TYPE_PKCS7);
1355
            boundary = NULL;
1356
        }
1357
    }
1358
    else if (curHdr && (!XSTRNCMP(curHdr->body, kAppPkcs7Mime,
1359
                                  XSTR_SIZEOF(kAppPkcs7Mime)) ||
1360
                        !XSTRNCMP(curHdr->body, kAppXPkcs7Mime,
1361
                                  XSTR_SIZEOF(kAppXPkcs7Mime)))) {
1362
        sectionLen = wolfSSL_BIO_get_len(in);
1363
        if (sectionLen <= 0) {
1364
            goto error;
1365
        }
1366
        ret = wolfSSL_BIO_read(in, section, sectionLen);
1367
        if (ret < 0 || ret != sectionLen) {
1368
            WOLFSSL_MSG("Error reading input BIO.");
1369
            goto error;
1370
        }
1371
    }
1372
    else {
1373
        WOLFSSL_MSG("S/MIME headers not found.");
1374
        goto error;
1375
    }
1376
1377
    curHdr = wc_MIME_find_header_name(kCTE, allHdrs);
1378
    if (curHdr == NULL) {
1379
        WOLFSSL_MSG("Content-Transfer-Encoding header not found, "
1380
                    "assuming base64 encoding.");
1381
    }
1382
    else if (XSTRNCMP(curHdr->body, "base64", XSTRLEN("base64"))) {
1383
        WOLFSSL_MSG("S/MIME encodings other than base64 are not "
1384
                    "currently supported.\n");
1385
        goto error;
1386
    }
1387
1388
    if (section == NULL || sectionLen <= 0) {
1389
        goto error;
1390
    }
1391
    outLen = (word32)((sectionLen*3+3)/4)+1;
1392
    out = (byte*)XMALLOC(outLen*sizeof(byte), NULL, DYNAMIC_TYPE_PKCS7);
1393
    outHead = out;
1394
    if (outHead == NULL) {
1395
        goto error;
1396
    }
1397
    /* Strip trailing newlines. */
1398
    while ((sectionLen > 0) &&
1399
           (section[sectionLen-1] == '\r' || section[sectionLen-1] == '\n')) {
1400
        sectionLen--;
1401
    }
1402
    section[sectionLen] = '\0';
1403
    ret = Base64_Decode((const byte*)section, (word32)sectionLen, out, &outLen);
1404
    if (ret < 0) {
1405
        WOLFSSL_MSG("Error base64 decoding S/MIME message.");
1406
        goto error;
1407
    }
1408
    pkcs7 = wolfSSL_d2i_PKCS7_only(NULL, (const unsigned char**)&out,
1409
        (int)outLen, bcontMem, (word32)bcontMemSz);
1410
1411
    wc_MIME_free_hdrs(allHdrs);
1412
    XFREE(outHead, NULL, DYNAMIC_TYPE_PKCS7);
1413
    XFREE(section, NULL, DYNAMIC_TYPE_PKCS7);
1414
1415
    return pkcs7;
1416
1417
error:
1418
    wc_MIME_free_hdrs(allHdrs);
1419
    XFREE(boundary, NULL, DYNAMIC_TYPE_PKCS7);
1420
    XFREE(outHead, NULL, DYNAMIC_TYPE_PKCS7);
1421
    XFREE(section, NULL, DYNAMIC_TYPE_PKCS7);
1422
    XFREE(canonSection, NULL, DYNAMIC_TYPE_PKCS7);
1423
    XFREE(canonLine, NULL, DYNAMIC_TYPE_PKCS7);
1424
    if (bcont) {
1425
        wolfSSL_BIO_free(*bcont);
1426
        *bcont = NULL; /* reset 'bcount' pointer to NULL on failure */
1427
    }
1428
1429
    return NULL;
1430
}
1431
1432
/* Convert hash algo OID (from Hash_Sum in asn.h) to SMIME string equivalent.
1433
 * Returns hash algorithm string or "unknown" if not found */
1434
static const char* wolfSSL_SMIME_HashOIDToString(int hashOID)
1435
{
1436
    switch (hashOID) {
1437
        case MD5h:
1438
            return "md5";
1439
        case SHAh:
1440
            return "sha1";
1441
        case SHA224h:
1442
            return "sha-224";
1443
        case SHA256h:
1444
            return "sha-256";
1445
        case SHA384h:
1446
            return "sha-384";
1447
        case SHA512h:
1448
            return "sha-512";
1449
        case SHA3_224h:
1450
            return "sha3-224";
1451
        case SHA3_384h:
1452
            return "sha3-384";
1453
        case SHA3_512h:
1454
            return "sha3-512";
1455
        default:
1456
            break;
1457
    }
1458
1459
    return "unknown";
1460
}
1461
1462
/* Convert PKCS#7 type (from PKCS7_TYPES in pkcs7.h) to SMIME string.
1463
 * RFC2633 only defines signed-data, enveloped-data, certs-only.
1464
 * Returns string on success, NULL on unknown type. */
1465
static const char* wolfSSL_SMIME_PKCS7TypeToString(int type)
1466
{
1467
    switch (type) {
1468
        case SIGNED_DATA:
1469
            return "signed-data";
1470
        case ENVELOPED_DATA:
1471
            return "enveloped-data";
1472
        default:
1473
            break;
1474
    }
1475
1476
    return NULL;
1477
}
1478
1479
/**
1480
 * Convert PKCS7 structure to SMIME format, adding necessary headers.
1481
 *
1482
 * Handles generation of PKCS7 bundle (ie: signedData). PKCS7 structure
1483
 * should be set up beforehand with PKCS7_sign/final/etc. Output is always
1484
 * Base64 encoded.
1485
 *
1486
 * out   - output BIO for SMIME formatted data to be placed
1487
 * pkcs7 - input PKCS7 structure, initialized and set up
1488
 * in    - input content to be encoded into PKCS7
1489
 * flags - flags to control behavior of PKCS7 generation
1490
 *
1491
 * Returns 1 on success, 0 or negative on failure
1492
 */
1493
int wolfSSL_SMIME_write_PKCS7(WOLFSSL_BIO* out, PKCS7* pkcs7, WOLFSSL_BIO* in,
1494
                              int flags)
1495
{
1496
    int i;
1497
    int ret = 1;
1498
    WOLFSSL_PKCS7* p7 = (WOLFSSL_PKCS7*)pkcs7;
1499
    byte* p7out = NULL;
1500
    int len = 0;
1501
1502
    char boundary[33]; /* 32 chars + \0 */
1503
    byte* sigBase64 = NULL;
1504
    word32 sigBase64Len = 0;
1505
    const char* p7TypeString = NULL;
1506
1507
    static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1508
1509
    if (out == NULL || p7 == NULL) {
1510
        WOLFSSL_MSG("Bad function arguments");
1511
        return 0;
1512
    }
1513
1514
    if (in != NULL && (p7->pkcs7.content == NULL || p7->pkcs7.contentSz == 0 ||
1515
                       p7->pkcs7.contentCRLF == 0)) {
1516
        /* store and adjust content line endings for CRLF if needed */
1517
        if (wolfSSL_PKCS7_final((PKCS7*)p7, in, flags) != 1) {
1518
            ret = 0;
1519
        }
1520
    }
1521
1522
    if (ret > 0) {
1523
        /* Generate signedData bundle, DER in output (dynamic) */
1524
        if ((len = wolfSSL_i2d_PKCS7((PKCS7*)p7, &p7out)) ==
1525
            WC_NO_ERR_TRACE(WOLFSSL_FAILURE))
1526
        {
1527
            WOLFSSL_MSG("Error in wolfSSL_i2d_PKCS7");
1528
            ret = 0;
1529
        }
1530
    }
1531
1532
    /* Base64 encode signedData bundle */
1533
    if (ret > 0) {
1534
        if (Base64_Encode(p7out, (word32)len, NULL, &sigBase64Len) !=
1535
            WC_NO_ERR_TRACE(LENGTH_ONLY_E)) {
1536
            ret = 0;
1537
        }
1538
        else {
1539
            sigBase64 = (byte*)XMALLOC(sigBase64Len, NULL,
1540
                                       DYNAMIC_TYPE_TMP_BUFFER);
1541
            if (sigBase64 == NULL) {
1542
                ret = 0;
1543
            }
1544
        }
1545
    }
1546
1547
    if (ret > 0) {
1548
        XMEMSET(sigBase64, 0, sigBase64Len);
1549
        if (Base64_Encode(p7out, (word32)len, sigBase64, &sigBase64Len) < 0) {
1550
            WOLFSSL_MSG("Error in Base64_Encode of signature");
1551
            ret = 0;
1552
        }
1553
    }
1554
1555
    /* build up SMIME message */
1556
    if (ret > 0) {
1557
        if (flags & PKCS7_DETACHED) {
1558
1559
            /* generate random boundary */
1560
            if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
1561
                WOLFSSL_MSG("No RNG to use");
1562
                ret = 0;
1563
            }
1564
1565
            if ((ret > 0) && (wc_LockMutex(&globalRNGMutex) != 0)) {
1566
                WOLFSSL_MSG("Bad Lock Mutex rng");
1567
                ret = 0;
1568
            }
1569
1570
            /* no need to generate random byte for null terminator (size-1) */
1571
            if (ret > 0) {
1572
                if (wc_RNG_GenerateBlock(&globalRNG, (byte*)boundary,
1573
                                  sizeof(boundary) - 1 ) != 0) {
1574
                    WOLFSSL_MSG("Error in wc_RNG_GenerateBlock");
1575
                    ret = 0;
1576
                }
1577
                wc_UnLockMutex(&globalRNGMutex);
1578
            }
1579
1580
            if (ret > 0) {
1581
                for (i = 0; i < (int)sizeof(boundary) - 1; i++) {
1582
                    boundary[i] =
1583
                        alphanum[boundary[i] % XSTR_SIZEOF(alphanum)];
1584
                }
1585
                boundary[sizeof(boundary)-1] = 0;
1586
            }
1587
1588
            if (ret > 0) {
1589
                /* S/MIME header beginning */
1590
                ret = wolfSSL_BIO_printf(out,
1591
                        "MIME-Version: 1.0\n"
1592
                        "Content-Type: multipart/signed; "
1593
                        "protocol=\"application/x-pkcs7-signature\"; "
1594
                        "micalg=\"%s\"; "
1595
                        "boundary=\"----%s\"\n\n"
1596
                        "This is an S/MIME signed message\n\n"
1597
                        "------%s\n",
1598
                        wolfSSL_SMIME_HashOIDToString(p7->pkcs7.hashOID),
1599
                        boundary, boundary);
1600
            }
1601
1602
            if (ret > 0) {
1603
                /* S/MIME content */
1604
                ret = wolfSSL_BIO_write(out,
1605
                        p7->pkcs7.content, p7->pkcs7.contentSz);
1606
            }
1607
1608
            if (ret > 0) {
1609
                /* S/SMIME header end boundary */
1610
                ret = wolfSSL_BIO_printf(out,
1611
                        "\n------%s\n", boundary);
1612
            }
1613
1614
            if (ret > 0) {
1615
                /* Signature and header */
1616
                ret = wolfSSL_BIO_printf(out,
1617
                        "Content-Type: application/x-pkcs7-signature; "
1618
                        "name=\"smime.p7s\"\n"
1619
                        "Content-Transfer-Encoding: base64\n"
1620
                        "Content-Disposition: attachment; "
1621
                        "filename=\"smime.p7s\"\n\n"
1622
                        "%.*s\n" /* Base64 encoded signature */
1623
                        "------%s--\n\n",
1624
                        sigBase64Len, sigBase64,
1625
                        boundary);
1626
            }
1627
        }
1628
        else {
1629
            p7TypeString = wolfSSL_SMIME_PKCS7TypeToString(p7->type);
1630
            if (p7TypeString == NULL) {
1631
                WOLFSSL_MSG("Unsupported PKCS7 SMIME type");
1632
                ret = 0;
1633
            }
1634
1635
            if (ret > 0) {
1636
                /* not detached */
1637
                ret = wolfSSL_BIO_printf(out,
1638
                        "MIME-Version: 1.0\n"
1639
                        "Content-Disposition: attachment; "
1640
                        "filename=\"smime.p7m\"\n"
1641
                        "Content-Type: application/x-pkcs7-mime; "
1642
                        "smime-type=%s; name=\"smime.p7m\"\n"
1643
                        "Content-Transfer-Encoding: base64\n\n"
1644
                        "%.*s\n" /* signature */,
1645
                        p7TypeString, sigBase64Len, sigBase64);
1646
            }
1647
        }
1648
    }
1649
1650
    XFREE(p7out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1651
    XFREE(sigBase64, NULL, DYNAMIC_TYPE_TMP_BUFFER);
1652
1653
    if (ret > 0) {
1654
        return WOLFSSL_SUCCESS;
1655
    }
1656
1657
    return WOLFSSL_FAILURE;
1658
}
1659
1660
#endif /* HAVE_SMIME */
1661
#endif /* !NO_BIO */
1662
#endif /* OPENSSL_ALL */
1663
1664
#endif /* HAVE_PKCS7 */
1665
/*******************************************************************************
1666
 * END OF PKCS7 APIs
1667
 ******************************************************************************/
1668
1669
/*******************************************************************************
1670
 * START OF PKCS12 APIs
1671
 ******************************************************************************/
1672
#ifdef OPENSSL_EXTRA
1673
1674
/* no-op function. Was initially used for adding encryption algorithms available
1675
 * for PKCS12 */
1676
void wolfSSL_PKCS12_PBE_add(void)
1677
0
{
1678
0
    WOLFSSL_ENTER("wolfSSL_PKCS12_PBE_add");
1679
0
}
1680
1681
#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
1682
WOLFSSL_X509_PKCS12 *wolfSSL_d2i_PKCS12_fp(XFILE fp,
1683
        WOLFSSL_X509_PKCS12 **pkcs12)
1684
0
{
1685
0
    WOLFSSL_ENTER("wolfSSL_d2i_PKCS12_fp");
1686
0
    return (WOLFSSL_X509_PKCS12 *)wolfSSL_d2i_X509_fp_ex(fp, (void **)pkcs12,
1687
0
        PKCS12_TYPE);
1688
0
}
1689
#endif /* !NO_FILESYSTEM */
1690
1691
#endif /* OPENSSL_EXTRA */
1692
1693
#if defined(HAVE_PKCS12)
1694
1695
#ifdef OPENSSL_EXTRA
1696
1697
#if !defined(NO_ASN) && !defined(NO_PWDBASED)
1698
1699
#ifndef NO_BIO
1700
WC_PKCS12* wolfSSL_d2i_PKCS12_bio(WOLFSSL_BIO* bio, WC_PKCS12** pkcs12)
1701
0
{
1702
0
    WC_PKCS12* localPkcs12 = NULL;
1703
0
    unsigned char* mem = NULL;
1704
0
    long memSz;
1705
0
    int ret = -1;
1706
1707
0
    WOLFSSL_ENTER("wolfSSL_d2i_PKCS12_bio");
1708
1709
0
    if (bio == NULL) {
1710
0
        WOLFSSL_MSG("Bad Function Argument bio is NULL");
1711
0
        return NULL;
1712
0
    }
1713
1714
0
    memSz = wolfSSL_BIO_get_len(bio);
1715
0
    if (memSz <= 0) {
1716
0
        return NULL;
1717
0
    }
1718
0
    mem = (unsigned char*)XMALLOC(memSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1719
0
    if (mem == NULL) {
1720
0
        return NULL;
1721
0
    }
1722
1723
0
    if (mem != NULL) {
1724
0
        localPkcs12 = wc_PKCS12_new_ex(bio->heap);
1725
0
        if (localPkcs12 == NULL) {
1726
0
            WOLFSSL_MSG("Memory error");
1727
0
        }
1728
0
    }
1729
1730
0
    if (mem != NULL && localPkcs12 != NULL) {
1731
0
        if (wolfSSL_BIO_read(bio, mem, (int)memSz) == memSz) {
1732
0
            ret = wc_d2i_PKCS12(mem, (word32)memSz, localPkcs12);
1733
0
            if (ret < 0) {
1734
0
                WOLFSSL_MSG("Failed to get PKCS12 sequence");
1735
0
            }
1736
0
        }
1737
0
        else {
1738
0
            WOLFSSL_MSG("Failed to get data from bio struct");
1739
0
        }
1740
0
    }
1741
1742
    /* cleanup */
1743
0
    XFREE(mem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
1744
0
    if (ret < 0 && localPkcs12 != NULL) {
1745
0
        wc_PKCS12_free(localPkcs12);
1746
0
        localPkcs12 = NULL;
1747
0
    }
1748
0
    if (pkcs12 != NULL)
1749
0
        *pkcs12 = localPkcs12;
1750
1751
0
    return localPkcs12;
1752
0
}
1753
1754
/* Converts the PKCS12 to DER format and outputs it into bio.
1755
 *
1756
 * bio is the structure to hold output DER
1757
 * pkcs12 structure to create DER from
1758
 *
1759
 * return 1 for success or 0 if an error occurs
1760
 */
1761
int wolfSSL_i2d_PKCS12_bio(WOLFSSL_BIO *bio, WC_PKCS12 *pkcs12)
1762
0
{
1763
0
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
1764
1765
0
    WOLFSSL_ENTER("wolfSSL_i2d_PKCS12_bio");
1766
1767
0
    if ((bio != NULL) && (pkcs12 != NULL)) {
1768
0
        word32 certSz = 0;
1769
0
        byte *certDer = NULL;
1770
1771
0
        certSz = (word32)wc_i2d_PKCS12(pkcs12, &certDer, NULL);
1772
0
        if ((certSz > 0) && (certDer != NULL)) {
1773
0
            if (wolfSSL_BIO_write(bio, certDer, (int)certSz) == (int)certSz) {
1774
0
                ret = WOLFSSL_SUCCESS;
1775
0
            }
1776
0
        }
1777
1778
0
        XFREE(certDer, NULL, DYNAMIC_TYPE_PKCS);
1779
0
    }
1780
1781
0
    return ret;
1782
0
}
1783
#endif /* !NO_BIO */
1784
1785
/* Creates a new WC_PKCS12 structure
1786
 *
1787
 * pass  password to use
1788
 * name  friendlyName to use
1789
 * pkey  private key to go into PKCS12 bundle
1790
 * cert  certificate to go into PKCS12 bundle
1791
 * ca    extra certificates that can be added to bundle. Can be NULL
1792
 * keyNID  type of encryption to use on the key (-1 means no encryption)
1793
 * certNID type of encryption to use on the certificate
1794
 * itt     number of iterations with encryption
1795
 * macItt  number of iterations with mac creation
1796
 * keyType flag for signature and/or encryption key
1797
 *
1798
 * returns a pointer to a new WC_PKCS12 structure on success and NULL on fail
1799
 */
1800
WC_PKCS12* wolfSSL_PKCS12_create(char* pass, char* name, WOLFSSL_EVP_PKEY* pkey,
1801
        WOLFSSL_X509* cert, WOLF_STACK_OF(WOLFSSL_X509)* ca, int keyNID,
1802
        int certNID, int itt, int macItt, int keyType)
1803
0
{
1804
0
    WC_PKCS12* pkcs12;
1805
0
    WC_DerCertList* list = NULL;
1806
0
    word32 passSz;
1807
0
    byte* keyDer = NULL;
1808
0
    word32 keyDerSz;
1809
0
    byte* certDer;
1810
0
    int certDerSz;
1811
1812
0
    WOLFSSL_ENTER("wolfSSL_PKCS12_create");
1813
1814
0
    if (pass == NULL || pkey == NULL || cert == NULL) {
1815
0
        WOLFSSL_LEAVE("wolfSSL_PKCS12_create", BAD_FUNC_ARG);
1816
0
        return NULL;
1817
0
    }
1818
0
    passSz = (word32)XSTRLEN(pass);
1819
1820
0
    keyDer = (byte*)pkey->pkey.ptr;
1821
0
    keyDerSz = (word32)pkey->pkey_sz;
1822
1823
0
    certDer = (byte*)wolfSSL_X509_get_der(cert, &certDerSz);
1824
0
    if (certDer == NULL) {
1825
0
        return NULL;
1826
0
    }
1827
1828
0
    if (ca != NULL) {
1829
0
        unsigned long numCerts = ca->num;
1830
0
        WOLFSSL_STACK* sk = ca;
1831
1832
0
        while (numCerts > 0 && sk != NULL) {
1833
0
            byte* curDer;
1834
0
            WC_DerCertList* cur;
1835
0
            int   curDerSz = 0;
1836
1837
0
            cur = (WC_DerCertList*)XMALLOC(sizeof(WC_DerCertList), NULL,
1838
0
                    DYNAMIC_TYPE_PKCS);
1839
0
            if (cur == NULL) {
1840
0
                wc_FreeCertList(list, NULL);
1841
0
                return NULL;
1842
0
            }
1843
1844
0
            curDer = (byte*)wolfSSL_X509_get_der(sk->data.x509, &curDerSz);
1845
0
            if (curDer == NULL || curDerSz < 0) {
1846
0
                XFREE(cur, NULL, DYNAMIC_TYPE_PKCS);
1847
0
                wc_FreeCertList(list, NULL);
1848
0
                return NULL;
1849
0
            }
1850
1851
0
            cur->buffer = (byte*)XMALLOC(curDerSz, NULL, DYNAMIC_TYPE_PKCS);
1852
0
            if (cur->buffer == NULL) {
1853
0
                XFREE(cur, NULL, DYNAMIC_TYPE_PKCS);
1854
0
                wc_FreeCertList(list, NULL);
1855
0
                return NULL;
1856
0
            }
1857
0
            XMEMCPY(cur->buffer, curDer, curDerSz);
1858
0
            cur->bufferSz = (word32)curDerSz;
1859
0
            cur->next = list;
1860
0
            list = cur;
1861
1862
0
            sk = sk->next;
1863
0
            numCerts--;
1864
0
        }
1865
0
    }
1866
1867
0
    pkcs12 = wc_PKCS12_create(pass, passSz, name, keyDer, keyDerSz,
1868
0
            certDer, (word32)certDerSz, list, keyNID, certNID, itt, macItt,
1869
0
            keyType, NULL);
1870
1871
0
    if (ca != NULL) {
1872
0
        wc_FreeCertList(list, NULL);
1873
0
    }
1874
1875
0
    return pkcs12;
1876
0
}
1877
1878
1879
/* return WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure */
1880
int wolfSSL_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw,
1881
          WOLFSSL_EVP_PKEY** pkey, WOLFSSL_X509** cert,
1882
          WOLF_STACK_OF(WOLFSSL_X509)** ca)
1883
0
{
1884
0
    void* heap = NULL;
1885
0
    int ret;
1886
0
    byte* certData = NULL;
1887
0
    word32 certDataSz;
1888
0
    byte* pk = NULL;
1889
0
    word32 pkSz;
1890
0
    WC_DerCertList* certList = NULL;
1891
0
    WC_DECLARE_VAR(DeCert, DecodedCert, 1, 0);
1892
1893
0
    WOLFSSL_ENTER("wolfSSL_PKCS12_parse");
1894
1895
    /* make sure we init return args */
1896
0
    if (pkey) *pkey = NULL;
1897
0
    if (cert) *cert = NULL;
1898
0
    if (ca)   *ca = NULL;
1899
1900
0
    if (pkcs12 == NULL || psw == NULL || pkey == NULL || cert == NULL) {
1901
0
        WOLFSSL_MSG("Bad argument value");
1902
0
        return WOLFSSL_FAILURE;
1903
0
    }
1904
1905
0
    heap  = wc_PKCS12_GetHeap(pkcs12);
1906
1907
0
    if (ca == NULL) {
1908
0
        ret = wc_PKCS12_parse(pkcs12, psw, &pk, &pkSz, &certData, &certDataSz,
1909
0
            NULL);
1910
0
    }
1911
0
    else {
1912
0
        ret = wc_PKCS12_parse(pkcs12, psw, &pk, &pkSz, &certData, &certDataSz,
1913
0
            &certList);
1914
0
    }
1915
0
    if (ret < 0) {
1916
0
        WOLFSSL_LEAVE("wolfSSL_PKCS12_parse", ret);
1917
0
        return WOLFSSL_FAILURE;
1918
0
    }
1919
1920
0
#ifdef WOLFSSL_SMALL_STACK
1921
0
    DeCert = (DecodedCert *)XMALLOC(sizeof(*DeCert), heap,
1922
0
                                    DYNAMIC_TYPE_DCERT);
1923
0
    if (DeCert == NULL) {
1924
0
        WOLFSSL_MSG("out of memory");
1925
0
        return WOLFSSL_FAILURE;
1926
0
    }
1927
0
#endif
1928
1929
    /* Decode cert and place in X509 stack struct */
1930
0
    if (certList != NULL) {
1931
0
        WC_DerCertList* current = certList;
1932
1933
0
        *ca = (WOLF_STACK_OF(WOLFSSL_X509)*)XMALLOC(
1934
0
            sizeof(WOLF_STACK_OF(WOLFSSL_X509)), heap, DYNAMIC_TYPE_X509);
1935
0
        if (*ca == NULL) {
1936
0
            XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
1937
0
            XFREE(certData, heap, DYNAMIC_TYPE_PKCS);
1938
            /* Free up WC_DerCertList and move on */
1939
0
            while (current != NULL) {
1940
0
                WC_DerCertList* next = current->next;
1941
1942
0
                XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS);
1943
0
                XFREE(current, heap, DYNAMIC_TYPE_PKCS);
1944
0
                current = next;
1945
0
            }
1946
0
            ret = WOLFSSL_FAILURE;
1947
0
            goto out;
1948
0
        }
1949
0
        XMEMSET(*ca, 0, sizeof(WOLF_STACK_OF(WOLFSSL_X509)));
1950
1951
        /* add list of DER certs as X509's to stack */
1952
0
        while (current != NULL) {
1953
0
            WC_DerCertList*  toFree = current;
1954
0
            WOLFSSL_X509* x509;
1955
1956
0
            x509 = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap,
1957
0
                DYNAMIC_TYPE_X509);
1958
0
            InitX509(x509, 1, heap);
1959
0
            InitDecodedCert(DeCert, current->buffer, current->bufferSz, heap);
1960
0
            if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL, NULL)
1961
0
                                                                         != 0) {
1962
0
                WOLFSSL_MSG("Issue with parsing certificate");
1963
0
                FreeDecodedCert(DeCert);
1964
0
                wolfSSL_X509_free(x509);
1965
0
                x509 = NULL;
1966
0
            }
1967
0
            else {
1968
0
                if (CopyDecodedToX509(x509, DeCert) != 0) {
1969
0
                    WOLFSSL_MSG("Failed to copy decoded cert");
1970
0
                    FreeDecodedCert(DeCert);
1971
0
                    wolfSSL_X509_free(x509);
1972
0
                    x509 = NULL;
1973
0
                    wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
1974
0
                    XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
1975
0
                    XFREE(certData, heap, DYNAMIC_TYPE_PKCS);
1976
                    /* Free up WC_DerCertList */
1977
0
                    while (current != NULL) {
1978
0
                        WC_DerCertList* next = current->next;
1979
1980
0
                        XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS);
1981
0
                        XFREE(current, heap, DYNAMIC_TYPE_PKCS);
1982
0
                        current = next;
1983
0
                    }
1984
0
                    ret = WOLFSSL_FAILURE;
1985
0
                    goto out;
1986
0
                }
1987
0
                FreeDecodedCert(DeCert);
1988
1989
0
                if (wolfSSL_sk_X509_push(*ca, x509) <= 0) {
1990
0
                    WOLFSSL_MSG("Failed to push x509 onto stack");
1991
0
                    wolfSSL_X509_free(x509);
1992
0
                    x509 = NULL;
1993
0
                    wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
1994
0
                    XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
1995
0
                    XFREE(certData, heap, DYNAMIC_TYPE_PKCS);
1996
1997
                    /* Free up WC_DerCertList */
1998
0
                    while (current != NULL) {
1999
0
                        WC_DerCertList* next = current->next;
2000
2001
0
                        XFREE(current->buffer, heap, DYNAMIC_TYPE_PKCS);
2002
0
                        XFREE(current, heap, DYNAMIC_TYPE_PKCS);
2003
0
                        current = next;
2004
0
                    }
2005
0
                    ret = WOLFSSL_FAILURE;
2006
0
                    goto out;
2007
0
                }
2008
0
            }
2009
0
            current = current->next;
2010
0
            XFREE(toFree->buffer, heap, DYNAMIC_TYPE_PKCS);
2011
0
            XFREE(toFree, heap, DYNAMIC_TYPE_PKCS);
2012
0
        }
2013
0
    }
2014
2015
2016
    /* Decode cert and place in X509 struct */
2017
0
    if (certData != NULL) {
2018
0
        *cert = (WOLFSSL_X509*)XMALLOC(sizeof(WOLFSSL_X509), heap,
2019
0
            DYNAMIC_TYPE_X509);
2020
0
        if (*cert == NULL) {
2021
0
            XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
2022
0
            if (ca != NULL) {
2023
0
                wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
2024
0
            }
2025
0
            XFREE(certData, heap, DYNAMIC_TYPE_PKCS);
2026
0
            ret = WOLFSSL_FAILURE;
2027
0
            goto out;
2028
0
        }
2029
0
        InitX509(*cert, 1, heap);
2030
0
        InitDecodedCert(DeCert, certData, certDataSz, heap);
2031
0
        if (ParseCertRelative(DeCert, CERT_TYPE, NO_VERIFY, NULL, NULL) != 0) {
2032
0
            WOLFSSL_MSG("Issue with parsing certificate");
2033
0
        }
2034
0
        if (CopyDecodedToX509(*cert, DeCert) != 0) {
2035
0
            WOLFSSL_MSG("Failed to copy decoded cert");
2036
0
            FreeDecodedCert(DeCert);
2037
0
            XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
2038
0
            if (ca != NULL) {
2039
0
                wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
2040
0
            }
2041
0
            wolfSSL_X509_free(*cert); *cert = NULL;
2042
0
            XFREE(certData, heap, DYNAMIC_TYPE_PKCS);
2043
0
            ret = WOLFSSL_FAILURE;
2044
0
            goto out;
2045
0
        }
2046
0
        FreeDecodedCert(DeCert);
2047
0
        XFREE(certData, heap, DYNAMIC_TYPE_PKCS);
2048
0
    }
2049
2050
2051
    /* get key type */
2052
0
    ret = BAD_STATE_E;
2053
0
    if (pk != NULL) { /* decode key if present */
2054
0
        *pkey = wolfSSL_EVP_PKEY_new_ex(heap);
2055
0
        if (*pkey == NULL) {
2056
0
            wolfSSL_X509_free(*cert); *cert = NULL;
2057
0
            if (ca != NULL) {
2058
0
                wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
2059
0
            }
2060
0
            XFREE(pk, heap, DYNAMIC_TYPE_PUBLIC_KEY);
2061
0
            ret = WOLFSSL_FAILURE;
2062
0
            goto out;
2063
0
        }
2064
2065
0
    #ifndef NO_RSA
2066
0
        {
2067
0
            const unsigned char* pt = pk;
2068
0
            if (wolfSSL_d2i_PrivateKey(WC_EVP_PKEY_RSA, pkey, &pt, pkSz) !=
2069
0
                    NULL) {
2070
0
                ret = 0;
2071
0
            }
2072
0
        }
2073
0
    #endif /* NO_RSA */
2074
2075
0
    #ifdef HAVE_ECC
2076
0
        if (ret != 0) { /* if is in fail state check if ECC key */
2077
0
            const unsigned char* pt = pk;
2078
0
            if (wolfSSL_d2i_PrivateKey(WC_EVP_PKEY_EC, pkey, &pt, pkSz) !=
2079
0
                    NULL) {
2080
0
                ret = 0;
2081
0
            }
2082
0
        }
2083
0
    #endif /* HAVE_ECC */
2084
0
        XFREE(pk, heap, DYNAMIC_TYPE_PKCS);
2085
0
        if (ret != 0) { /* if is in fail state and no PKEY then fail */
2086
0
            wolfSSL_X509_free(*cert); *cert = NULL;
2087
0
            if (ca != NULL) {
2088
0
                wolfSSL_sk_X509_pop_free(*ca, NULL); *ca = NULL;
2089
0
            }
2090
0
            wolfSSL_EVP_PKEY_free(*pkey); *pkey = NULL;
2091
0
            WOLFSSL_MSG("Bad PKCS12 key format");
2092
0
            ret = WOLFSSL_FAILURE;
2093
0
            goto out;
2094
0
        }
2095
2096
0
        if (pkey != NULL && *pkey != NULL) {
2097
0
            (*pkey)->save_type = 0;
2098
0
        }
2099
0
    }
2100
2101
0
    (void)ret;
2102
0
    (void)ca;
2103
2104
0
    ret = WOLFSSL_SUCCESS;
2105
2106
0
out:
2107
2108
0
    WC_FREE_VAR_EX(DeCert, heap, DYNAMIC_TYPE_DCERT);
2109
2110
0
    return ret;
2111
0
}
2112
2113
int wolfSSL_PKCS12_verify_mac(WC_PKCS12 *pkcs12, const char *psw,
2114
        int pswLen)
2115
0
{
2116
0
    WOLFSSL_ENTER("wolfSSL_PKCS12_verify_mac");
2117
2118
0
    if (!pkcs12) {
2119
0
        return WOLFSSL_FAILURE;
2120
0
    }
2121
2122
0
    return wc_PKCS12_verify_ex(pkcs12, (const byte*)psw, (word32)pswLen) == 0 ?
2123
0
            WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
2124
0
}
2125
2126
#endif /* !NO_ASN && !NO_PWDBASED */
2127
2128
#endif /* OPENSSL_EXTRA */
2129
2130
#endif /* HAVE_PKCS12 */
2131
/*******************************************************************************
2132
 * END OF PKCS12 APIs
2133
 ******************************************************************************/
2134
2135
#endif /* !WOLFCRYPT_ONLY && !NO_CERTS */
2136
2137
#endif /* !WOLFSSL_SSL_P7P12_INCLUDED */