4e837718dcb4c91bd360e31de455d623bc44407e
[openssl.git] / crypto / cms / cms_kari.c
1 /*
2  * Copyright 2013-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/aes.h>
17 #include "cms_local.h"
18 #include "crypto/asn1.h"
19
20 DEFINE_STACK_OF(CMS_RecipientEncryptedKey)
21
22 /* Key Agreement Recipient Info (KARI) routines */
23
24 int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri,
25                                     X509_ALGOR **palg,
26                                     ASN1_OCTET_STRING **pukm)
27 {
28     if (ri->type != CMS_RECIPINFO_AGREE) {
29         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG,
30                CMS_R_NOT_KEY_AGREEMENT);
31         return 0;
32     }
33     if (palg)
34         *palg = ri->d.kari->keyEncryptionAlgorithm;
35     if (pukm)
36         *pukm = ri->d.kari->ukm;
37     return 1;
38 }
39
40 /* Retrieve recipient encrypted keys from a kari */
41
42 STACK_OF(CMS_RecipientEncryptedKey)
43 *CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri)
44 {
45     if (ri->type != CMS_RECIPINFO_AGREE) {
46         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS,
47                CMS_R_NOT_KEY_AGREEMENT);
48         return NULL;
49     }
50     return ri->d.kari->recipientEncryptedKeys;
51 }
52
53 int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri,
54                                         X509_ALGOR **pubalg,
55                                         ASN1_BIT_STRING **pubkey,
56                                         ASN1_OCTET_STRING **keyid,
57                                         X509_NAME **issuer,
58                                         ASN1_INTEGER **sno)
59 {
60     CMS_OriginatorIdentifierOrKey *oik;
61     if (ri->type != CMS_RECIPINFO_AGREE) {
62         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID,
63                CMS_R_NOT_KEY_AGREEMENT);
64         return 0;
65     }
66     oik = ri->d.kari->originator;
67     if (issuer)
68         *issuer = NULL;
69     if (sno)
70         *sno = NULL;
71     if (keyid)
72         *keyid = NULL;
73     if (pubalg)
74         *pubalg = NULL;
75     if (pubkey)
76         *pubkey = NULL;
77     if (oik->type == CMS_OIK_ISSUER_SERIAL) {
78         if (issuer)
79             *issuer = oik->d.issuerAndSerialNumber->issuer;
80         if (sno)
81             *sno = oik->d.issuerAndSerialNumber->serialNumber;
82     } else if (oik->type == CMS_OIK_KEYIDENTIFIER) {
83         if (keyid)
84             *keyid = oik->d.subjectKeyIdentifier;
85     } else if (oik->type == CMS_OIK_PUBKEY) {
86         if (pubalg)
87             *pubalg = oik->d.originatorKey->algorithm;
88         if (pubkey)
89             *pubkey = oik->d.originatorKey->publicKey;
90     } else
91         return 0;
92     return 1;
93 }
94
95 int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert)
96 {
97     CMS_OriginatorIdentifierOrKey *oik;
98     if (ri->type != CMS_RECIPINFO_AGREE) {
99         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP,
100                CMS_R_NOT_KEY_AGREEMENT);
101         return -2;
102     }
103     oik = ri->d.kari->originator;
104     if (oik->type == CMS_OIK_ISSUER_SERIAL)
105         return cms_ias_cert_cmp(oik->d.issuerAndSerialNumber, cert);
106     else if (oik->type == CMS_OIK_KEYIDENTIFIER)
107         return cms_keyid_cert_cmp(oik->d.subjectKeyIdentifier, cert);
108     return -1;
109 }
110
111 int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek,
112                                       ASN1_OCTET_STRING **keyid,
113                                       ASN1_GENERALIZEDTIME **tm,
114                                       CMS_OtherKeyAttribute **other,
115                                       X509_NAME **issuer, ASN1_INTEGER **sno)
116 {
117     CMS_KeyAgreeRecipientIdentifier *rid = rek->rid;
118     if (rid->type == CMS_REK_ISSUER_SERIAL) {
119         if (issuer)
120             *issuer = rid->d.issuerAndSerialNumber->issuer;
121         if (sno)
122             *sno = rid->d.issuerAndSerialNumber->serialNumber;
123         if (keyid)
124             *keyid = NULL;
125         if (tm)
126             *tm = NULL;
127         if (other)
128             *other = NULL;
129     } else if (rid->type == CMS_REK_KEYIDENTIFIER) {
130         if (keyid)
131             *keyid = rid->d.rKeyId->subjectKeyIdentifier;
132         if (tm)
133             *tm = rid->d.rKeyId->date;
134         if (other)
135             *other = rid->d.rKeyId->other;
136         if (issuer)
137             *issuer = NULL;
138         if (sno)
139             *sno = NULL;
140     } else
141         return 0;
142     return 1;
143 }
144
145 int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek,
146                                        X509 *cert)
147 {
148     CMS_KeyAgreeRecipientIdentifier *rid = rek->rid;
149     if (rid->type == CMS_REK_ISSUER_SERIAL)
150         return cms_ias_cert_cmp(rid->d.issuerAndSerialNumber, cert);
151     else if (rid->type == CMS_REK_KEYIDENTIFIER)
152         return cms_keyid_cert_cmp(rid->d.rKeyId->subjectKeyIdentifier, cert);
153     else
154         return -1;
155 }
156
157 int CMS_RecipientInfo_kari_set0_pkey_and_peer(CMS_RecipientInfo *ri, EVP_PKEY *pk, X509 *peer)
158 {
159     EVP_PKEY_CTX *pctx;
160     CMS_KeyAgreeRecipientInfo *kari = ri->d.kari;
161
162     EVP_PKEY_CTX_free(kari->pctx);
163     kari->pctx = NULL;
164     if (pk == NULL)
165         return 1;
166
167     pctx = EVP_PKEY_CTX_new(pk, NULL);
168     if (pctx == NULL || EVP_PKEY_derive_init(pctx) <= 0)
169         goto err;
170
171     if (peer != NULL) {
172         EVP_PKEY *pub_pkey = X509_get0_pubkey(peer);
173
174         if (EVP_PKEY_derive_set_peer(pctx, pub_pkey) <= 0)
175             goto err;
176     }
177
178     kari->pctx = pctx;
179     return 1;
180  err:
181     EVP_PKEY_CTX_free(pctx);
182     return 0;
183 }
184
185 int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk)
186 {
187     return CMS_RecipientInfo_kari_set0_pkey_and_peer(ri, pk, NULL);
188 }
189
190 EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri)
191 {
192     if (ri->type == CMS_RECIPINFO_AGREE)
193         return ri->d.kari->ctx;
194     return NULL;
195 }
196
197 /*
198  * Derive KEK and decrypt/encrypt with it to produce either the original CEK
199  * or the encrypted CEK.
200  */
201
202 static int cms_kek_cipher(unsigned char **pout, size_t *poutlen,
203                           const unsigned char *in, size_t inlen,
204                           CMS_KeyAgreeRecipientInfo *kari, int enc)
205 {
206     /* Key encryption key */
207     unsigned char kek[EVP_MAX_KEY_LENGTH];
208     size_t keklen;
209     int rv = 0;
210     unsigned char *out = NULL;
211     int outlen;
212     keklen = EVP_CIPHER_CTX_key_length(kari->ctx);
213     if (keklen > EVP_MAX_KEY_LENGTH)
214         return 0;
215     /* Derive KEK */
216     if (EVP_PKEY_derive(kari->pctx, kek, &keklen) <= 0)
217         goto err;
218     /* Set KEK in context */
219     if (!EVP_CipherInit_ex(kari->ctx, NULL, NULL, kek, NULL, enc))
220         goto err;
221     /* obtain output length of ciphered key */
222     if (!EVP_CipherUpdate(kari->ctx, NULL, &outlen, in, inlen))
223         goto err;
224     out = OPENSSL_malloc(outlen);
225     if (out == NULL)
226         goto err;
227     if (!EVP_CipherUpdate(kari->ctx, out, &outlen, in, inlen))
228         goto err;
229     *pout = out;
230     *poutlen = (size_t)outlen;
231     rv = 1;
232
233  err:
234     OPENSSL_cleanse(kek, keklen);
235     if (!rv)
236         OPENSSL_free(out);
237     EVP_CIPHER_CTX_reset(kari->ctx);
238     /* FIXME: WHY IS kari->pctx freed here?  /RL */
239     EVP_PKEY_CTX_free(kari->pctx);
240     kari->pctx = NULL;
241     return rv;
242 }
243
244 int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms,
245                                    CMS_RecipientInfo *ri,
246                                    CMS_RecipientEncryptedKey *rek)
247 {
248     int rv = 0;
249     unsigned char *enckey = NULL, *cek = NULL;
250     size_t enckeylen;
251     size_t ceklen;
252     CMS_EncryptedContentInfo *ec;
253
254     {
255         /*
256          * TODO(3.0) Remove this when we have functionality to deserialize
257          * parameters in EVP_PKEY form from an X509_ALGOR.
258          * This is needed to be able to replace the EC_KEY specific decoding
259          * that happens in ecdh_cms_set_peerkey() (crypto/ec/ec_ameth.c)
260          *
261          * THIS IS TEMPORARY
262          */
263         EVP_PKEY_CTX *pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
264         EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx);
265
266         EVP_PKEY_get0(pkey);
267         if (EVP_PKEY_id(pkey) == EVP_PKEY_NONE) {
268             CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_DECRYPT,
269                    CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
270             goto err;
271         }
272     }
273
274     enckeylen = rek->encryptedKey->length;
275     enckey = rek->encryptedKey->data;
276     /* Setup all parameters to derive KEK */
277     if (!cms_env_asn1_ctrl(ri, 1))
278         goto err;
279     /* Attempt to decrypt CEK */
280     if (!cms_kek_cipher(&cek, &ceklen, enckey, enckeylen, ri->d.kari, 0))
281         goto err;
282     ec = cms->d.envelopedData->encryptedContentInfo;
283     OPENSSL_clear_free(ec->key, ec->keylen);
284     ec->key = cek;
285     ec->keylen = ceklen;
286     cek = NULL;
287     rv = 1;
288  err:
289     OPENSSL_free(cek);
290     return rv;
291 }
292
293 /* Create ephemeral key and initialise context based on it */
294 static int cms_kari_create_ephemeral_key(CMS_KeyAgreeRecipientInfo *kari,
295                                          EVP_PKEY *pk)
296 {
297     EVP_PKEY_CTX *pctx = NULL;
298     EVP_PKEY *ekey = NULL;
299     int rv = 0;
300
301     pctx = EVP_PKEY_CTX_new(pk, NULL);
302     if (pctx == NULL)
303         goto err;
304     if (EVP_PKEY_keygen_init(pctx) <= 0)
305         goto err;
306     if (EVP_PKEY_keygen(pctx, &ekey) <= 0)
307         goto err;
308     EVP_PKEY_CTX_free(pctx);
309     pctx = EVP_PKEY_CTX_new(ekey, NULL);
310     if (pctx == NULL)
311         goto err;
312     if (EVP_PKEY_derive_init(pctx) <= 0)
313         goto err;
314     kari->pctx = pctx;
315     rv = 1;
316  err:
317     if (!rv)
318         EVP_PKEY_CTX_free(pctx);
319     EVP_PKEY_free(ekey);
320     return rv;
321 }
322
323 /* Set originator private key and initialise context based on it */
324 static int cms_kari_set_originator_private_key(CMS_KeyAgreeRecipientInfo *kari, EVP_PKEY *originatorPrivKey )
325 {
326     EVP_PKEY_CTX *pctx = NULL;
327     int rv = 0;
328
329     pctx = EVP_PKEY_CTX_new(originatorPrivKey, NULL);
330     if (pctx == NULL)
331         goto err;
332     if (EVP_PKEY_derive_init(pctx) <= 0)
333          goto err;
334
335     kari->pctx = pctx;
336     rv = 1;
337  err:
338     if (rv == 0)
339         EVP_PKEY_CTX_free(pctx);
340     return rv;
341 }
342
343 /* Initialise a kari based on passed certificate and key */
344
345 int cms_RecipientInfo_kari_init(CMS_RecipientInfo *ri,  X509 *recip, EVP_PKEY *recipPubKey, X509 * originator, EVP_PKEY *originatorPrivKey, unsigned int flags)
346 {
347     CMS_KeyAgreeRecipientInfo *kari;
348     CMS_RecipientEncryptedKey *rek = NULL;
349
350     ri->d.kari = M_ASN1_new_of(CMS_KeyAgreeRecipientInfo);
351     if (!ri->d.kari)
352         return 0;
353     ri->type = CMS_RECIPINFO_AGREE;
354
355     kari = ri->d.kari;
356     kari->version = 3;
357
358     rek = M_ASN1_new_of(CMS_RecipientEncryptedKey);
359     if (rek == NULL)
360         return 0;
361
362     if (!sk_CMS_RecipientEncryptedKey_push(kari->recipientEncryptedKeys, rek)) {
363         M_ASN1_free_of(rek, CMS_RecipientEncryptedKey);
364         return 0;
365     }
366
367     if (flags & CMS_USE_KEYID) {
368         rek->rid->type = CMS_REK_KEYIDENTIFIER;
369         rek->rid->d.rKeyId = M_ASN1_new_of(CMS_RecipientKeyIdentifier);
370         if (rek->rid->d.rKeyId == NULL)
371             return 0;
372         if (!cms_set1_keyid(&rek->rid->d.rKeyId->subjectKeyIdentifier, recip))
373             return 0;
374     } else {
375         rek->rid->type = CMS_REK_ISSUER_SERIAL;
376         if (!cms_set1_ias(&rek->rid->d.issuerAndSerialNumber, recip))
377             return 0;
378     }
379
380     if (originatorPrivKey == NULL && originator == NULL) {
381         /* Create ephemeral key */
382         if (!cms_kari_create_ephemeral_key(kari, recipPubKey))
383             return 0;
384     } else {
385          /* Use originator key */
386          CMS_OriginatorIdentifierOrKey *oik = ri->d.kari->originator;
387
388          if (originatorPrivKey == NULL && originator == NULL)
389             return 0;
390
391          if (flags & CMS_USE_ORIGINATOR_KEYID) {
392               oik->type = CMS_OIK_KEYIDENTIFIER;
393               oik->d.subjectKeyIdentifier = ASN1_OCTET_STRING_new();
394               if (oik->d.subjectKeyIdentifier == NULL)
395                    return 0;
396               if (!cms_set1_keyid(&oik->d.subjectKeyIdentifier, originator))
397                    return 0;
398          } else {
399               oik->type = CMS_REK_ISSUER_SERIAL;
400               if (!cms_set1_ias(&oik->d.issuerAndSerialNumber, originator))
401                    return 0;
402          }
403
404          if (!cms_kari_set_originator_private_key(kari, originatorPrivKey))
405              return 0;
406     }
407
408     EVP_PKEY_up_ref(recipPubKey);
409     rek->pkey = recipPubKey;
410     return 1;
411 }
412
413 static int cms_wrap_init(CMS_KeyAgreeRecipientInfo *kari,
414                          const EVP_CIPHER *cipher)
415 {
416     EVP_CIPHER_CTX *ctx = kari->ctx;
417     const EVP_CIPHER *kekcipher;
418     int keylen = EVP_CIPHER_key_length(cipher);
419     int ret;
420
421     /* If a suitable wrap algorithm is already set nothing to do */
422     kekcipher = EVP_CIPHER_CTX_cipher(ctx);
423     if (kekcipher != NULL) {
424         if (EVP_CIPHER_CTX_mode(ctx) != EVP_CIPH_WRAP_MODE)
425             return 0;
426         return 1;
427     }
428     else if (cipher != NULL
429          && (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_GET_WRAP_CIPHER)) {
430         ret = EVP_CIPHER_meth_get_ctrl(cipher)(NULL, EVP_CTRL_GET_WRAP_CIPHER,
431                                                0, &kekcipher);
432         if (ret <= 0)
433              return 0;
434
435         if (kekcipher != NULL) {
436              if (EVP_CIPHER_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
437                  return 0;
438
439              return EVP_EncryptInit_ex(ctx, kekcipher, NULL, NULL, NULL);
440         }
441     }
442
443     /*
444      * Pick a cipher based on content encryption cipher. If it is DES3 use
445      * DES3 wrap otherwise use AES wrap similar to key size.
446      */
447 #ifndef OPENSSL_NO_DES
448     if (EVP_CIPHER_type(cipher) == NID_des_ede3_cbc)
449         kekcipher = EVP_des_ede3_wrap();
450     else
451 #endif
452     if (keylen <= 16)
453         kekcipher = EVP_aes_128_wrap();
454     else if (keylen <= 24)
455         kekcipher = EVP_aes_192_wrap();
456     else
457         kekcipher = EVP_aes_256_wrap();
458     return EVP_EncryptInit_ex(ctx, kekcipher, NULL, NULL, NULL);
459 }
460
461 /* Encrypt content key in key agreement recipient info */
462
463 int cms_RecipientInfo_kari_encrypt(const CMS_ContentInfo *cms,
464                                    CMS_RecipientInfo *ri)
465 {
466     CMS_KeyAgreeRecipientInfo *kari;
467     CMS_EncryptedContentInfo *ec;
468     CMS_RecipientEncryptedKey *rek;
469     STACK_OF(CMS_RecipientEncryptedKey) *reks;
470     int i;
471
472     {
473         /*
474          * TODO(3.0) Remove this when we have figured out all the details
475          * need to set up encryption right.  With legacy keys, a *lot* is
476          * happening in the CMS specific EVP_PKEY_ASN1_METHOD functions,
477          * such as automatically setting a default KDF type, KDF digest,
478          * all that kind of stuff.
479          * With EVP_SIGNATURE, setting a default digest is done by getting
480          * the default MD for the key, and then inject that back into the
481          * signature implementation...  we could do something similar with
482          * CMS, possibly using CMS specific OSSL_PARAM keys, just like we
483          * have for certain AlgorithmIdentifier retrievals.
484          *
485          * THIS IS TEMPORARY
486          */
487         EVP_PKEY_CTX *pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
488         EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx);
489
490         EVP_PKEY_get0(pkey);
491         if (EVP_PKEY_id(pkey) == EVP_PKEY_NONE) {
492             CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT,
493                    CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
494             return 0;
495         }
496     }
497
498     if (ri->type != CMS_RECIPINFO_AGREE) {
499         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT, CMS_R_NOT_KEY_AGREEMENT);
500         return 0;
501     }
502     kari = ri->d.kari;
503     reks = kari->recipientEncryptedKeys;
504     ec = cms->d.envelopedData->encryptedContentInfo;
505     /* Initialise wrap algorithm parameters */
506     if (!cms_wrap_init(kari, ec->cipher))
507         return 0;
508     /*
509      * If no originator key set up initialise for ephemeral key the public key
510      * ASN1 structure will set the actual public key value.
511      */
512     if (kari->originator->type == -1) {
513         CMS_OriginatorIdentifierOrKey *oik = kari->originator;
514         oik->type = CMS_OIK_PUBKEY;
515         oik->d.originatorKey = M_ASN1_new_of(CMS_OriginatorPublicKey);
516         if (!oik->d.originatorKey)
517             return 0;
518     }
519     /* Initialise KDF algorithm */
520     if (!cms_env_asn1_ctrl(ri, 0))
521         return 0;
522     /* For each rek, derive KEK, encrypt CEK */
523     for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) {
524         unsigned char *enckey;
525         size_t enckeylen;
526         rek = sk_CMS_RecipientEncryptedKey_value(reks, i);
527         if (EVP_PKEY_derive_set_peer(kari->pctx, rek->pkey) <= 0)
528             return 0;
529         if (!cms_kek_cipher(&enckey, &enckeylen, ec->key, ec->keylen,
530                             kari, 1))
531             return 0;
532         ASN1_STRING_set0(rek->encryptedKey, enckey, enckeylen);
533     }
534
535     return 1;
536
537 }