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