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