Coverage Report

Created: 2026-10-28 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl35/crypto/asn1/asn_mime.c
Line
Count
Source
1
/*
2
 * Copyright 2008-2026 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
53.8M
#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
    int r;
132
0
    BIO_printf(out, "-----BEGIN %s-----\n", hdr);
133
0
    r = B64_write_ASN1(out, val, in, flags, it);
134
0
    BIO_printf(out, "-----END %s-----\n", hdr);
135
0
    return r;
136
0
}
137
138
static ASN1_VALUE *b64_read_asn1(BIO *bio, const ASN1_ITEM *it, ASN1_VALUE **x,
139
    OSSL_LIB_CTX *libctx, const char *propq)
140
15.3k
{
141
15.3k
    BIO *b64;
142
15.3k
    ASN1_VALUE *val;
143
144
15.3k
    if ((b64 = BIO_new(BIO_f_base64())) == NULL) {
145
0
        ERR_raise(ERR_LIB_ASN1, ERR_R_BIO_LIB);
146
0
        return 0;
147
0
    }
148
15.3k
    bio = BIO_push(b64, bio);
149
15.3k
    val = ASN1_item_d2i_bio_ex(it, bio, x, libctx, propq);
150
15.3k
    if (!val)
151
15.3k
        ERR_raise(ERR_LIB_ASN1, ASN1_R_DECODE_ERROR);
152
15.3k
    (void)BIO_flush(bio);
153
15.3k
    BIO_pop(bio);
154
15.3k
    BIO_free(b64);
155
15.3k
    return val;
156
15.3k
}
157
158
/* Generate the MIME "micalg" parameter from RFC3851, RFC4490 */
159
160
static int asn1_write_micalg(BIO *out, STACK_OF(X509_ALGOR) *mdalgs)
161
0
{
162
0
    const EVP_MD *md;
163
0
    int i, have_unknown = 0, write_comma, ret = 0, md_nid;
164
0
    have_unknown = 0;
165
0
    write_comma = 0;
166
0
    for (i = 0; i < sk_X509_ALGOR_num(mdalgs); i++) {
167
0
        if (write_comma)
168
0
            BIO_write(out, ",", 1);
169
0
        write_comma = 1;
170
0
        md_nid = OBJ_obj2nid(sk_X509_ALGOR_value(mdalgs, i)->algorithm);
171
172
        /* RFC 8702 does not define a micalg for SHAKE, assuming "shake-<bitlen>" */
173
0
        if (md_nid == NID_shake128) {
174
0
            if (BIO_puts(out, "shake-128") < 0)
175
0
                goto err;
176
0
            continue;
177
0
        }
178
0
        if (md_nid == NID_shake256) {
179
0
            if (BIO_puts(out, "shake-256") < 0)
180
0
                goto err;
181
0
            continue;
182
0
        }
183
184
0
        md = EVP_get_digestbynid(md_nid);
185
0
        if (md && md->md_ctrl) {
186
0
            int rv;
187
0
            char *micstr;
188
0
            rv = md->md_ctrl(NULL, EVP_MD_CTRL_MICALG, 0, &micstr);
189
0
            if (rv > 0) {
190
0
                BIO_puts(out, micstr);
191
0
                OPENSSL_free(micstr);
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
            BIO_puts(out, "sha1");
200
0
            break;
201
202
0
        case NID_md5:
203
0
            BIO_puts(out, "md5");
204
0
            break;
205
206
0
        case NID_sha256:
207
0
            BIO_puts(out, "sha-256");
208
0
            break;
209
210
0
        case NID_sha384:
211
0
            BIO_puts(out, "sha-384");
212
0
            break;
213
214
0
        case NID_sha512:
215
0
            BIO_puts(out, "sha-512");
216
0
            break;
217
218
0
        case NID_id_GostR3411_94:
219
0
            BIO_puts(out, "gostr3411-94");
220
0
            break;
221
222
0
        case NID_id_GostR3411_2012_256:
223
0
            BIO_puts(out, "gostr3411-2012-256");
224
0
            break;
225
226
0
        case NID_id_GostR3411_2012_512:
227
0
            BIO_puts(out, "gostr3411-2012-512");
228
0
            break;
229
230
0
        default:
231
0
            if (have_unknown) {
232
0
                write_comma = 0;
233
0
            } else {
234
0
                BIO_puts(out, "unknown");
235
0
                have_unknown = 1;
236
0
            }
237
0
            break;
238
0
        }
239
0
    }
240
241
0
    ret = 1;
242
0
err:
243
244
0
    return ret;
245
0
}
246
247
/* SMIME sender */
248
249
int SMIME_write_ASN1_ex(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
250
    int ctype_nid, int econt_nid,
251
    STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it,
252
    OSSL_LIB_CTX *libctx, const char *propq)
253
0
{
254
0
    char bound[33], c;
255
0
    int i;
256
0
    const char *mime_prefix, *mime_eol, *cname = "smime.p7m";
257
0
    const char *msg_type = NULL;
258
259
0
    if (flags & SMIME_OLDMIME)
260
0
        mime_prefix = "application/x-pkcs7-";
261
0
    else
262
0
        mime_prefix = "application/pkcs7-";
263
264
0
    if (flags & SMIME_CRLFEOL)
265
0
        mime_eol = "\r\n";
266
0
    else
267
0
        mime_eol = "\n";
268
0
    if ((flags & SMIME_DETACHED) && data) {
269
        /* We want multipart/signed */
270
        /* Generate a random boundary */
271
0
        if (RAND_bytes_ex(libctx, (unsigned char *)bound, 32, 0) <= 0)
272
0
            return 0;
273
0
        for (i = 0; i < 32; i++) {
274
0
            c = bound[i] & 0xf;
275
0
            if (c < 10)
276
0
                c += '0';
277
0
            else
278
0
                c += 'A' - 10;
279
0
            bound[i] = c;
280
0
        }
281
0
        bound[32] = 0;
282
0
        BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
283
0
        BIO_printf(bio, "Content-Type: multipart/signed;");
284
0
        BIO_printf(bio, " protocol=\"%ssignature\";", mime_prefix);
285
0
        BIO_puts(bio, " micalg=\"");
286
0
        if (!asn1_write_micalg(bio, mdalgs))
287
0
            return 0;
288
0
        BIO_printf(bio, "\"; boundary=\"----%s\"%s%s",
289
0
            bound, mime_eol, mime_eol);
290
0
        BIO_printf(bio, "This is an S/MIME signed message%s%s",
291
0
            mime_eol, mime_eol);
292
        /* Now write out the first part */
293
0
        BIO_printf(bio, "------%s%s", bound, mime_eol);
294
0
        if (!asn1_output_data(bio, data, val, flags, it))
295
0
            return 0;
296
0
        BIO_printf(bio, "%s------%s%s", mime_eol, bound, mime_eol);
297
298
        /* Headers for signature */
299
300
0
        BIO_printf(bio, "Content-Type: %ssignature;", mime_prefix);
301
0
        BIO_printf(bio, " name=\"smime.p7s\"%s", mime_eol);
302
0
        BIO_printf(bio, "Content-Transfer-Encoding: base64%s", mime_eol);
303
0
        BIO_printf(bio, "Content-Disposition: attachment;");
304
0
        BIO_printf(bio, " filename=\"smime.p7s\"%s%s", mime_eol, mime_eol);
305
0
        B64_write_ASN1(bio, val, NULL, 0, it);
306
0
        BIO_printf(bio, "%s------%s--%s%s", mime_eol, bound,
307
0
            mime_eol, mime_eol);
308
0
        return 1;
309
0
    }
310
311
    /* Determine smime-type header */
312
313
0
    if (ctype_nid == NID_pkcs7_enveloped) {
314
0
        msg_type = "enveloped-data";
315
0
    } else if (ctype_nid == NID_id_smime_ct_authEnvelopedData) {
316
0
        msg_type = "authEnveloped-data";
317
0
    } else if (ctype_nid == NID_pkcs7_signed) {
318
0
        if (econt_nid == NID_id_smime_ct_receipt)
319
0
            msg_type = "signed-receipt";
320
0
        else if (sk_X509_ALGOR_num(mdalgs) >= 0)
321
0
            msg_type = "signed-data";
322
0
        else
323
0
            msg_type = "certs-only";
324
0
    } else if (ctype_nid == NID_id_smime_ct_compressedData) {
325
0
        msg_type = "compressed-data";
326
0
        cname = "smime.p7z";
327
0
    }
328
    /* MIME headers */
329
0
    BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
330
0
    BIO_printf(bio, "Content-Disposition: attachment;");
331
0
    BIO_printf(bio, " filename=\"%s\"%s", cname, mime_eol);
332
0
    BIO_printf(bio, "Content-Type: %smime;", mime_prefix);
333
0
    if (msg_type)
334
0
        BIO_printf(bio, " smime-type=%s;", msg_type);
335
0
    BIO_printf(bio, " name=\"%s\"%s", cname, mime_eol);
336
0
    BIO_printf(bio, "Content-Transfer-Encoding: base64%s%s",
337
0
        mime_eol, mime_eol);
338
0
    if (!B64_write_ASN1(bio, val, data, flags, it))
339
0
        return 0;
340
0
    BIO_printf(bio, "%s", mime_eol);
341
0
    return 1;
342
0
}
343
344
int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
345
    int ctype_nid, int econt_nid,
346
    STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it)
