3 * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
6 /* ====================================================================
7 * Copyright (c) 1999-2008 The OpenSSL Project. All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the
21 * 3. All advertising materials mentioning features or use of this
22 * software must display the following acknowledgment:
23 * "This product includes software developed by the OpenSSL Project
24 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
26 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27 * endorse or promote products derived from this software without
28 * prior written permission. For written permission, please contact
29 * licensing@OpenSSL.org.
31 * 5. Products derived from this software may not be called "OpenSSL"
32 * nor may "OpenSSL" appear in their names without prior written
33 * permission of the OpenSSL Project.
35 * 6. Redistributions of any form whatsoever must retain the following
37 * "This product includes software developed by the OpenSSL Project
38 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
40 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
44 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51 * OF THE POSSIBILITY OF SUCH DAMAGE.
52 * ====================================================================
59 #include <openssl/rand.h>
60 #include <openssl/x509.h>
61 #include <openssl/asn1.h>
62 #include <openssl/asn1t.h>
65 * Generalised MIME like utilities for streaming ASN1. Although many have a
66 * PKCS7/CMS like flavour others are more general purpose.
70 * MIME format structures Note that all are translated to lower case apart
71 * from parameter values. Quotes are stripped off
75 char *param_name; /* Param name e.g. "micalg" */
76 char *param_value; /* Param value e.g. "sha1" */
79 DECLARE_STACK_OF(MIME_PARAM)
80 IMPLEMENT_STACK_OF(MIME_PARAM)
83 char *name; /* Name of line e.g. "content-type" */
84 char *value; /* Value of line e.g. "text/plain" */
85 STACK_OF(MIME_PARAM) *params; /* Zero or more parameters */
88 DECLARE_STACK_OF(MIME_HEADER)
89 IMPLEMENT_STACK_OF(MIME_HEADER)
91 static char *strip_ends(char *name);
92 static char *strip_start(char *name);
93 static char *strip_end(char *name);
94 static MIME_HEADER *mime_hdr_new(char *name, char *value);
95 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value);
96 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio);
97 static int mime_hdr_cmp(const MIME_HEADER *const *a,
98 const MIME_HEADER *const *b);
99 static int mime_param_cmp(const MIME_PARAM *const *a,
100 const MIME_PARAM *const *b);
101 static void mime_param_free(MIME_PARAM *param);
102 static int mime_bound_check(char *line, int linelen, char *bound, int blen);
103 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret);
104 static int strip_eol(char *linebuf, int *plen);
105 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name);
106 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name);
107 static void mime_hdr_free(MIME_HEADER *hdr);
109 #define MAX_SMLEN 1024
110 #define mime_debug(x) /* x */
112 /* Base 64 read and write of ASN1 structure */
114 static int B64_write_ASN1(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
119 b64 = BIO_new(BIO_f_base64());
121 ASN1err(ASN1_F_B64_WRITE_ASN1, ERR_R_MALLOC_FAILURE);
125 * prepend the b64 BIO so all data is base64 encoded.
127 out = BIO_push(b64, out);
128 r = ASN1_item_i2d_bio(it, out, val);
129 (void)BIO_flush(out);
135 static ASN1_VALUE *b64_read_asn1(BIO *bio, const ASN1_ITEM *it)
139 if (!(b64 = BIO_new(BIO_f_base64()))) {
140 ASN1err(ASN1_F_B64_READ_ASN1, ERR_R_MALLOC_FAILURE);
143 bio = BIO_push(b64, bio);
144 val = ASN1_item_d2i_bio(it, bio, NULL);
146 ASN1err(ASN1_F_B64_READ_ASN1, ASN1_R_DECODE_ERROR);
147 (void)BIO_flush(bio);
153 /* Generate the MIME "micalg" parameter from RFC3851, RFC4490 */
155 static int asn1_write_micalg(BIO *out, STACK_OF(X509_ALGOR) *mdalgs)
157 int i, have_unknown = 0, write_comma, md_nid;
160 for (i = 0; i < sk_X509_ALGOR_num(mdalgs); i++) {
162 BIO_write(out, ",", 1);
164 md_nid = OBJ_obj2nid(sk_X509_ALGOR_value(mdalgs, i)->algorithm);
167 BIO_puts(out, "sha1");
171 BIO_puts(out, "md5");
175 BIO_puts(out, "sha-256");
179 BIO_puts(out, "sha-384");
183 BIO_puts(out, "sha-512");
190 BIO_puts(out, "unknown");
204 int int_smime_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
205 int ctype_nid, int econt_nid,
206 STACK_OF(X509_ALGOR) *mdalgs,
207 asn1_output_data_fn * data_fn, const ASN1_ITEM *it)
211 const char *mime_prefix, *mime_eol, *cname = "smime.p7m";
212 const char *msg_type = NULL;
213 if (flags & SMIME_OLDMIME)
214 mime_prefix = "application/x-pkcs7-";
216 mime_prefix = "application/pkcs7-";
218 if (flags & SMIME_CRLFEOL)
222 if ((flags & SMIME_DETACHED) && data) {
223 /* We want multipart/signed */
224 /* Generate a random boundary */
225 RAND_pseudo_bytes((unsigned char *)bound, 32);
226 for (i = 0; i < 32; i++) {
235 BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
236 BIO_printf(bio, "Content-Type: multipart/signed;");
237 BIO_printf(bio, " protocol=\"%ssignature\";", mime_prefix);
238 BIO_puts(bio, " micalg=\"");
239 asn1_write_micalg(bio, mdalgs);
240 BIO_printf(bio, "\"; boundary=\"----%s\"%s%s",
241 bound, mime_eol, mime_eol);
242 BIO_printf(bio, "This is an S/MIME signed message%s%s",
244 /* Now write out the first part */
245 BIO_printf(bio, "------%s%s", bound, mime_eol);
246 if (!data_fn(bio, data, val, flags, it))
248 BIO_printf(bio, "%s------%s%s", mime_eol, bound, mime_eol);
250 /* Headers for signature */
252 BIO_printf(bio, "Content-Type: %ssignature;", mime_prefix);
253 BIO_printf(bio, " name=\"smime.p7s\"%s", mime_eol);
254 BIO_printf(bio, "Content-Transfer-Encoding: base64%s", mime_eol);
255 BIO_printf(bio, "Content-Disposition: attachment;");
256 BIO_printf(bio, " filename=\"smime.p7s\"%s%s", mime_eol, mime_eol);
257 B64_write_ASN1(bio, val, NULL, 0, it);
258 BIO_printf(bio, "%s------%s--%s%s", mime_eol, bound,
263 /* Determine smime-type header */
265 if (ctype_nid == NID_pkcs7_enveloped)
266 msg_type = "enveloped-data";
267 else if (ctype_nid == NID_pkcs7_signed) {
268 if (econt_nid == NID_id_smime_ct_receipt)
269 msg_type = "signed-receipt";
270 else if (sk_X509_ALGOR_num(mdalgs) >= 0)
271 msg_type = "signed-data";
273 msg_type = "certs-only";
274 } else if (ctype_nid == NID_id_smime_ct_compressedData) {
275 msg_type = "compressed-data";
279 BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
280 BIO_printf(bio, "Content-Disposition: attachment;");
281 BIO_printf(bio, " filename=\"%s\"%s", cname, mime_eol);
282 BIO_printf(bio, "Content-Type: %smime;", mime_prefix);
284 BIO_printf(bio, " smime-type=%s;", msg_type);
285 BIO_printf(bio, " name=\"%s\"%s", cname, mime_eol);
286 BIO_printf(bio, "Content-Transfer-Encoding: base64%s%s",
288 if (!B64_write_ASN1(bio, val, data, flags, it))
290 BIO_printf(bio, "%s", mime_eol);
296 /* Handle output of ASN1 data */
298 static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
302 const ASN1_AUX *aux = it->funcs;
303 ASN1_STREAM_ARG sarg;
305 if (!(flags & SMIME_DETACHED)) {
306 SMIME_crlf_copy(data, out, flags);
310 if (!aux || !aux->asn1_cb) {
311 ASN1err(ASN1_F_ASN1_OUTPUT_DATA, ASN1_R_STREAMING_NOT_SUPPORTED);
316 sarg.ndef_bio = NULL;
317 sarg.boundary = NULL;
319 /* Let ASN1 code prepend any needed BIOs */
321 if (aux->asn1_cb(ASN1_OP_DETACHED_PRE, &val, it, &sarg) <= 0)
324 /* Copy data across, passing through filter BIOs for processing */
325 SMIME_crlf_copy(data, sarg.ndef_bio, flags);
327 /* Finalize structure */
328 if (aux->asn1_cb(ASN1_OP_DETACHED_POST, &val, it, &sarg) <= 0)
331 /* Now remove any digests prepended to the BIO */
333 while (sarg.ndef_bio != out) {
334 tmpbio = BIO_pop(sarg.ndef_bio);
335 BIO_free(sarg.ndef_bio);
336 sarg.ndef_bio = tmpbio;
346 * SMIME reader: handle multipart/signed and opaque signing. in multipart
347 * case the content is placed in a memory BIO pointed to by "bcont". In
348 * opaque this is set to NULL
351 ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it)
354 STACK_OF(MIME_HEADER) *headers = NULL;
355 STACK_OF(BIO) *parts = NULL;
364 if (!(headers = mime_parse_hdr(bio))) {
365 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_MIME_PARSE_ERROR);
369 if (!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
370 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
371 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_CONTENT_TYPE);
375 /* Handle multipart/signed */
377 if (!strcmp(hdr->value, "multipart/signed")) {
378 /* Split into two parts */
379 prm = mime_param_find(hdr, "boundary");
380 if (!prm || !prm->param_value) {
381 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
382 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_MULTIPART_BOUNDARY);
385 ret = multi_split(bio, prm->param_value, &parts);
386 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
387 if (!ret || (sk_BIO_num(parts) != 2)) {
388 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_MULTIPART_BODY_FAILURE);
389 sk_BIO_pop_free(parts, BIO_vfree);
393 /* Parse the signature piece */
394 asnin = sk_BIO_value(parts, 1);
396 if (!(headers = mime_parse_hdr(asnin))) {
397 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_MIME_SIG_PARSE_ERROR);
398 sk_BIO_pop_free(parts, BIO_vfree);
402 /* Get content type */
404 if (!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
405 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
406 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_SIG_CONTENT_TYPE);
410 if (strcmp(hdr->value, "application/x-pkcs7-signature") &&
411 strcmp(hdr->value, "application/pkcs7-signature")) {
412 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_SIG_INVALID_MIME_TYPE);
413 ERR_add_error_data(2, "type: ", hdr->value);
414 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
415 sk_BIO_pop_free(parts, BIO_vfree);
418 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
420 if (!(val = b64_read_asn1(asnin, it))) {
421 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_ASN1_SIG_PARSE_ERROR);
422 sk_BIO_pop_free(parts, BIO_vfree);
427 *bcont = sk_BIO_value(parts, 0);
431 sk_BIO_pop_free(parts, BIO_vfree);
435 /* OK, if not multipart/signed try opaque signature */
437 if (strcmp(hdr->value, "application/x-pkcs7-mime") &&
438 strcmp(hdr->value, "application/pkcs7-mime")) {
439 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_INVALID_MIME_TYPE);
440 ERR_add_error_data(2, "type: ", hdr->value);
441 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
445 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
447 if (!(val = b64_read_asn1(bio, it))) {
448 ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_ASN1_PARSE_ERROR);
455 /* Copy text from one BIO to another making the output CRLF at EOL */
456 int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
461 char linebuf[MAX_SMLEN];
463 * Buffer output so we don't write one line at a time. This is useful
464 * when streaming as we don't end up with one OCTET STRING per line.
466 bf = BIO_new(BIO_f_buffer());
469 out = BIO_push(bf, out);
470 if (flags & SMIME_BINARY) {
471 while ((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0)
472 BIO_write(out, linebuf, len);
474 if (flags & SMIME_TEXT)
475 BIO_printf(out, "Content-Type: text/plain\r\n\r\n");
476 while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
477 eol = strip_eol(linebuf, &len);
479 BIO_write(out, linebuf, len);
481 BIO_write(out, "\r\n", 2);
484 (void)BIO_flush(out);
490 /* Strip off headers if they are text/plain */
491 int SMIME_text(BIO *in, BIO *out)
495 STACK_OF(MIME_HEADER) *headers;
498 if (!(headers = mime_parse_hdr(in))) {
499 ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_MIME_PARSE_ERROR);
502 if (!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
503 ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_MIME_NO_CONTENT_TYPE);
504 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
507 if (strcmp(hdr->value, "text/plain")) {
508 ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_INVALID_MIME_TYPE);
509 ERR_add_error_data(2, "type: ", hdr->value);
510 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
513 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
514 while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
515 BIO_write(out, iobuf, len);
522 * Split a multipart/XXX message body into component parts: result is
523 * canonical parts in a STACK of bios
526 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret)
528 char linebuf[MAX_SMLEN];
530 int eol = 0, next_eol = 0;
532 STACK_OF(BIO) *parts;
533 char state, part, first;
535 blen = strlen(bound);
539 parts = sk_BIO_new_null();
541 while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
542 state = mime_bound_check(linebuf, len, bound, blen);
546 } else if (state == 2) {
547 sk_BIO_push(parts, bpart);
550 /* Strip CR+LF from linebuf */
551 next_eol = strip_eol(linebuf, &len);
555 sk_BIO_push(parts, bpart);
556 bpart = BIO_new(BIO_s_mem());
557 BIO_set_mem_eof_return(bpart, 0);
559 BIO_write(bpart, "\r\n", 2);
562 BIO_write(bpart, linebuf, len);
568 /* This is the big one: parse MIME header lines up to message body */
570 #define MIME_INVALID 0
576 #define MIME_COMMENT 6
578 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
582 char linebuf[MAX_SMLEN];
583 MIME_HEADER *mhdr = NULL;
584 STACK_OF(MIME_HEADER) *headers;
585 int len, state, save_state = 0;
587 headers = sk_MIME_HEADER_new(mime_hdr_cmp);
590 while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
591 /* If whitespace at line start then continuation line */
592 if (mhdr && isspace((unsigned char)linebuf[0]))
597 /* Go through all characters */
598 for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
602 * State machine to handle MIME headers if this looks horrible
603 * that's because it *is*
611 ntmp = strip_ends(q);
618 mime_debug("Found End Value\n");
620 mhdr = mime_hdr_new(ntmp, strip_ends(q));
621 sk_MIME_HEADER_push(headers, mhdr);
625 } else if (c == '(') {
627 state = MIME_COMMENT;
641 ntmp = strip_ends(q);
650 mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
653 } else if (c == '"') {
654 mime_debug("Found Quote\n");
656 } else if (c == '(') {
658 state = MIME_COMMENT;
664 mime_debug("Found Match Quote\n");
671 if (state == MIME_TYPE) {
672 mhdr = mime_hdr_new(ntmp, strip_ends(q));
673 sk_MIME_HEADER_push(headers, mhdr);
674 } else if (state == MIME_VALUE)
675 mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
677 break; /* Blank line means end of headers */
684 static char *strip_ends(char *name)
686 return strip_end(strip_start(name));
689 /* Strip a parameter of whitespace from start of param */
690 static char *strip_start(char *name)
693 /* Look for first non white space or quote */
694 for (p = name; (c = *p); p++) {
696 /* Next char is start of string if non null */
699 /* Else null string */
702 if (!isspace((unsigned char)c))
708 /* As above but strip from end of string : maybe should handle brackets? */
709 static char *strip_end(char *name)
714 /* Look for first non white space or quote */
715 for (p = name + strlen(name) - 1; p >= name; p--) {
723 if (isspace((unsigned char)c))
731 static MIME_HEADER *mime_hdr_new(char *name, char *value)
734 char *tmpname, *tmpval, *p;
737 if (!(tmpname = BUF_strdup(name)))
739 for (p = tmpname; *p; p++) {
749 if (!(tmpval = BUF_strdup(value)))
751 for (p = tmpval; *p; p++) {
760 mhdr = (MIME_HEADER *)OPENSSL_malloc(sizeof(MIME_HEADER));
763 mhdr->name = tmpname;
764 mhdr->value = tmpval;
765 if (!(mhdr->params = sk_MIME_PARAM_new(mime_param_cmp)))
770 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value)
772 char *tmpname, *tmpval, *p;
776 tmpname = BUF_strdup(name);
779 for (p = tmpname; *p; p++) {
789 tmpval = BUF_strdup(value);
794 /* Parameter values are case sensitive so leave as is */
795 mparam = (MIME_PARAM *)OPENSSL_malloc(sizeof(MIME_PARAM));
798 mparam->param_name = tmpname;
799 mparam->param_value = tmpval;
800 sk_MIME_PARAM_push(mhdr->params, mparam);
804 static int mime_hdr_cmp(const MIME_HEADER *const *a,
805 const MIME_HEADER *const *b)
807 if (!(*a)->name || !(*b)->name)
808 return ! !(*a)->name - ! !(*b)->name;
810 return (strcmp((*a)->name, (*b)->name));
813 static int mime_param_cmp(const MIME_PARAM *const *a,
814 const MIME_PARAM *const *b)
816 if (!(*a)->param_name || !(*b)->param_name)
817 return ! !(*a)->param_name - ! !(*b)->param_name;
818 return (strcmp((*a)->param_name, (*b)->param_name));
821 /* Find a header with a given name (if possible) */
823 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name)
828 idx = sk_MIME_HEADER_find(hdrs, &htmp);
831 return sk_MIME_HEADER_value(hdrs, idx);
834 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name)
838 param.param_name = name;
839 idx = sk_MIME_PARAM_find(hdr->params, ¶m);
842 return sk_MIME_PARAM_value(hdr->params, idx);
845 static void mime_hdr_free(MIME_HEADER *hdr)
848 OPENSSL_free(hdr->name);
850 OPENSSL_free(hdr->value);
852 sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
856 static void mime_param_free(MIME_PARAM *param)
858 if (param->param_name)
859 OPENSSL_free(param->param_name);
860 if (param->param_value)
861 OPENSSL_free(param->param_value);
866 * Check for a multipart boundary. Returns:
871 static int mime_bound_check(char *line, int linelen, char *bound, int blen)
874 linelen = strlen(line);
876 blen = strlen(bound);
877 /* Quickly eliminate if line length too short */
878 if (blen + 2 > linelen)
880 /* Check for part boundary */
881 if (!strncmp(line, "--", 2) && !strncmp(line + 2, bound, blen)) {
882 if (!strncmp(line + blen + 2, "--", 2))
890 static int strip_eol(char *linebuf, int *plen)
895 p = linebuf + len - 1;
896 for (p = linebuf + len - 1; len > 0; len--, p--) {