asn_mime.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. /* asn_mime.c */
  2. /*
  3. * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
  4. * project.
  5. */
  6. /* ====================================================================
  7. * Copyright (c) 1999-2008 The OpenSSL Project. All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. *
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. *
  16. * 2. Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in
  18. * the documentation and/or other materials provided with the
  19. * distribution.
  20. *
  21. * 3. All advertising materials mentioning features or use of this
  22. * software must display the following acknowledgment:
  23. * "This product includes software developed by the OpenSSL Project
  24. * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  25. *
  26. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  27. * endorse or promote products derived from this software without
  28. * prior written permission. For written permission, please contact
  29. * licensing@OpenSSL.org.
  30. *
  31. * 5. Products derived from this software may not be called "OpenSSL"
  32. * nor may "OpenSSL" appear in their names without prior written
  33. * permission of the OpenSSL Project.
  34. *
  35. * 6. Redistributions of any form whatsoever must retain the following
  36. * acknowledgment:
  37. * "This product includes software developed by the OpenSSL Project
  38. * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  41. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  43. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  44. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  45. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  46. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  47. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  48. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  49. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  50. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  51. * OF THE POSSIBILITY OF SUCH DAMAGE.
  52. * ====================================================================
  53. *
  54. */
  55. #include <stdio.h>
  56. #include <ctype.h>
  57. #include "cryptlib.h"
  58. #include <openssl/rand.h>
  59. #include <openssl/x509.h>
  60. #include <openssl/asn1.h>
  61. #include <openssl/asn1t.h>
  62. #include "asn1_locl.h"
  63. /*
  64. * Generalised MIME like utilities for streaming ASN1. Although many have a
  65. * PKCS7/CMS like flavour others are more general purpose.
  66. */
  67. /*
  68. * MIME format structures Note that all are translated to lower case apart
  69. * from parameter values. Quotes are stripped off
  70. */
  71. typedef struct {
  72. char *param_name; /* Param name e.g. "micalg" */
  73. char *param_value; /* Param value e.g. "sha1" */
  74. } MIME_PARAM;
  75. DECLARE_STACK_OF(MIME_PARAM)
  76. IMPLEMENT_STACK_OF(MIME_PARAM)
  77. typedef struct {
  78. char *name; /* Name of line e.g. "content-type" */
  79. char *value; /* Value of line e.g. "text/plain" */
  80. STACK_OF(MIME_PARAM) *params; /* Zero or more parameters */
  81. } MIME_HEADER;
  82. DECLARE_STACK_OF(MIME_HEADER)
  83. IMPLEMENT_STACK_OF(MIME_HEADER)
  84. static int asn1_output_data(BIO *out, BIO *data, ASN1_VALUE *val, int flags,
  85. const ASN1_ITEM *it);
  86. static char *strip_ends(char *name);
  87. static char *strip_start(char *name);
  88. static char *strip_end(char *name);
  89. static MIME_HEADER *mime_hdr_new(char *name, char *value);
  90. static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value);
  91. static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio);
  92. static int mime_hdr_cmp(const MIME_HEADER *const *a,
  93. const MIME_HEADER *const *b);
  94. static int mime_param_cmp(const MIME_PARAM *const *a,
  95. const MIME_PARAM *const *b);
  96. static void mime_param_free(MIME_PARAM *param);
  97. static int mime_bound_check(char *line, int linelen, char *bound, int blen);
  98. static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret);
  99. static int strip_eol(char *linebuf, int *plen);
  100. static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name);
  101. static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name);
  102. static void mime_hdr_free(MIME_HEADER *hdr);
  103. #define MAX_SMLEN 1024
  104. #define mime_debug(x) /* x */
  105. /* Output an ASN1 structure in BER format streaming if necessary */
  106. int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
  107. const ASN1_ITEM *it)
  108. {
  109. /* If streaming create stream BIO and copy all content through it */
  110. if (flags & SMIME_STREAM) {
  111. BIO *bio, *tbio;
  112. bio = BIO_new_NDEF(out, val, it);
  113. if (!bio) {
  114. ASN1err(ASN1_F_I2D_ASN1_BIO_STREAM, ERR_R_MALLOC_FAILURE);
  115. return 0;
  116. }
  117. SMIME_crlf_copy(in, bio, flags);
  118. (void)BIO_flush(bio);
  119. /* Free up successive BIOs until we hit the old output BIO */
  120. do {
  121. tbio = BIO_pop(bio);
  122. BIO_free(bio);
  123. bio = tbio;
  124. } while (bio != out);
  125. }
  126. /*
  127. * else just write out ASN1 structure which will have all content stored
  128. * internally
  129. */
  130. else
  131. ASN1_item_i2d_bio(it, out, val);
  132. return 1;
  133. }
  134. /* Base 64 read and write of ASN1 structure */
  135. static int B64_write_ASN1(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
  136. const ASN1_ITEM *it)
  137. {
  138. BIO *b64;
  139. int r;
  140. b64 = BIO_new(BIO_f_base64());
  141. if (!b64) {
  142. ASN1err(ASN1_F_B64_WRITE_ASN1, ERR_R_MALLOC_FAILURE);
  143. return 0;
  144. }
  145. /*
  146. * prepend the b64 BIO so all data is base64 encoded.
  147. */
  148. out = BIO_push(b64, out);
  149. r = i2d_ASN1_bio_stream(out, val, in, flags, it);
  150. (void)BIO_flush(out);
  151. BIO_pop(out);
  152. BIO_free(b64);
  153. return r;
  154. }
  155. /* Streaming ASN1 PEM write */
  156. int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
  157. const char *hdr, const ASN1_ITEM *it)
  158. {
  159. int r;
  160. BIO_printf(out, "-----BEGIN %s-----\n", hdr);
  161. r = B64_write_ASN1(out, val, in, flags, it);
  162. BIO_printf(out, "-----END %s-----\n", hdr);
  163. return r;
  164. }
  165. static ASN1_VALUE *b64_read_asn1(BIO *bio, const ASN1_ITEM *it)
  166. {
  167. BIO *b64;
  168. ASN1_VALUE *val;
  169. if (!(b64 = BIO_new(BIO_f_base64()))) {
  170. ASN1err(ASN1_F_B64_READ_ASN1, ERR_R_MALLOC_FAILURE);
  171. return 0;
  172. }
  173. bio = BIO_push(b64, bio);
  174. val = ASN1_item_d2i_bio(it, bio, NULL);
  175. if (!val)
  176. ASN1err(ASN1_F_B64_READ_ASN1, ASN1_R_DECODE_ERROR);
  177. (void)BIO_flush(bio);
  178. bio = BIO_pop(bio);
  179. BIO_free(b64);
  180. return val;
  181. }
  182. /* Generate the MIME "micalg" parameter from RFC3851, RFC4490 */
  183. static int asn1_write_micalg(BIO *out, STACK_OF(X509_ALGOR) *mdalgs)
  184. {
  185. const EVP_MD *md;
  186. int i, have_unknown = 0, write_comma, ret = 0, md_nid;
  187. have_unknown = 0;
  188. write_comma = 0;
  189. for (i = 0; i < sk_X509_ALGOR_num(mdalgs); i++) {
  190. if (write_comma)
  191. BIO_write(out, ",", 1);
  192. write_comma = 1;
  193. md_nid = OBJ_obj2nid(sk_X509_ALGOR_value(mdalgs, i)->algorithm);
  194. md = EVP_get_digestbynid(md_nid);
  195. if (md && md->md_ctrl) {
  196. int rv;
  197. char *micstr;
  198. rv = md->md_ctrl(NULL, EVP_MD_CTRL_MICALG, 0, &micstr);
  199. if (rv > 0) {
  200. BIO_puts(out, micstr);
  201. OPENSSL_free(micstr);
  202. continue;
  203. }
  204. if (rv != -2)
  205. goto err;
  206. }
  207. switch (md_nid) {
  208. case NID_sha1:
  209. BIO_puts(out, "sha1");
  210. break;
  211. case NID_md5:
  212. BIO_puts(out, "md5");
  213. break;
  214. case NID_sha256:
  215. BIO_puts(out, "sha-256");
  216. break;
  217. case NID_sha384:
  218. BIO_puts(out, "sha-384");
  219. break;
  220. case NID_sha512:
  221. BIO_puts(out, "sha-512");
  222. break;
  223. case NID_id_GostR3411_94:
  224. BIO_puts(out, "gostr3411-94");
  225. goto err;
  226. break;
  227. default:
  228. if (have_unknown)
  229. write_comma = 0;
  230. else {
  231. BIO_puts(out, "unknown");
  232. have_unknown = 1;
  233. }
  234. break;
  235. }
  236. }
  237. ret = 1;
  238. err:
  239. return ret;
  240. }
  241. /* SMIME sender */
  242. int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
  243. int ctype_nid, int econt_nid,
  244. STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it)
  245. {
  246. char bound[33], c;
  247. int i;
  248. const char *mime_prefix, *mime_eol, *cname = "smime.p7m";
  249. const char *msg_type = NULL;
  250. if (flags & SMIME_OLDMIME)
  251. mime_prefix = "application/x-pkcs7-";
  252. else
  253. mime_prefix = "application/pkcs7-";
  254. if (flags & SMIME_CRLFEOL)
  255. mime_eol = "\r\n";
  256. else
  257. mime_eol = "\n";
  258. if ((flags & SMIME_DETACHED) && data) {
  259. /* We want multipart/signed */
  260. /* Generate a random boundary */
  261. if (RAND_bytes((unsigned char *)bound, 32) <= 0)
  262. return 0;
  263. for (i = 0; i < 32; i++) {
  264. c = bound[i] & 0xf;
  265. if (c < 10)
  266. c += '0';
  267. else
  268. c += 'A' - 10;
  269. bound[i] = c;
  270. }
  271. bound[32] = 0;
  272. BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
  273. BIO_printf(bio, "Content-Type: multipart/signed;");
  274. BIO_printf(bio, " protocol=\"%ssignature\";", mime_prefix);
  275. BIO_puts(bio, " micalg=\"");
  276. asn1_write_micalg(bio, mdalgs);
  277. BIO_printf(bio, "\"; boundary=\"----%s\"%s%s",
  278. bound, mime_eol, mime_eol);
  279. BIO_printf(bio, "This is an S/MIME signed message%s%s",
  280. mime_eol, mime_eol);
  281. /* Now write out the first part */
  282. BIO_printf(bio, "------%s%s", bound, mime_eol);
  283. if (!asn1_output_data(bio, data, val, flags, it))
  284. return 0;
  285. BIO_printf(bio, "%s------%s%s", mime_eol, bound, mime_eol);
  286. /* Headers for signature */
  287. BIO_printf(bio, "Content-Type: %ssignature;", mime_prefix);
  288. BIO_printf(bio, " name=\"smime.p7s\"%s", mime_eol);
  289. BIO_printf(bio, "Content-Transfer-Encoding: base64%s", mime_eol);
  290. BIO_printf(bio, "Content-Disposition: attachment;");
  291. BIO_printf(bio, " filename=\"smime.p7s\"%s%s", mime_eol, mime_eol);
  292. B64_write_ASN1(bio, val, NULL, 0, it);
  293. BIO_printf(bio, "%s------%s--%s%s", mime_eol, bound,
  294. mime_eol, mime_eol);
  295. return 1;
  296. }
  297. /* Determine smime-type header */
  298. if (ctype_nid == NID_pkcs7_enveloped)
  299. msg_type = "enveloped-data";
  300. else if (ctype_nid == NID_pkcs7_signed) {
  301. if (econt_nid == NID_id_smime_ct_receipt)
  302. msg_type = "signed-receipt";
  303. else if (sk_X509_ALGOR_num(mdalgs) >= 0)
  304. msg_type = "signed-data";
  305. else
  306. msg_type = "certs-only";
  307. } else if (ctype_nid == NID_id_smime_ct_compressedData) {
  308. msg_type = "compressed-data";
  309. cname = "smime.p7z";
  310. }
  311. /* MIME headers */
  312. BIO_printf(bio, "MIME-Version: 1.0%s", mime_eol);
  313. BIO_printf(bio, "Content-Disposition: attachment;");
  314. BIO_printf(bio, " filename=\"%s\"%s", cname, mime_eol);
  315. BIO_printf(bio, "Content-Type: %smime;", mime_prefix);
  316. if (msg_type)
  317. BIO_printf(bio, " smime-type=%s;", msg_type);
  318. BIO_printf(bio, " name=\"%s\"%s", cname, mime_eol);
  319. BIO_printf(bio, "Content-Transfer-Encoding: base64%s%s",
  320. mime_eol, mime_eol);
  321. if (!B64_write_ASN1(bio, val, data, flags, it))
  322. return 0;
  323. BIO_printf(bio, "%s", mime_eol);
  324. return 1;
  325. }
  326. /* Handle output of ASN1 data */
  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. * If data is not deteched or resigning then the output BIO is already
  336. * set up to finalise when it is written through.
  337. */
  338. if (!(flags & SMIME_DETACHED) || (flags & PKCS7_REUSE_DIGEST)) {
  339. SMIME_crlf_copy(data, out, flags);
  340. return 1;
  341. }
  342. if (!aux || !aux->asn1_cb) {
  343. ASN1err(ASN1_F_ASN1_OUTPUT_DATA, ASN1_R_STREAMING_NOT_SUPPORTED);
  344. return 0;
  345. }
  346. sarg.out = out;
  347. sarg.ndef_bio = NULL;
  348. sarg.boundary = NULL;
  349. /* Let ASN1 code prepend any needed BIOs */
  350. if (aux->asn1_cb(ASN1_OP_DETACHED_PRE, &val, it, &sarg) <= 0)
  351. return 0;
  352. /* Copy data across, passing through filter BIOs for processing */
  353. SMIME_crlf_copy(data, sarg.ndef_bio, flags);
  354. /* Finalize structure */
  355. if (aux->asn1_cb(ASN1_OP_DETACHED_POST, &val, it, &sarg) <= 0)
  356. rv = 0;
  357. /* Now remove any digests prepended to the BIO */
  358. while (sarg.ndef_bio != out) {
  359. tmpbio = BIO_pop(sarg.ndef_bio);
  360. BIO_free(sarg.ndef_bio);
  361. sarg.ndef_bio = tmpbio;
  362. }
  363. return rv;
  364. }
  365. /*
  366. * SMIME reader: handle multipart/signed and opaque signing. in multipart
  367. * case the content is placed in a memory BIO pointed to by "bcont". In
  368. * opaque this is set to NULL
  369. */
  370. ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it)
  371. {
  372. BIO *asnin;
  373. STACK_OF(MIME_HEADER) *headers = NULL;
  374. STACK_OF(BIO) *parts = NULL;
  375. MIME_HEADER *hdr;
  376. MIME_PARAM *prm;
  377. ASN1_VALUE *val;
  378. int ret;
  379. if (bcont)
  380. *bcont = NULL;
  381. if (!(headers = mime_parse_hdr(bio))) {
  382. ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_MIME_PARSE_ERROR);
  383. return NULL;
  384. }
  385. if (!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
  386. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  387. ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_CONTENT_TYPE);
  388. return NULL;
  389. }
  390. /* Handle multipart/signed */
  391. if (!strcmp(hdr->value, "multipart/signed")) {
  392. /* Split into two parts */
  393. prm = mime_param_find(hdr, "boundary");
  394. if (!prm || !prm->param_value) {
  395. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  396. ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_MULTIPART_BOUNDARY);
  397. return NULL;
  398. }
  399. ret = multi_split(bio, prm->param_value, &parts);
  400. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  401. if (!ret || (sk_BIO_num(parts) != 2)) {
  402. ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_MULTIPART_BODY_FAILURE);
  403. sk_BIO_pop_free(parts, BIO_vfree);
  404. return NULL;
  405. }
  406. /* Parse the signature piece */
  407. asnin = sk_BIO_value(parts, 1);
  408. if (!(headers = mime_parse_hdr(asnin))) {
  409. ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_MIME_SIG_PARSE_ERROR);
  410. sk_BIO_pop_free(parts, BIO_vfree);
  411. return NULL;
  412. }
  413. /* Get content type */
  414. if (!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
  415. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  416. ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_NO_SIG_CONTENT_TYPE);
  417. return NULL;
  418. }
  419. if (strcmp(hdr->value, "application/x-pkcs7-signature") &&
  420. strcmp(hdr->value, "application/pkcs7-signature")) {
  421. ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_SIG_INVALID_MIME_TYPE);
  422. ERR_add_error_data(2, "type: ", hdr->value);
  423. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  424. sk_BIO_pop_free(parts, BIO_vfree);
  425. return NULL;
  426. }
  427. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  428. /* Read in ASN1 */
  429. if (!(val = b64_read_asn1(asnin, it))) {
  430. ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_ASN1_SIG_PARSE_ERROR);
  431. sk_BIO_pop_free(parts, BIO_vfree);
  432. return NULL;
  433. }
  434. if (bcont) {
  435. *bcont = sk_BIO_value(parts, 0);
  436. BIO_free(asnin);
  437. sk_BIO_free(parts);
  438. } else
  439. sk_BIO_pop_free(parts, BIO_vfree);
  440. return val;
  441. }
  442. /* OK, if not multipart/signed try opaque signature */
  443. if (strcmp(hdr->value, "application/x-pkcs7-mime") &&
  444. strcmp(hdr->value, "application/pkcs7-mime")) {
  445. ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_INVALID_MIME_TYPE);
  446. ERR_add_error_data(2, "type: ", hdr->value);
  447. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  448. return NULL;
  449. }
  450. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  451. if (!(val = b64_read_asn1(bio, it))) {
  452. ASN1err(ASN1_F_SMIME_READ_ASN1, ASN1_R_ASN1_PARSE_ERROR);
  453. return NULL;
  454. }
  455. return val;
  456. }
  457. /* Copy text from one BIO to another making the output CRLF at EOL */
  458. int SMIME_crlf_copy(BIO *in, BIO *out, int flags)
  459. {
  460. BIO *bf;
  461. char eol;
  462. int len;
  463. char linebuf[MAX_SMLEN];
  464. /*
  465. * Buffer output so we don't write one line at a time. This is useful
  466. * when streaming as we don't end up with one OCTET STRING per line.
  467. */
  468. bf = BIO_new(BIO_f_buffer());
  469. if (!bf)
  470. return 0;
  471. out = BIO_push(bf, out);
  472. if (flags & SMIME_BINARY) {
  473. while ((len = BIO_read(in, linebuf, MAX_SMLEN)) > 0)
  474. BIO_write(out, linebuf, len);
  475. } else {
  476. if (flags & SMIME_TEXT)
  477. BIO_printf(out, "Content-Type: text/plain\r\n\r\n");
  478. while ((len = BIO_gets(in, linebuf, MAX_SMLEN)) > 0) {
  479. eol = strip_eol(linebuf, &len);
  480. if (len)
  481. BIO_write(out, linebuf, len);
  482. if (eol)
  483. BIO_write(out, "\r\n", 2);
  484. }
  485. }
  486. (void)BIO_flush(out);
  487. BIO_pop(out);
  488. BIO_free(bf);
  489. return 1;
  490. }
  491. /* Strip off headers if they are text/plain */
  492. int SMIME_text(BIO *in, BIO *out)
  493. {
  494. char iobuf[4096];
  495. int len;
  496. STACK_OF(MIME_HEADER) *headers;
  497. MIME_HEADER *hdr;
  498. if (!(headers = mime_parse_hdr(in))) {
  499. ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_MIME_PARSE_ERROR);
  500. return 0;
  501. }
  502. if (!(hdr = mime_hdr_find(headers, "content-type")) || !hdr->value) {
  503. ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_MIME_NO_CONTENT_TYPE);
  504. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  505. return 0;
  506. }
  507. if (strcmp(hdr->value, "text/plain")) {
  508. ASN1err(ASN1_F_SMIME_TEXT, ASN1_R_INVALID_MIME_TYPE);
  509. ERR_add_error_data(2, "type: ", hdr->value);
  510. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  511. return 0;
  512. }
  513. sk_MIME_HEADER_pop_free(headers, mime_hdr_free);
  514. while ((len = BIO_read(in, iobuf, sizeof(iobuf))) > 0)
  515. BIO_write(out, iobuf, len);
  516. if (len < 0)
  517. return 0;
  518. return 1;
  519. }
  520. /*
  521. * Split a multipart/XXX message body into component parts: result is
  522. * canonical parts in a STACK of bios
  523. */
  524. static int multi_split(BIO *bio, char *bound, STACK_OF(BIO) **ret)
  525. {
  526. char linebuf[MAX_SMLEN];
  527. int len, blen;
  528. int eol = 0, next_eol = 0;
  529. BIO *bpart = NULL;
  530. STACK_OF(BIO) *parts;
  531. char state, part, first;
  532. blen = strlen(bound);
  533. part = 0;
  534. state = 0;
  535. first = 1;
  536. parts = sk_BIO_new_null();
  537. *ret = parts;
  538. while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
  539. state = mime_bound_check(linebuf, len, bound, blen);
  540. if (state == 1) {
  541. first = 1;
  542. part++;
  543. } else if (state == 2) {
  544. sk_BIO_push(parts, bpart);
  545. return 1;
  546. } else if (part) {
  547. /* Strip CR+LF from linebuf */
  548. next_eol = strip_eol(linebuf, &len);
  549. if (first) {
  550. first = 0;
  551. if (bpart)
  552. sk_BIO_push(parts, bpart);
  553. bpart = BIO_new(BIO_s_mem());
  554. if (bpart == NULL)
  555. return 1;
  556. BIO_set_mem_eof_return(bpart, 0);
  557. } else if (eol)
  558. BIO_write(bpart, "\r\n", 2);
  559. eol = next_eol;
  560. if (len)
  561. BIO_write(bpart, linebuf, len);
  562. }
  563. }
  564. return 0;
  565. }
  566. /* This is the big one: parse MIME header lines up to message body */
  567. #define MIME_INVALID 0
  568. #define MIME_START 1
  569. #define MIME_TYPE 2
  570. #define MIME_NAME 3
  571. #define MIME_VALUE 4
  572. #define MIME_QUOTE 5
  573. #define MIME_COMMENT 6
  574. static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio)
  575. {
  576. char *p, *q, c;
  577. char *ntmp;
  578. char linebuf[MAX_SMLEN];
  579. MIME_HEADER *mhdr = NULL;
  580. STACK_OF(MIME_HEADER) *headers;
  581. int len, state, save_state = 0;
  582. headers = sk_MIME_HEADER_new(mime_hdr_cmp);
  583. if (!headers)
  584. return NULL;
  585. while ((len = BIO_gets(bio, linebuf, MAX_SMLEN)) > 0) {
  586. /* If whitespace at line start then continuation line */
  587. if (mhdr && isspace((unsigned char)linebuf[0]))
  588. state = MIME_NAME;
  589. else
  590. state = MIME_START;
  591. ntmp = NULL;
  592. /* Go through all characters */
  593. for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
  594. p++) {
  595. /*
  596. * State machine to handle MIME headers if this looks horrible
  597. * that's because it *is*
  598. */
  599. switch (state) {
  600. case MIME_START:
  601. if (c == ':') {
  602. state = MIME_TYPE;
  603. *p = 0;
  604. ntmp = strip_ends(q);
  605. q = p + 1;
  606. }
  607. break;
  608. case MIME_TYPE:
  609. if (c == ';') {
  610. mime_debug("Found End Value\n");
  611. *p = 0;
  612. mhdr = mime_hdr_new(ntmp, strip_ends(q));
  613. sk_MIME_HEADER_push(headers, mhdr);
  614. ntmp = NULL;
  615. q = p + 1;
  616. state = MIME_NAME;
  617. } else if (c == '(') {
  618. save_state = state;
  619. state = MIME_COMMENT;
  620. }
  621. break;
  622. case MIME_COMMENT:
  623. if (c == ')') {
  624. state = save_state;
  625. }
  626. break;
  627. case MIME_NAME:
  628. if (c == '=') {
  629. state = MIME_VALUE;
  630. *p = 0;
  631. ntmp = strip_ends(q);
  632. q = p + 1;
  633. }
  634. break;
  635. case MIME_VALUE:
  636. if (c == ';') {
  637. state = MIME_NAME;
  638. *p = 0;
  639. mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
  640. ntmp = NULL;
  641. q = p + 1;
  642. } else if (c == '"') {
  643. mime_debug("Found Quote\n");
  644. state = MIME_QUOTE;
  645. } else if (c == '(') {
  646. save_state = state;
  647. state = MIME_COMMENT;
  648. }
  649. break;
  650. case MIME_QUOTE:
  651. if (c == '"') {
  652. mime_debug("Found Match Quote\n");
  653. state = MIME_VALUE;
  654. }
  655. break;
  656. }
  657. }
  658. if (state == MIME_TYPE) {
  659. mhdr = mime_hdr_new(ntmp, strip_ends(q));
  660. sk_MIME_HEADER_push(headers, mhdr);
  661. } else if (state == MIME_VALUE)
  662. mime_hdr_addparam(mhdr, ntmp, strip_ends(q));
  663. if (p == linebuf)
  664. break; /* Blank line means end of headers */
  665. }
  666. return headers;
  667. }
  668. static char *strip_ends(char *name)
  669. {
  670. return strip_end(strip_start(name));
  671. }
  672. /* Strip a parameter of whitespace from start of param */
  673. static char *strip_start(char *name)
  674. {
  675. char *p, c;
  676. /* Look for first non white space or quote */
  677. for (p = name; (c = *p); p++) {
  678. if (c == '"') {
  679. /* Next char is start of string if non null */
  680. if (p[1])
  681. return p + 1;
  682. /* Else null string */
  683. return NULL;
  684. }
  685. if (!isspace((unsigned char)c))
  686. return p;
  687. }
  688. return NULL;
  689. }
  690. /* As above but strip from end of string : maybe should handle brackets? */
  691. static char *strip_end(char *name)
  692. {
  693. char *p, c;
  694. if (!name)
  695. return NULL;
  696. /* Look for first non white space or quote */
  697. for (p = name + strlen(name) - 1; p >= name; p--) {
  698. c = *p;
  699. if (c == '"') {
  700. if (p - 1 == name)
  701. return NULL;
  702. *p = 0;
  703. return name;
  704. }
  705. if (isspace((unsigned char)c))
  706. *p = 0;
  707. else
  708. return name;
  709. }
  710. return NULL;
  711. }
  712. static MIME_HEADER *mime_hdr_new(char *name, char *value)
  713. {
  714. MIME_HEADER *mhdr;
  715. char *tmpname, *tmpval, *p;
  716. int c;
  717. if (name) {
  718. if (!(tmpname = BUF_strdup(name)))
  719. return NULL;
  720. for (p = tmpname; *p; p++) {
  721. c = (unsigned char)*p;
  722. if (isupper(c)) {
  723. c = tolower(c);
  724. *p = c;
  725. }
  726. }
  727. } else
  728. tmpname = NULL;
  729. if (value) {
  730. if (!(tmpval = BUF_strdup(value)))
  731. return NULL;
  732. for (p = tmpval; *p; p++) {
  733. c = (unsigned char)*p;
  734. if (isupper(c)) {
  735. c = tolower(c);
  736. *p = c;
  737. }
  738. }
  739. } else
  740. tmpval = NULL;
  741. mhdr = (MIME_HEADER *)OPENSSL_malloc(sizeof(MIME_HEADER));
  742. if (!mhdr)
  743. return NULL;
  744. mhdr->name = tmpname;
  745. mhdr->value = tmpval;
  746. if (!(mhdr->params = sk_MIME_PARAM_new(mime_param_cmp)))
  747. return NULL;
  748. return mhdr;
  749. }
  750. static int mime_hdr_addparam(MIME_HEADER *mhdr, char *name, char *value)
  751. {
  752. char *tmpname, *tmpval, *p;
  753. int c;
  754. MIME_PARAM *mparam;
  755. if (name) {
  756. tmpname = BUF_strdup(name);
  757. if (!tmpname)
  758. return 0;
  759. for (p = tmpname; *p; p++) {
  760. c = (unsigned char)*p;
  761. if (isupper(c)) {
  762. c = tolower(c);
  763. *p = c;
  764. }
  765. }
  766. } else
  767. tmpname = NULL;
  768. if (value) {
  769. tmpval = BUF_strdup(value);
  770. if (!tmpval)
  771. return 0;
  772. } else
  773. tmpval = NULL;
  774. /* Parameter values are case sensitive so leave as is */
  775. mparam = (MIME_PARAM *)OPENSSL_malloc(sizeof(MIME_PARAM));
  776. if (!mparam)
  777. return 0;
  778. mparam->param_name = tmpname;
  779. mparam->param_value = tmpval;
  780. sk_MIME_PARAM_push(mhdr->params, mparam);
  781. return 1;
  782. }
  783. static int mime_hdr_cmp(const MIME_HEADER *const *a,
  784. const MIME_HEADER *const *b)
  785. {
  786. if (!(*a)->name || !(*b)->name)
  787. return ! !(*a)->name - ! !(*b)->name;
  788. return (strcmp((*a)->name, (*b)->name));
  789. }
  790. static int mime_param_cmp(const MIME_PARAM *const *a,
  791. const MIME_PARAM *const *b)
  792. {
  793. if (!(*a)->param_name || !(*b)->param_name)
  794. return ! !(*a)->param_name - ! !(*b)->param_name;
  795. return (strcmp((*a)->param_name, (*b)->param_name));
  796. }
  797. /* Find a header with a given name (if possible) */
  798. static MIME_HEADER *mime_hdr_find(STACK_OF(MIME_HEADER) *hdrs, char *name)
  799. {
  800. MIME_HEADER htmp;
  801. int idx;
  802. htmp.name = name;
  803. idx = sk_MIME_HEADER_find(hdrs, &htmp);
  804. if (idx < 0)
  805. return NULL;
  806. return sk_MIME_HEADER_value(hdrs, idx);
  807. }
  808. static MIME_PARAM *mime_param_find(MIME_HEADER *hdr, char *name)
  809. {
  810. MIME_PARAM param;
  811. int idx;
  812. param.param_name = name;
  813. idx = sk_MIME_PARAM_find(hdr->params, &param);
  814. if (idx < 0)
  815. return NULL;
  816. return sk_MIME_PARAM_value(hdr->params, idx);
  817. }
  818. static void mime_hdr_free(MIME_HEADER *hdr)
  819. {
  820. if (hdr->name)
  821. OPENSSL_free(hdr->name);
  822. if (hdr->value)
  823. OPENSSL_free(hdr->value);
  824. if (hdr->params)
  825. sk_MIME_PARAM_pop_free(hdr->params, mime_param_free);
  826. OPENSSL_free(hdr);
  827. }
  828. static void mime_param_free(MIME_PARAM *param)
  829. {
  830. if (param->param_name)
  831. OPENSSL_free(param->param_name);
  832. if (param->param_value)
  833. OPENSSL_free(param->param_value);
  834. OPENSSL_free(param);
  835. }
  836. /*-
  837. * Check for a multipart boundary. Returns:
  838. * 0 : no boundary
  839. * 1 : part boundary
  840. * 2 : final boundary
  841. */
  842. static int mime_bound_check(char *line, int linelen, char *bound, int blen)
  843. {
  844. if (linelen == -1)
  845. linelen = strlen(line);
  846. if (blen == -1)
  847. blen = strlen(bound);
  848. /* Quickly eliminate if line length too short */
  849. if (blen + 2 > linelen)
  850. return 0;
  851. /* Check for part boundary */
  852. if (!strncmp(line, "--", 2) && !strncmp(line + 2, bound, blen)) {
  853. if (!strncmp(line + blen + 2, "--", 2))
  854. return 2;
  855. else
  856. return 1;
  857. }
  858. return 0;
  859. }
  860. static int strip_eol(char *linebuf, int *plen)
  861. {
  862. int len = *plen;
  863. char *p, c;
  864. int is_eol = 0;
  865. p = linebuf + len - 1;
  866. for (p = linebuf + len - 1; len > 0; len--, p--) {
  867. c = *p;
  868. if (c == '\n')
  869. is_eol = 1;
  870. else if (c != '\r')
  871. break;
  872. }
  873. *plen = len;
  874. return is_eol;
  875. }