347
0
{
348
0
    return SMIME_write_ASN1_ex(bio, val, data, flags, ctype_nid, econt_nid,
349
0
        mdalgs, it, NULL, NULL);
350
0
}
351
352
/* Handle output of ASN1 data */
353
354
/* cannot constify val because of CMS_dataFinal() */
355
static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
356
    const ASN1_ITEM *it)
357
0
{
358
0
    BIO *tmpbio;
359
0
    const ASN1_AUX *aux = it->funcs;
360
0
    ASN1_STREAM_ARG sarg;
361
0
    int rv = 1;
362
363
    /*
364
     * If data is not detached or resigning then the output BIO is already
365
     * set up to finalise when it is written through.
366
     */
367
0
    if (!(flags & SMIME_DETACHED) || (flags & PKCS7_REUSE_DIGEST)) {
368
0
        return SMIME_crlf_copy(data, out, flags);
369
0
    }
370
371
0
    if (!aux || !aux->asn1_cb) {
372
0
        ERR_raise(ERR_LIB_ASN1, ASN1_R_STREAMING_NOT_SUPPORTED);
373
0
        return 0;
374
0
    }
375
376
0
    sarg.out = out;
377
0
    sarg.ndef_bio = NULL;
378
0
    sarg.boundary = NULL;
379
380
    /* Let ASN1 code prepend any needed BIOs */
381
382
0
    if (aux->asn1_cb(ASN1_OP_DETACHED_PRE, &val, it, &sarg) <= 0)
383
0
        return 0;
384
385
    /* Copy data across, passing through filter BIOs for processing */
386
0
    if (!SMIME_crlf_copy(data, sarg.ndef_bio, flags))
387
0
        rv = 0;
388
389
    /* Finalize structure */
390
0
    if (aux->asn1_cb(ASN1_OP_DETACHED_POST, &val, it, &sarg) <= 0)
391
0
        rv = 0;
392
393
    /* Now remove any digests prepended to the BIO */
394
395
0
    while (sarg.ndef_bio != out) {
396
0
        tmpbio = BIO_pop(sarg.ndef_bio);
397
0
        BIO_free(sarg.ndef_bio);
398
0
        sarg.ndef_bio = tmpbio;
399
0
    }
400
401
0
    return rv;
402
0
}
403
404
/*
405
 * SMIME reader: handle multipart/signed and opaque signing. in multipart
406
 * case the content is placed in a memory BIO pointed to by "bcont". In
407
 * opaque this is set to NULL
408
 */
