3e1328cceaadb83b04dbfc641e4c5f8b09a922ac
[openssl.git] / crypto / cms / cms_pwri.c
1 /*
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 "internal/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 "internal/asn1_int.h"
64
65 int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri,
66                                     unsigned char *pass, ossl_ssize_t passlen)
67 {
68     CMS_PasswordRecipientInfo *pwri;
69     if (ri->type != CMS_RECIPINFO_PASS) {
70         CMSerr(CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD, CMS_R_NOT_PWRI);
71         return 0;
72     }
73
74     pwri = ri->d.pwri;
75     pwri->pass = pass;
76     if (pass && passlen < 0)
77         passlen = strlen((char *)pass);
78     pwri->passlen = passlen;
79     return 1;
80 }
81
82 CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms,
83                                                int iter, int wrap_nid,
84                                                int pbe_nid,
85                                                unsigned char *pass,
86                                                ossl_ssize_t passlen,
87                                                const EVP_CIPHER *kekciph)
88 {
89     CMS_RecipientInfo *ri = NULL;
90     CMS_EnvelopedData *env;
91     CMS_PasswordRecipientInfo *pwri;
92     EVP_CIPHER_CTX *ctx = NULL;
93     X509_ALGOR *encalg = NULL;
94     unsigned char iv[EVP_MAX_IV_LENGTH];
95     int ivlen;
96
97     env = cms_get0_enveloped(cms);
98     if (!env)
99         return NULL;
100
101     if (wrap_nid <= 0)
102         wrap_nid = NID_id_alg_PWRI_KEK;
103
104     if (pbe_nid <= 0)
105         pbe_nid = NID_id_pbkdf2;
106
107     /* Get from enveloped data */
108     if (kekciph == NULL)
109         kekciph = env->encryptedContentInfo->cipher;
110
111     if (kekciph == NULL) {
112         CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD, CMS_R_NO_CIPHER);
113         return NULL;
114     }
115     if (wrap_nid != NID_id_alg_PWRI_KEK) {
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     if (encalg == NULL) {
124         goto merr;
125     }
126     ctx = EVP_CIPHER_CTX_new();
127
128     if (EVP_EncryptInit_ex(ctx, kekciph, NULL, NULL, NULL) <= 0) {
129         CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD, ERR_R_EVP_LIB);
130         goto err;
131     }
132
133     ivlen = EVP_CIPHER_CTX_iv_length(ctx);
134
135     if (ivlen > 0) {
136         if (RAND_bytes(iv, ivlen) <= 0)
137             goto err;
138         if (EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv) <= 0) {
139             CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD, ERR_R_EVP_LIB);
140             goto err;
141         }
142         encalg->parameter = ASN1_TYPE_new();
143         if (!encalg->parameter) {
144             CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD, ERR_R_MALLOC_FAILURE);
145             goto err;
146         }
147         if (EVP_CIPHER_param_to_asn1(ctx, encalg->parameter) <= 0) {
148             CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD,
149                    CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR);
150             goto err;
151         }
152     }
153
154     encalg->algorithm = OBJ_nid2obj(EVP_CIPHER_CTX_type(ctx));
155
156     EVP_CIPHER_CTX_free(ctx);
157     ctx = NULL;
158
159     /* Initialize recipient info */
160     ri = M_ASN1_new_of(CMS_RecipientInfo);
161     if (ri == NULL)
162         goto merr;
163
164     ri->d.pwri = M_ASN1_new_of(CMS_PasswordRecipientInfo);
165     if (ri->d.pwri == NULL)
166         goto merr;
167     ri->type = CMS_RECIPINFO_PASS;
168
169     pwri = ri->d.pwri;
170     /* Since this is overwritten, free up empty structure already there */
171     X509_ALGOR_free(pwri->keyEncryptionAlgorithm);
172     pwri->keyEncryptionAlgorithm = X509_ALGOR_new();
173     if (pwri->keyEncryptionAlgorithm == NULL)
174         goto merr;
175     pwri->keyEncryptionAlgorithm->algorithm = OBJ_nid2obj(wrap_nid);
176     pwri->keyEncryptionAlgorithm->parameter = ASN1_TYPE_new();
177     if (pwri->keyEncryptionAlgorithm->parameter == NULL)
178         goto merr;
179
180     if (!ASN1_item_pack(encalg, ASN1_ITEM_rptr(X509_ALGOR),
181                         &pwri->keyEncryptionAlgorithm->parameter->
182                         value.sequence))
183          goto merr;
184     pwri->keyEncryptionAlgorithm->parameter->type = V_ASN1_SEQUENCE;
185
186     X509_ALGOR_free(encalg);
187     encalg = NULL;
188
189     /* Setup PBE algorithm */
190
191     pwri->keyDerivationAlgorithm = PKCS5_pbkdf2_set(iter, NULL, 0, -1, -1);
192
193     if (!pwri->keyDerivationAlgorithm)
194         goto err;
195
196     CMS_RecipientInfo_set0_password(ri, pass, passlen);
197     pwri->version = 0;
198
199     if (!sk_CMS_RecipientInfo_push(env->recipientInfos, ri))
200         goto merr;
201
202     return ri;
203
204  merr:
205     CMSerr(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD, ERR_R_MALLOC_FAILURE);
206  err:
207     EVP_CIPHER_CTX_free(ctx);
208     if (ri)
209         M_ASN1_free_of(ri, CMS_RecipientInfo);
210     X509_ALGOR_free(encalg);
211     return NULL;
212
213 }
214
215 /*
216  * This is an implementation of the key wrapping mechanism in RFC3211, at
217  * some point this should go into EVP.
218  */
219
220 static int kek_unwrap_key(unsigned char *out, size_t *outlen,
221                           const unsigned char *in, size_t inlen,
222                           EVP_CIPHER_CTX *ctx)
223 {
224     size_t blocklen = EVP_CIPHER_CTX_block_size(ctx);
225     unsigned char *tmp;
226     int outl, rv = 0;
227     if (inlen < 2 * blocklen) {
228         /* too small */
229         return 0;
230     }
231     if (inlen % blocklen) {
232         /* Invalid size */
233         return 0;
234     }
235     tmp = OPENSSL_malloc(inlen);
236     if (tmp == NULL)
237         return 0;
238     /* setup IV by decrypting last two blocks */
239     if (!EVP_DecryptUpdate(ctx, tmp + inlen - 2 * blocklen, &outl,
240                            in + inlen - 2 * blocklen, blocklen * 2)
241         /*
242          * Do a decrypt of last decrypted block to set IV to correct value
243          * output it to start of buffer so we don't corrupt decrypted block
244          * this works because buffer is at least two block lengths long.
245          */
246         || !EVP_DecryptUpdate(ctx, tmp, &outl,
247                               tmp + inlen - blocklen, blocklen)
248         /* Can now decrypt first n - 1 blocks */
249         || !EVP_DecryptUpdate(ctx, tmp, &outl, in, inlen - blocklen)
250
251         /* Reset IV to original value */
252         || !EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL)
253         /* Decrypt again */
254         || !EVP_DecryptUpdate(ctx, tmp, &outl, tmp, inlen))
255         goto err;
256     /* Check check bytes */
257     if (((tmp[1] ^ tmp[4]) & (tmp[2] ^ tmp[5]) & (tmp[3] ^ tmp[6])) != 0xff) {
258         /* Check byte failure */
259         goto err;
260     }
261     if (inlen < (size_t)(tmp[0] - 4)) {
262         /* Invalid length value */
263         goto err;
264     }
265     *outlen = (size_t)tmp[0];
266     memcpy(out, tmp + 4, *outlen);
267     rv = 1;
268  err:
269     OPENSSL_clear_free(tmp, inlen);
270     return rv;
271
272 }
273
274 static int kek_wrap_key(unsigned char *out, size_t *outlen,
275                         const unsigned char *in, size_t inlen,
276                         EVP_CIPHER_CTX *ctx)
277 {
278     size_t blocklen = EVP_CIPHER_CTX_block_size(ctx);
279     size_t olen;
280     int dummy;
281     /*
282      * First decide length of output buffer: need header and round up to
283      * multiple of block length.
284      */
285     olen = (inlen + 4 + blocklen - 1) / blocklen;
286     olen *= blocklen;
287     if (olen < 2 * blocklen) {
288         /* Key too small */
289         return 0;
290     }
291     if (inlen > 0xFF) {
292         /* Key too large */
293         return 0;
294     }
295     if (out) {
296         /* Set header */
297         out[0] = (unsigned char)inlen;
298         out[1] = in[0] ^ 0xFF;
299         out[2] = in[1] ^ 0xFF;
300         out[3] = in[2] ^ 0xFF;
301         memcpy(out + 4, in, inlen);
302         /* Add random padding to end */
303         if (olen > inlen + 4
304             && RAND_bytes(out + 4 + inlen, olen - 4 - inlen) <= 0)
305             return 0;
306         /* Encrypt twice */
307         if (!EVP_EncryptUpdate(ctx, out, &dummy, out, olen)
308             || !EVP_EncryptUpdate(ctx, out, &dummy, out, olen))
309             return 0;
310     }
311
312     *outlen = olen;
313
314     return 1;
315 }
316
317 /* Encrypt/Decrypt content key in PWRI recipient info */
318
319 int cms_RecipientInfo_pwri_crypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri,
320                                  int en_de)
321 {
322     CMS_EncryptedContentInfo *ec;
323     CMS_PasswordRecipientInfo *pwri;
324     int r = 0;
325     X509_ALGOR *algtmp, *kekalg = NULL;
326     EVP_CIPHER_CTX *kekctx = NULL;
327     const EVP_CIPHER *kekcipher;
328     unsigned char *key = NULL;
329     size_t keylen;
330
331     ec = cms->d.envelopedData->encryptedContentInfo;
332
333     pwri = ri->d.pwri;
334
335     if (!pwri->pass) {
336         CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT, CMS_R_NO_PASSWORD);
337         return 0;
338     }
339     algtmp = pwri->keyEncryptionAlgorithm;
340
341     if (!algtmp || OBJ_obj2nid(algtmp->algorithm) != NID_id_alg_PWRI_KEK) {
342         CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT,
343                CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM);
344         return 0;
345     }
346
347     kekalg = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(X509_ALGOR),
348                                        algtmp->parameter);
349
350     if (kekalg == NULL) {
351         CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT,
352                CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER);
353         return 0;
354     }
355
356     kekcipher = EVP_get_cipherbyobj(kekalg->algorithm);
357
358     if (!kekcipher) {
359         CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT, CMS_R_UNKNOWN_CIPHER);
360         return 0;
361     }
362
363     kekctx = EVP_CIPHER_CTX_new();
364     if (kekctx == NULL) {
365         CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT, ERR_R_MALLOC_FAILURE);
366         return 0;
367     }
368     /* Fixup cipher based on AlgorithmIdentifier to set IV etc */
369     if (!EVP_CipherInit_ex(kekctx, kekcipher, NULL, NULL, NULL, en_de))
370         goto err;
371     EVP_CIPHER_CTX_set_padding(kekctx, 0);
372     if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) < 0) {
373         CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT,
374                CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR);
375         goto err;
376     }
377
378     algtmp = pwri->keyDerivationAlgorithm;
379
380     /* Finish password based key derivation to setup key in "ctx" */
381
382     if (EVP_PBE_CipherInit(algtmp->algorithm,
383                            (char *)pwri->pass, pwri->passlen,
384                            algtmp->parameter, kekctx, en_de) < 0) {
385         CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT, ERR_R_EVP_LIB);
386         goto err;
387     }
388
389     /* Finally wrap/unwrap the key */
390
391     if (en_de) {
392
393         if (!kek_wrap_key(NULL, &keylen, ec->key, ec->keylen, kekctx))
394             goto err;
395
396         key = OPENSSL_malloc(keylen);
397
398         if (key == NULL)
399             goto err;
400
401         if (!kek_wrap_key(key, &keylen, ec->key, ec->keylen, kekctx))
402             goto err;
403         pwri->encryptedKey->data = key;
404         pwri->encryptedKey->length = keylen;
405     } else {
406         key = OPENSSL_malloc(pwri->encryptedKey->length);
407
408         if (key == NULL) {
409             CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT, ERR_R_MALLOC_FAILURE);
410             goto err;
411         }
412         if (!kek_unwrap_key(key, &keylen,
413                             pwri->encryptedKey->data,
414                             pwri->encryptedKey->length, kekctx)) {
415             CMSerr(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT, CMS_R_UNWRAP_FAILURE);
416             goto err;
417         }
418
419         ec->key = key;
420         ec->keylen = keylen;
421
422     }
423
424     r = 1;
425
426  err:
427
428     EVP_CIPHER_CTX_free(kekctx);
429
430     if (!r)
431         OPENSSL_free(key);
432     X509_ALGOR_free(kekalg);
433
434     return r;
435
436 }