2 /* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
5 /* ====================================================================
6 * Copyright (c) 1999-2003 The OpenSSL Project. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
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
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/)"
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.
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.
34 * 6. Redistributions of any form whatsoever must retain the following
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
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 * ====================================================================
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
62 #include <openssl/rand.h>
63 #include <openssl/x509.h>
65 /* MIME and related routines */
67 /* MIME format structures
68 * Note that all are translated to lower case apart from
69 * parameter values. Quotes are stripped off
73 char *param_name; /* Param name e.g. "micalg" */
74 char *param_value; /* Param value e.g. "sha1" */
77 DECLARE_STACK_OF(MIME_PARAM)
78 IMPLEMENT_STACK_OF(MIME_PARAM)
81 char *name; /* Name of line e.g. "content-type" */
82 char *value; /* Value of line e.g. "text/plain" */
83 STACK_OF(MIME_PARAM) *params; /* Zero or more parameters */
86 DECLARE_STACK_OF(MIME_HEADER)
87 IMPLEMENT_STACK_OF(MIME_HEADER)
89 static int pkcs7_output_data(BIO *bio, BIO *data, PKCS7 *p7, int flags);
90 static int B64_write_PKCS7(BIO *bio, PKCS7 *p7);
91 static PKCS7 *B64_read_PKCS7(BIO *bio);
92 static char * strip_ends(char *name);
93 static char * strip_start(char *name);
94 static char * strip_end(char *name);
95 static MIME_HEADER *mime_hdr_new(char *name, char *value);
96 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value);
97 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio);
98 static int mime_hdr_cmp(const MIME_HEADER * const *a,
99 const MIME_HEADER * const *b);
100 static int mime_param_cmp(const MIME_PARAM * const *a,
101 const MIME_PARAM * const *b);
102 static void mime_param_free(MIME_PARAM *param);
103 static int mime_bound_check(char *line, int linelen, char *bound, int blen);
104 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret);
105 static int iscrlf(char c);
106 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name);
107 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name);
108 static void mime_hdr_free(MIME_HEADER *hdr);
110 #define MAX_SMLEN 1024
111 #define mime_debug(x) /* x */
114 typedef void (*stkfree)();
116 /* Base 64 read and write of PKCS#7 structure */
118 static int B64_write_PKCS7(BIO *bio, PKCS7 *p7)
121 if(!(b64 = BIO_new(BIO_f_base64()))) {
122 PKCS7err(PKCS7_F_B64_WRITE_PKCS7,ERR_R_MALLOC_FAILURE);
125 bio = BIO_push(b64, bio);
126 i2d_PKCS7_bio(bio, p7);
133 static PKCS7 *B64_read_PKCS7(BIO *bio)
137 if(!(b64 = BIO_new(BIO_f_base64()))) {
138 PKCS7err(PKCS7_F_B64_READ_PKCS7,ERR_R_MALLOC_FAILURE);
141 bio = BIO_push(b64, bio);
142 if(!(p7 = d2i_PKCS7_bio(bio, NULL)))
143 PKCS7err(PKCS7_F_B64_READ_PKCS7,PKCS7_R_DECODE_ERROR);
152 int SMIME_write_PKCS7(BIO *bio, PKCS7 *p7, BIO *data, int flags)
156 if((flags & PKCS7_DETACHED) && data) {
157 /* We want multipart/signed */
158 /* Generate a random boundary */
159 RAND_pseudo_bytes((unsigned char *)bound, 32);
160 for(i = 0; i < 32; i++) {
167 BIO_printf(bio, "MIME-Version: 1.0\n");
168 BIO_printf(bio, "Content-Type: multipart/signed;");
169 BIO_printf(bio, " protocol=\"application/x-pkcs7-signature\";");
170 BIO_printf(bio, " micalg=sha1; boundary=\"----%s\"\n\n", bound);
171 BIO_printf(bio, "This is an S/MIME signed message\n\n");
172 /* Now write out the first part */
173 BIO_printf(bio, "------%s\r\n", bound);
175 pkcs7_output_data(bio, data, p7, flags);
177 BIO_printf(bio, "\n------%s\n", bound);
179 /* Headers for signature */
181 BIO_printf(bio, "Content-Type: application/x-pkcs7-signature; name=\"smime.p7s\"\n");
182 BIO_printf(bio, "Content-Transfer-Encoding: base64\n");
183 BIO_printf(bio, "Content-Disposition: attachment; filename=\"smime.p7s\"\n\n");
184 B64_write_PKCS7(bio, p7);
185 BIO_printf(bio,"\n------%s--\n\n", bound);
189 BIO_printf(bio, "MIME-Version: 1.0\n");
190 BIO_printf(bio, "Content-Disposition: attachment; filename=\"smime.p7m\"\n");
191 BIO_printf(bio, "Content-Type: application/x-pkcs7-mime; name=\"smime.p7m\"\n");
192 BIO_printf(bio, "Content-Transfer-Encoding: base64\n\n");
193 B64_write_PKCS7(bio, p7);
194 BIO_printf(bio, "\n");
198 /* Handle output of PKCS#7 data */
201 static int pkcs7_output_data(BIO *out, BIO *data, PKCS7 *p7, int flags)
205 if (!(flags & PKCS7_STREAM))
207 SMIME_crlf_copy(data, out, flags);
211 /* Partial sign operation */
213 /* Initialize sign operation */
214 p7bio = PKCS7_dataInit(p7, out);
216 /* Copy data across, computing digests etc */
217 SMIME_crlf_copy(data, p7bio, flags);
219 /* Must be detached */
220 PKCS7_set_detached(p7, 1);
222 /* Finalize signatures */
223 PKCS7_dataFinal(p7, p7bio);
225 /* Now remove any digests from output BIO */
229 tmpbio = BIO_pop(p7bio);
239 /* SMIME reader: handle multipart/signed and opaque signing.
240 * in multipart case the content is placed in a memory BIO
241 * pointed to by "bcont". In opaque this is set to NULL
244 PKCS7 *SMIME_read_PKCS7(BIO *bio, BIO **bcont)
247 STACK_OF(MIME_HEADER) *headers = NULL;
248 STACK_OF(BIO) *parts = NULL;
254 if(bcont) *bcont = NULL;
256 if (!(headers = mime_parse_hdr(bio))) {
257 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_MIME_PARSE_ERROR);
261 if(!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
262 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
263 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_CONTENT_TYPE);
267 /* Handle multipart/signed */
269 if(!strcmp(hdr->value, "multipart/signed")) {
270 /* Split into two parts */
271 prm = mime_param_find(hdr, "boundary");
272 if(!prm || !prm->param_value) {
273 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
274 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_MULTIPART_BOUNDARY);
277 ret = multi_split(bio, prm->param_value, &parts);
278 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
279 if(!ret || (sk_BIO_num(parts) != 2) ) {
280 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_MULTIPART_BODY_FAILURE);
281 sk_BIO_pop_free(parts, BIO_vfree);
285 /* Parse the signature piece */
286 p7in = sk_BIO_value(parts, 1);
288 if (!(headers = mime_parse_hdr(p7in))) {
289 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_MIME_SIG_PARSE_ERROR);
290 sk_BIO_pop_free(parts, BIO_vfree);
294 /* Get content type */
296 if(!(hdr = mime_hdr_find(headers, "content-type")) ||
298 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
299 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_SIG_CONTENT_TYPE);
303 if(strcmp(hdr->value, "application/x-pkcs7-signature") &&
304 strcmp(hdr->value, "application/pkcs7-signature")) {
305 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
306 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_SIG_INVALID_MIME_TYPE);
307 ERR_add_error_data(2, "type: ", hdr->value);
308 sk_BIO_pop_free(parts, BIO_vfree);
311 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
313 if(!(p7 = B64_read_PKCS7(p7in))) {
314 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_PKCS7_SIG_PARSE_ERROR);
315 sk_BIO_pop_free(parts, BIO_vfree);
320 *bcont = sk_BIO_value(parts, 0);
323 } else sk_BIO_pop_free(parts, BIO_vfree);
327 /* OK, if not multipart/signed try opaque signature */
329 if (strcmp (hdr->value, "application/x-pkcs7-mime") &&
330 strcmp (hdr->value, "application/pkcs7-mime")) {
331 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_INVALID_MIME_TYPE);
332 ERR_add_error_data(2, "type: ", hdr->value);
333 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
337 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
339 if(!(p7 = B64_read_PKCS7(bio))) {
340 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_PKCS7_PARSE_ERROR);
347 /* Copy text from one BIO to another making the output CRLF at EOL */
348 int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
352 char linebuf[MAX_SMLEN];
353 if(flags & PKCS7_BINARY) {
354 while((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0)
355 BIO_write(out, linebuf, len);
358 if(flags & PKCS7_TEXT)
359 BIO_printf(out, "Content-Type: text/plain\r\n\r\n");
360 while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
362 while(iscrlf(linebuf[len - 1])) {
366 BIO_write(out, linebuf, len);
367 if(eol) BIO_write(out, "\r\n", 2);
372 /* Strip off headers if they are text/plain */
373 int SMIME_text(BIO *in, BIO *out)
377 STACK_OF(MIME_HEADER) *headers;
380 if (!(headers = mime_parse_hdr(in))) {
381 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_MIME_PARSE_ERROR);
384 if(!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
385 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_MIME_NO_CONTENT_TYPE);
386 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
389 if (strcmp (hdr->value, "text/plain")) {
390 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_INVALID_MIME_TYPE);
391 ERR_add_error_data(2, "type: ", hdr->value);
392 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
395 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
396 while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
397 BIO_write(out, iobuf, len);
401 /* Split a multipart/XXX message body into component parts: result is
402 * canonical parts in a STACK of bios
405 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret)
407 char linebuf[MAX_SMLEN];
410 STACK_OF(BIO) *parts;
411 char state, part, first;
413 blen = strlen(bound);
417 parts = sk_BIO_new_null();
419 while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
420 state = mime_bound_check(linebuf, len, bound, blen);
424 } else if(state == 2) {
425 sk_BIO_push(parts, bpart);
430 if(bpart) sk_BIO_push(parts, bpart);
431 bpart = BIO_new(BIO_s_mem());
433 } else BIO_write(bpart, "\r\n", 2);
434 /* Strip CR+LF from linebuf */
435 while(iscrlf(linebuf[len - 1])) len--;
436 BIO_write(bpart, linebuf, len);
442 static int iscrlf(char c)
444 if(c == '\r' || c == '\n') return 1;
448 /* This is the big one: parse MIME header lines up to message body */
450 #define MIME_INVALID 0
456 #define MIME_COMMENT 6
459 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
463 char linebuf[MAX_SMLEN];
464 MIME_HEADER *mhdr = NULL;
465 STACK_OF(MIME_HEADER) *headers;
466 int len, state, save_state = 0;
468 headers = sk_MIME_HEADER_new(mime_hdr_cmp);
469 while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
470 /* If whitespace at line start then continuation line */
471 if(mhdr && isspace((unsigned char)linebuf[0])) state = MIME_NAME;
472 else state = MIME_START;
474 /* Go through all characters */
475 for(p = linebuf, q = linebuf; (c = *p) && (c!='\r') && (c!='\n'); p++) {
477 /* State machine to handle MIME headers
478 * if this looks horrible that's because it *is*
486 ntmp = strip_ends(q);
493 mime_debug("Found End Value\n");
495 mhdr = mime_hdr_new(ntmp, strip_ends(q));
496 sk_MIME_HEADER_push(headers, mhdr);
500 } else if(c == '(') {
502 state = MIME_COMMENT;
516 ntmp = strip_ends(q);
525 mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
528 } else if (c == '"') {
529 mime_debug("Found Quote\n");
531 } else if(c == '(') {
533 state = MIME_COMMENT;
539 mime_debug("Found Match Quote\n");
546 if(state == MIME_TYPE) {
547 mhdr = mime_hdr_new(ntmp, strip_ends(q));
548 sk_MIME_HEADER_push(headers, mhdr);
549 } else if(state == MIME_VALUE)
550 mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
551 if(p == linebuf) break; /* Blank line means end of headers */
558 static char *strip_ends(char *name)
560 return strip_end(strip_start(name));
563 /* Strip a parameter of whitespace from start of param */
564 static char *strip_start(char *name)
567 /* Look for first non white space or quote */
568 for(p = name; (c = *p) ;p++) {
570 /* Next char is start of string if non null */
571 if(p[1]) return p + 1;
572 /* Else null string */
575 if(!isspace((unsigned char)c)) return p;
580 /* As above but strip from end of string : maybe should handle brackets? */
581 static char *strip_end(char *name)
584 if(!name) return NULL;
585 /* Look for first non white space or quote */
586 for(p = name + strlen(name) - 1; p >= name ;p--) {
589 if(p - 1 == name) return NULL;
593 if(isspace((unsigned char)c)) *p = 0;
599 static MIME_HEADER *mime_hdr_new(char *name, char *value)
602 char *tmpname, *tmpval, *p;
605 if(!(tmpname = BUF_strdup(name))) return NULL;
606 for(p = tmpname ; *p; p++) {
613 } else tmpname = NULL;
615 if(!(tmpval = BUF_strdup(value))) return NULL;
616 for(p = tmpval ; *p; p++) {
623 } else tmpval = NULL;
624 mhdr = (MIME_HEADER *) OPENSSL_malloc(sizeof(MIME_HEADER));
625 if(!mhdr) return NULL;
626 mhdr->name = tmpname;
627 mhdr->value = tmpval;
628 if(!(mhdr->params = sk_MIME_PARAM_new(mime_param_cmp))) return NULL;
632 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value)
634 char *tmpname, *tmpval, *p;
638 tmpname = BUF_strdup(name);
639 if(!tmpname) return 0;
640 for(p = tmpname ; *p; p++) {
647 } else tmpname = NULL;
649 tmpval = BUF_strdup(value);
650 if(!tmpval) return 0;
651 } else tmpval = NULL;
652 /* Parameter values are case sensitive so leave as is */
653 mparam = (MIME_PARAM *) OPENSSL_malloc(sizeof(MIME_PARAM));
654 if(!mparam) return 0;
655 mparam->param_name = tmpname;
656 mparam->param_value = tmpval;
657 sk_MIME_PARAM_push(mhdr->params, mparam);
661 static int mime_hdr_cmp(const MIME_HEADER * const *a,
662 const MIME_HEADER * const *b)
664 return(strcmp((*a)->name, (*b)->name));
667 static int mime_param_cmp(const MIME_PARAM * const *a,
668 const MIME_PARAM * const *b)
670 return(strcmp((*a)->param_name, (*b)->param_name));
673 /* Find a header with a given name (if possible) */
675 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name)
680 idx = sk_MIME_HEADER_find(hdrs, &htmp);
681 if(idx < 0) return NULL;
682 return sk_MIME_HEADER_value(hdrs, idx);
685 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name)
689 param.param_name = name;
690 idx = sk_MIME_PARAM_find(hdr->params, ¶m);
691 if(idx < 0) return NULL;
692 return sk_MIME_PARAM_value(hdr->params, idx);
695 static void mime_hdr_free(MIME_HEADER *hdr)
697 if(hdr->name) OPENSSL_free(hdr->name);
698 if(hdr->value) OPENSSL_free(hdr->value);
699 if(hdr->params) sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
703 static void mime_param_free(MIME_PARAM *param)
705 if(param->param_name) OPENSSL_free(param->param_name);
706 if(param->param_value) OPENSSL_free(param->param_value);
710 /* Check for a multipart boundary. Returns:
715 static int mime_bound_check(char *line, int linelen, char *bound, int blen)
717 if(linelen == -1) linelen = strlen(line);
718 if(blen == -1) blen = strlen(bound);
719 /* Quickly eliminate if line length too short */
720 if(blen + 2 > linelen) return 0;
721 /* Check for part boundary */
722 if(!strncmp(line, "--", 2) && !strncmp(line + 2, bound, blen)) {
723 if(!strncmp(line + blen + 2, "--", 2)) return 2;