409
410
ASN1_VALUE *SMIME_read_ASN1_ex(BIO *bio, int flags, BIO **bcont,
411
    const ASN1_ITEM *it, ASN1_VALUE **x,
412
    OSSL_LIB_CTX *libctx, const char *propq)
413
27.3k
{
414
27.3k
    BIO *asnin;
415
27.3k
    STACK_OF(MIME_HEADER) *headers = NULL;
416
27.3k
    STACK_OF(BIO) *parts = NULL;
417
27.3k
    MIME_HEADER *hdr;
418
27.3k
    MIME_PARAM *prm;
419
27.3k
    ASN1_VALUE *val;
420
27.3k
    int ret;
421
422
27.3k
    if (bcont)
423
0
        *bcont = NULL;
424
425
27.3k
    if ((headers = mime_parse_hdr(bio)) == NULL) {
426
0
        ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_PARSE_ERROR);
427
0
        return NULL;
428
0
    }
429
430
27.3k
    if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
431
22.2k
        || hdr->value == NULL) {
432
5.81k
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
433
5.81k
        ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_CONTENT_TYPE);
434
5.81k
        return NULL;
435
5.81k
    }
436
437
    /* Handle multipart/signed */
438
439
21.5k
    if (strcmp(hdr->value, "multipart/signed") == 0) {
440
        /* Split into two parts */
441
6.35k
        prm = mime_param_find(hdr, "boundary");
442
6.35k
        if (prm == NULL || prm->param_value == NULL) {
443
49
            sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
444
49
            ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_MULTIPART_BOUNDARY);
445
49
            return NULL;
446
49
        }
447
6.30k
        ret = multi_split(bio, flags, prm->param_value, &parts);
448
6.30k
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
449
6.30k
        if (!ret || (sk_BIO_num(parts) != 2)) {
450
2.67k
            ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_MULTIPART_BODY_FAILURE);
451
2.67k
            sk_BIO_pop_free(parts, BIO_vfree);
452
2.67k
            return NULL;
453
2.67k
        }
454
455
        /* Parse the signature piece */
456
3.63k
        asnin = sk_BIO_value(parts, 1);
457
458
3.63k
        if ((headers = mime_parse_hdr(asnin)) == NULL) {
459
0
            ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_SIG_PARSE_ERROR);
460
0
            sk_BIO_pop_free(parts, BIO_vfree);
461
0
            return NULL;
462
0
        }
463
464
        /* Get content type */
