2 /* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
5 /* ====================================================================
6 * Copyright (c) 1999 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 IMPLEMENT_STACK_OF(MIME_PARAM)
80 char *name; /* Name of line e.g. "content-type" */
81 char *value; /* Value of line e.g. "text/plain" */
82 STACK_OF(MIME_PARAM) *params; /* Zero or more parameters */
85 IMPLEMENT_STACK_OF(MIME_HEADER)
87 static int B64_write_PKCS7(BIO *bio, PKCS7 *p7);
88 static PKCS7 *B64_read_PKCS7(BIO *bio);
89 static char * strip_ends(char *name);
90 static char * strip_start(char *name);
91 static char * strip_end(char *name);
92 static MIME_HEADER *mime_hdr_new(char *name, char *value);
93 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value);
94 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio);
95 static int mime_hdr_cmp(MIME_HEADER **a, MIME_HEADER **b);
96 static int mime_param_cmp(MIME_PARAM **a, MIME_PARAM **b);
97 static void mime_param_free(MIME_PARAM *param);
98 static int mime_bound_check(char *line, int linelen, char *bound, int blen);
99 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret);
100 static int iscrlf(char c);
101 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name);
102 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name);
103 static void mime_hdr_free(MIME_HEADER *hdr);
105 #define MAX_SMLEN 1024
106 #define mime_debug(x) /* x */
109 typedef void (*stkfree)();
111 /* Base 64 read and write of PKCS#7 structure */
113 static int B64_write_PKCS7(BIO *bio, PKCS7 *p7)
116 if(!(b64 = BIO_new(BIO_f_base64()))) {
117 PKCS7err(PKCS7_F_B64_WRITE_PKCS7,ERR_R_MALLOC_FAILURE);
120 bio = BIO_push(b64, bio);
121 i2d_PKCS7_bio(bio, p7);
128 static PKCS7 *B64_read_PKCS7(BIO *bio)
132 if(!(b64 = BIO_new(BIO_f_base64()))) {
133 PKCS7err(PKCS7_F_B64_READ_PKCS7,ERR_R_MALLOC_FAILURE);
136 bio = BIO_push(b64, bio);
137 if(!(p7 = d2i_PKCS7_bio(bio, NULL)))
138 PKCS7err(PKCS7_F_B64_READ_PKCS7,PKCS7_R_DECODE_ERROR);
147 int SMIME_write_PKCS7(BIO *bio, PKCS7 *p7, BIO *data, int flags)
149 char linebuf[MAX_SMLEN];
152 if((flags & PKCS7_DETACHED) && data) {
153 /* We want multipart/signed */
154 /* Generate a random boundary */
155 RAND_pseudo_bytes((unsigned char *)bound, 32);
156 for(i = 0; i < 32; i++) {
163 BIO_printf(bio, "MIME-Version: 1.0\n");
164 BIO_printf(bio, "Content-Type: multipart/signed ; ");
165 BIO_printf(bio, "protocol=\"application/x-pkcs7-signature\" ; ");
166 BIO_printf(bio, "micalg=sha1 ; boundary=\"----%s\"\n\n", bound);
167 BIO_printf(bio, "This is an S/MIME signed message\n\n");
168 /* Now write out the first part */
169 BIO_printf(bio, "------%s\r\n", bound);
170 if(flags & PKCS7_TEXT) BIO_printf(bio, "Content-Type: text/plain\n\n");
171 while((i = BIO_read(data, linebuf, MAX_SMLEN)) > 0)
172 BIO_write(bio, linebuf, i);
173 BIO_printf(bio, "\n------%s\n", bound);
175 /* Headers for signature */
177 BIO_printf(bio, "Content-Type: application/x-pkcs7-signature; name=\"smime.p7s\"\n");
178 BIO_printf(bio, "Content-Transfer-Encoding: base64\n");
179 BIO_printf(bio, "Content-Disposition: attachment; filename=\"smime.p7s\"\n\n");
180 B64_write_PKCS7(bio, p7);
181 BIO_printf(bio,"\n------%s--\n\n", bound);
185 BIO_printf(bio, "MIME-Version: 1.0\n");
186 BIO_printf(bio, "Content-Disposition: attachment; filename=\"smime.p7m\"\n");
187 BIO_printf(bio, "Content-Type: application/x-pkcs7-mime; name=\"smime.p7m\"\n");
188 BIO_printf(bio, "Content-Transfer-Encoding: base64\n\n");
189 B64_write_PKCS7(bio, p7);
190 BIO_printf(bio, "\n");
194 /* SMIME reader: handle multipart/signed and opaque signing.
195 * in multipart case the content is placed in a memory BIO
196 * pointed to by "bcont". In opaque this is set to NULL
199 PKCS7 *SMIME_read_PKCS7(BIO *bio, BIO **bcont)
202 STACK_OF(MIME_HEADER) *headers = NULL;
203 STACK_OF(BIO) *parts = NULL;
209 if(bcont) *bcont = NULL;
211 if (!(headers = mime_parse_hdr(bio))) {
212 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_MIME_PARSE_ERROR);
216 if(!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
217 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
218 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_CONTENT_TYPE);
222 /* Handle multipart/signed */
224 if(!strcmp(hdr->value, "multipart/signed")) {
225 /* Split into two parts */
226 prm = mime_param_find(hdr, "boundary");
227 if(!prm || !prm->param_value) {
228 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
229 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_MULTIPART_BOUNDARY);
232 ret = multi_split(bio, prm->param_value, &parts);
233 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
234 if(!ret || (sk_BIO_num(parts) != 2) ) {
235 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_MULTIPART_BODY_FAILURE);
236 sk_BIO_pop_free(parts, BIO_vfree);
240 /* Parse the signature piece */
241 p7in = sk_BIO_value(parts, 1);
243 if (!(headers = mime_parse_hdr(p7in))) {
244 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_MIME_SIG_PARSE_ERROR);
245 sk_BIO_pop_free(parts, BIO_vfree);
249 /* Get content type */
251 if(!(hdr = mime_hdr_find(headers, "content-type")) ||
253 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
254 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_NO_SIG_CONTENT_TYPE);
258 if(strcmp(hdr->value, "application/x-pkcs7-signature") &&
259 strcmp(hdr->value, "application/pkcs7-signature")) {
260 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
261 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_SIG_INVALID_MIME_TYPE);
262 ERR_add_error_data(2, "type: ", hdr->value);
263 sk_BIO_pop_free(parts, BIO_vfree);
266 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
268 if(!(p7 = B64_read_PKCS7(p7in))) {
269 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_PKCS7_SIG_PARSE_ERROR);
270 sk_BIO_pop_free(parts, BIO_vfree);
275 *bcont = sk_BIO_value(parts, 0);
278 } else sk_BIO_pop_free(parts, BIO_vfree);
282 /* OK, if not multipart/signed try opaque signature */
284 if (strcmp (hdr->value, "application/x-pkcs7-mime") &&
285 strcmp (hdr->value, "application/pkcs7-mime")) {
286 PKCS7err(PKCS7_F_SMIME_READ_PKCS7,PKCS7_R_INVALID_MIME_TYPE);
287 ERR_add_error_data(2, "type: ", hdr->value);
288 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
292 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
294 if(!(p7 = B64_read_PKCS7(bio))) {
295 PKCS7err(PKCS7_F_SMIME_READ_PKCS7, PKCS7_R_PKCS7_PARSE_ERROR);
302 /* Copy text from one BIO to another making the output CRLF at EOL */
303 int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
307 char linebuf[MAX_SMLEN];
308 if(flags & PKCS7_BINARY) {
309 while((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0)
310 BIO_write(out, linebuf, len);
313 if(flags & PKCS7_TEXT) BIO_printf(out, "Content-Type: text/plain\r\n\r\n");
314 while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
316 while(iscrlf(linebuf[len - 1])) {
320 BIO_write(out, linebuf, len);
321 if(eol) BIO_write(out, "\r\n", 2);
326 /* Strip off headers if they are text/plain */
327 int SMIME_text(BIO *in, BIO *out)
331 STACK_OF(MIME_HEADER) *headers;
334 if (!(headers = mime_parse_hdr(in))) {
335 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_MIME_PARSE_ERROR);
338 if(!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
339 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_MIME_NO_CONTENT_TYPE);
340 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
343 if (strcmp (hdr->value, "text/plain")) {
344 PKCS7err(PKCS7_F_SMIME_TEXT,PKCS7_R_INVALID_MIME_TYPE);
345 ERR_add_error_data(2, "type: ", hdr->value);
346 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
349 sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
350 while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
351 BIO_write(out, iobuf, len);
355 /* Split a multipart/XXX message body into component parts: result is
356 * canonical parts in a STACK of bios
359 static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret)
361 char linebuf[MAX_SMLEN];
364 STACK_OF(BIO) *parts;
365 char state, part, first;
367 blen = strlen(bound);
371 parts = sk_BIO_new(NULL);
373 while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
374 state = mime_bound_check(linebuf, len, bound, blen);
378 } else if(state == 2) {
379 sk_BIO_push(parts, bpart);
384 if(bpart) sk_BIO_push(parts, bpart);
385 bpart = BIO_new(BIO_s_mem());
387 } else BIO_write(bpart, "\r\n", 2);
388 /* Strip CR+LF from linebuf */
389 while(iscrlf(linebuf[len - 1])) len--;
390 BIO_write(bpart, linebuf, len);
396 static int iscrlf(char c)
398 if(c == '\r' || c == '\n') return 1;
402 /* This is the big one: parse MIME header lines up to message body */
404 #define MIME_INVALID 0
410 #define MIME_COMMENT 6
413 static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
417 char linebuf[MAX_SMLEN];
418 MIME_HEADER *mhdr = NULL;
419 STACK_OF(MIME_HEADER) *headers;
420 int len, state, save_state = 0;
422 headers = sk_MIME_HEADER_new(mime_hdr_cmp);
423 while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
424 /* If whitespace at line start then continuation line */
425 if(mhdr && isspace((unsigned char)linebuf[0])) state = MIME_NAME;
426 else state = MIME_START;
428 /* Go through all characters */
429 for(p = linebuf, q = linebuf; (c = *p) && (c!='\r') && (c!='\n'); p++) {
431 /* State machine to handle MIME headers
432 * if this looks horrible that's because it *is*
440 ntmp = strip_ends(q);
447 mime_debug("Found End Value\n");
449 mhdr = mime_hdr_new(ntmp, strip_ends(q));
450 sk_MIME_HEADER_push(headers, mhdr);
454 } else if(c == '(') {
456 state = MIME_COMMENT;
470 ntmp = strip_ends(q);
479 mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
482 } else if (c == '"') {
483 mime_debug("Found Quote\n");
485 } else if(c == '(') {
487 state = MIME_COMMENT;
493 mime_debug("Found Match Quote\n");
500 if(state == MIME_TYPE) {
501 mhdr = mime_hdr_new(ntmp, strip_ends(q));
502 sk_MIME_HEADER_push(headers, mhdr);
503 } else if(state == MIME_VALUE)
504 mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
505 if(p == linebuf) break; /* Blank line means end of headers */
512 static char *strip_ends(char *name)
514 return strip_end(strip_start(name));
517 /* Strip a parameter of whitespace from start of param */
518 static char *strip_start(char *name)
521 /* Look for first non white space or quote */
522 for(p = name; (c = *p) ;p++) {
524 /* Next char is start of string if non null */
525 if(p[1]) return p + 1;
526 /* Else null string */
529 if(!isspace((unsigned char)c)) return p;
534 /* As above but strip from end of string : maybe should handle brackets? */
535 static char *strip_end(char *name)
538 if(!name) return NULL;
539 /* Look for first non white space or quote */
540 for(p = name + strlen(name) - 1; p >= name ;p--) {
543 if(p - 1 == name) return NULL;
547 if(isspace((unsigned char)c)) *p = 0;
553 static MIME_HEADER *mime_hdr_new(char *name, char *value)
556 char *tmpname, *tmpval, *p;
559 if(!(tmpname = BUF_strdup(name))) return NULL;
560 for(p = tmpname ; *p; p++) {
567 } else tmpname = NULL;
569 if(!(tmpval = BUF_strdup(value))) return NULL;
570 for(p = tmpval ; *p; p++) {
577 } else tmpval = NULL;
578 mhdr = (MIME_HEADER *) Malloc(sizeof(MIME_HEADER));
579 if(!mhdr) return NULL;
580 mhdr->name = tmpname;
581 mhdr->value = tmpval;
582 if(!(mhdr->params = sk_MIME_PARAM_new(mime_param_cmp))) return NULL;
586 static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value)
588 char *tmpname, *tmpval, *p;
592 tmpname = BUF_strdup(name);
593 if(!tmpname) return 0;
594 for(p = tmpname ; *p; p++) {
601 } else tmpname = NULL;
603 tmpval = BUF_strdup(value);
604 if(!tmpval) return 0;
605 } else tmpval = NULL;
606 /* Parameter values are case sensitive so leave as is */
607 mparam = (MIME_PARAM *) Malloc(sizeof(MIME_PARAM));
608 if(!mparam) return 0;
609 mparam->param_name = tmpname;
610 mparam->param_value = tmpval;
611 sk_MIME_PARAM_push(mhdr->params, mparam);
615 static int mime_hdr_cmp(MIME_HEADER **a, MIME_HEADER **b)
617 return(strcmp((*a)->name, (*b)->name));
620 static int mime_param_cmp(MIME_PARAM **a, MIME_PARAM **b)
622 return(strcmp((*a)->param_name, (*b)->param_name));
625 /* Find a header with a given name (if possible) */
627 static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name)
632 idx = sk_MIME_HEADER_find(hdrs, &htmp);
633 if(idx < 0) return NULL;
634 return sk_MIME_HEADER_value(hdrs, idx);
637 static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name)
641 param.param_name = name;
642 idx = sk_MIME_PARAM_find(hdr->params, ¶m);
643 if(idx < 0) return NULL;
644 return sk_MIME_PARAM_value(hdr->params, idx);
647 static void mime_hdr_free(MIME_HEADER *hdr)
649 if(hdr->name) Free(hdr->name);
650 if(hdr->value) Free(hdr->value);
651 if(hdr->params) sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
655 static void mime_param_free(MIME_PARAM *param)
657 if(param->param_name) Free(param->param_name);
658 if(param->param_value) Free(param->param_value);
662 /* Check for a multipart boundary. Returns:
667 static int mime_bound_check(char *line, int linelen, char *bound, int blen)
669 if(linelen == -1) linelen = strlen(line);
670 if(blen == -1) blen = strlen(bound);
671 /* Quickly eliminate if line length too short */
672 if(blen + 2 > linelen) return 0;
673 /* Check for part boundary */
674 if(!strncmp(line, "--", 2) && !strncmp(line + 2, bound, blen)) {
675 if(!strncmp(line + blen + 2, "--", 2)) return 2;