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