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