Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl36/crypto/asn1/asn_mime.c
Line
Count
Source
1
/*
2
 * Copyright 2008-2025 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include <stdio.h>
11
#include "crypto/ctype.h"
12
#include "internal/cryptlib.h"
13
#include <openssl/rand.h>
14
#include <openssl/x509.h>
15
#include <openssl/asn1.h>
16
#include <openssl/asn1t.h>
17
#include <openssl/cms.h>
18
#include "crypto/evp.h"
19
#include "internal/bio.h"
20
#include "asn1_local.h"
21
22
/*
23
 * Generalised MIME like utilities for streaming ASN1. Although many have a
24
 * PKCS7/CMS like flavour others are more general purpose.
25
 */
26
27
/*
28
 * MIME format structures Note that all are translated to lower case apart
29
 * from parameter values. Quotes are stripped off
30
 */
31
32
struct mime_param_st {
33
    char *param_name; /* Param name e.g. "micalg" */
34
    char *param_value; /* Param value e.g. "sha1" */
35
};
36
37
struct mime_header_st {
38
    char *name; /* Name of line e.g. "content-type" */
39
    char *value; /* Value of line e.g. "text/plain" */
40
    STACK_OF(MIME_PARAM) *params; /* Zero or more parameters */
41
};
42
43
static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
44
    const ASN1_ITEM *it);
45
static char *strip_ends(char *name);
46
static char *strip_start(char *name);
47
static char *strip_end(char *name);
48
static MIME_HEADER *mime_hdr_new(const char *name, const char *value);
49
static int mime_hdr_addparam(MIME_HEADER *mhdr, const char *name, const char *value);
50
static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio);
51
static int mime_hdr_cmp(const MIME_HEADER *const *a,
52
    const MIME_HEADER *const *b);
53
static int mime_param_cmp(const MIME_PARAM *const *a,
54
    const MIME_PARAM *const *b);
55
static void mime_param_free(MIME_PARAM *param);
56
static int mime_bound_check(char *line, int linelen, const char *bound, int blen);
57
static int multi_split(BIO *bio, int flags, const char *bound, STACK_OF(BIO) **ret);
58
static int strip_eol(char *linebuf, int *plen, int flags);
59
static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, const char *name);
60
static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, const char *name);
61
static void mime_hdr_free(MIME_HEADER *hdr);
62
63
32.1M
#define MAX_SMLEN 1024
64
#define mime_debug(x) /* x */
65
66
/* Output an ASN1 structure in BER format streaming if necessary */
67
68
/* unfortunately cannot constify this due to CMS_stream() and PKCS7_stream() */
69
int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
70
    const ASN1_ITEM *it)
71
0
{
72
0
    int rv = 1;
73
74
    /* If streaming create stream BIO and copy all content through it */
75
0
    if (flags & SMIME_STREAM) {
76
0
        BIO *bio, *tbio;
77
0
        bio = BIO_new_NDEF(out, val, it);
78
0
        if (!bio) {
79
0
            ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
80
0
            return 0;
81
0
        }
82
0
        if (!SMIME_crlf_copy(in, bio, flags)) {
83
0
            rv = 0;
84
0
        }
85
86
0
        (void)BIO_flush(bio);
87
        /* Free up successive BIOs until we hit the old output BIO */
88
0
        do {
89
0
            tbio = BIO_pop(bio);
90
0
            BIO_free(bio);
91
0
            bio = tbio;
92
0
        } while (bio != out);
93
0
    }
94
    /*
95
     * else just write out ASN1 structure which will have all content stored
96
     * internally
97
     */
98
0
    else
99
0
        rv = ASN1_item_i2d_bio(it, out, val);
100
0
    return rv;
101
0
}
102
103
/* Base 64 read and write of ASN1 structure */
104
105
static int B64_write_ASN1(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
106
    const ASN1_ITEM *it)
107
0
{
108
0
    BIO *b64;
109
0
    int r;
110
0
    b64 = BIO_new(BIO_f_base64());
111
0
    if (b64 == NULL) {
112
0
        ERR_raise(ERR_LIB_ASN1, ERR_R_BIO_LIB);
113
0
        return 0;
114
0
    }
115
    /*
116
     * prepend the b64 BIO so all data is base64 encoded.
117
     */
118
0
    out = BIO_push(b64, out);
119
0
    r = i2d_ASN1_bio_stream(out, val, in, flags, it);
120
0
    (void)BIO_flush(out);
121
0
    BIO_pop(out);
122
0
    BIO_free(b64);
123
0
    return r;
124
0
}
125
126
/* Streaming ASN1 PEM write */
127
128
int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
129
    const char *hdr, const ASN1_ITEM *it)
130
0
{
131
0
    return BIO_printf(out, "-----BEGIN %s-----\n", hdr) >= 0
132
0
        && B64_write_ASN1(out, val, in, flags, it)
133
0
        && BIO_printf(out, "-----END %s-----\n", hdr) >= 0;
134
0
}
135
136
static ASN1_VALUE *b64_read_asn1(BIO *bio, const ASN1_ITEM *it, ASN1_VALUE **x,
137
    OSSL_LIB_CTX *libctx, const char *propq)
