Code hygiene; initialize some pointers.
[openssl.git] / crypto / pkcs7 / pk7_doit.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/rand.h>
13 #include <openssl/objects.h>
14 #include <openssl/x509.h>
15 #include <openssl/x509v3.h>
16 #include <openssl/err.h>
17
18 static int add_attribute(STACK_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype,
19                          void *value);
20 static ASN1_TYPE *get_attribute(STACK_OF(X509_ATTRIBUTE) *sk, int nid);
21
22 static int PKCS7_type_is_other(PKCS7 *p7)
23 {
24     int isOther = 1;
25
26     int nid = OBJ_obj2nid(p7->type);
27
28     switch (nid) {
29     case NID_pkcs7_data:
30     case NID_pkcs7_signed:
31     case NID_pkcs7_enveloped:
32     case NID_pkcs7_signedAndEnveloped:
33     case NID_pkcs7_digest:
34     case NID_pkcs7_encrypted:
35         isOther = 0;
36         break;
37     default:
38         isOther = 1;
39     }
40
41     return isOther;
42
43 }
44
45 static ASN1_OCTET_STRING *PKCS7_get_octet_string(PKCS7 *p7)
46 {
47     if (PKCS7_type_is_data(p7))
48         return p7->d.data;
49     if (PKCS7_type_is_other(p7) && p7->d.other
50         && (p7->d.other->type == V_ASN1_OCTET_STRING))
51         return p7->d.other->value.octet_string;
52     return NULL;
53 }
54
55 static int PKCS7_bio_add_digest(BIO **pbio, X509_ALGOR *alg)
56 {
57     BIO *btmp;
58     const EVP_MD *md;
59     if ((btmp = BIO_new(BIO_f_md())) == NULL) {
60         PKCS7err(PKCS7_F_PKCS7_BIO_ADD_DIGEST, ERR_R_BIO_LIB);
61         goto err;
62     }
63
64     md = EVP_get_digestbyobj(alg->algorithm);
65     if (md == NULL) {
66         PKCS7err(PKCS7_F_PKCS7_BIO_ADD_DIGEST, PKCS7_R_UNKNOWN_DIGEST_TYPE);
67         goto err;
68     }
69
70     BIO_set_md(btmp, md);
71     if (*pbio == NULL)
72         *pbio = btmp;
73     else if (!BIO_push(*pbio, btmp)) {
74         PKCS7err(PKCS7_F_PKCS7_BIO_ADD_DIGEST, ERR_R_BIO_LIB);
75         goto err;
76     }
77     btmp = NULL;
78
79     return 1;
80
81  err:
82     BIO_free(btmp);
83     return 0;
84
85 }
86
87 static int pkcs7_encode_rinfo(PKCS7_RECIP_INFO *ri,
88                               unsigned char *key, int keylen)
89 {
90     EVP_PKEY_CTX *pctx = NULL;
91     EVP_PKEY *pkey = NULL;
92     unsigned char *ek = NULL;
93     int ret = 0;
94     size_t eklen;
95
96     pkey = X509_get0_pubkey(ri->cert);
97
98     if (!pkey)
99         return 0;
100
101     pctx = EVP_PKEY_CTX_new(pkey, NULL);
102     if (!pctx)
103         return 0;
104
105     if (EVP_PKEY_encrypt_init(pctx) <= 0)
106         goto err;
107
108     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_ENCRYPT,
109                           EVP_PKEY_CTRL_PKCS7_ENCRYPT, 0, ri) <= 0) {
110         PKCS7err(PKCS7_F_PKCS7_ENCODE_RINFO, PKCS7_R_CTRL_ERROR);
111         goto err;
112     }
113
114     if (EVP_PKEY_encrypt(pctx, NULL, &eklen, key, keylen) <= 0)
115         goto err;
116
117     ek = OPENSSL_malloc(eklen);
118
119     if (ek == NULL) {
120         PKCS7err(PKCS7_F_PKCS7_ENCODE_RINFO, ERR_R_MALLOC_FAILURE);
121         goto err;
122     }
123
124     if (EVP_PKEY_encrypt(pctx, ek, &eklen, key, keylen) <= 0)
125         goto err;
126
127     ASN1_STRING_set0(ri->enc_key, ek, eklen);
128     ek = NULL;
129
130     ret = 1;
131
132  err:
133     EVP_PKEY_CTX_free(pctx);
134     OPENSSL_free(ek);
135     return ret;
136
137 }
138
139 static int pkcs7_decrypt_rinfo(unsigned char **pek, int *peklen,
140                                PKCS7_RECIP_INFO *ri, EVP_PKEY *pkey)
141 {
142     EVP_PKEY_CTX *pctx = NULL;
143     unsigned char *ek = NULL;
144     size_t eklen;
145
146     int ret = -1;
147
148     pctx = EVP_PKEY_CTX_new(pkey, NULL);
149     if (!pctx)
150         return -1;
151
152     if (EVP_PKEY_decrypt_init(pctx) <= 0)
153         goto err;
154
155     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DECRYPT,
156                           EVP_PKEY_CTRL_PKCS7_DECRYPT, 0, ri) <= 0) {
157         PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, PKCS7_R_CTRL_ERROR);
158         goto err;
159     }
160
161     if (EVP_PKEY_decrypt(pctx, NULL, &eklen,
162                          ri->enc_key->data, ri->enc_key->length) <= 0)
163         goto err;
164
165     ek = OPENSSL_malloc(eklen);
166
167     if (ek == NULL) {
168         PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, ERR_R_MALLOC_FAILURE);
169         goto err;
170     }
171
172     if (EVP_PKEY_decrypt(pctx, ek, &eklen,
173                          ri->enc_key->data, ri->enc_key->length) <= 0) {
174         ret = 0;
175         PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, ERR_R_EVP_LIB);
176         goto err;
177     }
178
179     ret = 1;
180
181     OPENSSL_clear_free(*pek, *peklen);
182     *pek = ek;
183     *peklen = eklen;
184
185  err:
186     EVP_PKEY_CTX_free(pctx);
187     if (!ret)
188         OPENSSL_free(ek);
189
190     return ret;
191 }
192
193 BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio)
194 {
195     int i;
196     BIO *out = NULL, *btmp = NULL;
197     X509_ALGOR *xa = NULL;
198     const EVP_CIPHER *evp_cipher = NULL;
199     STACK_OF(X509_ALGOR) *md_sk = NULL;
200     STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
201     X509_ALGOR *xalg = NULL;
202     PKCS7_RECIP_INFO *ri = NULL;
203     ASN1_OCTET_STRING *os = NULL;
204
205     if (p7 == NULL) {
206         PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_INVALID_NULL_POINTER);
207         return NULL;
208     }
209     /*
210      * The content field in the PKCS7 ContentInfo is optional, but that really
211      * only applies to inner content (precisely, detached signatures).
212      *
213      * When reading content, missing outer content is therefore treated as an
214      * error.
215      *
216      * When creating content, PKCS7_content_new() must be called before
217      * calling this method, so a NULL p7->d is always an error.
218      */
219     if (p7->d.ptr == NULL) {
220         PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_NO_CONTENT);
221         return NULL;
222     }
223
224     i = OBJ_obj2nid(p7->type);
225     p7->state = PKCS7_S_HEADER;
226
227     switch (i) {
228     case NID_pkcs7_signed:
229         md_sk = p7->d.sign->md_algs;
230         os = PKCS7_get_octet_string(p7->d.sign->contents);
231         break;
232     case NID_pkcs7_signedAndEnveloped:
233         rsk = p7->d.signed_and_enveloped->recipientinfo;
234         md_sk = p7->d.signed_and_enveloped->md_algs;
235         xalg = p7->d.signed_and_enveloped->enc_data->algorithm;
236         evp_cipher = p7->d.signed_and_enveloped->enc_data->cipher;
237         if (evp_cipher == NULL) {
238             PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED);
239             goto err;
240         }
241         break;
242     case NID_pkcs7_enveloped:
243         rsk = p7->d.enveloped->recipientinfo;
244         xalg = p7->d.enveloped->enc_data->algorithm;
245         evp_cipher = p7->d.enveloped->enc_data->cipher;
246         if (evp_cipher == NULL) {
247             PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED);
248             goto err;
249         }
250         break;
251     case NID_pkcs7_digest:
252         xa = p7->d.digest->md;
253         os = PKCS7_get_octet_string(p7->d.digest->contents);
254         break;
255     case NID_pkcs7_data:
256         break;
257     default:
258         PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
259         goto err;
260     }
261
262     for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++)
263         if (!PKCS7_bio_add_digest(&out, sk_X509_ALGOR_value(md_sk, i)))
264             goto err;
265
266     if (xa && !PKCS7_bio_add_digest(&out, xa))
267         goto err;
268
269     if (evp_cipher != NULL) {
270         unsigned char key[EVP_MAX_KEY_LENGTH];
271         unsigned char iv[EVP_MAX_IV_LENGTH];
272         int keylen, ivlen;
273         EVP_CIPHER_CTX *ctx;
274
275         if ((btmp = BIO_new(BIO_f_cipher())) == NULL) {
276             PKCS7err(PKCS7_F_PKCS7_DATAINIT, ERR_R_BIO_LIB);
277             goto err;
278         }
279         BIO_get_cipher_ctx(btmp, &ctx);
280         keylen = EVP_CIPHER_key_length(evp_cipher);
281         ivlen = EVP_CIPHER_iv_length(evp_cipher);
282         xalg->algorithm = OBJ_nid2obj(EVP_CIPHER_type(evp_cipher));
283         if (ivlen > 0)
284             if (RAND_bytes(iv, ivlen) <= 0)
285                 goto err;
286         if (EVP_CipherInit_ex(ctx, evp_cipher, NULL, NULL, NULL, 1) <= 0)
287             goto err;
288         if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
289             goto err;
290         if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1) <= 0)
291             goto err;
292
293         if (ivlen > 0) {
294             if (xalg->parameter == NULL) {
295                 xalg->parameter = ASN1_TYPE_new();
296                 if (xalg->parameter == NULL)
297                     goto err;
298             }
299             if (EVP_CIPHER_param_to_asn1(ctx, xalg->parameter) < 0)
300                 goto err;
301         }
302
303         /* Lets do the pub key stuff :-) */
304         for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
305             ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
306             if (pkcs7_encode_rinfo(ri, key, keylen) <= 0)
307                 goto err;
308         }
309         OPENSSL_cleanse(key, keylen);
310
311         if (out == NULL)
312             out = btmp;
313         else
314             BIO_push(out, btmp);
315         btmp = NULL;
316     }
317
318     if (bio == NULL) {
319         if (PKCS7_is_detached(p7))
320             bio = BIO_new(BIO_s_null());
321         else if (os && os->length > 0)
322             bio = BIO_new_mem_buf(os->data, os->length);
323         if (bio == NULL) {
324             bio = BIO_new(BIO_s_mem());
325             if (bio == NULL)
326                 goto err;
327             BIO_set_mem_eof_return(bio, 0);
328         }
329     }
330     if (out)
331         BIO_push(out, bio);
332     else
333         out = bio;
334     return out;
335
336  err:
337     BIO_free_all(out);
338     BIO_free_all(btmp);
339     return NULL;
340 }
341
342 static int pkcs7_cmp_ri(PKCS7_RECIP_INFO *ri, X509 *pcert)
343 {
344     int ret;
345     ret = X509_NAME_cmp(ri->issuer_and_serial->issuer,
346                         X509_get_issuer_name(pcert));
347     if (ret)
348         return ret;
349     return ASN1_INTEGER_cmp(X509_get_serialNumber(pcert),
350                             ri->issuer_and_serial->serial);
351 }
352
353 /* int */
354 BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)
355 {
356     int i, j;
357     BIO *out = NULL, *btmp = NULL, *etmp = NULL, *bio = NULL;
358     X509_ALGOR *xa;
359     ASN1_OCTET_STRING *data_body = NULL;
360     const EVP_MD *evp_md;
361     const EVP_CIPHER *evp_cipher = NULL;
362     EVP_CIPHER_CTX *evp_ctx = NULL;
363     X509_ALGOR *enc_alg = NULL;
364     STACK_OF(X509_ALGOR) *md_sk = NULL;
365     STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
366     PKCS7_RECIP_INFO *ri = NULL;
367     unsigned char *ek = NULL, *tkey = NULL;
368     int eklen = 0, tkeylen = 0;
369
370     if (p7 == NULL) {
371         PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_INVALID_NULL_POINTER);
372         return NULL;
373     }
374
375     if (p7->d.ptr == NULL) {
376         PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);
377         return NULL;
378     }
379
380     i = OBJ_obj2nid(p7->type);
381     p7->state = PKCS7_S_HEADER;
382
383     switch (i) {
384     case NID_pkcs7_signed:
385         /*
386          * p7->d.sign->contents is a PKCS7 structure consisting of a contentType
387          * field and optional content.
388          * data_body is NULL if that structure has no (=detached) content
389          * or if the contentType is wrong (i.e., not "data").
390          */
391         data_body = PKCS7_get_octet_string(p7->d.sign->contents);
392         if (!PKCS7_is_detached(p7) && data_body == NULL) {
393             PKCS7err(PKCS7_F_PKCS7_DATADECODE,
394                      PKCS7_R_INVALID_SIGNED_DATA_TYPE);
395             goto err;
396         }
397         md_sk = p7->d.sign->md_algs;
398         break;
399     case NID_pkcs7_signedAndEnveloped:
400         rsk = p7->d.signed_and_enveloped->recipientinfo;
401         md_sk = p7->d.signed_and_enveloped->md_algs;
402         /* data_body is NULL if the optional EncryptedContent is missing. */
403         data_body = p7->d.signed_and_enveloped->enc_data->enc_data;
404         enc_alg = p7->d.signed_and_enveloped->enc_data->algorithm;
405         evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);
406         if (evp_cipher == NULL) {
407             PKCS7err(PKCS7_F_PKCS7_DATADECODE,
408                      PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
409             goto err;
410         }
411         break;
412     case NID_pkcs7_enveloped:
413         rsk = p7->d.enveloped->recipientinfo;
414         enc_alg = p7->d.enveloped->enc_data->algorithm;
415         /* data_body is NULL if the optional EncryptedContent is missing. */
416         data_body = p7->d.enveloped->enc_data->enc_data;
417         evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);
418         if (evp_cipher == NULL) {
419             PKCS7err(PKCS7_F_PKCS7_DATADECODE,
420                      PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
421             goto err;
422         }
423         break;
424     default:
425         PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
426         goto err;
427     }
428
429     /* Detached content must be supplied via in_bio instead. */
430     if (data_body == NULL && in_bio == NULL) {
431         PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);
432         goto err;
433     }
434
435     /* We will be checking the signature */
436     if (md_sk != NULL) {
437         for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++) {
438             xa = sk_X509_ALGOR_value(md_sk, i);
439             if ((btmp = BIO_new(BIO_f_md())) == NULL) {
440                 PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);
441                 goto err;
442             }
443
444             j = OBJ_obj2nid(xa->algorithm);
445             evp_md = EVP_get_digestbynid(j);
446             if (evp_md == NULL) {
447                 PKCS7err(PKCS7_F_PKCS7_DATADECODE,
448                          PKCS7_R_UNKNOWN_DIGEST_TYPE);
449                 goto err;
450             }
451
452             BIO_set_md(btmp, evp_md);
453             if (out == NULL)
454                 out = btmp;
455             else
456                 BIO_push(out, btmp);
457             btmp = NULL;
458         }
459     }
460
461     if (evp_cipher != NULL) {
462         if ((etmp = BIO_new(BIO_f_cipher())) == NULL) {
463             PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);
464             goto err;
465         }
466
467         /*
468          * It was encrypted, we need to decrypt the secret key with the
469          * private key
470          */
471
472         /*
473          * Find the recipientInfo which matches the passed certificate (if
474          * any)
475          */
476
477         if (pcert) {
478             for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
479                 ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
480                 if (!pkcs7_cmp_ri(ri, pcert))
481                     break;
482                 ri = NULL;
483             }
484             if (ri == NULL) {
485                 PKCS7err(PKCS7_F_PKCS7_DATADECODE,
486                          PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE);
487                 goto err;
488             }
489         }
490
491         /* If we haven't got a certificate try each ri in turn */
492         if (pcert == NULL) {
493             /*
494              * Always attempt to decrypt all rinfo even after success as a
495              * defence against MMA timing attacks.
496              */
497             for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
498                 ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
499
500                 if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)
501                     goto err;
502                 ERR_clear_error();
503             }
504         } else {
505             /* Only exit on fatal errors, not decrypt failure */
506             if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)
507                 goto err;
508             ERR_clear_error();
509         }
510
511         evp_ctx = NULL;
512         BIO_get_cipher_ctx(etmp, &evp_ctx);
513         if (EVP_CipherInit_ex(evp_ctx, evp_cipher, NULL, NULL, NULL, 0) <= 0)
514             goto err;
515         if (EVP_CIPHER_asn1_to_param(evp_ctx, enc_alg->parameter) < 0)
516             goto err;
517         /* Generate random key as MMA defence */
518         tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);
519         tkey = OPENSSL_malloc(tkeylen);
520         if (tkey == NULL)
521             goto err;
522         if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)
523             goto err;
524         if (ek == NULL) {
525             ek = tkey;
526             eklen = tkeylen;
527             tkey = NULL;
528         }
529
530         if (eklen != EVP_CIPHER_CTX_key_length(evp_ctx)) {
531             /*
532              * Some S/MIME clients don't use the same key and effective key
533              * length. The key length is determined by the size of the
534              * decrypted RSA key.
535              */
536             if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, eklen)) {
537                 /* Use random key as MMA defence */
538                 OPENSSL_clear_free(ek, eklen);
539                 ek = tkey;
540                 eklen = tkeylen;
541                 tkey = NULL;
542             }
543         }
544         /* Clear errors so we don't leak information useful in MMA */
545         ERR_clear_error();
546         if (EVP_CipherInit_ex(evp_ctx, NULL, NULL, ek, NULL, 0) <= 0)
547             goto err;
548
549         OPENSSL_clear_free(ek, eklen);
550         ek = NULL;
551         OPENSSL_clear_free(tkey, tkeylen);
552         tkey = NULL;
553
554         if (out == NULL)
555             out = etmp;
556         else
557             BIO_push(out, etmp);
558         etmp = NULL;
559     }
560     if (in_bio != NULL) {
561         bio = in_bio;
562     } else {
563         if (data_body->length > 0)
564             bio = BIO_new_mem_buf(data_body->data, data_body->length);
565         else {
566             bio = BIO_new(BIO_s_mem());
567             if (bio == NULL)
568                 goto err;
569             BIO_set_mem_eof_return(bio, 0);
570         }
571         if (bio == NULL)
572             goto err;
573     }
574     BIO_push(out, bio);
575     bio = NULL;
576     return out;
577
578  err:
579     OPENSSL_clear_free(ek, eklen);
580     OPENSSL_clear_free(tkey, tkeylen);
581     BIO_free_all(out);
582     BIO_free_all(btmp);
583     BIO_free_all(etmp);
584     BIO_free_all(bio);
585     return NULL;
586 }
587
588 static BIO *PKCS7_find_digest(EVP_MD_CTX **pmd, BIO *bio, int nid)
589 {
590     for (;;) {
591         bio = BIO_find_type(bio, BIO_TYPE_MD);
592         if (bio == NULL) {
593             PKCS7err(PKCS7_F_PKCS7_FIND_DIGEST,
594                      PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
595             return NULL;
596         }
597         BIO_get_md_ctx(bio, pmd);
598         if (*pmd == NULL) {
599             PKCS7err(PKCS7_F_PKCS7_FIND_DIGEST, ERR_R_INTERNAL_ERROR);
600             return NULL;
601         }
602         if (EVP_MD_CTX_type(*pmd) == nid)
603             return bio;
604         bio = BIO_next(bio);
605     }
606     return NULL;
607 }
608
609 static int do_pkcs7_signed_attrib(PKCS7_SIGNER_INFO *si, EVP_MD_CTX *mctx)
610 {
611     unsigned char md_data[EVP_MAX_MD_SIZE];
612     unsigned int md_len;
613
614     /* Add signing time if not already present */
615     if (!PKCS7_get_signed_attribute(si, NID_pkcs9_signingTime)) {
616         if (!PKCS7_add0_attrib_signing_time(si, NULL)) {
617             PKCS7err(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB, ERR_R_MALLOC_FAILURE);
618             return 0;
619         }
620     }
621
622     /* Add digest */
623     if (!EVP_DigestFinal_ex(mctx, md_data, &md_len)) {
624         PKCS7err(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB, ERR_R_EVP_LIB);
625         return 0;
626     }
627     if (!PKCS7_add1_attrib_digest(si, md_data, md_len)) {
628         PKCS7err(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB, ERR_R_MALLOC_FAILURE);
629         return 0;
630     }
631
632     /* Now sign the attributes */
633     if (!PKCS7_SIGNER_INFO_sign(si))
634         return 0;
635
636     return 1;
637 }
638
639 int PKCS7_dataFinal(PKCS7 *p7, BIO *bio)
640 {
641     int ret = 0;
642     int i, j;
643     BIO *btmp;
644     PKCS7_SIGNER_INFO *si;
645     EVP_MD_CTX *mdc, *ctx_tmp;
646     STACK_OF(X509_ATTRIBUTE) *sk;
647     STACK_OF(PKCS7_SIGNER_INFO) *si_sk = NULL;
648     ASN1_OCTET_STRING *os = NULL;
649
650     if (p7 == NULL) {
651         PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_INVALID_NULL_POINTER);
652         return 0;
653     }
654
655     if (p7->d.ptr == NULL) {
656         PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_NO_CONTENT);
657         return 0;
658     }
659
660     ctx_tmp = EVP_MD_CTX_new();
661     if (ctx_tmp == NULL) {
662         PKCS7err(PKCS7_F_PKCS7_DATAFINAL, ERR_R_MALLOC_FAILURE);
663         return 0;
664     }
665
666     i = OBJ_obj2nid(p7->type);
667     p7->state = PKCS7_S_HEADER;
668
669     switch (i) {
670     case NID_pkcs7_data:
671         os = p7->d.data;
672         break;
673     case NID_pkcs7_signedAndEnveloped:
674         /* XXXXXXXXXXXXXXXX */
675         si_sk = p7->d.signed_and_enveloped->signer_info;
676         os = p7->d.signed_and_enveloped->enc_data->enc_data;
677         if (os == NULL) {
678             os = ASN1_OCTET_STRING_new();
679             if (os == NULL) {
680                 PKCS7err(PKCS7_F_PKCS7_DATAFINAL, ERR_R_MALLOC_FAILURE);
681                 goto err;
682             }
683             p7->d.signed_and_enveloped->enc_data->enc_data = os;
684         }
685         break;
686     case NID_pkcs7_enveloped:
687         /* XXXXXXXXXXXXXXXX */
688         os = p7->d.enveloped->enc_data->enc_data;
689         if (os == NULL) {
690             os = ASN1_OCTET_STRING_new();
691             if (os == NULL) {
692                 PKCS7err(PKCS7_F_PKCS7_DATAFINAL, ERR_R_MALLOC_FAILURE);
693                 goto err;
694             }
695             p7->d.enveloped->enc_data->enc_data = os;
696         }
697         break;
698     case NID_pkcs7_signed:
699         si_sk = p7->d.sign->signer_info;
700         os = PKCS7_get_octet_string(p7->d.sign->contents);
701         /* If detached data then the content is excluded */
702         if (PKCS7_type_is_data(p7->d.sign->contents) && p7->detached) {
703             ASN1_OCTET_STRING_free(os);
704             os = NULL;
705             p7->d.sign->contents->d.data = NULL;
706         }
707         break;
708
709     case NID_pkcs7_digest:
710         os = PKCS7_get_octet_string(p7->d.digest->contents);
711         /* If detached data then the content is excluded */
712         if (PKCS7_type_is_data(p7->d.digest->contents) && p7->detached) {
713             ASN1_OCTET_STRING_free(os);
714             os = NULL;
715             p7->d.digest->contents->d.data = NULL;
716         }
717         break;
718
719     default:
720         PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
721         goto err;
722     }
723
724     if (si_sk != NULL) {
725         for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(si_sk); i++) {
726             si = sk_PKCS7_SIGNER_INFO_value(si_sk, i);
727             if (si->pkey == NULL)
728                 continue;
729
730             j = OBJ_obj2nid(si->digest_alg->algorithm);
731
732             btmp = bio;
733
734             btmp = PKCS7_find_digest(&mdc, btmp, j);
735
736             if (btmp == NULL)
737                 goto err;
738
739             /*
740              * We now have the EVP_MD_CTX, lets do the signing.
741              */
742             if (!EVP_MD_CTX_copy_ex(ctx_tmp, mdc))
743                 goto err;
744
745             sk = si->auth_attr;
746
747             /*
748              * If there are attributes, we add the digest attribute and only
749              * sign the attributes
750              */
751             if (sk_X509_ATTRIBUTE_num(sk) > 0) {
752                 if (!do_pkcs7_signed_attrib(si, ctx_tmp))
753                     goto err;
754             } else {
755                 unsigned char *abuf = NULL;
756                 unsigned int abuflen;
757                 abuflen = EVP_PKEY_size(si->pkey);
758                 abuf = OPENSSL_malloc(abuflen);
759                 if (abuf == NULL)
760                     goto err;
761
762                 if (!EVP_SignFinal(ctx_tmp, abuf, &abuflen, si->pkey)) {
763                     OPENSSL_free(abuf);
764                     PKCS7err(PKCS7_F_PKCS7_DATAFINAL, ERR_R_EVP_LIB);
765                     goto err;
766                 }
767                 ASN1_STRING_set0(si->enc_digest, abuf, abuflen);
768             }
769         }
770     } else if (i == NID_pkcs7_digest) {
771         unsigned char md_data[EVP_MAX_MD_SIZE];
772         unsigned int md_len;
773         if (!PKCS7_find_digest(&mdc, bio,
774                                OBJ_obj2nid(p7->d.digest->md->algorithm)))
775             goto err;
776         if (!EVP_DigestFinal_ex(mdc, md_data, &md_len))
777             goto err;
778         if (!ASN1_OCTET_STRING_set(p7->d.digest->digest, md_data, md_len))
779             goto err;
780     }
781
782     if (!PKCS7_is_detached(p7)) {
783         /*
784          * NOTE(emilia): I think we only reach os == NULL here because detached
785          * digested data support is broken.
786          */
787         if (os == NULL)
788             goto err;
789         if (!(os->flags & ASN1_STRING_FLAG_NDEF)) {
790             char *cont;
791             long contlen;
792             btmp = BIO_find_type(bio, BIO_TYPE_MEM);
793             if (btmp == NULL) {
794                 PKCS7err(PKCS7_F_PKCS7_DATAFINAL, PKCS7_R_UNABLE_TO_FIND_MEM_BIO);
795                 goto err;
796             }
797             contlen = BIO_get_mem_data(btmp, &cont);
798             /*
799              * Mark the BIO read only then we can use its copy of the data
800              * instead of making an extra copy.
801              */
802             BIO_set_flags(btmp, BIO_FLAGS_MEM_RDONLY);
803             BIO_set_mem_eof_return(btmp, 0);
804             ASN1_STRING_set0(os, (unsigned char *)cont, contlen);
805         }
806     }
807     ret = 1;
808  err:
809     EVP_MD_CTX_free(ctx_tmp);
810     return (ret);
811 }
812
813 int PKCS7_SIGNER_INFO_sign(PKCS7_SIGNER_INFO *si)
814 {
815     EVP_MD_CTX *mctx;
816     EVP_PKEY_CTX *pctx = NULL;
817     unsigned char *abuf = NULL;
818     int alen;
819     size_t siglen;
820     const EVP_MD *md = NULL;
821
822     md = EVP_get_digestbyobj(si->digest_alg->algorithm);
823     if (md == NULL)
824         return 0;
825
826     mctx = EVP_MD_CTX_new();
827     if (mctx == NULL) {
828         PKCS7err(PKCS7_F_PKCS7_SIGNER_INFO_SIGN, ERR_R_MALLOC_FAILURE);
829         goto err;
830     }
831
832     if (EVP_DigestSignInit(mctx, &pctx, md, NULL, si->pkey) <= 0)
833         goto err;
834
835     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
836                           EVP_PKEY_CTRL_PKCS7_SIGN, 0, si) <= 0) {
837         PKCS7err(PKCS7_F_PKCS7_SIGNER_INFO_SIGN, PKCS7_R_CTRL_ERROR);
838         goto err;
839     }
840
841     alen = ASN1_item_i2d((ASN1_VALUE *)si->auth_attr, &abuf,
842                          ASN1_ITEM_rptr(PKCS7_ATTR_SIGN));
843     if (!abuf)
844         goto err;
845     if (EVP_DigestSignUpdate(mctx, abuf, alen) <= 0)
846         goto err;
847     OPENSSL_free(abuf);
848     abuf = NULL;
849     if (EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0)
850         goto err;
851     abuf = OPENSSL_malloc(siglen);
852     if (abuf == NULL)
853         goto err;
854     if (EVP_DigestSignFinal(mctx, abuf, &siglen) <= 0)
855         goto err;
856
857     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
858                           EVP_PKEY_CTRL_PKCS7_SIGN, 1, si) <= 0) {
859         PKCS7err(PKCS7_F_PKCS7_SIGNER_INFO_SIGN, PKCS7_R_CTRL_ERROR);
860         goto err;
861     }
862
863     EVP_MD_CTX_free(mctx);
864
865     ASN1_STRING_set0(si->enc_digest, abuf, siglen);
866
867     return 1;
868
869  err:
870     OPENSSL_free(abuf);
871     EVP_MD_CTX_free(mctx);
872     return 0;
873
874 }
875
876 int PKCS7_dataVerify(X509_STORE *cert_store, X509_STORE_CTX *ctx, BIO *bio,
877                      PKCS7 *p7, PKCS7_SIGNER_INFO *si)
878 {
879     PKCS7_ISSUER_AND_SERIAL *ias;
880     int ret = 0, i;
881     STACK_OF(X509) *cert;
882     X509 *x509;
883
884     if (p7 == NULL) {
885         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, PKCS7_R_INVALID_NULL_POINTER);
886         return 0;
887     }
888
889     if (p7->d.ptr == NULL) {
890         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, PKCS7_R_NO_CONTENT);
891         return 0;
892     }
893
894     if (PKCS7_type_is_signed(p7)) {
895         cert = p7->d.sign->cert;
896     } else if (PKCS7_type_is_signedAndEnveloped(p7)) {
897         cert = p7->d.signed_and_enveloped->cert;
898     } else {
899         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, PKCS7_R_WRONG_PKCS7_TYPE);
900         goto err;
901     }
902     /* XXXXXXXXXXXXXXXXXXXXXXX */
903     ias = si->issuer_and_serial;
904
905     x509 = X509_find_by_issuer_and_serial(cert, ias->issuer, ias->serial);
906
907     /* were we able to find the cert in passed to us */
908     if (x509 == NULL) {
909         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY,
910                  PKCS7_R_UNABLE_TO_FIND_CERTIFICATE);
911         goto err;
912     }
913
914     /* Lets verify */
915     if (!X509_STORE_CTX_init(ctx, cert_store, x509, cert)) {
916         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, ERR_R_X509_LIB);
917         goto err;
918     }
919     X509_STORE_CTX_set_purpose(ctx, X509_PURPOSE_SMIME_SIGN);
920     i = X509_verify_cert(ctx);
921     if (i <= 0) {
922         PKCS7err(PKCS7_F_PKCS7_DATAVERIFY, ERR_R_X509_LIB);
923         X509_STORE_CTX_cleanup(ctx);
924         goto err;
925     }
926     X509_STORE_CTX_cleanup(ctx);
927
928     return PKCS7_signatureVerify(bio, p7, si, x509);
929  err:
930     return ret;
931 }
932
933 int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si,
934                           X509 *x509)
935 {
936     ASN1_OCTET_STRING *os;
937     EVP_MD_CTX *mdc_tmp, *mdc;
938     int ret = 0, i;
939     int md_type;
940     STACK_OF(X509_ATTRIBUTE) *sk;
941     BIO *btmp;
942     EVP_PKEY *pkey;
943
944     mdc_tmp = EVP_MD_CTX_new();
945     if (mdc_tmp == NULL) {
946         PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, ERR_R_MALLOC_FAILURE);
947         goto err;
948     }
949
950     if (!PKCS7_type_is_signed(p7) && !PKCS7_type_is_signedAndEnveloped(p7)) {
951         PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_WRONG_PKCS7_TYPE);
952         goto err;
953     }
954
955     md_type = OBJ_obj2nid(si->digest_alg->algorithm);
956
957     btmp = bio;
958     for (;;) {
959         if ((btmp == NULL) ||
960             ((btmp = BIO_find_type(btmp, BIO_TYPE_MD)) == NULL)) {
961             PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
962                      PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
963             goto err;
964         }
965         BIO_get_md_ctx(btmp, &mdc);
966         if (mdc == NULL) {
967             PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, ERR_R_INTERNAL_ERROR);
968             goto err;
969         }
970         if (EVP_MD_CTX_type(mdc) == md_type)
971             break;
972         /*
973          * Workaround for some broken clients that put the signature OID
974          * instead of the digest OID in digest_alg->algorithm
975          */
976         if (EVP_MD_pkey_type(EVP_MD_CTX_md(mdc)) == md_type)
977             break;
978         btmp = BIO_next(btmp);
979     }
980
981     /*
982      * mdc is the digest ctx that we want, unless there are attributes, in
983      * which case the digest is the signed attributes
984      */
985     if (!EVP_MD_CTX_copy_ex(mdc_tmp, mdc))
986         goto err;
987
988     sk = si->auth_attr;
989     if ((sk != NULL) && (sk_X509_ATTRIBUTE_num(sk) != 0)) {
990         unsigned char md_dat[EVP_MAX_MD_SIZE], *abuf = NULL;
991         unsigned int md_len;
992         int alen;
993         ASN1_OCTET_STRING *message_digest;
994
995         if (!EVP_DigestFinal_ex(mdc_tmp, md_dat, &md_len))
996             goto err;
997         message_digest = PKCS7_digest_from_attributes(sk);
998         if (!message_digest) {
999             PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY,
1000                      PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST);
1001             goto err;
1002         }
1003         if ((message_digest->length != (int)md_len) ||
1004             (memcmp(message_digest->data, md_dat, md_len))) {
1005             PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_DIGEST_FAILURE);
1006             ret = -1;
1007             goto err;
1008         }
1009
1010         if (!EVP_VerifyInit_ex(mdc_tmp, EVP_get_digestbynid(md_type), NULL))
1011             goto err;
1012
1013         alen = ASN1_item_i2d((ASN1_VALUE *)sk, &abuf,
1014                              ASN1_ITEM_rptr(PKCS7_ATTR_VERIFY));
1015         if (alen <= 0) {
1016             PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, ERR_R_ASN1_LIB);
1017             ret = -1;
1018             goto err;
1019         }
1020         if (!EVP_VerifyUpdate(mdc_tmp, abuf, alen))
1021             goto err;
1022
1023         OPENSSL_free(abuf);
1024     }
1025
1026     os = si->enc_digest;
1027     pkey = X509_get0_pubkey(x509);
1028     if (!pkey) {
1029         ret = -1;
1030         goto err;
1031     }
1032
1033     i = EVP_VerifyFinal(mdc_tmp, os->data, os->length, pkey);
1034     if (i <= 0) {
1035         PKCS7err(PKCS7_F_PKCS7_SIGNATUREVERIFY, PKCS7_R_SIGNATURE_FAILURE);
1036         ret = -1;
1037         goto err;
1038     }
1039     ret = 1;
1040  err:
1041     EVP_MD_CTX_free(mdc_tmp);
1042     return (ret);
1043 }
1044
1045 PKCS7_ISSUER_AND_SERIAL *PKCS7_get_issuer_and_serial(PKCS7 *p7, int idx)
1046 {
1047     STACK_OF(PKCS7_RECIP_INFO) *rsk;
1048     PKCS7_RECIP_INFO *ri;
1049     int i;
1050
1051     i = OBJ_obj2nid(p7->type);
1052     if (i != NID_pkcs7_signedAndEnveloped)
1053         return NULL;
1054     if (p7->d.signed_and_enveloped == NULL)
1055         return NULL;
1056     rsk = p7->d.signed_and_enveloped->recipientinfo;
1057     if (rsk == NULL)
1058         return NULL;
1059     if (sk_PKCS7_RECIP_INFO_num(rsk) <= idx)
1060         return (NULL);
1061     ri = sk_PKCS7_RECIP_INFO_value(rsk, idx);
1062     return (ri->issuer_and_serial);
1063 }
1064
1065 ASN1_TYPE *PKCS7_get_signed_attribute(PKCS7_SIGNER_INFO *si, int nid)
1066 {
1067     return (get_attribute(si->auth_attr, nid));
1068 }
1069
1070 ASN1_TYPE *PKCS7_get_attribute(PKCS7_SIGNER_INFO *si, int nid)
1071 {
1072     return (get_attribute(si->unauth_attr, nid));
1073 }
1074
1075 static ASN1_TYPE *get_attribute(STACK_OF(X509_ATTRIBUTE) *sk, int nid)
1076 {
1077     int idx;
1078     X509_ATTRIBUTE *xa;
1079     idx = X509at_get_attr_by_NID(sk, nid, -1);
1080     xa = X509at_get_attr(sk, idx);
1081     return X509_ATTRIBUTE_get0_type(xa, 0);
1082 }
1083
1084 ASN1_OCTET_STRING *PKCS7_digest_from_attributes(STACK_OF(X509_ATTRIBUTE) *sk)
1085 {
1086     ASN1_TYPE *astype;
1087     if ((astype = get_attribute(sk, NID_pkcs9_messageDigest)) == NULL)
1088         return NULL;
1089     return astype->value.octet_string;
1090 }
1091
1092 int PKCS7_set_signed_attributes(PKCS7_SIGNER_INFO *p7si,
1093                                 STACK_OF(X509_ATTRIBUTE) *sk)
1094 {
1095     int i;
1096
1097     sk_X509_ATTRIBUTE_pop_free(p7si->auth_attr, X509_ATTRIBUTE_free);
1098     p7si->auth_attr = sk_X509_ATTRIBUTE_dup(sk);
1099     if (p7si->auth_attr == NULL)
1100         return 0;
1101     for (i = 0; i < sk_X509_ATTRIBUTE_num(sk); i++) {
1102         if ((sk_X509_ATTRIBUTE_set(p7si->auth_attr, i,
1103                                    X509_ATTRIBUTE_dup(sk_X509_ATTRIBUTE_value
1104                                                       (sk, i))))
1105             == NULL)
1106             return (0);
1107     }
1108     return 1;
1109 }
1110
1111 int PKCS7_set_attributes(PKCS7_SIGNER_INFO *p7si,
1112                          STACK_OF(X509_ATTRIBUTE) *sk)
1113 {
1114     int i;
1115
1116     sk_X509_ATTRIBUTE_pop_free(p7si->unauth_attr, X509_ATTRIBUTE_free);
1117     p7si->unauth_attr = sk_X509_ATTRIBUTE_dup(sk);
1118     if (p7si->unauth_attr == NULL)
1119         return 0;
1120     for (i = 0; i < sk_X509_ATTRIBUTE_num(sk); i++) {
1121         if ((sk_X509_ATTRIBUTE_set(p7si->unauth_attr, i,
1122                                    X509_ATTRIBUTE_dup(sk_X509_ATTRIBUTE_value
1123                                                       (sk, i))))
1124             == NULL)
1125             return (0);
1126     }
1127     return 1;
1128 }
1129
1130 int PKCS7_add_signed_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
1131                                void *value)
1132 {
1133     return (add_attribute(&(p7si->auth_attr), nid, atrtype, value));
1134 }
1135
1136 int PKCS7_add_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
1137                         void *value)
1138 {
1139     return (add_attribute(&(p7si->unauth_attr), nid, atrtype, value));
1140 }
1141
1142 static int add_attribute(STACK_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype,
1143                          void *value)
1144 {
1145     X509_ATTRIBUTE *attr = NULL;
1146
1147     if (*sk == NULL) {
1148         if ((*sk = sk_X509_ATTRIBUTE_new_null()) == NULL)
1149             return 0;
1150  new_attrib:
1151         if ((attr = X509_ATTRIBUTE_create(nid, atrtype, value)) == NULL)
1152             return 0;
1153         if (!sk_X509_ATTRIBUTE_push(*sk, attr)) {
1154             X509_ATTRIBUTE_free(attr);
1155             return 0;
1156         }
1157     } else {
1158         int i;
1159
1160         for (i = 0; i < sk_X509_ATTRIBUTE_num(*sk); i++) {
1161             attr = sk_X509_ATTRIBUTE_value(*sk, i);
1162             if (OBJ_obj2nid(X509_ATTRIBUTE_get0_object(attr)) == nid) {
1163                 X509_ATTRIBUTE_free(attr);
1164                 attr = X509_ATTRIBUTE_create(nid, atrtype, value);
1165                 if (attr == NULL)
1166                     return 0;
1167                 if (!sk_X509_ATTRIBUTE_set(*sk, i, attr)) {
1168                     X509_ATTRIBUTE_free(attr);
1169                     return 0;
1170                 }
1171                 goto end;
1172             }
1173         }
1174         goto new_attrib;
1175     }
1176  end:
1177     return 1;
1178 }