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