138
12.3k
{
139
12.3k
    BIO *b64;
140
12.3k
    ASN1_VALUE *val;
141
142
12.3k
    if ((b64 = BIO_new(BIO_f_base64())) == NULL) {
143
0
        ERR_raise(ERR_LIB_ASN1, ERR_R_BIO_LIB);
144
0
        return 0;
145
0
    }
146
12.3k
    bio = BIO_push(b64, bio);
147
12.3k
    val = ASN1_item_d2i_bio_ex(it, bio, x, libctx, propq);
148
12.3k
    if (!val)
149
12.3k
        ERR_raise(ERR_LIB_ASN1, ASN1_R_DECODE_ERROR);
150
12.3k
    (void)BIO_flush(bio);
151
12.3k
    BIO_pop(bio);
152
12.3k
    BIO_free(b64);
153
12.3k
    return val;
154
12.3k
}
155
156
/* Generate the MIME "micalg" parameter from RFC3851, RFC4490 */
157
158
static int asn1_write_micalg(BIO *out, STACK_OF(X509_ALGOR) *mdalgs)
159
0
{
160
0
    const EVP_MD *md;
161
0
    int i, have_unknown = 0, write_comma, ret = 0, md_nid;
162
0
    have_unknown = 0;
163
0
    write_comma = 0;
164
0
    for (i = 0; i < sk_X509_ALGOR_num(mdalgs); i++) {
165
0
        if (write_comma && BIO_puts(out, ",") < 0)
166
0
            goto err;
167
0
        write_comma = 1;
168
0
        md_nid = OBJ_obj2nid(sk_X509_ALGOR_value(mdalgs, i)->algorithm);
169
170
        /* RFC 8702 does not define a micalg for SHAKE, assuming "shake-<bitlen>" */
171
0
        if (md_nid == NID_shake128) {
172
0
            if (BIO_puts(out, "shake-128") < 0)
173
0
                goto err;
174
0
            continue;
175
0
        }
176
0
        if (md_nid == NID_shake256) {
177
0
            if (BIO_puts(out, "shake-256") < 0)
178
0
                goto err;
179
0
            continue;
180
0
        }
181
182
0
        md = EVP_get_digestbynid(md_nid);
183
0
        if (md && md->md_ctrl) {
184
0
            int rv;
185
0
            char *micstr;
186
0
            rv = md->md_ctrl(NULL, EVP_MD_CTRL_MICALG, 0, &micstr);
187
0
            if (rv > 0) {
188
0
                rv = BIO_puts(out, micstr);
189
0
                OPENSSL_free(micstr);
190
0
                if (rv < 0)
191
0
                    goto err;
192
0
                continue;
193
0
            }
194
0
            if (rv != -2)
195
0
                goto err;
196
0
        }
197
0
        switch (md_nid) {
198
0
        case NID_sha1:
199
0
            if (BIO_puts(out, "sha1") < 0)
200
0
                goto err;
201
0
            break;
202
203
0
        case NID_md5:
204
0
            if (BIO_puts(out, "md5") < 0)
205
0
                goto err;
206
0
            break;
207
208
0
        case NID_sha256:
209
0
            if (BIO_puts(out, "sha-256") < 0)
210
0
                goto err;
211
0
            break;
212
213
0
        case NID_sha384:
214
0
            if (BIO_puts(out, "sha-384") < 0)
215
0
                goto err;
216
0
            break;
217
218
0
        case NID_sha512:
219
0
            if (BIO_puts(out, "sha-512") < 0)
220
0
                goto err;
221
0
            break;
222
223
0
        case NID_id_GostR3411_94:
224
0
            if (BIO_puts(out, "gostr3411-94") < 0)
225
0
                goto err;
226
0
            break;
227
228
0
        case NID_id_GostR3411_2012_256:
229
0
            if (BIO_puts(out, "gostr3411-2012-256") < 0)
230
0
                goto err;
231
0
            break;
232
233
0
        case NID_id_GostR3411_2012_512:
234
0
            if (BIO_puts(out, "gostr3411-2012-512") < 0)
235
0
                goto err;
236
0
            break;
237
238
0
        default:
239
0
            if (have_unknown) {
240
0
                write_comma = 0;
241
0
            } else {
242
0
                if (BIO_puts(out, "unknown") < 0)
243
0
                    goto err;
244
0
                have_unknown = 1;
245
0
            }
246
0
            break;
247
0
        }
248
0
    }
249
250
0
    ret = 1;
251
0
err:
252
253
0
    return ret;
254
0
}
255
256
/* SMIME sender */
257
258
int SMIME_write_ASN1_ex(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
259
    int ctype_nid, int econt_nid,
260
    STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it,
261
    OSSL_LIB_CTX *libctx, const char *propq)
