Implementation of Russian GOST CMS
[openssl.git] / crypto / cms / cms_kari.c
1 /*
2  * Copyright 2013-2016 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     enckeylen = rek->encryptedKey->length;
252     enckey = rek->encryptedKey->data;
253     /* Setup all parameters to derive KEK */
254     if (!cms_env_asn1_ctrl(ri, 1))
255         goto err;
256     /* Attempt to decrypt CEK */
257     if (!cms_kek_cipher(&cek, &ceklen, enckey, enckeylen, ri->d.kari, 0))
258         goto err;
259     ec = cms->d.envelopedData->encryptedContentInfo;
260     OPENSSL_clear_free(ec->key, ec->keylen);
261     ec->key = cek;
262     ec->keylen = ceklen;
263     cek = NULL;
264     rv = 1;
265  err:
266     OPENSSL_free(cek);
267     return rv;
268 }
269
270 /* Create ephemeral key and initialise context based on it */
271 static int cms_kari_create_ephemeral_key(CMS_KeyAgreeRecipientInfo *kari,
272                                          EVP_PKEY *pk)
273 {
274     EVP_PKEY_CTX *pctx = NULL;
275     EVP_PKEY *ekey = NULL;
276     int rv = 0;
277
278     pctx = EVP_PKEY_CTX_new(pk, NULL);
279     if (pctx == NULL)
280         goto err;
281     if (EVP_PKEY_keygen_init(pctx) <= 0)
282         goto err;
283     if (EVP_PKEY_keygen(pctx, &ekey) <= 0)
284         goto err;
285     EVP_PKEY_CTX_free(pctx);
286     pctx = EVP_PKEY_CTX_new(ekey, NULL);
287     if (pctx == NULL)
288         goto err;
289     if (EVP_PKEY_derive_init(pctx) <= 0)
290         goto err;
291     kari->pctx = pctx;
292     rv = 1;
293  err:
294     if (!rv)
295         EVP_PKEY_CTX_free(pctx);
296     EVP_PKEY_free(ekey);
297     return rv;
298 }
299
300 /* Set originator private key and initialise context based on it */
301 static int cms_kari_set_originator_private_key(CMS_KeyAgreeRecipientInfo *kari, EVP_PKEY *originatorPrivKey )
302 {
303     EVP_PKEY_CTX *pctx = NULL;
304     int rv = 0;
305
306     pctx = EVP_PKEY_CTX_new(originatorPrivKey, NULL);
307     if (pctx == NULL)
308         goto err;
309     if (EVP_PKEY_derive_init(pctx) <= 0)
310          goto err;
311
312     kari->pctx = pctx;
313     rv = 1;
314  err:
315     if (rv == 0)
316         EVP_PKEY_CTX_free(pctx);
317     return rv;
318 }
319
320 /* Initialise a kari based on passed certificate and key */
321
322 int cms_RecipientInfo_kari_init(CMS_RecipientInfo *ri,  X509 *recip, EVP_PKEY *recipPubKey, X509 * originator, EVP_PKEY *originatorPrivKey, unsigned int flags)
323 {
324     CMS_KeyAgreeRecipientInfo *kari;
325     CMS_RecipientEncryptedKey *rek = NULL;
326
327     ri->d.kari = M_ASN1_new_of(CMS_KeyAgreeRecipientInfo);
328     if (!ri->d.kari)
329         return 0;
330     ri->type = CMS_RECIPINFO_AGREE;
331
332     kari = ri->d.kari;
333     kari->version = 3;
334
335     rek = M_ASN1_new_of(CMS_RecipientEncryptedKey);
336     if (rek == NULL)
337         return 0;
338
339     if (!sk_CMS_RecipientEncryptedKey_push(kari->recipientEncryptedKeys, rek)) {
340         M_ASN1_free_of(rek, CMS_RecipientEncryptedKey);
341         return 0;
342     }
343
344     if (flags & CMS_USE_KEYID) {
345         rek->rid->type = CMS_REK_KEYIDENTIFIER;
346         rek->rid->d.rKeyId = M_ASN1_new_of(CMS_RecipientKeyIdentifier);
347         if (rek->rid->d.rKeyId == NULL)
348             return 0;
349         if (!cms_set1_keyid(&rek->rid->d.rKeyId->subjectKeyIdentifier, recip))
350             return 0;
351     } else {
352         rek->rid->type = CMS_REK_ISSUER_SERIAL;
353         if (!cms_set1_ias(&rek->rid->d.issuerAndSerialNumber, recip))
354             return 0;
355     }
356
357     if (originatorPrivKey == NULL && originator == NULL) {
358         /* Create ephemeral key */
359         if (!cms_kari_create_ephemeral_key(kari, recipPubKey))
360             return 0;
361     } else {
362          /* Use originator key */
363          CMS_OriginatorIdentifierOrKey *oik = ri->d.kari->originator;
364
365          if (originatorPrivKey == NULL && originator == NULL)
366             return 0;
367
368          if (flags & CMS_USE_ORIGINATOR_KEYID) {
369               oik->type = CMS_OIK_KEYIDENTIFIER;
370               oik->d.subjectKeyIdentifier = ASN1_OCTET_STRING_new();
371               if (oik->d.subjectKeyIdentifier == NULL)
372                    return 0;
373               if (!cms_set1_keyid(&oik->d.subjectKeyIdentifier, originator))
374                    return 0;
375          } else {
376               oik->type = CMS_REK_ISSUER_SERIAL;
377               if (!cms_set1_ias(&oik->d.issuerAndSerialNumber, originator))
378                    return 0;
379          }
380
381          if (!cms_kari_set_originator_private_key(kari, originatorPrivKey))
382              return 0;
383     }
384
385     EVP_PKEY_up_ref(recipPubKey);
386     rek->pkey = recipPubKey;
387     return 1;
388 }
389
390 static int cms_wrap_init(CMS_KeyAgreeRecipientInfo *kari,
391                          const EVP_CIPHER *cipher)
392 {
393     EVP_CIPHER_CTX *ctx = kari->ctx;
394     const EVP_CIPHER *kekcipher;
395     int keylen = EVP_CIPHER_key_length(cipher);
396     int ret;
397
398     /* If a suitable wrap algorithm is already set nothing to do */
399     kekcipher = EVP_CIPHER_CTX_cipher(ctx);
400     if (kekcipher != NULL) {
401         if (EVP_CIPHER_CTX_mode(ctx) != EVP_CIPH_WRAP_MODE)
402             return 0;
403         return 1;
404     }
405     else if (cipher != NULL
406          && (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_GET_WRAP_CIPHER)) {
407         ret = EVP_CIPHER_meth_get_ctrl(cipher)(NULL, EVP_CTRL_GET_WRAP_CIPHER,
408                                                0, &kekcipher);
409         if (ret <= 0)
410              return 0;
411
412         if (kekcipher != NULL) {
413              if (EVP_CIPHER_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
414                  return 0;
415
416              return EVP_EncryptInit_ex(ctx, kekcipher, NULL, NULL, NULL);
417         }
418     }
419
420     /*
421      * Pick a cipher based on content encryption cipher. If it is DES3 use
422      * DES3 wrap otherwise use AES wrap similar to key size.
423      */
424 #ifndef OPENSSL_NO_DES
425     if (EVP_CIPHER_type(cipher) == NID_des_ede3_cbc)
426         kekcipher = EVP_des_ede3_wrap();
427     else
428 #endif
429     if (keylen <= 16)
430         kekcipher = EVP_aes_128_wrap();
431     else if (keylen <= 24)
432         kekcipher = EVP_aes_192_wrap();
433     else
434         kekcipher = EVP_aes_256_wrap();
435     return EVP_EncryptInit_ex(ctx, kekcipher, NULL, NULL, NULL);
436 }
437
438 /* Encrypt content key in key agreement recipient info */
439
440 int cms_RecipientInfo_kari_encrypt(const CMS_ContentInfo *cms,
441                                    CMS_RecipientInfo *ri)
442 {
443     CMS_KeyAgreeRecipientInfo *kari;
444     CMS_EncryptedContentInfo *ec;
445     CMS_RecipientEncryptedKey *rek;
446     STACK_OF(CMS_RecipientEncryptedKey) *reks;
447     int i;
448
449     if (ri->type != CMS_RECIPINFO_AGREE) {
450         CMSerr(CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT, CMS_R_NOT_KEY_AGREEMENT);
451         return 0;
452     }
453     kari = ri->d.kari;
454     reks = kari->recipientEncryptedKeys;
455     ec = cms->d.envelopedData->encryptedContentInfo;
456     /* Initialise wrap algorithm parameters */
457     if (!cms_wrap_init(kari, ec->cipher))
458         return 0;
459     /*
460      * If no originator key set up initialise for ephemeral key the public key
461      * ASN1 structure will set the actual public key value.
462      */
463     if (kari->originator->type == -1) {
464         CMS_OriginatorIdentifierOrKey *oik = kari->originator;
465         oik->type = CMS_OIK_PUBKEY;
466         oik->d.originatorKey = M_ASN1_new_of(CMS_OriginatorPublicKey);
467         if (!oik->d.originatorKey)
468             return 0;
469     }
470     /* Initialise KDF algorithm */
471     if (!cms_env_asn1_ctrl(ri, 0))
472         return 0;
473     /* For each rek, derive KEK, encrypt CEK */
474     for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) {
475         unsigned char *enckey;
476         size_t enckeylen;
477         rek = sk_CMS_RecipientEncryptedKey_value(reks, i);
478         if (EVP_PKEY_derive_set_peer(kari->pctx, rek->pkey) <= 0)
479             return 0;
480         if (!cms_kek_cipher(&enckey, &enckeylen, ec->key, ec->keylen,
481                             kari, 1))
482             return 0;
483         ASN1_STRING_set0(rek->encryptedKey, enckey, enckeylen);
484     }
485
486     return 1;
487
488 }