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