465
466
3.63k
        if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
467
3.41k
            || hdr->value == NULL) {
468
231
            sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
469
231
            ERR_raise(ERR_LIB_ASN1, ASN1_R_NO_SIG_CONTENT_TYPE);
470
231
            sk_BIO_pop_free(parts, BIO_vfree);
471
231
            return NULL;
472
231
        }
473
474
3.40k
        if (strcmp(hdr->value, "application/x-pkcs7-signature") && strcmp(hdr->value, "application/pkcs7-signature")) {
475
1.10k
            ERR_raise_data(ERR_LIB_ASN1, ASN1_R_SIG_INVALID_MIME_TYPE,
476
1.10k
                "type: %s", hdr->value);
477
1.10k
            sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
478
1.10k
            sk_BIO_pop_free(parts, BIO_vfree);
479
1.10k
            return NULL;
480
1.10k
        }
481
2.29k
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
482
        /* Read in ASN1 */
483
2.29k
        if ((val = b64_read_asn1(asnin, it, x, libctx, propq)) == NULL) {
484
2.15k
            ERR_raise(ERR_LIB_ASN1, ASN1_R_ASN1_SIG_PARSE_ERROR);
485
2.15k
            sk_BIO_pop_free(parts, BIO_vfree);
486
2.15k
            return NULL;
487
2.15k
        }
488
489
141
        if (bcont) {
490
0
            *bcont = sk_BIO_value(parts, 0);
491
0
            BIO_free(asnin);
492
0
            sk_BIO_free(parts);
493
141
        } else {
494
141
            sk_BIO_pop_free(parts, BIO_vfree);
495
141
        }
496
141
        return val;
497
2.29k
    }
498
499
    /* OK, if not multipart/signed try opaque signature */
500
501
15.2k
    if (strcmp(hdr->value, "application/x-pkcs7-mime") && strcmp(hdr->value, "application/pkcs7-mime")) {
502
2.12k
        ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_MIME_TYPE,
503
2.12k
            "type: %s", hdr->value);
504
2.12k
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
505
2.12k
        return NULL;
506
2.12k
    }
507
508
13.0k
    sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
509
510
13.0k
    if ((val = b64_read_asn1(bio, it, x, libctx, propq)) == NULL) {
511
12.3k
        ERR_raise(ERR_LIB_ASN1, ASN1_R_ASN1_PARSE_ERROR);
512
12.3k
        return NULL;
513
12.3k
    }
514
773
    return val;
515
13.0k
}
516
517
ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it)
518
0
{
519
0
    return SMIME_read_ASN1_ex(bio, 0, bcont, it, NULL, NULL, NULL);
520
0
}
521
522
/* Copy text from one BIO to another making the output CRLF at EOL */
523
int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
524
{
525
    BIO *bf;
526
    char eol;
527
    int len;
528
    char linebuf[MAX_SMLEN];
529
    int ret;
530
531
    if (in == NULL || out == NULL) {
532
        ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_NULL_PARAMETER);
533
        return 0;
534
    }
535
536
    /*
537
     * Buffer output so we don't write one line at a time. This is useful
538
     * when streaming as we don't end up with one OCTET STRING per line.
539
     */
540
    bf = BIO_new(BIO_f_buffer());
541
    if (bf == NULL) {
542
        ERR_raise(ERR_LIB_ASN1, ERR_R_BIO_LIB);
543
        return 0;
544
    }
545
    out = BIO_push(bf, out);
546
    if (flags & SMIME_BINARY) {
547
        while ((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0)
548
            BIO_write(out, linebuf, len);
549
    } else {
550
        int eolcnt = 0;
551
        if (flags & SMIME_TEXT)
552
            BIO_printf(out, "Content-Type: text/plain\r\n\r\n");
553
        while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
554
            eol = strip_eol(linebuf, &len, flags);
555
            if (len > 0) {
556
                /* Not EOF: write out all CRLF */
557
                if (flags & SMIME_ASCIICRLF) {
558
                    int i;
559
                    for (i = 0; i < eolcnt; i++)
560
                        BIO_write(out, "\r\n", 2);
561
                    eolcnt = 0;
562
                }
563
                BIO_write(out, linebuf, len);
564
                if (eol)
565
                    BIO_write(out, "\r\n", 2);
566
            } else if (flags & SMIME_ASCIICRLF) {
567
                eolcnt++;
568
            } else if (eol) {
569
                BIO_write(out, "\r\n", 2);
570
            }
571
        }
572
    }
573
    ret = BIO_flush(out);
574
    BIO_pop(out);
575
    BIO_free(bf);
576
    if (ret <= 0)
577
        return 0;
578
579
    return 1;
