Fix no-des
[openssl.git] / crypto / cms / cms_kari.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project.
4  */
5 /* ====================================================================
6  * Copyright (c) 2013 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  */
53
54 #include "internal/cryptlib.h"
55 #include <openssl/asn1t.h>
56 #include <openssl/pem.h>
57 #include <openssl/x509v3.h>
58 #include <openssl/err.h>
59 #include <openssl/cms.h>
60 #include <openssl/rand.h>
61 #include <openssl/aes.h>
62 #include "cms_lcl.h"
63 #include "internal/asn1_int.h"
64
65 /* Key Agreement Recipient Info (KARI) routines */
66
67 int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri,
68                                     X509_ALGOR **palg,
69                                     ASN1_OCTET_STRING **pukm)
70 {
71     if (ri->type != CMS_RECIPINFO_AGREE) {
72         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG,
73                CMS_R_NOT_KEY_AGREEMENT);
74         return 0;
75     }
76     if (palg)
77         *palg = ri->d.kari->keyEncryptionAlgorithm;
78     if (pukm)
79         *pukm = ri->d.kari->ukm;
80     return 1;
81 }
82
83 /* Retrieve recipient encrypted keys from a kari */
84
85 STACK_OF(CMS_RecipientEncryptedKey)
86 *CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri)
87 {
88     if (ri->type != CMS_RECIPINFO_AGREE) {
89         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS,
90                CMS_R_NOT_KEY_AGREEMENT);
91         return NULL;
92     }
93     return ri->d.kari->recipientEncryptedKeys;
94 }
95
96 int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri,
97                                         X509_ALGOR **pubalg,
98                                         ASN1_BIT_STRING **pubkey,
99                                         ASN1_OCTET_STRING **keyid,
100                                         X509_NAME **issuer,
101                                         ASN1_INTEGER **sno)
102 {
103     CMS_OriginatorIdentifierOrKey *oik;
104     if (ri->type != CMS_RECIPINFO_AGREE) {
105         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID,
106                CMS_R_NOT_KEY_AGREEMENT);
107         return 0;
108     }
109     oik = ri->d.kari->originator;
110     if (issuer)
111         *issuer = NULL;
112     if (sno)
113         *sno = NULL;
114     if (keyid)
115         *keyid = NULL;
116     if (pubalg)
117         *pubalg = NULL;
118     if (pubkey)
119         *pubkey = NULL;
120     if (oik->type == CMS_OIK_ISSUER_SERIAL) {
121         if (issuer)
122             *issuer = oik->d.issuerAndSerialNumber->issuer;
123         if (sno)
124             *sno = oik->d.issuerAndSerialNumber->serialNumber;
125     } else if (oik->type == CMS_OIK_KEYIDENTIFIER) {
126         if (keyid)
127             *keyid = oik->d.subjectKeyIdentifier;
128     } else if (oik->type == CMS_OIK_PUBKEY) {
129         if (pubalg)
130             *pubalg = oik->d.originatorKey->algorithm;
131         if (pubkey)
132             *pubkey = oik->d.originatorKey->publicKey;
133     } else
134         return 0;
135     return 1;
136 }
137
138 int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert)
139 {
140     CMS_OriginatorIdentifierOrKey *oik;
141     if (ri->type != CMS_RECIPINFO_AGREE) {
142         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP,
143                CMS_R_NOT_KEY_AGREEMENT);
144         return -2;
145     }
146     oik = ri->d.kari->originator;
147     if (oik->type == CMS_OIK_ISSUER_SERIAL)
148         return cms_ias_cert_cmp(oik->d.issuerAndSerialNumber, cert);
149     else if (oik->type == CMS_OIK_KEYIDENTIFIER)
150         return cms_keyid_cert_cmp(oik->d.subjectKeyIdentifier, cert);
151     return -1;
152 }
153
154 int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek,
155                                       ASN1_OCTET_STRING **keyid,
156                                       ASN1_GENERALIZEDTIME **tm,
157                                       CMS_OtherKeyAttribute **other,
158                                       X509_NAME **issuer, ASN1_INTEGER **sno)
159 {
160     CMS_KeyAgreeRecipientIdentifier *rid = rek->rid;
161     if (rid->type == CMS_REK_ISSUER_SERIAL) {
162         if (issuer)
163             *issuer = rid->d.issuerAndSerialNumber->issuer;
164         if (sno)
165             *sno = rid->d.issuerAndSerialNumber->serialNumber;
166         if (keyid)
167             *keyid = NULL;
168         if (tm)
169             *tm = NULL;
170         if (other)
171             *other = NULL;
172     } else if (rid->type == CMS_REK_KEYIDENTIFIER) {
173         if (keyid)
174             *keyid = rid->d.rKeyId->subjectKeyIdentifier;
175         if (tm)
176             *tm = rid->d.rKeyId->date;
177         if (other)
178             *other = rid->d.rKeyId->other;
179         if (issuer)
180             *issuer = NULL;
181         if (sno)
182             *sno = NULL;
183     } else
184         return 0;
185     return 1;
186 }
187
188 int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek,
189                                        X509 *cert)
190 {
191     CMS_KeyAgreeRecipientIdentifier *rid = rek->rid;
192     if (rid->type == CMS_REK_ISSUER_SERIAL)
193         return cms_ias_cert_cmp(rid->d.issuerAndSerialNumber, cert);
194     else if (rid->type == CMS_REK_KEYIDENTIFIER)
195         return cms_keyid_cert_cmp(rid->d.rKeyId->subjectKeyIdentifier, cert);
196     else
197         return -1;
198 }
199
200 int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk)
201 {
202     EVP_PKEY_CTX *pctx;
203     CMS_KeyAgreeRecipientInfo *kari = ri->d.kari;
204
205     EVP_PKEY_CTX_free(kari->pctx);
206     kari->pctx = NULL;
207     if (!pk)
208         return 1;
209     pctx = EVP_PKEY_CTX_new(pk, NULL);
210     if (!pctx || !EVP_PKEY_derive_init(pctx))
211         goto err;
212     kari->pctx = pctx;
213     return 1;
214  err:
215     EVP_PKEY_CTX_free(pctx);
216     return 0;
217 }
218
219 EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri)
220 {
221     if (ri->type == CMS_RECIPINFO_AGREE)
222         return ri->d.kari->ctx;
223     return NULL;
224 }
225
226 /*
227  * Derive KEK and decrypt/encrypt with it to produce either the original CEK
228  * or the encrypted CEK.
229  */
230
231 static int cms_kek_cipher(unsigned char **pout, size_t *poutlen,
232                           const unsigned char *in, size_t inlen,
233                           CMS_KeyAgreeRecipientInfo *kari, int enc)
234 {
235     /* Key encryption key */
236     unsigned char kek[EVP_MAX_KEY_LENGTH];
237     size_t keklen;
238     int rv = 0;
239     unsigned char *out = NULL;
240     int outlen;
241     keklen = EVP_CIPHER_CTX_key_length(kari->ctx);
242     if (keklen > EVP_MAX_KEY_LENGTH)
243         return 0;
244     /* Derive KEK */
245     if (EVP_PKEY_derive(kari->pctx, kek, &keklen) <= 0)
246         goto err;
247     /* Set KEK in context */
248     if (!EVP_CipherInit_ex(kari->ctx, NULL, NULL, kek, NULL, enc))
249         goto err;
250     /* obtain output length of ciphered key */
251     if (!EVP_CipherUpdate(kari->ctx, NULL, &outlen, in, inlen))
252         goto err;
253     out = OPENSSL_malloc(outlen);
254     if (out == NULL)
255         goto err;
256     if (!EVP_CipherUpdate(kari->ctx, out, &outlen, in, inlen))
257         goto err;
258     *pout = out;
259     *poutlen = (size_t)outlen;
260     rv = 1;
261
262  err:
263     OPENSSL_cleanse(kek, keklen);
264     if (!rv)
265         OPENSSL_free(out);
266     EVP_CIPHER_CTX_reset(kari->ctx);
267     /* FIXME: WHY IS kari->pctx freed here?  /RL */
268     EVP_PKEY_CTX_free(kari->pctx);
269     kari->pctx = NULL;
270     return rv;
271 }
272
273 int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms,
274                                    CMS_RecipientInfo *ri,
275                                    CMS_RecipientEncryptedKey *rek)
276 {
277     int rv = 0;
278     unsigned char *enckey = NULL, *cek = NULL;
279     size_t enckeylen;
280     size_t ceklen;
281     CMS_EncryptedContentInfo *ec;
282     enckeylen = rek->encryptedKey->length;
283     enckey = rek->encryptedKey->data;
284     /* Setup all parameters to derive KEK */
285     if (!cms_env_asn1_ctrl(ri, 1))
286         goto err;
287     /* Attempt to decrypt CEK */
288     if (!cms_kek_cipher(&cek, &ceklen, enckey, enckeylen, ri->d.kari, 0))
289         goto err;
290     ec = cms->d.envelopedData->encryptedContentInfo;
291     OPENSSL_clear_free(ec->key, ec->keylen);
292     ec->key = cek;
293     ec->keylen = ceklen;
294     cek = NULL;
295     rv = 1;
296  err:
297     OPENSSL_free(cek);
298     return rv;
299 }
300
301 /* Create ephemeral key and initialise context based on it */
302 static int cms_kari_create_ephemeral_key(CMS_KeyAgreeRecipientInfo *kari,
303                                          EVP_PKEY *pk)
304 {
305     EVP_PKEY_CTX *pctx = NULL;
306     EVP_PKEY *ekey = NULL;
307     int rv = 0;
308     pctx = EVP_PKEY_CTX_new(pk, NULL);
309     if (!pctx)
310         goto err;
311     if (EVP_PKEY_keygen_init(pctx) <= 0)
312         goto err;
313     if (EVP_PKEY_keygen(pctx, &ekey) <= 0)
314         goto err;
315     EVP_PKEY_CTX_free(pctx);
316     pctx = EVP_PKEY_CTX_new(ekey, NULL);
317     if (!pctx)
318         goto err;
319     if (EVP_PKEY_derive_init(pctx) <= 0)
320         goto err;
321     kari->pctx = pctx;
322     rv = 1;
323  err:
324     if (!rv)
325         EVP_PKEY_CTX_free(pctx);
326     EVP_PKEY_free(ekey);
327     return rv;
328 }
329
330 /* Initialise a ktri based on passed certificate and key */
331
332 int cms_RecipientInfo_kari_init(CMS_RecipientInfo *ri, X509 *recip,
333                                 EVP_PKEY *pk, unsigned int flags)
334 {
335     CMS_KeyAgreeRecipientInfo *kari;
336     CMS_RecipientEncryptedKey *rek = NULL;
337
338     ri->d.kari = M_ASN1_new_of(CMS_KeyAgreeRecipientInfo);
339     if (!ri->d.kari)
340         return 0;
341     ri->type = CMS_RECIPINFO_AGREE;
342
343     kari = ri->d.kari;
344     kari->version = 3;
345
346     rek = M_ASN1_new_of(CMS_RecipientEncryptedKey);
347     if (!sk_CMS_RecipientEncryptedKey_push(kari->recipientEncryptedKeys, rek)) {
348         M_ASN1_free_of(rek, CMS_RecipientEncryptedKey);
349         return 0;
350     }
351
352     if (flags & CMS_USE_KEYID) {
353         rek->rid->type = CMS_REK_KEYIDENTIFIER;
354         rek->rid->d.rKeyId = M_ASN1_new_of(CMS_RecipientKeyIdentifier);
355         if (rek->rid->d.rKeyId == NULL)
356             return 0;
357         if (!cms_set1_keyid(&rek->rid->d.rKeyId->subjectKeyIdentifier, recip))
358             return 0;
359     } else {
360         rek->rid->type = CMS_REK_ISSUER_SERIAL;
361         if (!cms_set1_ias(&rek->rid->d.issuerAndSerialNumber, recip))
362             return 0;
363     }
364
365     /* Create ephemeral key */
366     if (!cms_kari_create_ephemeral_key(kari, pk))
367         return 0;
368
369     EVP_PKEY_up_ref(pk);
370     rek->pkey = pk;
371     return 1;
372 }
373
374 static int cms_wrap_init(CMS_KeyAgreeRecipientInfo *kari,
375                          const EVP_CIPHER *cipher)
376 {
377     EVP_CIPHER_CTX *ctx = kari->ctx;
378     const EVP_CIPHER *kekcipher;
379     int keylen = EVP_CIPHER_key_length(cipher);
380     /* If a suitable wrap algorithm is already set nothing to do */
381     kekcipher = EVP_CIPHER_CTX_cipher(ctx);
382
383     if (kekcipher) {
384         if (EVP_CIPHER_CTX_mode(ctx) != EVP_CIPH_WRAP_MODE)
385             return 0;
386         return 1;
387     }
388     /*
389      * Pick a cipher based on content encryption cipher. If it is DES3 use
390      * DES3 wrap otherwise use AES wrap similar to key size.
391      */
392 #ifndef OPENSSL_NO_DES
393     if (EVP_CIPHER_type(cipher) == NID_des_ede3_cbc)
394         kekcipher = EVP_des_ede3_wrap();
395     else
396 #endif
397     if (keylen <= 16)
398         kekcipher = EVP_aes_128_wrap();
399     else if (keylen <= 24)
400         kekcipher = EVP_aes_192_wrap();
401     else
402         kekcipher = EVP_aes_256_wrap();
403     return EVP_EncryptInit_ex(ctx, kekcipher, NULL, NULL, NULL);
404 }
405
406 /* Encrypt content key in key agreement recipient info */
407
408 int cms_RecipientInfo_kari_encrypt(CMS_ContentInfo *cms,
409                                    CMS_RecipientInfo *ri)
410 {
411     CMS_KeyAgreeRecipientInfo *kari;
412     CMS_EncryptedContentInfo *ec;
413     CMS_RecipientEncryptedKey *rek;
414     STACK_OF(CMS_RecipientEncryptedKey) *reks;
415     int i;
416
417     if (ri->type != CMS_RECIPINFO_AGREE) {
418         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT, CMS_R_NOT_KEY_AGREEMENT);
419         return 0;
420     }
421     kari = ri->d.kari;
422     reks = kari->recipientEncryptedKeys;
423     ec = cms->d.envelopedData->encryptedContentInfo;
424     /* Initialise wrap algorithm parameters */
425     if (!cms_wrap_init(kari, ec->cipher))
426         return 0;
427     /*
428      * If no originator key set up initialise for ephemeral key the public key
429      * ASN1 structure will set the actual public key value.
430      */
431     if (kari->originator->type == -1) {
432         CMS_OriginatorIdentifierOrKey *oik = kari->originator;
433         oik->type = CMS_OIK_PUBKEY;
434         oik->d.originatorKey = M_ASN1_new_of(CMS_OriginatorPublicKey);
435         if (!oik->d.originatorKey)
436             return 0;
437     }
438     /* Initialise KDF algorithm */
439     if (!cms_env_asn1_ctrl(ri, 0))
440         return 0;
441     /* For each rek, derive KEK, encrypt CEK */
442     for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) {
443         unsigned char *enckey;
444         size_t enckeylen;
445         rek = sk_CMS_RecipientEncryptedKey_value(reks, i);
446         if (EVP_PKEY_derive_set_peer(kari->pctx, rek->pkey) <= 0)
447             return 0;
448         if (!cms_kek_cipher(&enckey, &enckeylen, ec->key, ec->keylen,
449                             kari, 1))
450             return 0;
451         ASN1_STRING_set0(rek->encryptedKey, enckey, enckeylen);
452     }
453
454     return 1;
455
456 }