a27828056379ffdbd0528c755a8fe730e8a8aee1
[openssl.git] / crypto / cms / cms_pwri.c
1 /*
2  * Copyright 2009-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 "internal/cryptlib.h"
11 #include <openssl/asn1t.h>
12 #include <openssl/pem.h>
13 #include <openssl/x509v3.h>
14 #include <openssl/err.h>
15 #include <openssl/cms.h>
16 #include <openssl/rand.h>
17 #include <openssl/aes.h>
18 #include "internal/sizes.h"
19 #include "crypto/asn1.h"
20 #include "cms_local.h"
21
22 int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri,
23                                     unsigned char *pass, ossl_ssize_t passlen)
24 {
25     CMS_PasswordRecipientInfo *pwri;
26     if (ri->type != CMS_RECIPINFO_PASS) {
27         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_PWRI);
28         return 0;
29     }
30
31     pwri = ri->d.pwri;
32     pwri->pass = pass;
33     if (pass && passlen < 0)
34         passlen = strlen((char *)pass);
35     pwri->passlen = passlen;
36     return 1;
37 }
38
39 CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms,
40                                                int iter, int wrap_nid,
41                                                int pbe_nid,
42                                                unsigned char *pass,
43                                                ossl_ssize_t passlen,
44                                                const EVP_CIPHER *kekciph)
45 {
46     STACK_OF(CMS_RecipientInfo) *ris;
47     CMS_RecipientInfo *ri = NULL;
48     CMS_EncryptedContentInfo *ec;
49     CMS_PasswordRecipientInfo *pwri;
50     EVP_CIPHER_CTX *ctx = NULL;
51     X509_ALGOR *encalg = NULL;
52     unsigned char iv[EVP_MAX_IV_LENGTH];
53     int ivlen;
54     const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
55
56     ec = ossl_cms_get0_env_enc_content(cms);
57     if (ec == NULL)
58         return NULL;
59     ris = CMS_get0_RecipientInfos(cms);
60     if (ris == NULL)
61         return NULL;
62
63     if (wrap_nid <= 0)
64         wrap_nid = NID_id_alg_PWRI_KEK;
65
66     if (pbe_nid <= 0)
67         pbe_nid = NID_id_pbkdf2;
68
69     /* Get from enveloped data */
70     if (kekciph == NULL)
71         kekciph = ec->cipher;
72
73     if (kekciph == NULL) {
74         ERR_raise(ERR_LIB_CMS, CMS_R_NO_CIPHER);
75         return NULL;
76     }
77     if (wrap_nid != NID_id_alg_PWRI_KEK) {
78         ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM);
79         return NULL;
80     }
81
82     /* Setup algorithm identifier for cipher */
83     encalg = X509_ALGOR_new();
84     if (encalg == NULL) {
85         goto merr;
86     }
87     ctx = EVP_CIPHER_CTX_new();
88
89     if (EVP_EncryptInit_ex(ctx, kekciph, NULL, NULL, NULL) <= 0) {
90         ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
91         goto err;
92     }
93
94     ivlen = EVP_CIPHER_CTX_iv_length(ctx);
95
96     if (ivlen > 0) {
97         if (RAND_bytes_ex(ossl_cms_ctx_get0_libctx(cms_ctx), iv, ivlen) <= 0)
98             goto err;
99         if (EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv) <= 0) {
100             ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
101             goto err;
102         }
103         encalg->parameter = ASN1_TYPE_new();
104         if (!encalg->parameter) {
105             ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
106             goto err;
107         }
108         if (EVP_CIPHER_param_to_asn1(ctx, encalg->parameter) <= 0) {
109             ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR);
110             goto err;
111         }
112     }
113
114     encalg->algorithm = OBJ_nid2obj(EVP_CIPHER_CTX_type(ctx));
115
116     EVP_CIPHER_CTX_free(ctx);
117     ctx = NULL;
118
119     /* Initialize recipient info */
120     ri = M_ASN1_new_of(CMS_RecipientInfo);
121     if (ri == NULL)
122         goto merr;
123
124     ri->d.pwri = M_ASN1_new_of(CMS_PasswordRecipientInfo);
125     if (ri->d.pwri == NULL)
126         goto merr;
127     ri->type = CMS_RECIPINFO_PASS;
128
129     pwri = ri->d.pwri;
130     pwri->cms_ctx = cms_ctx;
131     /* Since this is overwritten, free up empty structure already there */
132     X509_ALGOR_free(pwri->keyEncryptionAlgorithm);
133     pwri->keyEncryptionAlgorithm = X509_ALGOR_new();
134     if (pwri->keyEncryptionAlgorithm == NULL)
135         goto merr;
136     pwri->keyEncryptionAlgorithm->algorithm = OBJ_nid2obj(wrap_nid);
137     pwri->keyEncryptionAlgorithm->parameter = ASN1_TYPE_new();
138     if (pwri->keyEncryptionAlgorithm->parameter == NULL)
139         goto merr;
140
141     if (!ASN1_item_pack(encalg, ASN1_ITEM_rptr(X509_ALGOR),
142                         &pwri->keyEncryptionAlgorithm->parameter->
143                         value.sequence))
144          goto merr;
145     pwri->keyEncryptionAlgorithm->parameter->type = V_ASN1_SEQUENCE;
146
147     X509_ALGOR_free(encalg);
148     encalg = NULL;
149
150     /* Setup PBE algorithm */
151
152     pwri->keyDerivationAlgorithm = PKCS5_pbkdf2_set(iter, NULL, 0, -1, -1);
153
154     if (pwri->keyDerivationAlgorithm == NULL)
155         goto err;
156
157     CMS_RecipientInfo_set0_password(ri, pass, passlen);
158     pwri->version = 0;
159
160     if (!sk_CMS_RecipientInfo_push(ris, ri))
161         goto merr;
162
163     return ri;
164
165  merr:
166     ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
167  err:
168     EVP_CIPHER_CTX_free(ctx);
169     if (ri)
170         M_ASN1_free_of(ri, CMS_RecipientInfo);
171     X509_ALGOR_free(encalg);
172     return NULL;
173
174 }
175
176 /*
177  * This is an implementation of the key wrapping mechanism in RFC3211, at
178  * some point this should go into EVP.
179  */
180
181 static int kek_unwrap_key(unsigned char *out, size_t *outlen,
182                           const unsigned char *in, size_t inlen,
183                           EVP_CIPHER_CTX *ctx)
184 {
185     size_t blocklen = EVP_CIPHER_CTX_block_size(ctx);
186     unsigned char *tmp;
187     int outl, rv = 0;
188     if (inlen < 2 * blocklen) {
189         /* too small */
190         return 0;
191     }
192     if (inlen % blocklen) {
193         /* Invalid size */
194         return 0;
195     }
196     if ((tmp = OPENSSL_malloc(inlen)) == NULL) {
197         ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
198         return 0;
199     }
200     /* setup IV by decrypting last two blocks */
201     if (!EVP_DecryptUpdate(ctx, tmp + inlen - 2 * blocklen, &outl,
202                            in + inlen - 2 * blocklen, blocklen * 2)
203         /*
204          * Do a decrypt of last decrypted block to set IV to correct value
205          * output it to start of buffer so we don't corrupt decrypted block
206          * this works because buffer is at least two block lengths long.
207          */
208         || !EVP_DecryptUpdate(ctx, tmp, &outl,
209                               tmp + inlen - blocklen, blocklen)
210         /* Can now decrypt first n - 1 blocks */
211         || !EVP_DecryptUpdate(ctx, tmp, &outl, in, inlen - blocklen)
212
213         /* Reset IV to original value */
214         || !EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL)
215         /* Decrypt again */
216         || !EVP_DecryptUpdate(ctx, tmp, &outl, tmp, inlen))
217         goto err;
218     /* Check check bytes */
219     if (((tmp[1] ^ tmp[4]) & (tmp[2] ^ tmp[5]) & (tmp[3] ^ tmp[6])) != 0xff) {
220         /* Check byte failure */
221         goto err;
222     }
223     if (inlen < (size_t)(tmp[0] - 4)) {
224         /* Invalid length value */
225         goto err;
226     }
227     *outlen = (size_t)tmp[0];
228     memcpy(out, tmp + 4, *outlen);
229     rv = 1;
230  err:
231     OPENSSL_clear_free(tmp, inlen);
232     return rv;
233
234 }
235
236 static int kek_wrap_key(unsigned char *out, size_t *outlen,
237                         const unsigned char *in, size_t inlen,
238                         EVP_CIPHER_CTX *ctx, const CMS_CTX *cms_ctx)
239 {
240     size_t blocklen = EVP_CIPHER_CTX_block_size(ctx);
241     size_t olen;
242     int dummy;
243     /*
244      * First decide length of output buffer: need header and round up to
245      * multiple of block length.
246      */
247     olen = (inlen + 4 + blocklen - 1) / blocklen;
248     olen *= blocklen;
249     if (olen < 2 * blocklen) {
250         /* Key too small */
251         return 0;
252     }
253     if (inlen > 0xFF) {
254         /* Key too large */
255         return 0;
256     }
257     if (out) {
258         /* Set header */
259         out[0] = (unsigned char)inlen;
260         out[1] = in[0] ^ 0xFF;
261         out[2] = in[1] ^ 0xFF;
262         out[3] = in[2] ^ 0xFF;
263         memcpy(out + 4, in, inlen);
264         /* Add random padding to end */
265         if (olen > inlen + 4
266             && RAND_bytes_ex(ossl_cms_ctx_get0_libctx(cms_ctx), out + 4 + inlen,
267                              olen - 4 - inlen) <= 0)
268             return 0;
269         /* Encrypt twice */
270         if (!EVP_EncryptUpdate(ctx, out, &dummy, out, olen)
271             || !EVP_EncryptUpdate(ctx, out, &dummy, out, olen))
272             return 0;
273     }
274
275     *outlen = olen;
276
277     return 1;
278 }
279
280 /* Encrypt/Decrypt content key in PWRI recipient info */
281
282 int ossl_cms_RecipientInfo_pwri_crypt(const CMS_ContentInfo *cms,
283                                       CMS_RecipientInfo *ri, int en_de)
284 {
285     CMS_EncryptedContentInfo *ec;
286     CMS_PasswordRecipientInfo *pwri;
287     int r = 0;
288     X509_ALGOR *algtmp, *kekalg = NULL;
289     EVP_CIPHER_CTX *kekctx = NULL;
290     char name[OSSL_MAX_NAME_SIZE];
291     EVP_CIPHER *kekcipher;
292     unsigned char *key = NULL;
293     size_t keylen;
294     const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
295
296     ec = ossl_cms_get0_env_enc_content(cms);
297
298     pwri = ri->d.pwri;
299
300     if (pwri->pass == NULL) {
301         ERR_raise(ERR_LIB_CMS, CMS_R_NO_PASSWORD);
302         return 0;
303     }
304     algtmp = pwri->keyEncryptionAlgorithm;
305
306     if (!algtmp || OBJ_obj2nid(algtmp->algorithm) != NID_id_alg_PWRI_KEK) {
307         ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM);
308         return 0;
309     }
310
311     kekalg = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(X509_ALGOR),
312                                        algtmp->parameter);
313
314     if (kekalg == NULL) {
315         ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER);
316         return 0;
317     }
318
319     OBJ_obj2txt(name, sizeof(name), kekalg->algorithm, 0);
320     kekcipher = EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(cms_ctx), name,
321                                  ossl_cms_ctx_get0_propq(cms_ctx));
322
323     if (kekcipher == NULL) {
324         ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_CIPHER);
325         goto err;
326     }
327
328     kekctx = EVP_CIPHER_CTX_new();
329     if (kekctx == NULL) {
330         ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
331         goto err;
332     }
333     /* Fixup cipher based on AlgorithmIdentifier to set IV etc */
334     if (!EVP_CipherInit_ex(kekctx, kekcipher, NULL, NULL, NULL, en_de))
335         goto err;
336     EVP_CIPHER_CTX_set_padding(kekctx, 0);
337     if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0) {
338         ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR);
339         goto err;
340     }
341
342     algtmp = pwri->keyDerivationAlgorithm;
343
344     /* Finish password based key derivation to setup key in "ctx" */
345
346     if (EVP_PBE_CipherInit(algtmp->algorithm,
347                            (char *)pwri->pass, pwri->passlen,
348                            algtmp->parameter, kekctx, en_de) < 0) {
349         ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
350         goto err;
351     }
352
353     /* Finally wrap/unwrap the key */
354
355     if (en_de) {
356
357         if (!kek_wrap_key(NULL, &keylen, ec->key, ec->keylen, kekctx, cms_ctx))
358             goto err;
359
360         key = OPENSSL_malloc(keylen);
361
362         if (key == NULL)
363             goto err;
364
365         if (!kek_wrap_key(key, &keylen, ec->key, ec->keylen, kekctx, cms_ctx))
366             goto err;
367         pwri->encryptedKey->data = key;
368         pwri->encryptedKey->length = keylen;
369     } else {
370         key = OPENSSL_malloc(pwri->encryptedKey->length);
371
372         if (key == NULL) {
373             ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
374             goto err;
375         }
376         if (!kek_unwrap_key(key, &keylen,
377                             pwri->encryptedKey->data,
378                             pwri->encryptedKey->length, kekctx)) {
379             ERR_raise(ERR_LIB_CMS, CMS_R_UNWRAP_FAILURE);
380             goto err;
381         }
382
383         OPENSSL_clear_free(ec->key, ec->keylen);
384         ec->key = key;
385         ec->keylen = keylen;
386
387     }
388
389     r = 1;
390
391  err:
392     EVP_CIPHER_free(kekcipher);
393     EVP_CIPHER_CTX_free(kekctx);
394
395     if (!r)
396         OPENSSL_free(key);
397     X509_ALGOR_free(kekalg);
398
399     return r;
400
401 }