Coverage Report

Created: 2026-09-12 06:55

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