asn_mime.c 29 KB

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