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