1 /*
2 * Copyright 2013-2026 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 /*
11 * Low level key APIs (DH etc) are deprecated for public use, but still ok for
12 * internal use.
13 */
14 #include "internal/deprecated.h"
15
16 #include "internal/cryptlib.h"
17 #include <openssl/asn1t.h>
18 #include <openssl/pem.h>
19 #include <openssl/x509v3.h>
20 #include <openssl/err.h>
21 #include <openssl/cms.h>
22 #include <openssl/aes.h>
23 #include "cms_local.h"
24 #include "crypto/asn1.h"
25
26 /* Key Agreement Recipient Info (KARI) routines */
27
CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo * ri,X509_ALGOR ** palg,ASN1_OCTET_STRING ** pukm)28 int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri,
29 X509_ALGOR **palg,
30 ASN1_OCTET_STRING **pukm)
31 {
32 if (ri->type != CMS_RECIPINFO_AGREE) {
33 ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT);
34 return 0;
35 }
36 if (palg)
37 *palg = ri->d.kari->keyEncryptionAlgorithm;
38 if (pukm)
39 *pukm = ri->d.kari->ukm;
40 return 1;
41 }
42
43 /* Retrieve recipient encrypted keys from a kari */
44
STACK_OF(CMS_RecipientEncryptedKey)45 STACK_OF(CMS_RecipientEncryptedKey)
46 *CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri)
47 {
48 if (ri->type != CMS_RECIPINFO_AGREE) {
49 ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT);
50 return NULL;
51 }
52 return ri->d.kari->recipientEncryptedKeys;
53 }
54
CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo * ri,X509_ALGOR ** pubalg,ASN1_BIT_STRING ** pubkey,ASN1_OCTET_STRING ** keyid,X509_NAME ** issuer,ASN1_INTEGER ** sno)55 int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri,
56 X509_ALGOR **pubalg,
57 ASN1_BIT_STRING **pubkey,
58 ASN1_OCTET_STRING **keyid,
59 X509_NAME **issuer,
60 ASN1_INTEGER **sno)
61 {
62 CMS_OriginatorIdentifierOrKey *oik;
63
64 if (ri->type != CMS_RECIPINFO_AGREE) {
65 ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT);
66 return 0;
67 }
68 oik = ri->d.kari->originator;
69 if (issuer)
70 *issuer = NULL;
71 if (sno)
72 *sno = NULL;
73 if (keyid)
74 *keyid = NULL;
75 if (pubalg)
76 *pubalg = NULL;
77 if (pubkey)
78 *pubkey = NULL;
79 if (oik->type == CMS_OIK_ISSUER_SERIAL) {
80 if (issuer)
81 *issuer = oik->d.issuerAndSerialNumber->issuer;
82 if (sno)
83 *sno = oik->d.issuerAndSerialNumber->serialNumber;
84 } else if (oik->type == CMS_OIK_KEYIDENTIFIER) {
85 if (keyid)
86 *keyid = oik->d.subjectKeyIdentifier;
87 } else if (oik->type == CMS_OIK_PUBKEY) {
88 if (pubalg)
89 *pubalg = oik->d.originatorKey->algorithm;
90 if (pubkey)
91 *pubkey = oik->d.originatorKey->publicKey;
92 } else
93 return 0;
94 return 1;
95 }
96
CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo * ri,X509 * cert)97 int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert)
98 {
99 CMS_OriginatorIdentifierOrKey *oik;
100
101 if (ri->type != CMS_RECIPINFO_AGREE) {
102 ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT);
103 return -2;
104 }
105 oik = ri->d.kari->originator;
106 if (oik->type == CMS_OIK_ISSUER_SERIAL)
107 return ossl_cms_ias_cert_cmp(oik->d.issuerAndSerialNumber, cert);
108 else if (oik->type == CMS_OIK_KEYIDENTIFIER)
109 return ossl_cms_keyid_cert_cmp(oik->d.subjectKeyIdentifier, cert);
110 return -1;
111 }
112
CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey * rek,ASN1_OCTET_STRING ** keyid,ASN1_GENERALIZEDTIME ** tm,CMS_OtherKeyAttribute ** other,X509_NAME ** issuer,ASN1_INTEGER ** sno)113 int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek,
114 ASN1_OCTET_STRING **keyid,
115 ASN1_GENERALIZEDTIME **tm,
116 CMS_OtherKeyAttribute **other,
117 X509_NAME **issuer, ASN1_INTEGER **sno)
118 {
119 CMS_KeyAgreeRecipientIdentifier *rid = rek->rid;
120
121 if (rid->type == CMS_REK_ISSUER_SERIAL) {
122 if (issuer)
123 *issuer = rid->d.issuerAndSerialNumber->issuer;
124 if (sno)
125 *sno = rid->d.issuerAndSerialNumber->serialNumber;
126 if (keyid)
127 *keyid = NULL;
128 if (tm)
129 *tm = NULL;
130 if (other)
131 *other = NULL;
132 } else if (rid->type == CMS_REK_KEYIDENTIFIER) {
133 if (keyid)
134 *keyid = rid->d.rKeyId->subjectKeyIdentifier;
135 if (tm)
136 *tm = rid->d.rKeyId->date;
137 if (other)
138 *other = rid->d.rKeyId->other;
139 if (issuer)
140 *issuer = NULL;
141 if (sno)
142 *sno = NULL;
143 } else
144 return 0;
145 return 1;
146 }
147
CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey * rek,X509 * cert)148 int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek,
149 X509 *cert)
150 {
151 CMS_KeyAgreeRecipientIdentifier *rid = rek->rid;
152
153 if (rid->type == CMS_REK_ISSUER_SERIAL)
154 return ossl_cms_ias_cert_cmp(rid->d.issuerAndSerialNumber, cert);
155 else if (rid->type == CMS_REK_KEYIDENTIFIER)
156 return ossl_cms_keyid_cert_cmp(rid->d.rKeyId->subjectKeyIdentifier,
157 cert);
158 else
159 return -1;
160 }
161
CMS_RecipientInfo_kari_set0_pkey_and_peer(CMS_RecipientInfo * ri,EVP_PKEY * pk,X509 * peer)162 int CMS_RecipientInfo_kari_set0_pkey_and_peer(CMS_RecipientInfo *ri,
163 EVP_PKEY *pk, X509 *peer)
164 {
165 EVP_PKEY_CTX *pctx;
166 CMS_KeyAgreeRecipientInfo *kari = ri->d.kari;
167
168 EVP_PKEY_CTX_free(kari->pctx);
169 kari->pctx = NULL;
170 if (pk == NULL)
171 return 1;
172
173 pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(kari->cms_ctx),
174 pk,
175 ossl_cms_ctx_get0_propq(kari->cms_ctx));
176 if (pctx == NULL || EVP_PKEY_derive_init(pctx) <= 0)
177 goto err;
178
179 if (peer != NULL) {
180 EVP_PKEY *pub_pkey = X509_get0_pubkey(peer);
181
182 if (EVP_PKEY_derive_set_peer(pctx, pub_pkey) <= 0)
183 goto err;
184 }
185
186 kari->pctx = pctx;
187 return 1;
188 err:
189 EVP_PKEY_CTX_free(pctx);
190 return 0;
191 }
192
CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo * ri,EVP_PKEY * pk)193 int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk)
194 {
195 return CMS_RecipientInfo_kari_set0_pkey_and_peer(ri, pk, NULL);
196 }
197
CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo * ri)198 EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri)
199 {
200 if (ri->type == CMS_RECIPINFO_AGREE)
201 return ri->d.kari->ctx;
202 return NULL;
203 }
204
205 /*
206 * Derive KEK and decrypt/encrypt with it to produce either the original CEK
207 * or the encrypted CEK.
208 */
209
cms_kek_cipher(unsigned char ** pout,size_t * poutlen,const unsigned char * in,size_t inlen,CMS_KeyAgreeRecipientInfo * kari,int enc)210 static int cms_kek_cipher(unsigned char **pout, size_t *poutlen,
211 const unsigned char *in, size_t inlen,
212 CMS_KeyAgreeRecipientInfo *kari, int enc)
213 {
214 /* Key encryption key */
215 unsigned char kek[EVP_MAX_KEY_LENGTH];
216 size_t keklen;
217 int rv = 0;
218 unsigned char *out = NULL;
219 size_t out_alloc_len = 0;
220 int outlen;
221 size_t outsize;
222
223 keklen = EVP_CIPHER_CTX_get_key_length(kari->ctx);
224 if (keklen > EVP_MAX_KEY_LENGTH)
225 return 0;
226 /* Derive KEK */
227 if (EVP_PKEY_derive(kari->pctx, kek, &keklen) <= 0)
228 goto err;
229 /* Set KEK in context */
230 if (!EVP_CipherInit_ex(kari->ctx, NULL, NULL, kek, NULL, enc))
231 goto err;
232 /* obtain output length of ciphered key */
233 if (!EVP_CipherUpdate(kari->ctx, NULL, &outlen, in, inlen))
234 goto err;
235 /*
236 * On its integrity-failure paths that primitive writes and cleanses up to
237 * inlen bytes of the output buffer. Size the buffer for that worst case so
238 * a failed unwrap cannot write past the allocation.
239 */
240 outsize = (size_t)outlen < inlen ? inlen : (size_t)outlen;
241 out = OPENSSL_malloc(outsize);
242 if (out == NULL)
243 goto err;
244 out_alloc_len = (size_t)outlen;
245 if (!EVP_CipherUpdate(kari->ctx, out, &outlen, in, (int)inlen))
246 goto err;
247 *pout = out;
248 *poutlen = (size_t)outlen;
249 rv = 1;
250
251 err:
252 OPENSSL_cleanse(kek, keklen);
253 if (!rv)
254 OPENSSL_clear_free(out, out_alloc_len);
255 EVP_CIPHER_CTX_reset(kari->ctx);
256 /* FIXME: WHY IS kari->pctx freed here? /RL */
257 EVP_PKEY_CTX_free(kari->pctx);
258 kari->pctx = NULL;
259 return rv;
260 }
261
CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo * cms,CMS_RecipientInfo * ri,CMS_RecipientEncryptedKey * rek)262 int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms,
263 CMS_RecipientInfo *ri,
264 CMS_RecipientEncryptedKey *rek)
265 {
266 int rv = 0;
267 unsigned char *enckey = NULL, *cek = NULL;
268 size_t enckeylen;
269 size_t ceklen;
270 CMS_EncryptedContentInfo *ec;
271
272 enckeylen = rek->encryptedKey->length;
273 enckey = rek->encryptedKey->data;
274 /* Setup all parameters to derive KEK */
275 if (!ossl_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 = ossl_cms_get0_env_enc_content(cms);
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 */
cms_kari_create_ephemeral_key(CMS_KeyAgreeRecipientInfo * kari,EVP_PKEY * pk)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 const CMS_CTX *ctx = kari->cms_ctx;
299 OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx);
300 const char *propq = ossl_cms_ctx_get0_propq(ctx);
301
302 pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propq);
303 if (pctx == NULL)
304 goto err;
305 if (EVP_PKEY_keygen_init(pctx) <= 0)
306 goto err;
307 if (EVP_PKEY_keygen(pctx, &ekey) <= 0)
308 goto err;
309 EVP_PKEY_CTX_free(pctx);
310 pctx = EVP_PKEY_CTX_new_from_pkey(libctx, ekey, propq);
311 if (pctx == NULL)
312 goto err;
313 if (EVP_PKEY_derive_init(pctx) <= 0)
314 goto err;
315 kari->pctx = pctx;
316 rv = 1;
317 err:
318 if (!rv)
319 EVP_PKEY_CTX_free(pctx);
320 EVP_PKEY_free(ekey);
321 return rv;
322 }
323
324 /* Set originator private key and initialise context based on it */
cms_kari_set_originator_private_key(CMS_KeyAgreeRecipientInfo * kari,EVP_PKEY * originatorPrivKey)325 static int cms_kari_set_originator_private_key(CMS_KeyAgreeRecipientInfo *kari,
326 EVP_PKEY *originatorPrivKey)
327 {
328 EVP_PKEY_CTX *pctx = NULL;
329 int rv = 0;
330 const CMS_CTX *ctx = kari->cms_ctx;
331
332 pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
333 originatorPrivKey,
334 ossl_cms_ctx_get0_propq(ctx));
335 if (pctx == NULL)
336 goto err;
337 if (EVP_PKEY_derive_init(pctx) <= 0)
338 goto err;
339
340 kari->pctx = pctx;
341 rv = 1;
342 err:
343 if (rv == 0)
344 EVP_PKEY_CTX_free(pctx);
345 return rv;
346 }
347
348 /* Initialise a kari based on passed certificate and key */
349
ossl_cms_RecipientInfo_kari_init(CMS_RecipientInfo * ri,X509 * recip,EVP_PKEY * recipPubKey,X509 * originator,EVP_PKEY * originatorPrivKey,unsigned int flags,const CMS_CTX * ctx)350 int ossl_cms_RecipientInfo_kari_init(CMS_RecipientInfo *ri, X509 *recip,
351 EVP_PKEY *recipPubKey, X509 *originator,
352 EVP_PKEY *originatorPrivKey,
353 unsigned int flags, const CMS_CTX *ctx)
354 {
355 CMS_KeyAgreeRecipientInfo *kari;
356 CMS_RecipientEncryptedKey *rek = NULL;
357
358 ri->d.kari = M_ASN1_new_of(CMS_KeyAgreeRecipientInfo);
359 if (ri->d.kari == NULL)
360 return 0;
361 ri->type = CMS_RECIPINFO_AGREE;
362
363 kari = ri->d.kari;
364 kari->version = 3;
365 kari->cms_ctx = ctx;
366
367 rek = M_ASN1_new_of(CMS_RecipientEncryptedKey);
368 if (rek == NULL)
369 return 0;
370
371 if (!sk_CMS_RecipientEncryptedKey_push(kari->recipientEncryptedKeys, rek)) {
372 M_ASN1_free_of(rek, CMS_RecipientEncryptedKey);
373 return 0;
374 }
375
376 if (flags & CMS_USE_KEYID) {
377 rek->rid->type = CMS_REK_KEYIDENTIFIER;
378 rek->rid->d.rKeyId = M_ASN1_new_of(CMS_RecipientKeyIdentifier);
379 if (rek->rid->d.rKeyId == NULL)
380 return 0;
381 if (!ossl_cms_set1_keyid(&rek->rid->d.rKeyId->subjectKeyIdentifier, recip))
382 return 0;
383 } else {
384 rek->rid->type = CMS_REK_ISSUER_SERIAL;
385 if (!ossl_cms_set1_ias(&rek->rid->d.issuerAndSerialNumber, recip))
386 return 0;
387 }
388
389 if (originatorPrivKey == NULL && originator == NULL) {
390 /* Create ephemeral key */
391 if (!cms_kari_create_ephemeral_key(kari, recipPubKey))
392 return 0;
393 } else {
394 /* Use originator key */
395 CMS_OriginatorIdentifierOrKey *oik = ri->d.kari->originator;
396
397 if (originatorPrivKey == NULL || originator == NULL)
398 return 0;
399
400 if (flags & CMS_USE_ORIGINATOR_KEYID) {
401 oik->type = CMS_OIK_KEYIDENTIFIER;
402 oik->d.subjectKeyIdentifier = ASN1_OCTET_STRING_new();
403 if (oik->d.subjectKeyIdentifier == NULL)
404 return 0;
405 if (!ossl_cms_set1_keyid(&oik->d.subjectKeyIdentifier, originator))
406 return 0;
407 } else {
408 oik->type = CMS_REK_ISSUER_SERIAL;
409 if (!ossl_cms_set1_ias(&oik->d.issuerAndSerialNumber, originator))
410 return 0;
411 }
412
413 if (!cms_kari_set_originator_private_key(kari, originatorPrivKey))
414 return 0;
415 }
416
417 if (!EVP_PKEY_up_ref(recipPubKey))
418 return 0;
419
420 rek->pkey = recipPubKey;
421 return 1;
422 }
423
cms_wrap_init(CMS_KeyAgreeRecipientInfo * kari,const EVP_CIPHER * cipher)424 static int cms_wrap_init(CMS_KeyAgreeRecipientInfo *kari,
425 const EVP_CIPHER *cipher)
426 {
427 const CMS_CTX *cms_ctx = kari->cms_ctx;
428 EVP_CIPHER_CTX *ctx = kari->ctx;
429 const EVP_CIPHER *kekcipher;
430 EVP_CIPHER *fetched_kekcipher;
431 const char *kekcipher_name;
432 int keylen;
433 int ret;
434
435 /* If a suitable wrap algorithm is already set nothing to do */
436 kekcipher = EVP_CIPHER_CTX_get0_cipher(ctx);
437 if (kekcipher != NULL) {
438 if (EVP_CIPHER_CTX_get_mode(ctx) != EVP_CIPH_WRAP_MODE)
439 return 0;
440 return 1;
441 }
442 if (cipher == NULL)
443 return 0;
444 keylen = EVP_CIPHER_get_key_length(cipher);
445 if ((EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_GET_WRAP_CIPHER) != 0) {
446 ret = EVP_CIPHER_meth_get_ctrl(cipher)(NULL, EVP_CTRL_GET_WRAP_CIPHER,
447 0, &kekcipher);
448 if (ret <= 0)
449 return 0;
450
451 if (kekcipher != NULL) {
452 if (EVP_CIPHER_get_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
453 return 0;
454 kekcipher_name = EVP_CIPHER_get0_name(kekcipher);
455 goto enc;
456 }
457 }
458
459 /*
460 * Pick a cipher based on content encryption cipher. If it is DES3 use
461 * DES3 wrap otherwise use AES wrap similar to key size.
462 */
463 #ifndef OPENSSL_NO_DES
464 if (EVP_CIPHER_get_type(cipher) == NID_des_ede3_cbc)
465 kekcipher_name = SN_id_smime_alg_CMS3DESwrap;
466 else
467 #endif
468 if (keylen <= 16)
469 kekcipher_name = SN_id_aes128_wrap;
470 else if (keylen <= 24)
471 kekcipher_name = SN_id_aes192_wrap;
472 else
473 kekcipher_name = SN_id_aes256_wrap;
474 enc:
475 fetched_kekcipher = EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(cms_ctx),
476 kekcipher_name,
477 ossl_cms_ctx_get0_propq(cms_ctx));
478 if (fetched_kekcipher == NULL)
479 return 0;
480 ret = EVP_EncryptInit_ex(ctx, fetched_kekcipher, NULL, NULL, NULL);
481 EVP_CIPHER_free(fetched_kekcipher);
482 return ret;
483 }
484
485 /* Encrypt content key in key agreement recipient info */
486
ossl_cms_RecipientInfo_kari_encrypt(const CMS_ContentInfo * cms,CMS_RecipientInfo * ri)487 int ossl_cms_RecipientInfo_kari_encrypt(const CMS_ContentInfo *cms,
488 CMS_RecipientInfo *ri)
489 {
490 CMS_KeyAgreeRecipientInfo *kari;
491 CMS_EncryptedContentInfo *ec;
492 CMS_RecipientEncryptedKey *rek;
493 STACK_OF(CMS_RecipientEncryptedKey) *reks;
494 int i;
495
496 if (ri->type != CMS_RECIPINFO_AGREE) {
497 ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT);
498 return 0;
499 }
500 kari = ri->d.kari;
501 reks = kari->recipientEncryptedKeys;
502 ec = ossl_cms_get0_env_enc_content(cms);
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 } else {
517 /*
518 * Currently it is not possible to get public key as it is not stored
519 * during kari initialization.
520 */
521 ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_UNSUPPORTED_STATIC_KEY_AGREEMENT);
522 return 0;
523 }
524 /* Initialise KDF algorithm */
525 if (!ossl_cms_env_asn1_ctrl(ri, 0))
526 return 0;
527 /* For each rek, derive KEK, encrypt CEK */
528 for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) {
529 unsigned char *enckey;
530 size_t enckeylen;
531 rek = sk_CMS_RecipientEncryptedKey_value(reks, i);
532 if (EVP_PKEY_derive_set_peer(kari->pctx, rek->pkey) <= 0)
533 return 0;
534 if (!cms_kek_cipher(&enckey, &enckeylen, ec->key, ec->keylen,
535 kari, 1))
536 return 0;
537 ASN1_STRING_set0(rek->encryptedKey, enckey, enckeylen);
538 }
539
540 return 1;
541 }
542