262
0
{
263
0
    char bound[33], c;
264
0
    int i;
265
0
    const char *mime_prefix, *mime_eol, *cname = "smime.p7m";
266
0
    const char *msg_type = NULL;
267
268
0
    if (flags & SMIME_OLDMIME)
269
0
        mime_prefix = "application/x-pkcs7-";
270
0
    else
271
0
        mime_prefix = "application/pkcs7-";
272
273
0
    if (flags & SMIME_CRLFEOL)
274
0
        mime_eol = "\r\n";
275
0
    else
276
0
        mime_eol = "\n";
277
0
    if ((flags & SMIME_DETACHED) && data) {
278
        /* We want multipart/signed */
279
        /* Generate a random boundary */
280
0
        if (RAND_bytes_ex(libctx, (unsigned char *)bound, 32, 0) <= 0)
281
0
            return 0;
282
0
        for (i = 0; i < 32; i++) {
283
0
            c = bound[i] & 0xf;
284
0
            if (c < 10)
285
0
                c += '0';
286
0
            else
287
0
                c += 'A' - 10;
288
0
            bound[i] = c;
289
0
        }
290
0
        bound[32] = 0;
291
0
        if (BIO_printf(bio, "MIME-Version: 1.0%s"
292
0
                            "Content-Type: multipart/signed; protocol=\"%ssignature\";"
293
0
                            " micalg=\"", /* not 'macalg', seee RFC 2311 section 3.4.3.2 */
294
0
                mime_eol, mime_prefix)
295
0
            < 0)
296
0
            return 0;
297
0
        if (!asn1_write_micalg(bio, mdalgs))
298
0
            return 0;
299
0
        if (BIO_printf(bio, "\"; boundary=\"----%s\"%s%s"
300
0
                            "This is an S/MIME signed message%s%s"
301
                            /* Now comes the first part */
302
0
                            "------%s%s",
303
0
                bound, mime_eol, mime_eol,
304
0
                mime_eol, mime_eol,
305
0
                bound, mime_eol)
306
0
            < 0)
307
0
            return 0;
308
0
        if (!asn1_output_data(bio, data, val, flags, it))
309
0
            return 0;
310
0
        if (BIO_printf(bio, "%s------%s%s", mime_eol, bound, mime_eol) < 0)
311
0
            return 0;
312
313
        /* Headers for signature */
314
315
0
        if (BIO_printf(bio, "Content-Type: %ssignature; name=\"smime.p7s\"%s"
316
0
                            "Content-Transfer-Encoding: base64%s"
317
0
                            "Content-Disposition: attachment; filename=\"smime.p7s\"%s%s",
318
0
                mime_prefix, mime_eol,
319
0
                mime_eol, mime_eol, mime_eol)
320
0
            < 0)
321
0
            return 0;
322
0
        if (!B64_write_ASN1(bio, val, NULL, 0, it)
323
0
            || BIO_printf(bio, "%s------%s--%s%s", mime_eol, bound, mime_eol, mime_eol) < 0)
324
0
            return 0;
325
0
        return 1;
326
0
    }
327
328
    /* Determine smime-type header */
329
330
0
    if (ctype_nid == NID_pkcs7_enveloped) {
331
0
        msg_type = "enveloped-data";
332
0
    } else if (ctype_nid == NID_id_smime_ct_authEnvelopedData) {
333
0
        msg_type = "authEnveloped-data";
334
0
    } else if (ctype_nid == NID_pkcs7_signed) {
335
0
        if (econt_nid == NID_id_smime_ct_receipt)
336
0
            msg_type = "signed-receipt";
337
0
        else if (sk_X509_ALGOR_num(mdalgs) >= 0)
338
0
            msg_type = "signed-data";
339
0
        else
340
0
            msg_type = "certs-only";
341
0
    } else if (ctype_nid == NID_id_smime_ct_compressedData) {
342
0
        msg_type = "compressed-data";
343
0
        cname = "smime.p7z";
344
0
    }
345
    /* MIME headers */
346
0
    if (BIO_printf(bio, "MIME-Version: 1.0%s"
347
0
                        "Content-Disposition: attachment;"
348
0
                        " filename=\"%s\"%s",
349
0
            mime_eol, cname, mime_eol)
350
0
        < 0)
351
0
        return 0;
352
0
    if (BIO_printf(bio, "Content-Type: %smime;", mime_prefix) < 0)
353
0
        return 0;
354
0
    if (msg_type != NULL && BIO_printf(bio, " smime-type=%s;", msg_type) < 0)
355
0
        return 0;
356
0
    if (BIO_printf(bio, " name=\"%s\"%s"
357
0
                        "Content-Transfer-Encoding: base64%s%s",
358
0
            cname, mime_eol, mime_eol, mime_eol)
359
0
        < 0)
360
0
        return 0;
361
0
    if (!B64_write_ASN1(bio, val, data, flags, it))
362
0
        return 0;
363
0
    return BIO_printf(bio, "%s", mime_eol) >= 0;
364
0
}
365
366
int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
367
    int ctype_nid, int econt_nid,
368
    STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it)
369
0
{
370
0
    return SMIME_write_ASN1_ex(bio, val, data, flags, ctype_nid, econt_nid,
371
0
        mdalgs, it, NULL, NULL);
372
0
}
373
374
/* Handle output of ASN1 data */
375
376
/* cannot constify val because of CMS_dataFinal() */
377
static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
378
    const ASN1_ITEM *it)
379
0
{
380
0
    BIO *tmpbio;
381
0
    const ASN1_AUX *aux = it->funcs;
382
0
    ASN1_STREAM_ARG sarg;
383
0
    int rv = 1;
384
385
    /*
386
     * If data is not detached or resigning then the output BIO is already
387
     * set up to finalise when it is written through.
388
     */
389
0
    if (!(flags & SMIME_DETACHED) || (flags & PKCS7_REUSE_DIGEST)) {
390
0
        return SMIME_crlf_copy(data, out, flags);
391
0
    }
392
393
0
    if (!aux || !aux->asn1_cb) {
394
0
        ERR_raise(ERR_LIB_ASN1, ASN1_R_STREAMING_NOT_SUPPORTED);
395
0
        return 0;
396
0
    }
397
398
0
    sarg.out = out;
399
0
    sarg.ndef_bio = NULL;
400
0
    sarg.boundary = NULL;
401
402
    /* Let ASN1 code prepend any needed BIOs */
403
404
0
    if (aux->asn1_cb(ASN1_OP_DETACHED_PRE, &val, it, &sarg) <= 0)
405
0
        return 0;
406
407
    /* Copy data across, passing through filter BIOs for processing */
408
0
    if (!SMIME_crlf_copy(data, sarg.ndef_bio, flags))
409
0
        rv = 0;
410
411
    /* Finalize structure */
412
0
    if (aux->asn1_cb(ASN1_OP_DETACHED_POST, &val, it, &sarg) <= 0)
413
0
        rv = 0;
414
415
    /* Now remove any digests prepended to the BIO */
416
417
0
    while (sarg.ndef_bio != out) {
418
0
        tmpbio = BIO_pop(sarg.ndef_bio);
419
0
        BIO_free(sarg.ndef_bio);
420
0
        sarg.ndef_bio = tmpbio;
421
0
    }
422
423
0
    return rv;
424
0
}
425
426
/*
427
 * SMIME reader: handle multipart/signed and opaque signing. in multipart
428
 * case the content is placed in a memory BIO pointed to by "bcont". In
429
 * opaque this is set to NULL
430
 */
