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