Coverage Report

Created: 2025-06-13 06:58

/src/openssl30/crypto/cms/cms_pwri.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2009-2022 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/rand.h>
17
#include <openssl/aes.h>
18
#include "internal/sizes.h"
19
#include "crypto/asn1.h"
20
#include "cms_local.h"
21
22
int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri,
23
                                    unsigned char *pass, ossl_ssize_t passlen)
24
0
{
25
0
    CMS_PasswordRecipientInfo *pwri;
26
0
    if (ri->type != CMS_RECIPINFO_PASS) {
27
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_PWRI);
28
0
        return 0;
29
0
    }
30
31
0
    pwri = ri->d.pwri;
32
0
    pwri->pass = pass;
33
0
    if (pass && passlen < 0)
34
0
        passlen = strlen((char *)pass);
35
0
    pwri->passlen = passlen;
36
0
    return 1;
37
0
}
38
39
CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms,
40
                                               int iter, int wrap_nid,
41
                                               int pbe_nid,
42
                                               unsigned char *pass,
43
                                               ossl_ssize_t passlen,
44
                                               const EVP_CIPHER *kekciph)
45
0
{
46
0
    STACK_OF(CMS_RecipientInfo) *ris;
47
0
    CMS_RecipientInfo *ri = NULL;
48
0
    CMS_EncryptedContentInfo *ec;
49
0
    CMS_PasswordRecipientInfo *pwri;
50
0
    EVP_CIPHER_CTX *ctx = NULL;
51
0
    X509_ALGOR *encalg = NULL;
52
0
    unsigned char iv[EVP_MAX_IV_LENGTH];
53
0
    int ivlen;
54
0
    const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
55
56
0
    ec = ossl_cms_get0_env_enc_content(cms);
57
0
    if (ec == NULL)
58
0
        return NULL;
59
0
    ris = CMS_get0_RecipientInfos(cms);
60
0
    if (ris == NULL)
61
0
        return NULL;
62
63
0
    if (wrap_nid <= 0)
64
0
        wrap_nid = NID_id_alg_PWRI_KEK;
65
66
0
    if (pbe_nid <= 0)
67
0
        pbe_nid = NID_id_pbkdf2;
68
69
    /* Get from enveloped data */
70
0
    if (kekciph == NULL)
71
0
        kekciph = ec->cipher;
72
73
0
    if (kekciph == NULL) {
74
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_CIPHER);
75
0
        return NULL;
76
0
    }
77
0
    if (wrap_nid != NID_id_alg_PWRI_KEK) {
78
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM);
79
0
        return NULL;
80
0
    }
81
82
    /* Setup algorithm identifier for cipher */
83
0
    encalg = X509_ALGOR_new();
84
0
    if (encalg == NULL) {
85
0
        goto merr;
86
0
    }
87
0
    ctx = EVP_CIPHER_CTX_new();
88
0
    if (ctx == NULL) {
89
0
        ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
90
0
        goto err;
91
0
    }
92
93
0
    if (EVP_EncryptInit_ex(ctx, kekciph, NULL, NULL, NULL) <= 0) {
94
0
        ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
95
0
        goto err;
96
0
    }
97
98
0
    ivlen = EVP_CIPHER_CTX_get_iv_length(ctx);
99
0
    if (ivlen < 0) {
100
0
        ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
101
0
        goto err;
102
0
    }
103
104
0
    if (ivlen > 0) {
105
0
        if (RAND_bytes_ex(ossl_cms_ctx_get0_libctx(cms_ctx), iv, ivlen, 0) <= 0)
106
0
            goto err;
107
0
        if (EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv) <= 0) {
108
0
            ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
109
0
            goto err;
110
0
        }
111
0
        encalg->parameter = ASN1_TYPE_new();
112
0
        if (!encalg->parameter) {
113
0
            ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
114
0
            goto err;
115
0
        }
116
0
        if (EVP_CIPHER_param_to_asn1(ctx, encalg->parameter) <= 0) {
117
0
            ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR);
118
0
            goto err;
119
0
        }
120
0
    }