431
432
ASN1_VALUE *SMIME_read_ASN1_ex(BIO *bio, int flags, BIO **bcont,
433
    const ASN1_ITEM *it, ASN1_VALUE **x,
434
    OSSL_LIB_CTX *libctx, const char *propq)
435
22.3k
{
436
22.3k
    BIO *asnin;
437
22.3k
    STACK_OF(MIME_HEADER) *headers = NULL;
438
22.3k
    STACK_OF(BIO) *parts = NULL;
439
22.3k
    MIME_HEADER *hdr;
440
22.3k
    MIME_PARAM *prm;
441
22.3k
    ASN1_VALUE *val;
442
22.3k
    int ret;
443
444
22.3k
    if (bcont)
445
0
        *bcont = NULL;
446
447
22.3k
    if ((headers = mime_parse_hdr(bio)) == NULL) {
448
0
        ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_PARSE_ERROR);
449
0
        return NULL;
450
0
    }
451
452
22.3k
    if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
453
18.1k
        || hdr->value == NULL) {
454
4.81k
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
455
4.81k
        ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_CONTENT_TYPE);
456
4.81k
        return NULL;
457
4.81k
    }
458
459
    /* Handle multipart/signed */
460
461
17.5k
    if (strcmp(hdr->value, "multipart/signed") == 0) {
462
        /* Split into two parts */
463
5.52k
        prm = mime_param_find(hdr, "boundary");
464
5.52k
        if (prm == NULL || prm->param_value == NULL) {
465
49
            sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
466
49
            ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_MULTIPART_BOUNDARY);
467
49
            return NULL;
468
49
        }
469
5.47k
        ret = multi_split(bio, flags, prm->param_value, &parts);
470
5.47k
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
471
5.47k
        if (!ret || (sk_BIO_num(parts) != 2)) {
472
2.19k
            ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_MULTIPART_BODY_FAILURE);
473
2.19k
            sk_BIO_pop_free(parts, BIO_vfree);
474
2.19k
            return NULL;
475
2.19k
        }
476
477
        /* Parse the signature piece */
478
3.28k
        asnin = sk_BIO_value(parts, 1);
479
480
3.28k
        if ((headers = mime_parse_hdr(asnin)) == NULL) {
481
0
            ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_SIG_PARSE_ERROR);
482
0
            sk_BIO_pop_free(parts, BIO_vfree);
483
0
            return NULL;
484
0
        }
485
486
        /* Get content type */
487
488
3.28k
        if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
489
3.09k
            || hdr->value == NULL) {
490
202
            sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
491
202
            ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_SIG_CONTENT_TYPE);
492
202
            sk_BIO_pop_free(parts, BIO_vfree);
493
202
            return NULL;
494
202
        }
495
496
3.07k
        if (strcmp(hdr->value, "application/x-pkcs7-signature") && strcmp(hdr->value, "application/pkcs7-signature")) {
497
922
            ERR_raise_data(ERR_LIB_ASN1, ASN1_R_SIG_INVALID_MIME_TYPE,
498
922
                "type: %s", hdr->value);
499
922
            sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
500
922
            sk_BIO_pop_free(parts, BIO_vfree);
501
922
            return NULL;
502
922
        }
503
2.15k
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
504
        /* Read in ASN1 */
505
2.15k
        if ((val = b64_read_asn1(asnin, it, x, libctx, propq)) == NULL) {
506
1.98k
            ERR_raise(ERR_LIB_ASN1, ASN1_R_ASN1_SIG_PARSE_ERROR);
507
1.98k
            sk_BIO_pop_free(parts, BIO_vfree);
508
1.98k
            return NULL;
509
1.98k
        }
510
511
176
        if (bcont) {
512
0
            *bcont = sk_BIO_value(parts, 0);
513
0
            BIO_free(asnin);
514
0
            sk_BIO_free(parts);
515
176
        } else {
516
176
            sk_BIO_pop_free(parts, BIO_vfree);
517
176
        }
518
176
        return val;
519
2.15k
    }
520
521
    /* OK, if not multipart/signed try opaque signature */
522
523
12.0k
    if (strcmp(hdr->value, "application/x-pkcs7-mime") && strcmp(hdr->value, "application/pkcs7-mime")) {
524
1.81k
        ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_MIME_TYPE,
525
1.81k
            "type: %s", hdr->value);
526
1.81k
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
527
1.81k
        return NULL;
528
1.81k
    }
529
530
10.2k
    sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
531
532
10.2k
    if ((val = b64_read_asn1(bio, it, x, libctx, propq)) == NULL) {
533
9.52k
        ERR_raise(ERR_LIB_ASN1, ASN1_R_ASN1_PARSE_ERROR);
534
9.52k
        return NULL;
535
9.52k
    }
