Coverage Report

Created: 2025-08-28 07:07

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