580
}
581
582
/* Strip off headers if they are text/plain */
583
int SMIME_text(BIO *in, BIO *out)
584
0
{
585
0
    char iobuf[4096];
586
0
    int len;
587
0
    STACK_OF(MIME_HEADER) *headers;
588
0
    MIME_HEADER *hdr;
589
590
0
    if ((headers = mime_parse_hdr(in)) == NULL) {
591
0
        ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_PARSE_ERROR);
592
0
        return 0;
593
0
    }
594
0
    if ((hdr = mime_hdr_find(headers, "content-type")) == NULL
595
0
        || hdr->value == NULL) {
596
0
        ERR_raise(ERR_LIB_ASN1, ASN1_R_MIME_NO_CONTENT_TYPE);
597
0
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
598
0
        return 0;
599
0
    }
600
0
    if (strcmp(hdr->value, "text/plain")) {
601
0
        ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_MIME_TYPE,
602
0
            "type: %s", hdr->value);
603
0
        sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
604
0
        return 0;
605
0
    }
606
0
    sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
607
0
    while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
608
0
        BIO_write(out, iobuf, len);
609
0
    if (len < 0)
610
0
        return 0;
611
0
    return 1;
612
0
}
613
614
/*
615
 * Split a multipart/XXX message body into component parts: result is
616
 * canonical parts in a STACK of bios
617
 */
618
619
static int multi_split(BIO *bio, int flags, const char *bound, STACK_OF(BIO) **ret)
620
2.12k
{
621
2.12k
    char linebuf[MAX_SMLEN];
622
2.12k
    int len, blen;
623
2.12k
    int eol = 0, next_eol = 0;
624
2.12k
    BIO *bpart = NULL;
625
2.12k
    STACK_OF(BIO) *parts;
626
2.12k
    char state, part, first;
627
628
2.12k
    blen = strlen(bound);
629
2.12k
    part = 0;
630
2.12k
    state = 0;
631
2.12k
    first = 1;
632
2.12k
    parts = sk_BIO_new_null();
633
2.12k
    *ret = parts;
634
2.12k
    if (*ret == NULL)
635
0
        return 0;
636
23.9M
    while ((len = BIO_get_line(bio, linebuf, MAX_SMLEN)) > 0) {
637
23.9M
        state = mime_bound_check(linebuf, len, bound, blen);
638
23.9M
        if (state == 1) {
639
2.15M
            first = 1;
640
2.15M
            part++;
641
21.7M
        } else if (state == 2) {
642
1.28k
            if (!sk_BIO_push(parts, bpart)) {
643
0
                BIO_free(bpart);
644
0
                return 0;
645
0
            }
646
1.28k
            return 1;
647
21.7M
        } else if (part != 0) {
648
            /* Strip (possibly CR +) LF from linebuf */
649
21.7M
            next_eol = strip_eol(linebuf, &len, flags);
650
21.7M
            if (first) {
651
2.12M
                first = 0;
652
2.12M
                if (bpart)
653
2.12M
                    if (!sk_BIO_push(parts, bpart)) {
654
0
                        BIO_free(bpart);
655
0
                        return 0;
656
0
                    }
657
2.12M
                bpart = BIO_new(BIO_s_mem());
658
2.12M
                if (bpart == NULL)
659
0
                    return 0;
660
2.12M
                BIO_set_mem_eof_return(bpart, 0);
661
19.6M
            } else if (eol) {
662
19.6M
                if (
663
19.6M
#ifndef OPENSSL_NO_CMS
664
19.6M
                    (flags & CMS_BINARY) == 0
665
#else
666
                    1
667
#endif
668
19.6M
                    || (flags & SMIME_CRLFEOL) != 0) {
669
19.6M
                    if (BIO_write(bpart, "\r\n", 2) < 2)
670
0
                        goto err;
671
19.6M
                } else if (BIO_write(bpart, "\n", 1) < 1)
672
0
                    goto err;
673
19.6M
            }
674
21.7M
            eol = next_eol;
675
21.7M
            if (len > 0 && BIO_write(bpart, linebuf, len) < len)
676
0
                goto err;
677
21.7M
        }
678
23.9M
    }
679
837
err:
680
837
    BIO_free(bpart);
681
837
    return 0;
682
2.12k
}
683
684
/* This is the big one: parse MIME header lines up to message body */
685
686
#define MIME_INVALID 0
687
67.4M
#define MIME_START 1
688
65.0M
#define MIME_TYPE 2
689
20.0M
#define MIME_NAME 3
690
14.9M
#define MIME_VALUE 4
691
283k
#define MIME_QUOTE 5
692
71.3k
#define MIME_COMMENT 6
693
694
static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
695
31.0k
{
696
31.0k
    char *p, *q, c;
697
31.0k
    char *ntmp;
698
31.0k
    char linebuf[MAX_SMLEN];
699
31.0k
    MIME_HEADER *mhdr = NULL, *new_hdr = NULL;
700
31.0k
    STACK_OF(MIME_HEADER) *headers;
701
31.0k
    int i, len, state, save_state = 0;
702
703
31.0k
    headers = sk_MIME_HEADER_new(mime_hdr_cmp);
704
31.0k
    if (headers == NULL)
705
0
        return NULL;
706
29.8M
    while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
707
        /* If whitespace at line start then continuation line */
708
29.8M
        if (mhdr && ossl_isspace(linebuf[0]))
709
930k
            state = MIME_NAME;
710
28.9M
        else
711
28.9M
            state = MIME_START;
712
29.8M
        ntmp = NULL;
713
        /* Go through all characters */
714
94.2M
        for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
715
64.3M
            p++) {
716
717
            /*
718
             * State machine to handle MIME headers if this looks horrible
719
             * that's because it *is*
720
             */
721
722
64.3M
            switch (state) {
723
38.4M
            case MIME_START:
724
38.4M
                if (c == ':') {
725
28.7M
                    state = MIME_TYPE;
726
28.7M
                    *p = 0;
727
28.7M
                    ntmp = strip_ends(q);
728
28.7M
                    q = p + 1;
729
28.7M
                }
730
38.4M
                break;
731
732
6.42M
            case MIME_TYPE:
733
6.42M
                if (c == ';') {
734
770k
                    mime_debug("Found End Value\n");
735
770k
                    *p = 0;
736
770k
                    new_hdr = mime_hdr_new(ntmp, strip_ends(q));
737
770k
                    if (new_hdr == NULL)
738
0
                        goto err;
739
770k
                    if (!sk_MIME_HEADER_push(headers, new_hdr))
740
0
                        goto err;
741
770k
                    mhdr = new_hdr;
742
770k
                    new_hdr = NULL;
743
770k
                    ntmp = NULL;
744
770k
                    q = p + 1;
745
770k
                    state = MIME_NAME;
746
5.64M
                } else if (c == '(') {
747
7.71k
                    save_state = state;
748
7.71k
                    state = MIME_COMMENT;
749
7.71k
                }
750
6.42M
                break;
751
752
6.42M
            case MIME_COMMENT:
753
56.4k
                if (c == ')') {
754
9.67k
                    state = save_state;
755
9.67k
                }
756
56.4k
                break;
757
758
12.5M
            case MIME_NAME:
759
12.5M
                if (c == '=') {
760
6.50M
                    state = MIME_VALUE;
761
6.50M
                    *p = 0;
762
6.50M
                    ntmp = strip_ends(q);
763
6.50M
                    q = p + 1;
764
6.50M
                }
765
12.5M
                break;
766
767
6.56M
            case MIME_VALUE:
768
6.56M
                if (c == ';') {
769
5.72M
                    state = MIME_NAME;
770
5.72M
                    *p = 0;
771
5.72M
                    mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
772
5.72M
                    ntmp = NULL;
773
5.72M
                    q = p + 1;
774
5.72M
                } else if (c == '"') {
775
29.5k
                    mime_debug("Found Quote\n");
776
29.5k
                    state = MIME_QUOTE;
777
809k
                } else if (c == '(') {
778
7.10k
                    save_state = state;
779
7.10k
                    state = MIME_COMMENT;
780
7.10k
                }
781
6.56M
                break;
782
783
253k
            case MIME_QUOTE:
784
253k
                if (c == '"') {
785
15.6k
                    mime_debug("Found Match Quote\n");
786
15.6k
                    state = MIME_VALUE;
787
15.6k
                }
788
253k
                break;
789
64.3M
            }
790
64.3M
        }
