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