536
687
    return val;
537
10.2k
}
538
539
ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it)
540
0
{
541
0
    return SMIME_read_ASN1_ex(bio, 0, bcont, it, NULL, NULL, NULL);
542
0
}
543
544
/* Copy text from one BIO to another making the output CRLF at EOL */
545
int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
546
0
{
547
0
    BIO *bf;
548
0
    char eol;
549
0
    int len;
550
0
    char linebuf[MAX_SMLEN];
551
0
    int ret = 0;
552
553
0
    if (in == NULL || out == NULL) {
554
0
        ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_NULL_PARAMETER);
555
0
        return 0;
556
0
    }
557
558
    /*
559
     * Buffer output so we don't write one line at a time. This is useful
560
     * when streaming as we don't end up with one OCTET STRING per line.
561
     */
562
0
    bf = BIO_new(BIO_f_buffer());
563
0
    if (bf == NULL) {
564
0
        ERR_raise(ERR_LIB_ASN1, ERR_R_BIO_LIB);
565
0
        return 0;
566
0
    }
567
0
    out = BIO_push(bf, out);
568
0
    if (flags & SMIME_BINARY) {
569
0
        while ((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0) {
570
0
            if (BIO_write(out, linebuf, len) != len && out != NULL)
571
0
                goto err;
572
0
        }
573
0
    } else {
574
0
        int eolcnt = 0;
575
576
0
        if ((flags & SMIME_TEXT) != 0
577
0
            && BIO_puts(out, "Content-Type: text/plain\r\n\r\n") < 0)
578
0
            goto err;
579
0
        while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
580
0
            eol = strip_eol(linebuf, &len, flags);
581
0
            if (len > 0) {
582
                /* Not EOF: write out all CRLF */
583
0
                if (flags & SMIME_ASCIICRLF) {
584
0
                    int i;
585
0
                    for (i = 0; i < eolcnt; i++)
586
0
                        if (BIO_puts(out, "\r\n") < 0)
587
0
                            goto err;
588
0
                    eolcnt = 0;
589
0
                }
590
0
                if (BIO_write(out, linebuf, len) != len && out != NULL)
591
0
                    goto err;
592
0
                if (eol && BIO_puts(out, "\r\n") < 0)
593
0
                    goto err;
594
0
            } else if (flags & SMIME_ASCIICRLF) {
595
0
                eolcnt++;
596
0
            } else if (eol) {
597
0
                if (BIO_puts(out, "\r\n") < 0)
598
0
                    goto err;
599
0
            }
600
0
        }
601
0
    }
602
0
    ret = 1;
603
604
0
err:
605
0
    ret = BIO_flush(out) > 0 && ret;
606
0
    BIO_pop(out);
607
0
    BIO_free(bf);
608
0
    return ret;
609
0
}
610
611
/* Strip off headers if they are text/plain */
612
int SMIME_text(BIO *in, BIO *out)
613
0
{
614
0
    char iobuf[4096];
615
0
    int len;
616
0
    STACK_OF(MIME_HEADER) *headers;
617
0
    MIME_HEADER *hdr;
618
619
0
    if ((headers = mime_parse_hdr(in)) == NULL) {
620
0
        ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_PARSE_ERROR);
621
0
        return 0;
622
0
    }
623
0
    if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
624
0
        || hdr->value == NULL) {
625
0
        ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_NO_CONTENT_TYPE);
626
0
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
627
0
        return 0;
628
0
    }
629
0
    if (strcmp(hdr->value, "text/plain")) {
630
0
        ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_MIME_TYPE,
631
0
            "type: %s", hdr->value);
632
0
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
633
0
        return 0;
634
0
    }
635
0
    sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
636
0
    while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
637
0
        if (BIO_write(out, iobuf, len) != len && out != NULL)
638
0
            return 0;
639
0
    return len >= 0;
640
0
}
641
642
/*
643
 * Split a multipart/XXX message body into component parts: result is
644
 * canonical parts in a STACK of bios
645
 */
