GH354: Memory leak fixes
[openssl.git] / crypto / pkcs7 / pk7_smime.c
1 /* pk7_smime.c */
2 /*
3  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
4  * project.
5  */
6 /* ====================================================================
7  * Copyright (c) 1999-2004 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  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59
60 /* Simple PKCS#7 processing functions */
61
62 #include <stdio.h>
63 #include "internal/cryptlib.h"
64 #include <openssl/x509.h>
65 #include <openssl/x509v3.h>
66
67 static int pkcs7_copy_existing_digest(PKCS7 *p7, PKCS7_SIGNER_INFO *si);
68
69 PKCS7 *PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
70                   BIO *data, int flags)
71 {
72     PKCS7 *p7;
73     int i;
74
75     if ((p7 = PKCS7_new()) == NULL) {
76         PKCS7err(PKCS7_F_PKCS7_SIGN, ERR_R_MALLOC_FAILURE);
77         return NULL;
78     }
79
80     if (!PKCS7_set_type(p7, NID_pkcs7_signed))
81         goto err;
82
83     if (!PKCS7_content_new(p7, NID_pkcs7_data))
84         goto err;
85
86     if (pkey && !PKCS7_sign_add_signer(p7, signcert, pkey, NULL, flags)) {
87         PKCS7err(PKCS7_F_PKCS7_SIGN, PKCS7_R_PKCS7_ADD_SIGNER_ERROR);
88         goto err;
89     }
90
91     if (!(flags & PKCS7_NOCERTS)) {
92         for (i = 0; i < sk_X509_num(certs); i++) {
93             if (!PKCS7_add_certificate(p7, sk_X509_value(certs, i)))
94                 goto err;
95         }
96     }
97
98     if (flags & PKCS7_DETACHED)
99         PKCS7_set_detached(p7, 1);
100
101     if (flags & (PKCS7_STREAM | PKCS7_PARTIAL))
102         return p7;
103
104     if (PKCS7_final(p7, data, flags))
105         return p7;
106
107  err:
108     PKCS7_free(p7);
109     return NULL;
110 }
111
112 int PKCS7_final(PKCS7 *p7, BIO *data, int flags)
113 {
114     BIO *p7bio;
115     int ret = 0;
116     if ((p7bio = PKCS7_dataInit(p7, NULL)) == NULL) {
117         PKCS7err(PKCS7_F_PKCS7_FINAL, ERR_R_MALLOC_FAILURE);
118         return 0;
119     }
120
121     SMIME_crlf_copy(data, p7bio, flags);
122
123     (void)BIO_flush(p7bio);
124
125     if (!PKCS7_dataFinal(p7, p7bio)) {
126         PKCS7err(PKCS7_F_PKCS7_FINAL, PKCS7_R_PKCS7_DATASIGN);
127         goto err;
128     }
129
130     ret = 1;
131
132  err:
133     BIO_free_all(p7bio);
134
135     return ret;
136
137 }
138
139 /* Check to see if a cipher exists and if so add S/MIME capabilities */
140
141 static int add_cipher_smcap(STACK_OF(X509_ALGOR) *sk, int nid, int arg)
142 {
143     if (EVP_get_cipherbynid(nid))
144         return PKCS7_simple_smimecap(sk, nid, arg);
145     return 1;
146 }
147
148 static int add_digest_smcap(STACK_OF(X509_ALGOR) *sk, int nid, int arg)
149 {
150     if (EVP_get_digestbynid(nid))
151         return PKCS7_simple_smimecap(sk, nid, arg);
152     return 1;
153 }
154
155 PKCS7_SIGNER_INFO *PKCS7_sign_add_signer(PKCS7 *p7, X509 *signcert,
156                                          EVP_PKEY *pkey, const EVP_MD *md,
157                                          int flags)
158 {
159     PKCS7_SIGNER_INFO *si = NULL;
160     STACK_OF(X509_ALGOR) *smcap = NULL;
161     if (!X509_check_private_key(signcert, pkey)) {
162         PKCS7err(PKCS7_F_PKCS7_SIGN_ADD_SIGNER,
163                  PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
164         return NULL;
165     }
166
167     if ((si = PKCS7_add_signature(p7, signcert, pkey, md)) == NULL) {
168         PKCS7err(PKCS7_F_PKCS7_SIGN_ADD_SIGNER,
169                  PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR);
170         return NULL;
171     }
172
173     if (!(flags & PKCS7_NOCERTS)) {
174         if (!PKCS7_add_certificate(p7, signcert))
175             goto err;
176     }
177
178     if (!(flags & PKCS7_NOATTR)) {
179         if (!PKCS7_add_attrib_content_type(si, NULL))
180             goto err;
181         /* Add SMIMECapabilities */
182         if (!(flags & PKCS7_NOSMIMECAP)) {
183             if ((smcap = sk_X509_ALGOR_new_null()) == NULL) {
184                 PKCS7err(PKCS7_F_PKCS7_SIGN_ADD_SIGNER, ERR_R_MALLOC_FAILURE);
185                 goto err;
186             }
187             if (!add_cipher_smcap(smcap, NID_aes_256_cbc, -1)
188                 || !add_digest_smcap(smcap, NID_id_GostR3411_94, -1)
189                 || !add_cipher_smcap(smcap, NID_id_Gost28147_89, -1)
190                 || !add_cipher_smcap(smcap, NID_aes_192_cbc, -1)
191                 || !add_cipher_smcap(smcap, NID_aes_128_cbc, -1)
192                 || !add_cipher_smcap(smcap, NID_des_ede3_cbc, -1)
193                 || !add_cipher_smcap(smcap, NID_rc2_cbc, 128)
194                 || !add_cipher_smcap(smcap, NID_rc2_cbc, 64)
195                 || !add_cipher_smcap(smcap, NID_des_cbc, -1)
196                 || !add_cipher_smcap(smcap, NID_rc2_cbc, 40)
197                 || !PKCS7_add_attrib_smimecap(si, smcap))
198                 goto err;
199             sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free);
200             smcap = NULL;
201         }
202         if (flags & PKCS7_REUSE_DIGEST) {
203             if (!pkcs7_copy_existing_digest(p7, si))
204                 goto err;
205             if (!(flags & PKCS7_PARTIAL) && !PKCS7_SIGNER_INFO_sign(si))
206                 goto err;
207         }
208     }
209     return si;
210  err:
211     sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free);
212     return NULL;
213 }
214
215 /*
216  * Search for a digest matching SignerInfo digest type and if found copy
217  * across.
218  */
219
220 static int pkcs7_copy_existing_digest(PKCS7 *p7, PKCS7_SIGNER_INFO *si)
221 {
222     int i;
223     STACK_OF(PKCS7_SIGNER_INFO) *sinfos;
224     PKCS7_SIGNER_INFO *sitmp;
225     ASN1_OCTET_STRING *osdig = NULL;
226     sinfos = PKCS7_get_signer_info(p7);
227     for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(sinfos); i++) {
228         sitmp = sk_PKCS7_SIGNER_INFO_value(sinfos, i);
229         if (si == sitmp)
230             break;
231         if (sk_X509_ATTRIBUTE_num(sitmp->auth_attr) <= 0)
232             continue;
233         if (!OBJ_cmp(si->digest_alg->algorithm, sitmp->digest_alg->algorithm)) {
234             osdig = PKCS7_digest_from_attributes(sitmp->auth_attr);
235             break;
236         }
237
238     }
239
240     if (osdig)
241         return PKCS7_add1_attrib_digest(si, osdig->data, osdig->length);
242
243     PKCS7err(PKCS7_F_PKCS7_COPY_EXISTING_DIGEST,
244              PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND);
245     return 0;
246 }
247
248 int PKCS7_verify(PKCS7 *p7, STACK_OF(X509) *certs, X509_STORE *store,
249                  BIO *indata, BIO *out, int flags)
250 {
251     STACK_OF(X509) *signers;
252     X509 *signer;
253     STACK_OF(PKCS7_SIGNER_INFO) *sinfos;
254     PKCS7_SIGNER_INFO *si;
255     X509_STORE_CTX cert_ctx;
256     char buf[4096];
257     int i, j = 0, k, ret = 0;
258     BIO *p7bio = NULL;
259     BIO *tmpin = NULL, *tmpout = NULL;
260
261     if (!p7) {
262         PKCS7err(PKCS7_F_PKCS7_VERIFY, PKCS7_R_INVALID_NULL_POINTER);
263         return 0;
264     }
265
266     if (!PKCS7_type_is_signed(p7)) {
267         PKCS7err(PKCS7_F_PKCS7_VERIFY, PKCS7_R_WRONG_CONTENT_TYPE);
268         return 0;
269     }
270
271     /* Check for no data and no content: no data to verify signature */
272     if (PKCS7_get_detached(p7) && !indata) {
273         PKCS7err(PKCS7_F_PKCS7_VERIFY, PKCS7_R_NO_CONTENT);
274         return 0;
275     }
276
277     /* Check for data and content: two sets of data */
278     if (!PKCS7_get_detached(p7) && indata) {
279         PKCS7err(PKCS7_F_PKCS7_VERIFY, PKCS7_R_CONTENT_AND_DATA_PRESENT);
280         return 0;
281     }
282
283     sinfos = PKCS7_get_signer_info(p7);
284
285     if (!sinfos || !sk_PKCS7_SIGNER_INFO_num(sinfos)) {
286         PKCS7err(PKCS7_F_PKCS7_VERIFY, PKCS7_R_NO_SIGNATURES_ON_DATA);
287         return 0;
288     }
289
290     signers = PKCS7_get0_signers(p7, certs, flags);
291     if (!signers)
292         return 0;
293
294     /* Now verify the certificates */
295
296     if (!(flags & PKCS7_NOVERIFY))
297         for (k = 0; k < sk_X509_num(signers); k++) {
298             signer = sk_X509_value(signers, k);
299             if (!(flags & PKCS7_NOCHAIN)) {
300                 if (!X509_STORE_CTX_init(&cert_ctx, store, signer,
301                                          p7->d.sign->cert)) {
302                     PKCS7err(PKCS7_F_PKCS7_VERIFY, ERR_R_X509_LIB);
303                     goto err;
304                 }
305                 X509_STORE_CTX_set_default(&cert_ctx, "smime_sign");
306             } else if (!X509_STORE_CTX_init(&cert_ctx, store, signer, NULL)) {
307                 PKCS7err(PKCS7_F_PKCS7_VERIFY, ERR_R_X509_LIB);
308                 goto err;
309             }
310             if (!(flags & PKCS7_NOCRL))
311                 X509_STORE_CTX_set0_crls(&cert_ctx, p7->d.sign->crl);
312             i = X509_verify_cert(&cert_ctx);
313             if (i <= 0)
314                 j = X509_STORE_CTX_get_error(&cert_ctx);
315             X509_STORE_CTX_cleanup(&cert_ctx);
316             if (i <= 0) {
317                 PKCS7err(PKCS7_F_PKCS7_VERIFY,
318                          PKCS7_R_CERTIFICATE_VERIFY_ERROR);
319                 ERR_add_error_data(2, "Verify error:",
320                                    X509_verify_cert_error_string(j));
321                 goto err;
322             }
323             /* Check for revocation status here */
324         }
325
326     /*
327      * Performance optimization: if the content is a memory BIO then store
328      * its contents in a temporary read only memory BIO. This avoids
329      * potentially large numbers of slow copies of data which will occur when
330      * reading from a read write memory BIO when signatures are calculated.
331      */
332
333     if (indata && (BIO_method_type(indata) == BIO_TYPE_MEM)) {
334         char *ptr;
335         long len;
336         len = BIO_get_mem_data(indata, &ptr);
337         tmpin = BIO_new_mem_buf(ptr, len);
338         if (tmpin == NULL) {
339             PKCS7err(PKCS7_F_PKCS7_VERIFY, ERR_R_MALLOC_FAILURE);
340             goto err;
341         }
342     } else
343         tmpin = indata;
344
345     if ((p7bio = PKCS7_dataInit(p7, tmpin)) == NULL)
346         goto err;
347
348     if (flags & PKCS7_TEXT) {
349         if ((tmpout = BIO_new(BIO_s_mem())) == NULL) {
350             PKCS7err(PKCS7_F_PKCS7_VERIFY, ERR_R_MALLOC_FAILURE);
351             goto err;
352         }
353         BIO_set_mem_eof_return(tmpout, 0);
354     } else
355         tmpout = out;
356
357     /* We now have to 'read' from p7bio to calculate digests etc. */
358     for (;;) {
359         i = BIO_read(p7bio, buf, sizeof(buf));
360         if (i <= 0)
361             break;
362         if (tmpout)
363             BIO_write(tmpout, buf, i);
364     }
365
366     if (flags & PKCS7_TEXT) {
367         if (!SMIME_text(tmpout, out)) {
368             PKCS7err(PKCS7_F_PKCS7_VERIFY, PKCS7_R_SMIME_TEXT_ERROR);
369             BIO_free(tmpout);
370             goto err;
371         }
372         BIO_free(tmpout);
373     }
374
375     /* Now Verify All Signatures */
376     if (!(flags & PKCS7_NOSIGS))
377         for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(sinfos); i++) {
378             si = sk_PKCS7_SIGNER_INFO_value(sinfos, i);
379             signer = sk_X509_value(signers, i);
380             j = PKCS7_signatureVerify(p7bio, p7, si, signer);
381             if (j <= 0) {
382                 PKCS7err(PKCS7_F_PKCS7_VERIFY, PKCS7_R_SIGNATURE_FAILURE);
383                 goto err;
384             }
385         }
386
387     ret = 1;
388
389  err:
390     if (tmpin == indata) {
391         if (indata)
392             BIO_pop(p7bio);
393     }
394     BIO_free_all(p7bio);
395     sk_X509_free(signers);
396     return ret;
397 }
398
399 STACK_OF(X509) *PKCS7_get0_signers(PKCS7 *p7, STACK_OF(X509) *certs,
400                                    int flags)
401 {
402     STACK_OF(X509) *signers;
403     STACK_OF(PKCS7_SIGNER_INFO) *sinfos;
404     PKCS7_SIGNER_INFO *si;
405     PKCS7_ISSUER_AND_SERIAL *ias;
406     X509 *signer;
407     int i;
408
409     if (!p7) {
410         PKCS7err(PKCS7_F_PKCS7_GET0_SIGNERS, PKCS7_R_INVALID_NULL_POINTER);
411         return NULL;
412     }
413
414     if (!PKCS7_type_is_signed(p7)) {
415         PKCS7err(PKCS7_F_PKCS7_GET0_SIGNERS, PKCS7_R_WRONG_CONTENT_TYPE);
416         return NULL;
417     }
418
419     /* Collect all the signers together */
420
421     sinfos = PKCS7_get_signer_info(p7);
422
423     if (sk_PKCS7_SIGNER_INFO_num(sinfos) <= 0) {
424         PKCS7err(PKCS7_F_PKCS7_GET0_SIGNERS, PKCS7_R_NO_SIGNERS);
425         return 0;
426     }
427
428     if ((signers = sk_X509_new_null()) == NULL) {
429         PKCS7err(PKCS7_F_PKCS7_GET0_SIGNERS, ERR_R_MALLOC_FAILURE);
430         return NULL;
431     }
432
433     for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(sinfos); i++) {
434         si = sk_PKCS7_SIGNER_INFO_value(sinfos, i);
435         ias = si->issuer_and_serial;
436         signer = NULL;
437         /* If any certificates passed they take priority */
438         if (certs)
439             signer = X509_find_by_issuer_and_serial(certs,
440                                                     ias->issuer, ias->serial);
441         if (!signer && !(flags & PKCS7_NOINTERN)
442             && p7->d.sign->cert)
443             signer =
444                 X509_find_by_issuer_and_serial(p7->d.sign->cert,
445                                                ias->issuer, ias->serial);
446         if (!signer) {
447             PKCS7err(PKCS7_F_PKCS7_GET0_SIGNERS,
448                      PKCS7_R_SIGNER_CERTIFICATE_NOT_FOUND);
449             sk_X509_free(signers);
450             return 0;
451         }
452
453         if (!sk_X509_push(signers, signer)) {
454             sk_X509_free(signers);
455             return NULL;
456         }
457     }
458     return signers;
459 }
460
461 /* Build a complete PKCS#7 enveloped data */
462
463 PKCS7 *PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, const EVP_CIPHER *cipher,
464                      int flags)
465 {
466     PKCS7 *p7;
467     BIO *p7bio = NULL;
468     int i;
469     X509 *x509;
470     if ((p7 = PKCS7_new()) == NULL) {
471         PKCS7err(PKCS7_F_PKCS7_ENCRYPT, ERR_R_MALLOC_FAILURE);
472         return NULL;
473     }
474
475     if (!PKCS7_set_type(p7, NID_pkcs7_enveloped))
476         goto err;
477     if (!PKCS7_set_cipher(p7, cipher)) {
478         PKCS7err(PKCS7_F_PKCS7_ENCRYPT, PKCS7_R_ERROR_SETTING_CIPHER);
479         goto err;
480     }
481
482     for (i = 0; i < sk_X509_num(certs); i++) {
483         x509 = sk_X509_value(certs, i);
484         if (!PKCS7_add_recipient(p7, x509)) {
485             PKCS7err(PKCS7_F_PKCS7_ENCRYPT, PKCS7_R_ERROR_ADDING_RECIPIENT);
486             goto err;
487         }
488     }
489
490     if (flags & PKCS7_STREAM)
491         return p7;
492
493     if (PKCS7_final(p7, in, flags))
494         return p7;
495
496  err:
497
498     BIO_free_all(p7bio);
499     PKCS7_free(p7);
500     return NULL;
501
502 }
503
504 int PKCS7_decrypt(PKCS7 *p7, EVP_PKEY *pkey, X509 *cert, BIO *data, int flags)
505 {
506     BIO *tmpmem;
507     int ret, i;
508     char buf[4096];
509
510     if (!p7) {
511         PKCS7err(PKCS7_F_PKCS7_DECRYPT, PKCS7_R_INVALID_NULL_POINTER);
512         return 0;
513     }
514
515     if (!PKCS7_type_is_enveloped(p7)) {
516         PKCS7err(PKCS7_F_PKCS7_DECRYPT, PKCS7_R_WRONG_CONTENT_TYPE);
517         return 0;
518     }
519
520     if (cert && !X509_check_private_key(cert, pkey)) {
521         PKCS7err(PKCS7_F_PKCS7_DECRYPT,
522                  PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
523         return 0;
524     }
525
526     if ((tmpmem = PKCS7_dataDecode(p7, pkey, NULL, cert)) == NULL) {
527         PKCS7err(PKCS7_F_PKCS7_DECRYPT, PKCS7_R_DECRYPT_ERROR);
528         return 0;
529     }
530
531     if (flags & PKCS7_TEXT) {
532         BIO *tmpbuf, *bread;
533         /* Encrypt BIOs can't do BIO_gets() so add a buffer BIO */
534         if ((tmpbuf = BIO_new(BIO_f_buffer())) == NULL) {
535             PKCS7err(PKCS7_F_PKCS7_DECRYPT, ERR_R_MALLOC_FAILURE);
536             BIO_free_all(tmpmem);
537             return 0;
538         }
539         if ((bread = BIO_push(tmpbuf, tmpmem)) == NULL) {
540             PKCS7err(PKCS7_F_PKCS7_DECRYPT, ERR_R_MALLOC_FAILURE);
541             BIO_free_all(tmpbuf);
542             BIO_free_all(tmpmem);
543             return 0;
544         }
545         ret = SMIME_text(bread, data);
546         if (ret > 0 && BIO_method_type(tmpmem) == BIO_TYPE_CIPHER) {
547             if (!BIO_get_cipher_status(tmpmem))
548                 ret = 0;
549         }
550         BIO_free_all(bread);
551         return ret;
552     } else {
553         for (;;) {
554             i = BIO_read(tmpmem, buf, sizeof(buf));
555             if (i <= 0) {
556                 ret = 1;
557                 if (BIO_method_type(tmpmem) == BIO_TYPE_CIPHER) {
558                     if (!BIO_get_cipher_status(tmpmem))
559                         ret = 0;
560                 }
561
562                 break;
563             }
564             if (BIO_write(data, buf, i) != i) {
565                 ret = 0;
566                 break;
567             }
568         }
569         BIO_free_all(tmpmem);
570         return ret;
571     }
572 }