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