Debian Codegraph @

debian/rust-vendor/openssl-src/openssl/crypto/asn1/asn_mime.c

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