646
647
static int multi_split(BIO *bio, int flags, const char *bound, STACK_OF(BIO) **ret)
648
1.16k
{
649
1.16k
    char linebuf[MAX_SMLEN];
650
1.16k
    int len, blen;
651
1.16k
    size_t blen_s = strlen(bound);
652
1.16k
    int eol = 0, next_eol = 0;
653
1.16k
    BIO *bpart = NULL;
654
1.16k
    STACK_OF(BIO) *parts;
655
1.16k
    char state, part, first;
656
657
1.16k
    if (blen_s > MAX_SMLEN)
658
0
        return 0;
659
1.16k
    blen = (int)blen_s;
660
1.16k
    part = 0;
661
1.16k
    state = 0;
662
1.16k
    first = 1;
663
1.16k
    parts = sk_BIO_new_null();
664
1.16k
    *ret = parts;
665
1.16k
    if (*ret == NULL)
666
0
        return 0;
667
8.21M
    while ((len = BIO_get_line(bio, linebuf, MAX_SMLEN)) > 0) {
668
8.21M
        state = mime_bound_check(linebuf, len, bound, blen);
669
8.21M
        if (state == 1) {
670
204k
            first = 1;
671
204k
            part++;
672
8.01M
        } else if (state == 2) {
673
792
            if (!sk_BIO_push(parts, bpart)) {
674
0
                BIO_free(bpart);
675
0
                return 0;
676
0
            }
677
792
            return 1;
678
8.01M
        } else if (part != 0) {
679
            /* Strip (possibly CR +) LF from linebuf */
680
8.00M
            next_eol = strip_eol(linebuf, &len, flags);
681
8.00M
            if (first) {
682
201k
                first = 0;
683
201k
                if (bpart)
684
201k
                    if (!sk_BIO_push(parts, bpart)) {
685
0
                        BIO_free(bpart);
686
0
                        return 0;
687
0
                    }
688
201k
                bpart = BIO_new(BIO_s_mem());
689
201k
                if (bpart == NULL)
690
0
                    return 0;
691
201k
                BIO_set_mem_eof_return(bpart, 0);
692
7.80M
            } else if (eol) {
693
7.79M
                if (
694
7.79M
#ifndef OPENSSL_NO_CMS
695
7.79M
                    (flags & CMS_BINARY) == 0
696
#else
697
                    1
698
#endif
699
7.79M
                    || (flags & SMIME_CRLFEOL) != 0) {
700
7.79M
                    if (BIO_puts(bpart, "\r\n") < 0)
701
0
                        return 0;
702
7.79M
                } else {
703
0
                    if (BIO_puts(bpart, "\n") < 0)
704
0
                        return 0;
705
0
                }
706
7.79M
            }
707
8.00M
            eol = next_eol;
708
8.00M
            if (len > 0 && BIO_write(bpart, linebuf, len) != len)
709
0
                return 0;
710
8.00M
        }
711
8.21M
    }
712
376
    BIO_free(bpart);
713
376
    return 0;
714
1.16k
}
715
716
/* This is the big one: parse MIME header lines up to message body */
717
718
#define MIME_INVALID 0
719
56.2M
#define MIME_START 1
720
49.1M
#define MIME_TYPE 2
721
5.02M
#define MIME_NAME 3
722
4.02M
#define MIME_VALUE 4
723
244k
#define MIME_QUOTE 5
724
129k
#define MIME_COMMENT 6
725
726
static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
727
25.6k
{
728
25.6k
    char *p, *q, c;
729
25.6k
    char *ntmp;
730
25.6k
    char linebuf[MAX_SMLEN];
731
25.6k
    MIME_HEADER *mhdr = NULL, *new_hdr = NULL;
732
25.6k
    STACK_OF(MIME_HEADER) *headers;
733
25.6k
    int i, len, state, save_state = 0;
734
735
25.6k
    headers = sk_MIME_HEADER_new(mime_hdr_cmp);
736
25.6k
    if (headers == NULL)
737
0
        return NULL;
738
23.9M
    while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
739
        /* If whitespace at line start then continuation line */
740
23.9M
        if (mhdr && ossl_isspace(linebuf[0]))
741
897k
            state = MIME_NAME;
742
23.0M
        else
743
23.0M
            state = MIME_START;
744
23.9M
        ntmp = NULL;
745
        /* Go through all characters */
746
64.1M
        for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
747
40.2M
            p++) {
748
749
            /*
750
             * State machine to handle MIME headers if this looks horrible
751
             * that's because it *is*
752
             */
753
754
40.2M
            switch (state) {
755
33.1M
            case MIME_START:
756
33.1M
                if (c == ':') {
757
22.9M
                    state = MIME_TYPE;
758
22.9M
                    *p = 0;
759
22.9M
                    ntmp = strip_ends(q);
760
22.9M
                    q = p + 1;
761
22.9M
                }
762
33.1M
                break;
763
764
2.22M
            case MIME_TYPE:
765
2.22M
                if (c == ';') {
766
47.1k
                    mime_debug("Found End Value\n");
767
47.1k
                    *p = 0;
768
47.1k
                    new_hdr = mime_hdr_new(ntmp, strip_ends(q));
769
47.1k
                    if (new_hdr == NULL)
770
0
                        goto err;
771
47.1k
                    if (!sk_MIME_HEADER_push(headers, new_hdr))
772
0
                        goto err;
773
47.1k
                    mhdr = new_hdr;
774
47.1k
                    new_hdr = NULL;
775
47.1k
                    ntmp = NULL;
776
47.1k
                    q = p + 1;
777
47.1k
                    state = MIME_NAME;
778
2.17M
                } else if (c == '(') {
779
48.2k
                    save_state = state;
780
48.2k
                    state = MIME_COMMENT;
781
48.2k
                }
782
2.22M
                break;
783
784
2.22M
            case MIME_COMMENT:
785
80.3k
                if (c == ')') {
786
48.7k
                    state = save_state;
787
48.7k
                }
788
80.3k
                break;
789
790
3.27M
            case MIME_NAME:
791
3.27M
                if (c == '=') {
792
1.68M
                    state = MIME_VALUE;
793
1.68M
                    *p = 0;
794
1.68M
                    ntmp = strip_ends(q);
795
1.68M
                    q = p + 1;
796
1.68M
                }
797
3.27M
                break;
798
799
1.27M
            case MIME_VALUE:
800
1.27M
                if (c == ';') {
801
810k
                    state = MIME_NAME;
802
810k
                    *p = 0;
803
810k
                    mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
804
810k
                    ntmp = NULL;
805
810k
                    q = p + 1;
806
810k
                } else if (c == '"') {
807
19.3k
                    mime_debug("Found Quote\n");
808
19.3k
                    state = MIME_QUOTE;
809
444k
                } else if (c == '(') {
810
1.11k
                    save_state = state;
811
1.11k
                    state = MIME_COMMENT;
812
1.11k
                }
813
1.27M
                break;
814
815
225k
            case MIME_QUOTE:
816
225k
                if (c == '"') {
817
18.7k
                    mime_debug("Found Match Quote\n");
818
18.7k
                    state = MIME_VALUE;
819
18.7k
                }
820
225k
                break;
821
40.2M
            }
822
40.2M
        }
