Coverage Report

Created: 2023-06-08 06:41

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