121
122
0
    encalg->algorithm = OBJ_nid2obj(EVP_CIPHER_CTX_get_type(ctx));
123
124
0
    EVP_CIPHER_CTX_free(ctx);
125
0
    ctx = NULL;
126
127
    /* Initialize recipient info */
128
0
    ri = M_ASN1_new_of(CMS_RecipientInfo);
129
0
    if (ri == NULL)
130
0
        goto merr;
131
132
0
    ri->d.pwri = M_ASN1_new_of(CMS_PasswordRecipientInfo);
133
0
    if (ri->d.pwri == NULL)
134
0
        goto merr;
135
0
    ri->type = CMS_RECIPINFO_PASS;
136
137
0
    pwri = ri->d.pwri;
138
0
    pwri->cms_ctx = cms_ctx;
139
    /* Since this is overwritten, free up empty structure already there */
140
0
    X509_ALGOR_free(pwri->keyEncryptionAlgorithm);
141
0
    pwri->keyEncryptionAlgorithm = X509_ALGOR_new();
142
0
    if (pwri->keyEncryptionAlgorithm == NULL)
143
0
        goto merr;
144
0
    pwri->keyEncryptionAlgorithm->algorithm = OBJ_nid2obj(wrap_nid);
145
0
    pwri->keyEncryptionAlgorithm->parameter = ASN1_TYPE_new();
146
0
    if (pwri->keyEncryptionAlgorithm->parameter == NULL)
147
0
        goto merr;
148
149
0
    if (!ASN1_item_pack(encalg, ASN1_ITEM_rptr(X509_ALGOR),
150
0
                        &pwri->keyEncryptionAlgorithm->parameter->
151
0
                        value.sequence))
152
0
         goto merr;
153
0
    pwri->keyEncryptionAlgorithm->parameter->type = V_ASN1_SEQUENCE;
154
155
0
    X509_ALGOR_free(encalg);
156
0
    encalg = NULL;
157
158
    /* Setup PBE algorithm */
159
160
0
    pwri->keyDerivationAlgorithm = PKCS5_pbkdf2_set_ex(iter, NULL, 0, -1, -1,
161
0
                                                       cms_ctx->libctx);
162
163
0
    if (pwri->keyDerivationAlgorithm == NULL)
164
0
        goto err;
165
166
0
    CMS_RecipientInfo_set0_password(ri, pass, passlen);
167
0
    pwri->version = 0;
168
169
0
    if (!sk_CMS_RecipientInfo_push(ris, ri))
170
0
        goto merr;
171
172
0
    return ri;
173
174
0
 merr:
175
0
    ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
176
0
 err:
177
0
    EVP_CIPHER_CTX_free(ctx);
178
0
    if (ri)
179
0
        M_ASN1_free_of(ri, CMS_RecipientInfo);
180
0
    X509_ALGOR_free(encalg);
181
0
    return NULL;
182
183
0
}
184
185
/*
186
 * This is an implementation of the key wrapping mechanism in RFC3211, at
187
 * some point this should go into EVP.
188
 */
189
190
static int kek_unwrap_key(unsigned char *out, size_t *outlen,
191
                          const unsigned char *in, size_t inlen,
192
                          EVP_CIPHER_CTX *ctx)
193
0
{
194
0
    size_t blocklen = EVP_CIPHER_CTX_get_block_size(ctx);
195
0
    unsigned char *tmp;
196
0
    int outl, rv = 0;
197
0
    if (inlen < 2 * blocklen) {
198
        /* too small */
199
0
        return 0;
200
0
    }
201
0
    if (inlen % blocklen) {
202
        /* Invalid size */
203
0
        return 0;
204
0
    }
205
0
    if ((tmp = OPENSSL_malloc(inlen)) == NULL) {
206
0
        ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
207
0
        return 0;
208
0
    }
209
    /* setup IV by decrypting last two blocks */
210
0
    if (!EVP_DecryptUpdate(ctx, tmp + inlen - 2 * blocklen, &outl,
211
0
                           in + inlen - 2 * blocklen, blocklen * 2)
212
        /*
213
         * Do a decrypt of last decrypted block to set IV to correct value
214
         * output it to start of buffer so we don't corrupt decrypted block
215
         * this works because buffer is at least two block lengths long.
216
         */
217
0
        || !EVP_DecryptUpdate(ctx, tmp, &outl,
218
0
                              tmp + inlen - blocklen, blocklen)
219
        /* Can now decrypt first n - 1 blocks */
220
0
        || !EVP_DecryptUpdate(ctx, tmp, &outl, in, inlen - blocklen)
221
222
        /* Reset IV to original value */
223
0
        || !EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL)
224
        /* Decrypt again */
225
0
        || !EVP_DecryptUpdate(ctx, tmp, &outl, tmp, inlen))