791
792
29.8M
        if (state == MIME_TYPE) {
793
27.9M
            new_hdr = mime_hdr_new(ntmp, strip_ends(q));
794
27.9M
            if (new_hdr == NULL)
795
0
                goto err;
796
27.9M
            if (!sk_MIME_HEADER_push(headers, new_hdr))
797
0
                goto err;
798
27.9M
            mhdr = new_hdr;
799
27.9M
            new_hdr = NULL;
800
27.9M
        } else if (state == MIME_VALUE) {
801
766k
            mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
802
766k
        }
803
29.8M
        if (p == linebuf)
804
22.1k
            break; /* Blank line means end of headers */
805
29.8M
    }
806
807
    /* Sort the headers and their params for faster searching */
808
31.0k
    sk_MIME_HEADER_sort(headers);
809
28.7M
    for (i = 0; i < sk_MIME_HEADER_num(headers); i++)
810
28.7M
        if ((mhdr = sk_MIME_HEADER_value(headers, i)) != NULL
811
28.7M
            && mhdr->params != NULL)
812
28.7M
            sk_MIME_PARAM_sort(mhdr->params);
813
31.0k
    return headers;
814
815
0
err:
816
0
    mime_hdr_free(new_hdr);
817
0
    sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
818
0
    return NULL;
