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