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