823
824
23.9M
        if (state == MIME_TYPE) {
825
22.9M
            new_hdr = mime_hdr_new(ntmp, strip_ends(q));
826
22.9M
            if (new_hdr == NULL)
827
0
                goto err;
828
22.9M
            if (!sk_MIME_HEADER_push(headers, new_hdr))
829
0
                goto err;
830
22.9M
            mhdr = new_hdr;
831
22.9M
            new_hdr = NULL;
832
22.9M
        } else if (state == MIME_VALUE) {
833
870k
            mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
834
870k
        }
835
23.9M
        if (p == linebuf)
836
18.3k
            break; /* Blank line means end of headers */
837
23.9M
    }
838
839
    /* Sort the headers and their params for faster searching */
840
25.6k
    sk_MIME_HEADER_sort(headers);
841
22.9M
    for (i = 0; i < sk_MIME_HEADER_num(headers); i++)
842
22.9M
        if ((mhdr = sk_MIME_HEADER_value(headers, i)) != NULL
843
22.9M
            && mhdr->params != NULL)
844
22.9M
            sk_MIME_PARAM_sort(mhdr->params);
845
25.6k
    return headers;
846
847
0
err:
848
0
    mime_hdr_free(new_hdr);
849
0
    sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
850
0
    return NULL;
851
25.6k
}
852
853
static char *strip_ends(char *name)
854
49.2M
{
855
49.2M
    return strip_end(strip_start(name));
856
49.2M
}
857
858
/* Strip a parameter of whitespace from start of param */
859
static char *strip_start(char *name)
860
49.2M
{
861
49.2M
    char *p, c;
862
    /* Look for first non whitespace or quote */
863
74.5M
    for (p = name; (c = *p); p++) {
864
25.9M
        if (c == '"') {
865
            /* Next char is start of string if non null */
866
105k
            if (p[1])
867
79.9k
                return p + 1;
868
            /* Else null string */
869
25.6k
            return NULL;
870
105k
        }
871
25.8M
        if (!ossl_isspace(c))
872
616k
            return p;
873
25.8M
    }
874
48.5M
    return NULL;
875
49.2M
}
876
877
/* As above but strip from end of string : maybe should handle brackets? */
878
static char *strip_end(char *name)
879
40.6M
{
880
40.6M
    char *p, c;
881
40.6M
    if (!name)
882
39.9M
        return NULL;
883
    /* Look for first non whitespace or quote */
884
1.07M
    for (p = name + strlen(name) - 1; p >= name; p--) {
885
1.05M
        c = *p;
886
1.05M
        if (c == '"') {
887
55.0k
            if (p - 1 == name)
888
4.43k
                return NULL;
889
50.6k
            *p = 0;
890
50.6k
            return name;
891
55.0k
        }
892
997k
        if (ossl_isspace(c))
893
409k
            *p = 0;
894
587k
        else
895
587k
            return name;
896
997k
    }
897
26.8k
    return NULL;
898
669k
}
899
900
static MIME_HEADER *mime_hdr_new(const char *name, const char *value)
901
22.9M
{
902
22.9M
    MIME_HEADER *mhdr = NULL;
903
22.9M
    char *tmpname = NULL, *tmpval = NULL, *p;
904
905
22.9M
    if (name) {
906
151k
        if ((tmpname = OPENSSL_strdup(name)) == NULL)
907
0
            return NULL;
908
1.16M
        for (p = tmpname; *p; p++)
909
1.00M
            *p = ossl_tolower(*p);
910
151k
    }
911
22.9M
    if (value) {
912
269k
        if ((tmpval = OPENSSL_strdup(value)) == NULL)
913
0
            goto err;
914
2.41M
        for (p = tmpval; *p; p++)
915
2.14M
            *p = ossl_tolower(*p);
916
269k
    }
917
22.9M
    mhdr = OPENSSL_malloc(sizeof(*mhdr));
918
22.9M
    if (mhdr == NULL)
919
0
        goto err;
920
22.9M
    mhdr->name = tmpname;
921
22.9M
    mhdr->value = tmpval;
922
22.9M
    if ((mhdr->params = sk_MIME_PARAM_new(mime_param_cmp)) == NULL)
923
0
        goto err;
924
22.9M
    return mhdr;
925
926
0
err:
927
0
    OPENSSL_free(tmpname);
928
0
    OPENSSL_free(tmpval);
929
0
    OPENSSL_free(mhdr);
930
0
    return NULL;
931
22.9M
}
932
933
static int mime_hdr_addparam(MIME_HEADER *mhdr, const char *name, const char *value)
934
1.68M
{
935
1.68M
    char *tmpname = NULL, *tmpval = NULL, *p;
936
1.68M
    MIME_PARAM *mparam = NULL;
937
938
1.68M
    if (name) {
939
95.1k
        tmpname = OPENSSL_strdup(name);
940
95.1k
        if (!tmpname)
941
0
            goto err;
942
600k
        for (p = tmpname; *p; p++)
943
505k
            *p = ossl_tolower(*p);
944
95.1k
    }
945
1.68M
    if (value) {
946
148k
        tmpval = OPENSSL_strdup(value);
947
148k
        if (!tmpval)
948
0
            goto err;
949
148k
    }
950
    /* Parameter values are case sensitive so leave as is */
951
1.68M
    mparam = OPENSSL_malloc(sizeof(*mparam));
952
1.68M
    if (mparam == NULL)
953
0
        goto err;
954
1.68M
    mparam->param_name = tmpname;
955
1.68M
    mparam->param_value = tmpval;
956
1.68M
    if (!sk_MIME_PARAM_push(mhdr->params, mparam))
957
0
        goto err;
958
1.68M
    return 1;
959
0
err:
960
0
    OPENSSL_free(tmpname);
961
0
    OPENSSL_free(tmpval);
962
0
    OPENSSL_free(mparam);
963
0
    return 0;
964
1.68M
}
965
966
static int mime_hdr_cmp(const MIME_HEADER *const *a,
967
    const MIME_HEADER *const *b)
