Coverage Report

Created: 2022-11-30 06:20

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