Coverage Report

Created: 2023-09-25 06:45

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