226
0
        goto err;
227
    /* Check check bytes */
228
0
    if (((tmp[1] ^ tmp[4]) & (tmp[2] ^ tmp[5]) & (tmp[3] ^ tmp[6])) != 0xff) {
229
        /* Check byte failure */
230
0
        goto err;
231
0
    }
232
0
    if (inlen < (size_t)(tmp[0] - 4)) {
233
        /* Invalid length value */
234
0
        goto err;
235
0
    }
236
0
    *outlen = (size_t)tmp[0];
237
0
    memcpy(out, tmp + 4, *outlen);
238
0
    rv = 1;
239
0
 err:
240
0
    OPENSSL_clear_free(tmp, inlen);
241
0
    return rv;
242
243
0
}
244
245
static int kek_wrap_key(unsigned char *out, size_t *outlen,
246
                        const unsigned char *in, size_t inlen,
247
                        EVP_CIPHER_CTX *ctx, const CMS_CTX *cms_ctx)
248
0
{
249
0
    size_t blocklen = EVP_CIPHER_CTX_get_block_size(ctx);
250
0
    size_t olen;
251
0
    int dummy;
252
    /*
253
     * First decide length of output buffer: need header and round up to
254
     * multiple of block length.
255
     */
256
0
    olen = (inlen + 4 + blocklen - 1) / blocklen;
257
0
    olen *= blocklen;
258
0
    if (olen < 2 * blocklen) {
259
        /* Key too small */
260
0
        return 0;
261
0
    }
262
0
    if (inlen > 0xFF) {
263
        /* Key too large */
264
0
        return 0;
265
0
    }
266
0
    if (out) {
267
        /* Set header */
268
0
        out[0] = (unsigned char)inlen;
269
0
        out[1] = in[0] ^ 0xFF;
270
0
        out[2] = in[1] ^ 0xFF;
271
0
        out[3] = in[2] ^ 0xFF;
272
0
        memcpy(out + 4, in, inlen);
273
        /* Add random padding to end */
274
0
        if (olen > inlen + 4
275
0
            && RAND_bytes_ex(ossl_cms_ctx_get0_libctx(cms_ctx), out + 4 + inlen,
276
0
                             olen - 4 - inlen, 0) <= 0)
277
0
            return 0;
278
        /* Encrypt twice */
279
0
        if (!EVP_EncryptUpdate(ctx, out, &dummy, out, olen)
280
0
            || !EVP_EncryptUpdate(ctx, out, &dummy, out, olen))
281
0
            return 0;
282
0
    }
283
284
0
    *outlen = olen;
285
286
0
    return 1;
287
0
}
288
289
/* Encrypt/Decrypt content key in PWRI recipient info */
290
291
int ossl_cms_RecipientInfo_pwri_crypt(const CMS_ContentInfo *cms,
292
                                      CMS_RecipientInfo *ri, int en_de)
293
0
{
294
0
    CMS_EncryptedContentInfo *ec;
295
0
    CMS_PasswordRecipientInfo *pwri;
296
0
    int r = 0;
297
0
    X509_ALGOR *algtmp, *kekalg = NULL;
298
0
    EVP_CIPHER_CTX *kekctx = NULL;
299
0
    char name[OSSL_MAX_NAME_SIZE];
300
0
    EVP_CIPHER *kekcipher;
301
0
    unsigned char *key = NULL;
302
0
    size_t keylen;
303
0
    const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
304
305
0
    ec = ossl_cms_get0_env_enc_content(cms);
306
307
0
    pwri = ri->d.pwri;
308
309
0
    if (pwri->pass == NULL) {
310
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_PASSWORD);
311
0
        return 0;
312
0
    }