819
31.0k
}
820
821
static char *strip_ends(char *name)
822
70.5M
{
823
70.5M
    return strip_end(strip_start(name));
824
70.5M
}
825
826
/* Strip a parameter of whitespace from start of param */
827
static char *strip_start(char *name)
828
70.5M
{
829
70.5M
    char *p, c;
830
    /* Look for first non whitespace or quote */
831
100M
    for (p = name; (c = *p); p++) {
832
33.0M
        if (c == '"') {
833
            /* Next char is start of string if non null */
834
1.86M
            if (p[1])
835
1.40M
                return p + 1;
836
            /* Else null string */
837
451k
            return NULL;
838
1.86M
        }
839
31.2M
        if (!ossl_isspace(c))
840
1.54M
            return p;
841
31.2M
    }
842
67.1M
    return NULL;
843
70.5M
}
844
845
/* As above but strip from end of string : maybe should handle brackets? */
846
static char *strip_end(char *name)
847
49.4M
{
848
49.4M
    char *p, c;
849
49.4M
    if (!name)
850
48.9M
        return NULL;
851
    /* Look for first non whitespace or quote */
852
613k
    for (p = name + strlen(name) - 1; p >= name; p--) {
853
612k
        c = *p;
854
612k
        if (c == '"') {
855
16.9k
            if (p - 1 == name)
856
5.66k
                return NULL;
857
11.3k
            *p = 0;
858
11.3k
            return name;
859
16.9k
        }
860
595k
        if (ossl_isspace(c))
861
127k
            *p = 0;
862
467k
        else
863
467k
            return name;
864
595k
    }
865
1.30k
    return NULL;
866
486k
}
867
868
static MIME_HEADER *mime_hdr_new(const char *name, const char *value)
869
28.7M
{
870
28.7M
    MIME_HEADER *mhdr = NULL;
871
28.7M
    char *tmpname = NULL, *tmpval = NULL, *p;
872
873
28.7M
    if (name) {
874
115k
        if ((tmpname = OPENSSL_strdup(name)) == NULL)
875
0
            return NULL;
876
1.14M
        for (p = tmpname; *p; p++)
877
1.03M
            *p = ossl_tolower(*p);
878
115k
    }
879
28.7M
    if (value) {
880
401k
        if ((tmpval = OPENSSL_strdup(value)) == NULL)
881
0
            goto err;
882
3.43M
        for (p = tmpval; *p; p++)
883
3.03M
            *p = ossl_tolower(*p);
884
401k
    }
885
28.7M
    mhdr = OPENSSL_malloc(sizeof(*mhdr));
886
28.7M
    if (mhdr == NULL)
887
0
        goto err;
888
28.7M
    mhdr->name = tmpname;
889
28.7M
    mhdr->value = tmpval;
890
28.7M
    if ((mhdr->params = sk_MIME_PARAM_new(mime_param_cmp)) == NULL)
891
0
        goto err;
892
28.7M
    return mhdr;
893
894
0
err:
895
0
    OPENSSL_free(tmpname);
896
0
    OPENSSL_free(tmpval);
897
0
    OPENSSL_free(mhdr);
898
0
    return NULL;
899
28.7M
}
900
901
static int mime_hdr_addparam(MIME_HEADER *mhdr, const char *name, const char *value)
902
6.49M
{
903
6.49M
    char *tmpname = NULL, *tmpval = NULL, *p;
904
6.49M
    MIME_PARAM *mparam = NULL;
905
906
6.49M
    if (name) {
907
898k
        tmpname = OPENSSL_strdup(name);
908
898k
        if (!tmpname)
909
0
            goto err;
910
4.89M
        for (p = tmpname; *p; p++)
911
3.99M
            *p = ossl_tolower(*p);
912
898k
    }
913
6.49M
    if (value) {
914
249k
        tmpval = OPENSSL_strdup(value);
915
249k
        if (!tmpval)
916
0
            goto err;
917
249k
    }
918
    /* Parameter values are case sensitive so leave as is */
919
6.49M
    mparam = OPENSSL_malloc(sizeof(*mparam));
920
6.49M
    if (mparam == NULL)
921
0
        goto err;
922
6.49M
    mparam->param_name = tmpname;
923
6.49M
    mparam->param_value = tmpval;
924
6.49M
    if (!sk_MIME_PARAM_push(mhdr->params, mparam))
925
0
        goto err;
926
6.49M
    return 1;
927
0
err:
928
0
    OPENSSL_free(tmpname);
929
0
    OPENSSL_free(tmpval);
930
0
    OPENSSL_free(mparam);
931
0
    return 0;
932
6.49M
}
933
934
static int mime_hdr_cmp(const MIME_HEADER *const *a,
935
    const MIME_HEADER *const *b)
