tolerate broken CMS/PKCS7 implementations using signature OID instead of digest
[openssl.git] / crypto / cms / cms_pwri.c
1 /* crypto/cms/cms_pwri.c */
2 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project.
4  */
5 /* ====================================================================
6  * Copyright (c) 2009 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer. 
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  */
53
54 #include "cryptlib.h"
55 #include <openssl/asn1t.h>
56 #include <openssl/pem.h>
57 #include <openssl/x509v3.h>
58 #include <openssl/err.h>
59 #include <openssl/cms.h>
60 #include <openssl/rand.h>
61 #include <openssl/aes.h>
62 #include "cms_lcl.h"
63 #include "asn1_locl.h"
64
65 int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, 
66                                 unsigned char *pass, ssize_t passlen)
67         {
68         CMS_PasswordRecipientInfo *pwri;
69         if (ri->type != CMS_RECIPINFO_PASS)
70                 {
71                 CMSerr(CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD, CMS_R_NOT_PWRI);
72                 return 0;
73                 }
74
75         pwri = ri->d.pwri;
76         pwri->pass = pass;
77         if (pass && passlen < 0)
78                 passlen = strlen((char *)pass);
79         pwri->passlen = passlen;
80         return 1;
81         }
82
83 CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms,
84                                         int iter, int wrap_nid, int pbe_nid,
85                                         unsigned char *pass, ssize_t passlen,
86                                         const EVP_CIPHER *kekciph)
87         {
88         CMS_RecipientInfo *ri = NULL;
89         CMS_EnvelopedData *env;
90         CMS_PasswordRecipientInfo *pwri;
91         EVP_CIPHER_CTX ctx;
92         X509_ALGOR *encalg = NULL;
93         unsigned char iv[EVP_MAX_IV_LENGTH];
94         int ivlen;
95         env = cms_get0_enveloped(cms);
96         if (!env)
97                 goto err;
98
99         if (wrap_nid <= 0)
100                 wrap_nid = NID_id_alg_PWRI_KEK;
101
102         if (pbe_nid <= 0)
103                 pbe_nid = NID_id_pbkdf2;
104
105         /* Get from enveloped data */
106         if (kekciph == NULL)
107                 kekciph = env->encryptedContentInfo->cipher;
108
109         if (kekciph == NULL)
110                 {
111                 CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD, CMS_R_NO_CIPHER);
112                 return NULL;
113                 }
114         if (wrap_nid != NID_id_alg_PWRI_KEK)
115                 {
116                 CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD,
117                                 CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM);
118                 return NULL;
119                 }
120
121         /* Setup algorithm identifier for cipher */
122         encalg = X509_ALGOR_new();
123         EVP_CIPHER_CTX_init(&ctx);
124
125         if (EVP_EncryptInit_ex(&ctx, kekciph, NULL, NULL, NULL) <= 0)
126                 {
127                 CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD, ERR_R_EVP_LIB);
128                 goto err;
129                 }
130
131         ivlen = EVP_CIPHER_CTX_iv_length(&ctx);
132
133         if (ivlen > 0)
134                 {
135                 if (RAND_pseudo_bytes(iv, ivlen) <= 0)
136                         goto err;
137                 if (EVP_EncryptInit_ex(&ctx, NULL, NULL, NULL, iv) <= 0)
138                         {
139                         CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD,
140                                                         ERR_R_EVP_LIB);
141                         goto err;
142                         }
143                 encalg->parameter = ASN1_TYPE_new();
144                 if (!encalg->parameter)
145                         {
146                         CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD,
147                                                         ERR_R_MALLOC_FAILURE);
148                         goto err;
149                         }
150                 if (EVP_CIPHER_param_to_asn1(&ctx, encalg->parameter) <= 0)
151                         {
152                         CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD,
153                                 CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR);
154                         goto err;
155                         }
156                 }
157
158
159         encalg->algorithm = OBJ_nid2obj(EVP_CIPHER_CTX_type(&ctx));
160
161         EVP_CIPHER_CTX_cleanup(&ctx);
162
163         /* Initialize recipient info */
164         ri = M_ASN1_new_of(CMS_RecipientInfo);
165         if (!ri)
166                 goto merr;
167
168         ri->d.pwri = M_ASN1_new_of(CMS_PasswordRecipientInfo);
169         if (!ri->d.pwri)
170                 goto merr;
171         ri->type = CMS_RECIPINFO_PASS;
172
173         pwri = ri->d.pwri;
174         /* Since this is overwritten, free up empty structure already there */
175         X509_ALGOR_free(pwri->keyEncryptionAlgorithm);
176         pwri->keyEncryptionAlgorithm = X509_ALGOR_new();
177         if (!pwri->keyEncryptionAlgorithm)
178                 goto merr;
179         pwri->keyEncryptionAlgorithm->algorithm = OBJ_nid2obj(wrap_nid);
180         pwri->keyEncryptionAlgorithm->parameter = ASN1_TYPE_new();
181         if (!pwri->keyEncryptionAlgorithm->parameter)
182                 goto merr;
183
184         if(!ASN1_item_pack(encalg, ASN1_ITEM_rptr(X509_ALGOR),
185             &pwri->keyEncryptionAlgorithm->parameter->value.sequence))
186                 goto merr;
187         pwri->keyEncryptionAlgorithm->parameter->type = V_ASN1_SEQUENCE;
188
189         X509_ALGOR_free(encalg);
190         encalg = NULL;
191
192         /* Setup PBE algorithm */
193
194         pwri->keyDerivationAlgorithm = PKCS5_pbkdf2_set(iter, NULL, 0, -1, -1);
195
196         if (!pwri->keyDerivationAlgorithm)
197                 goto err;
198
199         CMS_RecipientInfo_set0_password(ri, pass, passlen);
200         pwri->version = 0;
201
202         if (!sk_CMS_RecipientInfo_push(env->recipientInfos, ri))
203                 goto merr;
204
205         return ri;
206
207         merr:
208         CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD, ERR_R_MALLOC_FAILURE);
209         err:
210         EVP_CIPHER_CTX_cleanup(&ctx);
211         if (ri)
212                 M_ASN1_free_of(ri, CMS_RecipientInfo);
213         if (encalg)
214                 X509_ALGOR_free(encalg);
215         return NULL;
216
217         }
218
219 /* This is an implementation of the key wrapping mechanism in RFC3211,
220  * at some point this should go into EVP.
221  */
222
223 static int kek_unwrap_key(unsigned char *out, size_t *outlen,
224                 const unsigned char *in, size_t inlen, EVP_CIPHER_CTX *ctx)
225         {
226         size_t blocklen = EVP_CIPHER_CTX_block_size(ctx);
227         unsigned char *tmp;
228         int outl, rv = 0;
229         if (inlen < 2 * blocklen)
230                 {
231                 /* too small */
232                 return 0;
233                 }
234         if (inlen % blocklen)
235                 {
236                 /* Invalid size */
237                 return 0;
238                 }
239         tmp = OPENSSL_malloc(inlen);
240         /* setup IV by decrypting last two blocks */
241         EVP_DecryptUpdate(ctx, tmp + inlen - 2 * blocklen, &outl,
242                                 in  + inlen - 2 * blocklen, blocklen * 2);
243         /* Do a decrypt of last decrypted block to set IV to correct value
244          * output it to start of buffer so we don't corrupt decrypted block
245          * this works because buffer is at least two block lengths long.
246          */
247         EVP_DecryptUpdate(ctx, tmp, &outl,
248                                 tmp  + inlen - blocklen, blocklen);
249         /* Can now decrypt first n - 1 blocks */
250         EVP_DecryptUpdate(ctx, tmp, &outl, in, inlen - blocklen);
251
252         /* Reset IV to original value */
253         EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL);
254         /* Decrypt again */
255         EVP_DecryptUpdate(ctx, tmp, &outl, tmp, inlen);
256         /* Check check bytes */
257         if (((tmp[1] ^ tmp[4]) & (tmp[2] ^ tmp[5]) & (tmp[3] ^ tmp[6])) != 0xff)
258                 {
259                 /* Check byte failure */
260                 goto err;
261                 }
262         if (inlen < (size_t)(tmp[0] - 4 ))
263                 {
264                 /* Invalid length value */
265                 goto err;
266                 }
267         *outlen = (size_t)tmp[0];
268         memcpy(out, tmp + 4, *outlen);
269         rv = 1;
270         err:
271         OPENSSL_cleanse(tmp, inlen);
272         OPENSSL_free(tmp);
273         return rv;
274
275         }
276
277 static int kek_wrap_key(unsigned char *out, size_t *outlen,
278                 const unsigned char *in, size_t inlen, EVP_CIPHER_CTX *ctx)
279         {
280         size_t blocklen = EVP_CIPHER_CTX_block_size(ctx);
281         size_t olen;
282         int dummy;
283         /* First decide length of output buffer: need header and round up to
284          * multiple of block length.
285          */
286         olen = (inlen + 4 + blocklen - 1)/blocklen;
287         olen *= blocklen;
288         if (olen < 2 * blocklen)
289                 {
290                 /* Key too small */
291                 return 0;
292                 }
293         if (inlen > 0xFF)
294                 {
295                 /* Key too large */
296                 return 0;
297                 }
298         if (out)
299                 {
300                 /* Set header */
301                 out[0] = (unsigned char)inlen;
302                 out[1] = in[0] ^ 0xFF;
303                 out[2] = in[1] ^ 0xFF;
304                 out[3] = in[2] ^ 0xFF;
305                 memcpy(out + 4, in, inlen);
306                 /* Add random padding to end */
307                 if (olen > inlen + 4)
308                         RAND_pseudo_bytes(out + 4 + inlen, olen - 4 - inlen);
309                 /* Encrypt twice */
310                 EVP_EncryptUpdate(ctx, out, &dummy, out, olen);
311                 EVP_EncryptUpdate(ctx, out, &dummy, out, olen);
312                 }
313
314         *outlen = olen;
315
316         return 1;
317         }
318
319 /* Encrypt/Decrypt content key in PWRI recipient info */
320
321 int cms_RecipientInfo_pwri_crypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri,
322                                                         int en_de)
323         {
324         CMS_EncryptedContentInfo *ec;
325         CMS_PasswordRecipientInfo *pwri;
326         const unsigned char *p = NULL;
327         int plen;
328         int r = 0;
329         X509_ALGOR *algtmp, *kekalg = NULL;
330         EVP_CIPHER_CTX kekctx;
331         const EVP_CIPHER *kekcipher;
332         unsigned char *key = NULL;
333         size_t keylen;
334
335         ec = cms->d.envelopedData->encryptedContentInfo;
336
337         pwri = ri->d.pwri;
338         EVP_CIPHER_CTX_init(&kekctx);
339
340         if (!pwri->pass)
341                 {
342                 CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT, CMS_R_NO_PASSWORD);
343                 return 0;
344                 }
345         algtmp = pwri->keyEncryptionAlgorithm;
346
347         if (!algtmp || OBJ_obj2nid(algtmp->algorithm) != NID_id_alg_PWRI_KEK)
348                 {
349                 CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT,
350                                 CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM);
351                 return 0;
352                 }
353
354         if (algtmp->parameter->type == V_ASN1_SEQUENCE)
355                 {
356                 p = algtmp->parameter->value.sequence->data;
357                 plen = algtmp->parameter->value.sequence->length;
358                 kekalg = d2i_X509_ALGOR(NULL, &p, plen);
359                 }
360         if (kekalg == NULL)
361                 {
362                 CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT,
363                                 CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER);
364                 return 0;
365                 }
366
367         kekcipher = EVP_get_cipherbyobj(kekalg->algorithm);
368                 
369         if(!kekcipher)
370                 {
371                 CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT,
372                                 CMS_R_UNKNOWN_CIPHER);
373                 goto err;
374                 }
375
376         /* Fixup cipher based on AlgorithmIdentifier to set IV etc */
377         if (!EVP_CipherInit_ex(&kekctx, kekcipher, NULL, NULL, NULL, en_de))
378                 goto err;
379         EVP_CIPHER_CTX_set_padding(&kekctx, 0);
380         if(EVP_CIPHER_asn1_to_param(&kekctx, kekalg->parameter) < 0)
381                 {
382                 CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT,
383                                 CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR);
384                 goto err;
385                 }
386
387         algtmp = pwri->keyDerivationAlgorithm;
388
389         /* Finish password based key derivation to setup key in "ctx" */
390
391         if (EVP_PBE_CipherInit(algtmp->algorithm,
392                                 (char *)pwri->pass, pwri->passlen,
393                                 algtmp->parameter, &kekctx, en_de) < 0)
394                 {
395                 CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT, ERR_R_EVP_LIB);
396                 goto err;
397                 }
398
399         /* Finally wrap/unwrap the key */
400
401         if (en_de)
402                 {
403
404                 if (!kek_wrap_key(NULL, &keylen, ec->key, ec->keylen, &kekctx))
405                         goto err;
406
407                 key = OPENSSL_malloc(keylen);
408
409                 if (!key)
410                         goto err;
411
412                 if (!kek_wrap_key(key, &keylen, ec->key, ec->keylen, &kekctx))
413                         goto err;
414                 pwri->encryptedKey->data = key;
415                 pwri->encryptedKey->length = keylen;
416                 }
417         else
418                 {
419                 key = OPENSSL_malloc(pwri->encryptedKey->length);
420
421                 if (!key)
422                         {
423                         CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT,
424                                                         ERR_R_MALLOC_FAILURE);
425                         goto err;
426                         }
427                 if (!kek_unwrap_key(key, &keylen,
428                                         pwri->encryptedKey->data,
429                                         pwri->encryptedKey->length, &kekctx))
430                         {
431                         CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT,
432                                                         CMS_R_UNWRAP_FAILURE);
433                         goto err;
434                         }
435
436                 ec->key = key;
437                 ec->keylen = keylen;
438
439                 }
440
441         r = 1;
442
443         err:
444
445         EVP_CIPHER_CTX_cleanup(&kekctx);
446
447         if (!r && key)
448                 OPENSSL_free(key);
449         X509_ALGOR_free(kekalg);
450
451         return r;
452
453         }