313
0
    algtmp = pwri->keyEncryptionAlgorithm;
314
315
0
    if (!algtmp || OBJ_obj2nid(algtmp->algorithm) != NID_id_alg_PWRI_KEK) {
316
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM);
317
0
        return 0;
318
0
    }
319
320
0
    kekalg = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(X509_ALGOR),
321
0
                                       algtmp->parameter);
322
323
0
    if (kekalg == NULL) {
324
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER);
325
0
        return 0;
326
0
    }
327
328
0
    OBJ_obj2txt(name, sizeof(name), kekalg->algorithm, 0);
329
0
    kekcipher = EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(cms_ctx), name,
330
0
                                 ossl_cms_ctx_get0_propq(cms_ctx));
331
332
0
    if (kekcipher == NULL) {
333
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_CIPHER);
334
0
        goto err;
335
0
    }
336
337
0
    kekctx = EVP_CIPHER_CTX_new();
338
0
    if (kekctx == NULL) {
339
0
        ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
340
0
        goto err;
341
0
    }
342
    /* Fixup cipher based on AlgorithmIdentifier to set IV etc */
343
0
    if (!EVP_CipherInit_ex(kekctx, kekcipher, NULL, NULL, NULL, en_de))
344
0
        goto err;
345
0
    EVP_CIPHER_CTX_set_padding(kekctx, 0);
346
0
    if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0) {
347
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR);
348
0
        goto err;
349
0
    }
350
351
0
    algtmp = pwri->keyDerivationAlgorithm;
352
353
    /* Finish password based key derivation to setup key in "ctx" */
354
355
0
    if (EVP_PBE_CipherInit_ex(algtmp->algorithm,
356
0
                              (char *)pwri->pass, pwri->passlen,
357
0
                              algtmp->parameter, kekctx, en_de,
358
0
                              cms_ctx->libctx, cms_ctx->propq) < 0) {
359
0
        ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
360
0
        goto err;
361
0
    }
362
363
    /* Finally wrap/unwrap the key */
364
365
0
    if (en_de) {
366
367
0
        if (!kek_wrap_key(NULL, &keylen, ec->key, ec->keylen, kekctx, cms_ctx))
368
0
            goto err;
369
370
0
        key = OPENSSL_malloc(keylen);
371
372
0
        if (key == NULL)
373
0
            goto err;
374
375
0
        if (!kek_wrap_key(key, &keylen, ec->key, ec->keylen, kekctx, cms_ctx))
376
0
            goto err;
377
0
        pwri->encryptedKey->data = key;
378
0
        pwri->encryptedKey->length = keylen;
379
0
    } else {
380
0
        key = OPENSSL_malloc(pwri->encryptedKey->length);
381
382
0
        if (key == NULL) {
383
0
            ERR_raise(ERR_LIB_CMS, ERR_R_MALLOC_FAILURE);
384
0
            goto err;
385
0
        }
386
0
        if (!kek_unwrap_key(key, &keylen,
387
0
                            pwri->encryptedKey->data,
388
0
                            pwri->encryptedKey->length, kekctx)) {
389
0
            ERR_raise(ERR_LIB_CMS, CMS_R_UNWRAP_FAILURE);
390
0
            goto err;
391
0
        }
392
393
0
        OPENSSL_clear_free(ec->key, ec->keylen);
394
0
        ec->key = key;
395
0
        ec->keylen = keylen;
396
397
0
    }
398
399
0
    r = 1;
400
401
0
 err:
402
0
    EVP_CIPHER_free(kekcipher);
403
0
    EVP_CIPHER_CTX_free(kekctx);
404
405
0
    if (!r)
406
0
        OPENSSL_free(key);
407
0
    X509_ALGOR_free(kekalg);
408
409
0
    return r;
410
411
0
}