free NULL cleanup
[openssl.git] / crypto / cms / cms_kari.c
1 /* crypto/cms/cms_kari.c */
2 /*
3  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
4  * project.
5  */
6 /* ====================================================================
7  * Copyright (c) 2013 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 "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 DECLARE_ASN1_ITEM(CMS_KeyAgreeRecipientInfo)
67 DECLARE_ASN1_ITEM(CMS_RecipientEncryptedKey)
68 DECLARE_ASN1_ITEM(CMS_OriginatorPublicKey)
69
70 /* Key Agreement Recipient Info (KARI) routines */
71
72 int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri,
73                                     X509_ALGOR **palg,
74                                     ASN1_OCTET_STRING **pukm)
75 {
76     if (ri->type != CMS_RECIPINFO_AGREE) {
77         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG,
78                CMS_R_NOT_KEY_AGREEMENT);
79         return 0;
80     }
81     if (palg)
82         *palg = ri->d.kari->keyEncryptionAlgorithm;
83     if (pukm)
84         *pukm = ri->d.kari->ukm;
85     return 1;
86 }
87
88 /* Retrieve recipient encrypted keys from a kari */
89
90 STACK_OF(CMS_RecipientEncryptedKey)
91 *CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri)
92 {
93     if (ri->type != CMS_RECIPINFO_AGREE) {
94         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS,
95                CMS_R_NOT_KEY_AGREEMENT);
96         return NULL;
97     }
98     return ri->d.kari->recipientEncryptedKeys;
99 }
100
101 int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri,
102                                         X509_ALGOR **pubalg,
103                                         ASN1_BIT_STRING **pubkey,
104                                         ASN1_OCTET_STRING **keyid,
105                                         X509_NAME **issuer,
106                                         ASN1_INTEGER **sno)
107 {
108     CMS_OriginatorIdentifierOrKey *oik;
109     if (ri->type != CMS_RECIPINFO_AGREE) {
110         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID,
111                CMS_R_NOT_KEY_AGREEMENT);
112         return 0;
113     }
114     oik = ri->d.kari->originator;
115     if (issuer)
116         *issuer = NULL;
117     if (sno)
118         *sno = NULL;
119     if (keyid)
120         *keyid = NULL;
121     if (pubalg)
122         *pubalg = NULL;
123     if (pubkey)
124         *pubkey = NULL;
125     if (oik->type == CMS_OIK_ISSUER_SERIAL) {
126         if (issuer)
127             *issuer = oik->d.issuerAndSerialNumber->issuer;
128         if (sno)
129             *sno = oik->d.issuerAndSerialNumber->serialNumber;
130     } else if (oik->type == CMS_OIK_KEYIDENTIFIER) {
131         if (keyid)
132             *keyid = oik->d.subjectKeyIdentifier;
133     } else if (oik->type == CMS_OIK_PUBKEY) {
134         if (pubalg)
135             *pubalg = oik->d.originatorKey->algorithm;
136         if (pubkey)
137             *pubkey = oik->d.originatorKey->publicKey;
138     } else
139         return 0;
140     return 1;
141 }
142
143 int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert)
144 {
145     CMS_OriginatorIdentifierOrKey *oik;
146     if (ri->type != CMS_RECIPINFO_AGREE) {
147         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP,
148                CMS_R_NOT_KEY_AGREEMENT);
149         return -2;
150     }
151     oik = ri->d.kari->originator;
152     if (oik->type == CMS_OIK_ISSUER_SERIAL)
153         return cms_ias_cert_cmp(oik->d.issuerAndSerialNumber, cert);
154     else if (oik->type == CMS_OIK_KEYIDENTIFIER)
155         return cms_keyid_cert_cmp(oik->d.subjectKeyIdentifier, cert);
156     return -1;
157 }
158
159 int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek,
160                                       ASN1_OCTET_STRING **keyid,
161                                       ASN1_GENERALIZEDTIME **tm,
162                                       CMS_OtherKeyAttribute **other,
163                                       X509_NAME **issuer, ASN1_INTEGER **sno)
164 {
165     CMS_KeyAgreeRecipientIdentifier *rid = rek->rid;
166     if (rid->type == CMS_REK_ISSUER_SERIAL) {
167         if (issuer)
168             *issuer = rid->d.issuerAndSerialNumber->issuer;
169         if (sno)
170             *sno = rid->d.issuerAndSerialNumber->serialNumber;
171         if (keyid)
172             *keyid = NULL;
173         if (tm)
174             *tm = NULL;
175         if (other)
176             *other = NULL;
177     } else if (rid->type == CMS_REK_KEYIDENTIFIER) {
178         if (keyid)
179             *keyid = rid->d.rKeyId->subjectKeyIdentifier;
180         if (tm)
181             *tm = rid->d.rKeyId->date;
182         if (other)
183             *other = rid->d.rKeyId->other;
184         if (issuer)
185             *issuer = NULL;
186         if (sno)
187             *sno = NULL;
188     } else
189         return 0;
190     return 1;
191 }
192
193 int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek,
194                                        X509 *cert)
195 {
196     CMS_KeyAgreeRecipientIdentifier *rid = rek->rid;
197     if (rid->type == CMS_REK_ISSUER_SERIAL)
198         return cms_ias_cert_cmp(rid->d.issuerAndSerialNumber, cert);
199     else if (rid->type == CMS_REK_KEYIDENTIFIER)
200         return cms_keyid_cert_cmp(rid->d.rKeyId->subjectKeyIdentifier, cert);
201     else
202         return -1;
203 }
204
205 int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk)
206 {
207     EVP_PKEY_CTX *pctx;
208     CMS_KeyAgreeRecipientInfo *kari = ri->d.kari;
209     if (kari->pctx) {
210         EVP_PKEY_CTX_free(kari->pctx);
211         kari->pctx = NULL;
212     }
213     if (!pk)
214         return 1;
215     pctx = EVP_PKEY_CTX_new(pk, NULL);
216     if (!pctx || !EVP_PKEY_derive_init(pctx))
217         goto err;
218     kari->pctx = pctx;
219     return 1;
220  err:
221     EVP_PKEY_CTX_free(pctx);
222     return 0;
223 }
224
225 EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri)
226 {
227     if (ri->type == CMS_RECIPINFO_AGREE)
228         return &ri->d.kari->ctx;
229     return NULL;
230 }
231
232 /*
233  * Derive KEK and decrypt/encrypt with it to produce either the original CEK
234  * or the encrypted CEK.
235  */
236
237 static int cms_kek_cipher(unsigned char **pout, size_t *poutlen,
238                           const unsigned char *in, size_t inlen,
239                           CMS_KeyAgreeRecipientInfo *kari, int enc)
240 {
241     /* Key encryption key */
242     unsigned char kek[EVP_MAX_KEY_LENGTH];
243     size_t keklen;
244     int rv = 0;
245     unsigned char *out = NULL;
246     int outlen;
247     keklen = EVP_CIPHER_CTX_key_length(&kari->ctx);
248     if (keklen > EVP_MAX_KEY_LENGTH)
249         return 0;
250     /* Derive KEK */
251     if (EVP_PKEY_derive(kari->pctx, kek, &keklen) <= 0)
252         goto err;
253     /* Set KEK in context */
254     if (!EVP_CipherInit_ex(&kari->ctx, NULL, NULL, kek, NULL, enc))
255         goto err;
256     /* obtain output length of ciphered key */
257     if (!EVP_CipherUpdate(&kari->ctx, NULL, &outlen, in, inlen))
258         goto err;
259     out = OPENSSL_malloc(outlen);
260     if (!out)
261         goto err;
262     if (!EVP_CipherUpdate(&kari->ctx, out, &outlen, in, inlen))
263         goto err;
264     *pout = out;
265     *poutlen = (size_t)outlen;
266     rv = 1;
267
268  err:
269     OPENSSL_cleanse(kek, keklen);
270     if (!rv && out)
271         OPENSSL_free(out);
272     EVP_CIPHER_CTX_cleanup(&kari->ctx);
273     EVP_PKEY_CTX_free(kari->pctx);
274     kari->pctx = NULL;
275     return rv;
276 }
277
278 int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms,
279                                    CMS_RecipientInfo *ri,
280                                    CMS_RecipientEncryptedKey *rek)
281 {
282     int rv = 0;
283     unsigned char *enckey = NULL, *cek = NULL;
284     size_t enckeylen;
285     size_t ceklen;
286     CMS_EncryptedContentInfo *ec;
287     enckeylen = rek->encryptedKey->length;
288     enckey = rek->encryptedKey->data;
289     /* Setup all parameters to derive KEK */
290     if (!cms_env_asn1_ctrl(ri, 1))
291         goto err;
292     /* Attempt to decrypt CEK */
293     if (!cms_kek_cipher(&cek, &ceklen, enckey, enckeylen, ri->d.kari, 0))
294         goto err;
295     ec = cms->d.envelopedData->encryptedContentInfo;
296     if (ec->key) {
297         OPENSSL_cleanse(ec->key, ec->keylen);
298         OPENSSL_free(ec->key);
299     }
300     ec->key = cek;
301     ec->keylen = ceklen;
302     cek = NULL;
303     rv = 1;
304  err:
305     if (cek)
306         OPENSSL_free(cek);
307     return rv;
308 }
309
310 /* Create ephemeral key and initialise context based on it */
311 static int cms_kari_create_ephemeral_key(CMS_KeyAgreeRecipientInfo *kari,
312                                          EVP_PKEY *pk)
313 {
314     EVP_PKEY_CTX *pctx = NULL;
315     EVP_PKEY *ekey = NULL;
316     int rv = 0;
317     pctx = EVP_PKEY_CTX_new(pk, NULL);
318     if (!pctx)
319         goto err;
320     if (EVP_PKEY_keygen_init(pctx) <= 0)
321         goto err;
322     if (EVP_PKEY_keygen(pctx, &ekey) <= 0)
323         goto err;
324     EVP_PKEY_CTX_free(pctx);
325     pctx = EVP_PKEY_CTX_new(ekey, NULL);
326     if (!pctx)
327         goto err;
328     if (EVP_PKEY_derive_init(pctx) <= 0)
329         goto err;
330     kari->pctx = pctx;
331     rv = 1;
332  err:
333     if (!rv)
334         EVP_PKEY_CTX_free(pctx);
335     EVP_PKEY_free(ekey);
336     return rv;
337 }
338
339 /* Initialise a ktri based on passed certificate and key */
340
341 int cms_RecipientInfo_kari_init(CMS_RecipientInfo *ri, X509 *recip,
342                                 EVP_PKEY *pk, unsigned int flags)
343 {
344     CMS_KeyAgreeRecipientInfo *kari;
345     CMS_RecipientEncryptedKey *rek = NULL;
346
347     ri->d.kari = M_ASN1_new_of(CMS_KeyAgreeRecipientInfo);
348     if (!ri->d.kari)
349         return 0;
350     ri->type = CMS_RECIPINFO_AGREE;
351
352     kari = ri->d.kari;
353     kari->version = 3;
354
355     rek = M_ASN1_new_of(CMS_RecipientEncryptedKey);
356     if (!sk_CMS_RecipientEncryptedKey_push(kari->recipientEncryptedKeys, rek)) {
357         M_ASN1_free_of(rek, CMS_RecipientEncryptedKey);
358         return 0;
359     }
360
361     if (flags & CMS_USE_KEYID) {
362         rek->rid->type = CMS_REK_KEYIDENTIFIER;
363         if (!cms_set1_keyid(&rek->rid->d.rKeyId->subjectKeyIdentifier, recip))
364             return 0;
365     } else {
366         rek->rid->type = CMS_REK_ISSUER_SERIAL;
367         if (!cms_set1_ias(&rek->rid->d.issuerAndSerialNumber, recip))
368             return 0;
369     }
370
371     /* Create ephemeral key */
372     if (!cms_kari_create_ephemeral_key(kari, pk))
373         return 0;
374
375     CRYPTO_add(&pk->references, 1, CRYPTO_LOCK_EVP_PKEY);
376     rek->pkey = pk;
377     return 1;
378 }
379
380 static int cms_wrap_init(CMS_KeyAgreeRecipientInfo *kari,
381                          const EVP_CIPHER *cipher)
382 {
383     EVP_CIPHER_CTX *ctx = &kari->ctx;
384     const EVP_CIPHER *kekcipher;
385     int keylen = EVP_CIPHER_key_length(cipher);
386     /* If a suitable wrap algorithm is already set nothing to do */
387     kekcipher = EVP_CIPHER_CTX_cipher(ctx);
388
389     if (kekcipher) {
390         if (EVP_CIPHER_CTX_mode(ctx) != EVP_CIPH_WRAP_MODE)
391             return 0;
392         return 1;
393     }
394     /*
395      * Pick a cipher based on content encryption cipher. If it is DES3 use
396      * DES3 wrap otherwise use AES wrap similar to key size.
397      */
398     if (EVP_CIPHER_type(cipher) == NID_des_ede3_cbc)
399         kekcipher = EVP_des_ede3_wrap();
400     else if (keylen <= 16)
401         kekcipher = EVP_aes_128_wrap();
402     else if (keylen <= 24)
403         kekcipher = EVP_aes_192_wrap();
404     else
405         kekcipher = EVP_aes_256_wrap();
406     return EVP_EncryptInit_ex(ctx, kekcipher, NULL, NULL, NULL);
407 }
408
409 /* Encrypt content key in key agreement recipient info */
410
411 int cms_RecipientInfo_kari_encrypt(CMS_ContentInfo *cms,
412                                    CMS_RecipientInfo *ri)
413 {
414     CMS_KeyAgreeRecipientInfo *kari;
415     CMS_EncryptedContentInfo *ec;
416     CMS_RecipientEncryptedKey *rek;
417     STACK_OF(CMS_RecipientEncryptedKey) *reks;
418     int i;
419
420     if (ri->type != CMS_RECIPINFO_AGREE) {
421         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT, CMS_R_NOT_KEY_AGREEMENT);
422         return 0;
423     }
424     kari = ri->d.kari;
425     reks = kari->recipientEncryptedKeys;
426     ec = cms->d.envelopedData->encryptedContentInfo;
427     /* Initialise wrap algorithm parameters */
428     if (!cms_wrap_init(kari, ec->cipher))
429         return 0;
430     /*
431      * If no orignator key set up initialise for ephemeral key the public key
432      * ASN1 structure will set the actual public key value.
433      */
434     if (kari->originator->type == -1) {
435         CMS_OriginatorIdentifierOrKey *oik = kari->originator;
436         oik->type = CMS_OIK_PUBKEY;
437         oik->d.originatorKey = M_ASN1_new_of(CMS_OriginatorPublicKey);
438         if (!oik->d.originatorKey)
439             return 0;
440     }
441     /* Initialise KDF algorithm */
442     if (!cms_env_asn1_ctrl(ri, 0))
443         return 0;
444     /* For each rek, derive KEK, encrypt CEK */
445     for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) {
446         unsigned char *enckey;
447         size_t enckeylen;
448         rek = sk_CMS_RecipientEncryptedKey_value(reks, i);
449         if (EVP_PKEY_derive_set_peer(kari->pctx, rek->pkey) <= 0)
450             return 0;
451         if (!cms_kek_cipher(&enckey, &enckeylen, ec->key, ec->keylen,
452                             kari, 1))
453             return 0;
454         ASN1_STRING_set0(rek->encryptedKey, enckey, enckeylen);
455     }
456
457     return 1;
458
459 }