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