936
313M
{
937
313M
    if ((*a)->name == NULL || (*b)->name == NULL)
938
312M
        return ((*a)->name != NULL) - ((*b)->name != NULL);
939
940
752k
    return strcmp((*a)->name, (*b)->name);
941
313M
}
942
943
static int mime_param_cmp(const MIME_PARAM *const *a,
944
    const MIME_PARAM *const *b)
945
96.1M
{
946
96.1M
    if ((*a)->param_name == NULL || (*b)->param_name == NULL)
947
85.7M
        return ((*a)->param_name != NULL) - ((*b)->param_name != NULL);
948
10.4M
    return strcmp((*a)->param_name, (*b)->param_name);
949
96.1M
}
950
951
/* Find a header with a given name (if possible) */
952
953
static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, const char *name)
954
31.0k
{
955
31.0k
    MIME_HEADER htmp;
956
31.0k
    int idx;
957
958
31.0k
    htmp.name = (char *)name;
959
31.0k
    htmp.value = NULL;
960
31.0k
    htmp.params = NULL;
961
962
31.0k
    idx = sk_MIME_HEADER_find(hdrs, &htmp);
963
31.0k
    return sk_MIME_HEADER_value(hdrs, idx);
964
31.0k
}
965
966
static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, const char *name)
967
6.35k
{
968
6.35k
    MIME_PARAM param;
969
6.35k
    int idx;
970
971
6.35k
    param.param_name = (char *)name;
972
6.35k
    param.param_value = NULL;
973
6.35k
    idx = sk_MIME_PARAM_find(hdr->params, &param);
974
6.35k
    return sk_MIME_PARAM_value(hdr->params, idx);
975
6.35k
}
976
977
static void mime_hdr_free(MIME_HEADER *hdr)
978
28.7M
{
979
28.7M
    if (hdr == NULL)
980
0
        return;
981
28.7M
    OPENSSL_free(hdr->name);
982
28.7M
    OPENSSL_free(hdr->value);
983
28.7M
    if (hdr->params)
984
28.7M
        sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
985
28.7M
    OPENSSL_free(hdr);
986
28.7M
}
987
988
static void mime_param_free(MIME_PARAM *param)
989
6.49M
{
990
6.49M
    OPENSSL_free(param->param_name);
991
6.49M
    OPENSSL_free(param->param_value);
992
6.49M
    OPENSSL_free(param);
993
6.49M
}
994
995
/*-
996
 * Check for a multipart boundary. Returns:
997
 * 0 : no boundary
998
 * 1 : part boundary
999
 * 2 : final boundary
1000
 */
1001
static int mime_bound_check(char *line, int linelen, const char *bound, int blen)
1002
23.9M
{
1003
23.9M
    if (linelen == -1)
1004
0
        linelen = strlen(line);
1005
23.9M
    if (blen == -1)
1006
0
        blen = strlen(bound);
1007
    /* Quickly eliminate if line length too short */
1008
23.9M
    if (blen + 2 > linelen)
1009
21.1M
        return 0;
1010
    /* Check for part boundary */
1011
2.82M
    if ((CHECK_AND_SKIP_PREFIX(line, "--")) && strncmp(line, bound, blen) == 0)
1012
2.15M
        return HAS_PREFIX(line + blen, "--") ? 2 : 1;
1013
671k
    return 0;
1014
2.82M
}
1015
1016
static int strip_eol(char *linebuf, int *plen, int flags)
1017
35.9M
{
1018
35.9M
    int len = *plen;
1019
35.9M
    char *p, c;
1020
35.9M
    int is_eol = 0;
1021
1022
35.9M
#ifndef OPENSSL_NO_CMS
1023
35.9M
    if ((flags & CMS_BINARY) != 0) {
1024
0
        if (len <= 0 || linebuf[len - 1] != '\n')
1025
0
            return 0;
1026
0
        if ((flags & SMIME_CRLFEOL) != 0) {
1027
0
            if (len <= 1 || linebuf[len - 2] != '\r')
1028
0
                return 0;
1029
0
            len--;
1030
0
        }
1031
0
        len--;
1032
0
        *plen = len;
1033
0
        return 1;
1034
0
    }
1035
35.9M
#endif
1036
1037
71.9M
    for (p = linebuf + len - 1; len > 0; len--, p--) {
1038
42.9M
        c = *p;
1039
42.9M
        if (c == '\n') {
1040
35.9M
            is_eol = 1;
1041
35.9M
        } else if (is_eol && (flags & SMIME_ASCIICRLF) != 0 && c == 32) {
1042
            /* Strip trailing space on a line; 32 == ASCII for ' ' */
1043
0
            continue;
1044
6.92M
        } else if (c != '\r') {
1045
6.91M
            break;
1046
6.91M
        }
1047
42.9M
    }
1048
35.9M
    *plen = len;
1049
35.9M
    return is_eol;
1050
35.9M
}