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