968
253M
{
969
253M
    if ((*a)->name == NULL || (*b)->name == NULL)
970
251M
        return ((*a)->name != NULL) - ((*b)->name != NULL);
971
972
1.46M
    return strcmp((*a)->name, (*b)->name);
973
253M
}
974
975
static int mime_param_cmp(const MIME_PARAM *const *a,
976
    const MIME_PARAM *const *b)
977
22.8M
{
978
22.8M
    if ((*a)->param_name == NULL || (*b)->param_name == NULL)
979
21.9M
        return ((*a)->param_name != NULL) - ((*b)->param_name != NULL);
980
877k
    return strcmp((*a)->param_name, (*b)->param_name);
981
22.8M
}
982
983
/* Find a header with a given name (if possible) */
984
985
static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, const char *name)
986
25.6k
{
987
25.6k
    MIME_HEADER htmp;
988
25.6k
    int idx;
989
990
25.6k
    htmp.name = (char *)name;
991
25.6k
    htmp.value = NULL;
992
25.6k
    htmp.params = NULL;
993
994
25.6k
    idx = sk_MIME_HEADER_find(hdrs, &htmp);
995
25.6k
    return sk_MIME_HEADER_value(hdrs, idx);
996
25.6k
}
997
998
static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, const char *name)
999
5.52k
{
1000
5.52k
    MIME_PARAM param;
1001
5.52k
    int idx;
1002
1003
5.52k
    param.param_name = (char *)name;
1004
5.52k
    param.param_value = NULL;
1005
5.52k
    idx = sk_MIME_PARAM_find(hdr->params, &param);
1006
5.52k
    return sk_MIME_PARAM_value(hdr->params, idx);
1007
5.52k
}
1008
1009
static void mime_hdr_free(MIME_HEADER *hdr)
1010
22.9M
{
1011
22.9M
    if (hdr == NULL)
1012
0
        return;
1013
22.9M
    OPENSSL_free(hdr->name);
1014
22.9M
    OPENSSL_free(hdr->value);
1015
22.9M
    if (hdr->params)
1016
22.9M
        sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
1017
22.9M
    OPENSSL_free(hdr);
1018
22.9M
}
1019
1020
static void mime_param_free(MIME_PARAM *param)
1021
1.68M
{
1022
1.68M
    OPENSSL_free(param->param_name);
1023
1.68M
    OPENSSL_free(param->param_value);
1024
1.68M
    OPENSSL_free(param);
1025
1.68M
}
1026
1027
/*-
1028
 * Check for a multipart boundary. Returns:
1029
 * 0 : no boundary
1030
 * 1 : part boundary
1031
 * 2 : final boundary
1032
 */
1033
static int mime_bound_check(char *line, int linelen, const char *bound, int blen)
1034
18.1M
{
1035
18.1M
    if (linelen < 0 || blen < 0)
1036
0
        return 0;
1037
    /* Quickly eliminate if line length too short */
1038
18.1M
    if (blen + 2 > linelen)
1039
16.0M
        return 0;
1040
    /* Check for part boundary */
1041
2.10M
    if ((CHECK_AND_SKIP_PREFIX(line, "--")) && strncmp(line, bound, blen) == 0)
1042
1.05M
        return HAS_PREFIX(line + blen, "--") ? 2 : 1;
1043
1.04M
    return 0;
1044
2.10M
}
1045
1046
static int strip_eol(char *linebuf, int *plen, int flags)
1047
42.5M
{
1048
42.5M
    int len = *plen;
1049
42.5M
    char *p, c;
1050
42.5M
    int is_eol = 0;
1051
1052
42.5M
#ifndef OPENSSL_NO_CMS
1053
42.5M
    if ((flags & CMS_BINARY) != 0) {
1054
0
        if (len <= 0 || linebuf[len - 1] != '\n')
1055
0
            return 0;
1056
0
        if ((flags & SMIME_CRLFEOL) != 0) {
1057
0
            if (len <= 1 || linebuf[len - 2] != '\r')
1058
0
                return 0;
1059
0
            len--;
1060
0
        }
1061
0
        len--;
1062
0
        *plen = len;
1063
0
        return 1;
1064
0
    }
1065
42.5M
#endif
1066
1067
85.0M
    for (p = linebuf + len - 1; len > 0; len--, p--) {
1068
50.7M
        c = *p;
1069
50.7M
        if (c == '\n') {
1070
42.5M
            is_eol = 1;
1071
42.5M
        } else if (is_eol && (flags & SMIME_ASCIICRLF) != 0 && c == 32) {
1072
            /* Strip trailing space on a line; 32 == ASCII for ' ' */
1073
0
            continue;
1074
8.22M
        } else if (c != '\r') {
1075
8.21M
            break;
1076
8.21M
        }
1077
50.7M
    }
1078
42.5M
    *plen = len;
1079
42.5M
    return is_eol;
1080
42.5M
}