Coverage Report

Created: 2026-09-12 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl40/crypto/cms/cms_sd.c
Line
Count
Source
1
/*
2
 * Copyright 2008-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
#include "internal/cryptlib.h"
11
#include <openssl/asn1t.h>
12
#include <openssl/pem.h>
13
#include <openssl/x509.h>
14
#include <openssl/x509v3.h>
15
#include <openssl/err.h>
16
#include <openssl/cms.h>
17
#include <openssl/ess.h>
18
#include "internal/sizes.h"
19
#include "crypto/asn1.h"
20
#include "crypto/evp.h"
21
#include "crypto/ess.h"
22
#include "crypto/x509.h" /* for ossl_x509_add_cert_new() */
23
#include "cms_local.h"
24
25
/* CMS SignedData Utilities */
26
27
static CMS_SignedData *cms_get0_signed(CMS_ContentInfo *cms)
28
5.50k
{
29
5.50k
    if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_signed) {
30
4.26k
        ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA);
31
4.26k
        return NULL;
32
4.26k
    }
33
1.23k
    return cms->d.signedData;
34
5.50k
}
35
36
static CMS_SignedData *cms_signed_data_init(CMS_ContentInfo *cms)
37
0
{
38
0
    if (cms->d.other == NULL) {
39
0
        cms->d.signedData = M_ASN1_new_of(CMS_SignedData);
40
0
        if (!cms->d.signedData) {
41
0
            ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
42
0
            return NULL;
43
0
        }
44
0
        cms->d.signedData->version = 1;
45
0
        cms->d.signedData->encapContentInfo->eContentType = OBJ_nid2obj(NID_pkcs7_data);
46
0
        cms->d.signedData->encapContentInfo->partial = 1;
47
0
        ASN1_OBJECT_free(cms->contentType);
48
0
        cms->contentType = OBJ_nid2obj(NID_pkcs7_signed);
49
0
        return cms->d.signedData;
50
0
    }
51
0
    return cms_get0_signed(cms);
52
0
}
53
54
/* Just initialise SignedData e.g. for certs only structure */
55
int CMS_SignedData_init(CMS_ContentInfo *cms)
56
0
{
57
0
    if (cms_signed_data_init(cms))
58
0
        return 1;
59
0
    else
60
0
        return 0;
61
0
}
62
63
/* Check structures and fixup version numbers (if necessary) */
64
static void cms_sd_set_version(CMS_SignedData *sd)
65
0
{
66
0
    int i;
67
0
    CMS_CertificateChoices *cch;
68
0
    CMS_RevocationInfoChoice *rch;
69
0
    CMS_SignerInfo *si;
70
71
0
    for (i = 0; i < sk_CMS_CertificateChoices_num(sd->certificates); i++) {
72
0
        cch = sk_CMS_CertificateChoices_value(sd->certificates, i);
73
0
        if (cch->type == CMS_CERTCHOICE_OTHER) {
74
0
            if (sd->version < 5)
75
0
                sd->version = 5;
76
0
        } else if (cch->type == CMS_CERTCHOICE_V2ACERT) {
77
0
            if (sd->version < 4)
78
0
                sd->version = 4;
79
0
        } else if (cch->type == CMS_CERTCHOICE_V1ACERT) {
80
0
            if (sd->version < 3)
81
0
                sd->version = 3;
82
0
        }
83
0
    }
84
85
0
    for (i = 0; i < sk_CMS_RevocationInfoChoice_num(sd->crls); i++) {
86
0
        rch = sk_CMS_RevocationInfoChoice_value(sd->crls, i);
87
0
        if (rch->type == CMS_REVCHOICE_OTHER) {
88
0
            if (sd->version < 5)
89
0
                sd->version = 5;
90
0
        }
91
0
    }
92
93
0
    if ((OBJ_obj2nid(sd->encapContentInfo->eContentType) != NID_pkcs7_data)
94
0
        && (sd->version < 3))
95
0
        sd->version = 3;
96
97
0
    for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) {
98
0
        si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
99
0
        if (si->sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) {
100
0
            if (si->version < 3)
101
0
                si->version = 3;
102
0
            if (sd->version < 3)
103
0
                sd->version = 3;
104
0
        } else if (si->version < 1) {
105
0
            si->version = 1;
106
0
        }
107
0
    }
108
109
0
    if (sd->version < 1)
110
0
        sd->version = 1;
111
0
}
112
113
/*
114
 * RFC 5652 Section 11.1 Content Type
115
 * The content-type attribute within signed-data MUST
116
 *   1) be present if there are signed attributes
117
 *   2) match the content type in the signed-data,
118
 *   3) be a signed attribute.
119
 *   4) not have more than one copy of the attribute.
120
 *
121
 * Note that since the CMS_SignerInfo_sign() always adds the "signing time"
122
 * attribute, the content type attribute MUST be added also.
123
 * Assumptions: This assumes that the attribute does not already exist.
124
 */
125
static int cms_set_si_contentType_attr(CMS_ContentInfo *cms, CMS_SignerInfo *si)
126
0
{
127
0
    ASN1_OBJECT *ctype = cms->d.signedData->encapContentInfo->eContentType;
128
129
    /* Add the contentType attribute */
130
0
    return CMS_signed_add1_attr_by_NID(si, NID_pkcs9_contentType,
131
0
               V_ASN1_OBJECT, ctype, -1)
132
0
        > 0;
133
0
}
134
135
/* Copy an existing messageDigest value */
136
static int cms_copy_messageDigest(CMS_ContentInfo *cms, CMS_SignerInfo *si)
137
0
{
138
0
    STACK_OF(CMS_SignerInfo) *sinfos;
139
0
    CMS_SignerInfo *sitmp;
140
0
    int i;
141
142
0
    sinfos = CMS_get0_SignerInfos(cms);
143
0
    for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
144
0
        const ASN1_OCTET_STRING *messageDigest;
145
146
0
        sitmp = sk_CMS_SignerInfo_value(sinfos, i);
147
0
        if (sitmp == si)
148
0
            continue;
149
0
        if (CMS_signed_get_attr_count(sitmp) < 0)
150
0
            continue;
151
0
        if (OBJ_cmp(si->digestAlgorithm->algorithm,
152
0
                sitmp->digestAlgorithm->algorithm))
153
0
            continue;
154
0
        messageDigest = CMS_signed_get0_data_by_OBJ(sitmp,
155
0
            OBJ_nid2obj(NID_pkcs9_messageDigest),
156
0
            -3, V_ASN1_OCTET_STRING);
157
0
        if (!messageDigest) {
158
0
            ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE);
159
0
            return 0;
160
0
        }
161
162
0
        if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
163
0
                V_ASN1_OCTET_STRING,
164
0
                messageDigest, -1))
165
0
            return 1;
166
0
        else
167
0
            return 0;
168
0
    }
169
0
    ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_DIGEST);
170
0
    return 0;
171
0
}
172
173
int ossl_cms_set1_SignerIdentifier(CMS_SignerIdentifier *sid, X509 *cert,
174
    int type, const CMS_CTX *ctx)
175
0
{
176
0
    switch (type) {
177
0
    case CMS_SIGNERINFO_ISSUER_SERIAL:
178
0
        if (!ossl_cms_set1_ias(&sid->d.issuerAndSerialNumber, cert))
179
0
            return 0;
180
0
        break;
181
182
0
    case CMS_SIGNERINFO_KEYIDENTIFIER:
183
0
        if (!ossl_cms_set1_keyid(&sid->d.subjectKeyIdentifier, cert))
184
0
            return 0;
185
0
        break;
186
187
0
    default:
188
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_ID);
189
0
        return 0;
190
0
    }
191
192
0
    sid->type = type;
193
194
0
    return 1;
195
0
}
196
197
int ossl_cms_SignerIdentifier_get0_signer_id(CMS_SignerIdentifier *sid,
198
    ASN1_OCTET_STRING **keyid,
199
    X509_NAME **issuer,
200
    ASN1_INTEGER **sno)
201
0
{
202
0
    if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL) {
203
0
        if (issuer)
204
0
            *issuer = sid->d.issuerAndSerialNumber->issuer;
205
0
        if (sno)
206
0
            *sno = sid->d.issuerAndSerialNumber->serialNumber;
207
0
    } else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER) {
208
0
        if (keyid)
209
0
            *keyid = sid->d.subjectKeyIdentifier;
210
0
    } else {
211
0
        return 0;
212
0
    }
213
0
    return 1;
214
0
}
215
216
int ossl_cms_SignerIdentifier_cert_cmp(CMS_SignerIdentifier *sid, X509 *cert)
217
0
{
218
0
    if (sid->type == CMS_SIGNERINFO_ISSUER_SERIAL)
219
0
        return ossl_cms_ias_cert_cmp(sid->d.issuerAndSerialNumber, cert);
220
0
    else if (sid->type == CMS_SIGNERINFO_KEYIDENTIFIER)
221
0
        return ossl_cms_keyid_cert_cmp(sid->d.subjectKeyIdentifier, cert);
222
0
    else
223
0
        return -1;
224
0
}
225
226
static int cms_signature_nomd(EVP_PKEY *pkey)
227
0
{
228
0
    char def_md[80];
229
230
0
    return EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2
231
0
            && strcmp(def_md, "UNDEF") == 0
232
0
        ? 1
233
0
        : 0;
234
0
}
235
236
/* Method to map any, incl. provider-implemented PKEY types to OIDs */
237
/* (EC)DSA and all provider-delivered signatures implementation is the same */
238
static int cms_generic_sign(CMS_SignerInfo *si, int verify)
239
0
{
240
0
    if (!ossl_assert(verify == 0 || verify == 1))
241
0
        return -1;
242
243
0
    if (!verify) {
244
0
        EVP_PKEY *pkey = si->pkey;
245
0
        int snid, hnid, pknid = EVP_PKEY_get_id(pkey);
246
0
        X509_ALGOR *alg1, *alg2;
247
248
0
        CMS_SignerInfo_get0_algs(si, NULL, NULL, &alg1, &alg2);
249
0
        if (alg1 == NULL || alg1->algorithm == NULL)
250
0
            return -1;
251
0
        hnid = OBJ_obj2nid(alg1->algorithm);
252
0
        if (hnid == NID_undef)
253
0
            return -1;
254
0
        if (pknid <= 0) { /* check whether a provider registered a NID */
255
0
            const char *typename = EVP_PKEY_get0_type_name(pkey);
256
257
0
            if (typename != NULL)
258
0
                pknid = OBJ_txt2nid(typename);
259
0
        }
260
0
        if (pknid > 0 && cms_signature_nomd(pkey))
261
0
            snid = pknid;
262
0
        else if (!OBJ_find_sigid_by_algs(&snid, hnid, pknid))
263
0
            return -1;
264
0
        return X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, NULL);
265
0
    }
266
0
    return 1;
267
0
}
268
269
static int cms_sd_asn1_ctrl(CMS_SignerInfo *si, int cmd)
270
0
{
271
0
    EVP_PKEY *pkey = si->pkey;
272
0
    int i;
273
274
0
    if (EVP_PKEY_is_a(pkey, "DSA") || EVP_PKEY_is_a(pkey, "EC"))
275
0
        return cms_generic_sign(si, cmd) > 0;
276
0
    else if (EVP_PKEY_is_a(pkey, "RSA") || EVP_PKEY_is_a(pkey, "RSA-PSS"))
277
0
        return ossl_cms_rsa_sign(si, cmd) > 0;
278
279
    /* Now give engines, providers, etc a chance to handle this */
280
0
    if (pkey->ameth == NULL || pkey->ameth->pkey_ctrl == NULL)
281
0
        return cms_generic_sign(si, cmd) > 0;
282
0
    i = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_CMS_SIGN, cmd, si);
283
0
    if (i == -2) {
284
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
285
0
        return 0;
286
0
    }
287
0
    if (i <= 0) {
288
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE);
289
0
        return 0;
290
0
    }
291
0
    return 1;
292
0
}
293
294
/* Add SigningCertificate signed attribute to the signer info. */
295
static int ossl_cms_add1_signing_cert(CMS_SignerInfo *si,
296
    const ESS_SIGNING_CERT *sc)
297
0
{
298
0
    ASN1_STRING *seq = NULL;
299
0
    unsigned char *p, *pp = NULL;
300
0
    int ret, len = i2d_ESS_SIGNING_CERT(sc, NULL);
301
302
0
    if (len <= 0 || (pp = OPENSSL_malloc(len)) == NULL)
303
0
        return 0;
304
305
0
    p = pp;
306
0
    i2d_ESS_SIGNING_CERT(sc, &p);
307
0
    if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) {
308
0
        ASN1_STRING_free(seq);
309
0
        OPENSSL_free(pp);
310
0
        return 0;
311
0
    }
312
0
    OPENSSL_free(pp);
313
0
    ret = CMS_signed_add1_attr_by_NID(si, NID_id_smime_aa_signingCertificate,
314
0
        V_ASN1_SEQUENCE, seq, -1);
315
0
    ASN1_STRING_free(seq);
316
0
    return ret;
317
0
}
318
319
/* Add SigningCertificateV2 signed attribute to the signer info. */
320
static int ossl_cms_add1_signing_cert_v2(CMS_SignerInfo *si,
321
    const ESS_SIGNING_CERT_V2 *sc)
322
0
{
323
0
    ASN1_STRING *seq = NULL;
324
0
    unsigned char *p, *pp = NULL;
325
0
    int ret, len = i2d_ESS_SIGNING_CERT_V2(sc, NULL);
326
327
0
    if (len <= 0 || (pp = OPENSSL_malloc(len)) == NULL)
328
0
        return 0;
329
330
0
    p = pp;
331
0
    i2d_ESS_SIGNING_CERT_V2(sc, &p);
332
0
    if (!(seq = ASN1_STRING_new()) || !ASN1_STRING_set(seq, pp, len)) {
333
0
        ASN1_STRING_free(seq);
334
0
        OPENSSL_free(pp);
335
0
        return 0;
336
0
    }
337
0
    OPENSSL_free(pp);
338
0
    ret = CMS_signed_add1_attr_by_NID(si, NID_id_smime_aa_signingCertificateV2,
339
0
        V_ASN1_SEQUENCE, seq, -1);
340
0
    ASN1_STRING_free(seq);
341
0
    return ret;
342
0
}
343
344
static const struct {
345
    const char *name;
346
    int md_nid;
347
    int md_a_must; /* md is a 'MUST' */
348
    int noattr_md_nid; /* in case of 'without signed attributes' */
349
    int noattr_md_a_must; /* noattr_md is a 'MUST' not a 'SHOULD' */
350
} key2data[] = {
351
    {
352
        "ML-DSA-44",
353
        NID_shake256,
354
        0,
355
        NID_sha512,
356
        0,
357
    },
358
    {
359
        "ML-DSA-65",
360
        NID_shake256,
361
        0,
362
        NID_sha512,
363
        0,
364
    },
365
    {
366
        "ML-DSA-87",
367
        NID_shake256,
368
        0,
369
        NID_sha512,
370
        0,
371
    },
372
    {
373
        "ED25519",
374
        NID_sha512,
375
        1,
376
        NID_sha512,
377
        1,
378
    }, /* RFC 8419 */
379
    /* RFC 8419 3.1 ED448: id-shake256-len MUST be used => NID_undef for now */
380
    {
381
        "ED448",
382
        NID_undef,
383
        1,
384
        NID_shake256,
385
        1,
386
    },
387
    {
388
        "SLH-DSA-SHA2-128f",
389
        NID_sha256,
390
        0,
391
        NID_sha256,
392
        0,
393
    }, /* RFC 9814 */
394
    {
395
        "SLH-DSA-SHA2-128s",
396
        NID_sha256,
397
        0,
398
        NID_sha256,
399
        0,
400
    },
401
    {
402
        "SLH-DSA-SHA2-192f",
403
        NID_sha512,
404
        0,
405
        NID_sha512,
406
        0,
407
    },
408
    {
409
        "SLH-DSA-SHA2-192s",
410
        NID_sha512,
411
        0,
412
        NID_sha512,
413
        0,
414
    },
415
    {
416
        "SLH-DSA-SHA2-256f",
417
        NID_sha512,
418
        0,
419
        NID_sha512,
420
        0,
421
    },
422
    {
423
        "SLH-DSA-SHA2-256s",
424
        NID_sha512,
425
        0,
426
        NID_sha512,
427
        0,
428
    },
429
    {
430
        "SLH-DSA-SHAKE-128f",
431
        NID_shake128,
432
        0,
433
        NID_shake128,
434
        0,
435
    },
436
    {
437
        "SLH-DSA-SHAKE-128s",
438
        NID_shake128,
439
        0,
440
        NID_shake128,
441
        0,
442
    },
443
    {
444
        "SLH-DSA-SHAKE-192f",
445
        NID_shake256,
446
        0,
447
        NID_shake256,
448
        0,
449
    },
450
    {
451
        "SLH-DSA-SHAKE-192s",
452
        NID_shake256,
453
        0,
454
        NID_shake256,
455
        0,
456
    },
457
    {
458
        "SLH-DSA-SHAKE-256f",
459
        NID_shake256,
460
        0,
461
        NID_shake256,
462
        0,
463
    },
464
    {
465
        "SLH-DSA-SHAKE-256s",
466
        NID_shake256,
467
        0,
468
        NID_shake256,
469
        0,
470
    },
471
    {
472
        NULL,
473
        NID_undef,
474
        0,
475
        NID_undef,
476
        0,
477
    } /* last */
478
};
479
480
static const char *cms_mdless_signing(EVP_PKEY *pkey)
481
0
{
482
0
    unsigned int i;
483
0
    int def_nid = NID_undef;
484
485
0
    for (i = 0; key2data[i].name != NULL; i++) {
486
0
        if (EVP_PKEY_is_a(pkey, key2data[i].name))
487
0
            return key2data[i].name;
488
0
    }
489
0
    if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) <= 0) {
490
        /* Key doesn't have default digest, it's mdless */
491
0
        return EVP_PKEY_get0_type_name(pkey);
492
0
    }
493
0
    return NULL;
494
0
}
495
496
static const EVP_MD *ossl_cms_get_default_md(EVP_PKEY *pk, int *md_a_must)
497
0
{
498
0
    const EVP_MD *md;
499
0
    unsigned int i;
500
0
    int def_nid = NID_undef;
501
502
0
    *md_a_must = 0;
503
504
0
    for (i = 0; key2data[i].name != NULL; i++) {
505
0
        if (EVP_PKEY_is_a(pk, key2data[i].name)) {
506
0
            def_nid = key2data[i].md_nid;
507
0
            *md_a_must = key2data[i].md_a_must;
508
0
            break;
509
0
        }
510
0
    }
511
512
0
    if (def_nid == NID_undef && EVP_PKEY_get_default_digest_nid(pk, &def_nid) <= 0) {
513
0
        ERR_raise_data(ERR_LIB_CMS, CMS_R_NO_DEFAULT_DIGEST,
514
0
            "pkey nid=%d", EVP_PKEY_get_id(pk));
515
0
        return NULL;
516
0
    }
517
0
    md = EVP_get_digestbynid(def_nid);
518
0
    if (md == NULL)
519
0
        ERR_raise_data(ERR_LIB_CMS, CMS_R_NO_DEFAULT_DIGEST,
520
0
            "default md nid=%d", def_nid);
521
0
    return md;
522
0
}
523
524
static const EVP_MD *ossl_cms_get_noattr_md(EVP_PKEY *pk, int *noattr_md_a_must)
525
0
{
526
0
    unsigned int i;
527
528
0
    for (i = 0; key2data[i].name != NULL; i++) {
529
0
        if (EVP_PKEY_is_a(pk, key2data[i].name)) {
530
0
            *noattr_md_a_must = key2data[i].noattr_md_a_must;
531
0
            return EVP_get_digestbynid(key2data[i].noattr_md_nid);
532
0
        }
533
0
    }
534
0
    return NULL;
535
0
}
536
537
static int ossl_cms_adjust_md(EVP_PKEY *pk, const EVP_MD **md, unsigned int flags)
538
0
{
539
0
    const EVP_MD *tmp_md;
540
0
    int md_a_must = 0;
541
542
0
    while ((flags & CMS_NOATTR) != 0) {
543
        /*
544
         * Some key types require that a certain type of hash is being used in the
545
         * case of signed attributes being absent, others have a suggested hash.
546
         * In the latter case only use the suggested one if no hash is given.
547
         */
548
0
        int noattr_md_a_must = 0;
549
550
0
        tmp_md = ossl_cms_get_noattr_md(pk, &noattr_md_a_must);
551
0
        if (tmp_md == NULL)
552
0
            break; /* key type not listed - use the default */
553
554
0
        if (noattr_md_a_must)
555
0
            *md = tmp_md;
556
0
        else if (*md == NULL)
557
0
            *md = tmp_md;
558
0
        return 1;
559
0
    }
560
561
0
    if (*md != NULL)
562
0
        (void)ERR_set_mark(); /* No error if no default md and user-supplied md is set */
563
0
    tmp_md = ossl_cms_get_default_md(pk, &md_a_must);
564
0
    if (*md != NULL)
565
0
        (void)ERR_pop_to_mark();
566
0
    if (md_a_must)
567
0
        *md = tmp_md;
568
0
    else if (*md == NULL)
569
0
        *md = tmp_md;
570
571
0
    if (*md == NULL) /* ED448 case */
572
0
        return 0;
573
574
0
    return 1;
575
0
}
576
577
CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms,
578
    X509 *signer, EVP_PKEY *pk, const EVP_MD *md,
579
    unsigned int flags)
580
0
{
581
0
    CMS_SignedData *sd;
582
0
    CMS_SignerInfo *si = NULL;
583
0
    X509_ALGOR *alg;
584
0
    int i, type;
585
0
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
586
587
0
    if (!X509_check_private_key(signer, pk)) {
588
0
        ERR_raise(ERR_LIB_CMS, CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE);
589
0
        return NULL;
590
0
    }
591
0
    sd = cms_signed_data_init(cms);
592
0
    if (sd == NULL)
593
0
        goto err;
594
0
    si = M_ASN1_new_of(CMS_SignerInfo);
595
0
    if (si == NULL) {
596
0
        ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
597
0
        goto err;
598
0
    }
599
    /* Call for side-effect of computing hash and caching extensions */
600
0
    X509_check_purpose(signer, -1, -1);
601
602
0
    if (!X509_up_ref(signer))
603
0
        goto err;
604
0
    if (!EVP_PKEY_up_ref(pk)) {
605
0
        X509_free(signer);
606
0
        goto err;
607
0
    }
608
609
0
    si->cms_ctx = ctx;
610
0
    si->pkey = pk;
611
0
    si->signer = signer;
612
0
    si->mctx = EVP_MD_CTX_new();
613
0
    si->pctx = NULL;
614
0
    si->omit_signing_time = 0;
615
616
0
    if (si->mctx == NULL) {
617
0
        ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
618
0
        goto err;
619
0
    }
620
621
0
    if (flags & CMS_USE_KEYID) {
622
0
        si->version = 3;
623
0
        if (sd->version < 3)
624
0
            sd->version = 3;
625
0
        type = CMS_SIGNERINFO_KEYIDENTIFIER;
626
0
    } else {
627
0
        type = CMS_SIGNERINFO_ISSUER_SERIAL;
628
0
        si->version = 1;
629
0
    }
630
631
0
    if (!ossl_cms_set1_SignerIdentifier(si->sid, signer, type, ctx))
632
0
        goto err;
633
634
0
    if (ossl_cms_adjust_md(pk, &md, flags) != 1)
635
0
        goto err;
636
637
0
    if (!X509_ALGOR_set_md(si->digestAlgorithm, md))
638
0
        goto err;
639
640
    /* See if digest is present in digestAlgorithms */
641
0
    for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) {
642
0
        const ASN1_OBJECT *aoid;
643
0
        char name[OSSL_MAX_NAME_SIZE];
644
645
0
        alg = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
646
0
        X509_ALGOR_get0(&aoid, NULL, NULL, alg);
647
0
        OBJ_obj2txt(name, sizeof(name), aoid, 0);
648
0
        if (EVP_MD_is_a(md, name))
649
0
            break;
650
0
    }
651
0
    if (i == sk_X509_ALGOR_num(sd->digestAlgorithms)) {
652
0
        if ((alg = X509_ALGOR_new()) == NULL
653
0
            || !X509_ALGOR_set_md(alg, md)
654
0
            || !sk_X509_ALGOR_push(sd->digestAlgorithms, alg)) {
655
0
            X509_ALGOR_free(alg);
656
0
            ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
657
0
            goto err;
658
0
        }
659
0
    }
660
0
    if (!(flags & CMS_KEY_PARAM) && !cms_sd_asn1_ctrl(si, 0)) {
661
0
        ERR_raise_data(ERR_LIB_CMS, CMS_R_UNSUPPORTED_SIGNATURE_ALGORITHM,
662
0
            "pkey nid=%d", EVP_PKEY_get_id(pk));
663
0
        goto err;
664
0
    }
665
0
    if (!(flags & CMS_NOATTR)) {
666
        /*
667
         * Initialize signed attributes structure so other attributes
668
         * such as signing time etc are added later even if we add none here.
669
         */
670
0
        if (!si->signedAttrs) {
671
0
            si->signedAttrs = sk_X509_ATTRIBUTE_new_null();
672
0
            if (!si->signedAttrs) {
673
0
                ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
674
0
                goto err;
675
0
            }
676
0
        }
677
0
        if (!(flags & CMS_NOSMIMECAP)) {
678
0
            STACK_OF(X509_ALGOR) *smcap = NULL;
679
680
0
            i = CMS_add_standard_smimecap(&smcap);
681
0
            if (i)
682
0
                i = CMS_add_smimecap(si, smcap);
683
0
            sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free);
684
0
            if (!i) {
685
0
                ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
686
0
                goto err;
687
0
            }
688
0
        }
689
0
        if ((flags & CMS_NO_SIGNING_TIME) != 0) {
690
            /*
691
             * The signing-time signed attribute (NID_pkcs9_signingTime)
692
             * would normally be added later, in CMS_SignerInfo_sign(),
693
             * unless we set this flag here
694
             */
695
0
            si->omit_signing_time = 1;
696
0
        }
697
0
        if (flags & CMS_CADES) {
698
0
            ESS_SIGNING_CERT *sc = NULL;
699
0
            ESS_SIGNING_CERT_V2 *sc2 = NULL;
700
0
            int add_sc;
701
702
0
            if (EVP_MD_is_a(md, SN_sha1)) {
703
0
                if ((sc = OSSL_ESS_signing_cert_new_init(signer,
704
0
                         NULL, 1))
705
0
                    == NULL)
706
0
                    goto err;
707
0
                add_sc = ossl_cms_add1_signing_cert(si, sc);
708
0
                ESS_SIGNING_CERT_free(sc);
709
0
            } else {
710
0
                if ((sc2 = OSSL_ESS_signing_cert_v2_new_init(md, signer,
711
0
                         NULL, 1))
712
0
                    == NULL)
713
0
                    goto err;
714
0
                add_sc = ossl_cms_add1_signing_cert_v2(si, sc2);
715
0
                ESS_SIGNING_CERT_V2_free(sc2);
716
0
            }
717
0
            if (!add_sc)
718
0
                goto err;
719
0
        }
720
0
        if (flags & CMS_REUSE_DIGEST) {
721
0
            if (!cms_copy_messageDigest(cms, si))
722
0
                goto err;
723
0
            if (!cms_set_si_contentType_attr(cms, si))
724
0
                goto err;
725
0
            if (!(flags & (CMS_PARTIAL | CMS_KEY_PARAM)) && !CMS_SignerInfo_sign(si))
726
0
                goto err;
727
0
        }
728
0
    }
729
730
0
    if (!(flags & CMS_NOCERTS)) {
731
        /* NB ignore -1 return for duplicate cert */
732
0
        if (!CMS_add1_cert(cms, signer)) {
733
0
            ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
734
0
            goto err;
735
0
        }
736
0
    }
737
0
    if (flags & CMS_KEY_PARAM) {
738
0
        if (flags & CMS_NOATTR) {
739
0
            si->pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
740
0
                si->pkey,
741
0
                ossl_cms_ctx_get0_propq(ctx));
742
0
            if (si->pctx == NULL)
743
0
                goto err;
744
0
            if (EVP_PKEY_sign_init(si->pctx) <= 0)
745
0
                goto err;
746
0
            if (EVP_PKEY_CTX_set_signature_md(si->pctx, md) <= 0)
747
0
                goto err;
748
0
        } else if (EVP_DigestSignInit_ex(si->mctx, &si->pctx,
749
0
                       EVP_MD_get0_name(md),
750
0
                       ossl_cms_ctx_get0_libctx(ctx),
751
0
                       ossl_cms_ctx_get0_propq(ctx),
752
0
                       pk, NULL)
753
0
            <= 0) {
754
0
            si->pctx = NULL;
755
0
            goto err;
756
0
        } else {
757
0
            EVP_MD_CTX_set_flags(si->mctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX);
758
0
        }
759
0
    }
760
0
    if (sd->signerInfos == NULL)
761
0
        sd->signerInfos = sk_CMS_SignerInfo_new_null();
762
0
    if (sd->signerInfos == NULL || !sk_CMS_SignerInfo_push(sd->signerInfos, si)) {
763
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
764
0
        goto err;
765
0
    }
766
0
    return si;
767
768
0
err:
769
0
    M_ASN1_free_of(si, CMS_SignerInfo);
770
0
    return NULL;
771
0
}
772
773
void ossl_cms_SignerInfos_set_cmsctx(CMS_ContentInfo *cms)
774
5.50k
{
775
5.50k
    int i;
776
5.50k
    CMS_SignerInfo *si;
777
5.50k
    STACK_OF(CMS_SignerInfo) *sinfos;
778
5.50k
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
779
780
5.50k
    ERR_set_mark();
781
5.50k
    sinfos = CMS_get0_SignerInfos(cms);
782
5.50k
    ERR_pop_to_mark(); /* removes error in case sinfos == NULL */
783
784
12.0k
    for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
785
6.53k
        si = sk_CMS_SignerInfo_value(sinfos, i);
786
6.53k
        if (si != NULL)
787
6.53k
            si->cms_ctx = ctx;
788
6.53k
    }
789
5.50k
}
790
791
static int cms_add1_signingTime(CMS_SignerInfo *si, ASN1_TIME *t)
792
0
{
793
0
    ASN1_TIME *tt;
794
0
    int r = 0;
795
796
0
    if (t != NULL)
797
0
        tt = t;
798
0
    else
799
0
        tt = X509_gmtime_adj(NULL, 0);
800
801
0
    if (tt == NULL) {
802
0
        ERR_raise(ERR_LIB_CMS, ERR_R_X509_LIB);
803
0
        goto err;
804
0
    }
805
806
0
    if (CMS_signed_add1_attr_by_NID(si, NID_pkcs9_signingTime,
807
0
            tt->type, tt, -1)
808
0
        <= 0) {
809
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
810
0
        goto err;
811
0
    }
812
813
0
    r = 1;
814
0
err:
815
0
    if (t == NULL)
816
0
        ASN1_TIME_free(tt);
817
818
0
    return r;
819
0
}
820
821
EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si)
822
0
{
823
0
    return si->pctx;
824
0
}
825
826
EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si)
827
0
{
828
0
    return si->mctx;
829
0
}
830
831
STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms)
832
5.50k
{
833
5.50k
    CMS_SignedData *sd = cms_get0_signed(cms);
834
835
5.50k
    return sd != NULL ? sd->signerInfos : NULL;
836
5.50k
}
837
838
STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms)
839
0
{
840
0
    STACK_OF(X509) *signers = NULL;
841
0
    STACK_OF(CMS_SignerInfo) *sinfos;
842
0
    CMS_SignerInfo *si;
843
0
    int i;
844
845
0
    sinfos = CMS_get0_SignerInfos(cms);
846
0
    for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
847
0
        si = sk_CMS_SignerInfo_value(sinfos, i);
848
0
        if (si->signer != NULL) {
849
0
            if (!ossl_x509_add_cert_new(&signers, si->signer,
850
0
                    X509_ADD_FLAG_DEFAULT)) {
851
0
                sk_X509_free(signers);
852
0
                return NULL;
853
0
            }
854
0
        }
855
0
    }
856
0
    return signers;
857
0
}
858
859
void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer)
860
0
{
861
0
    if (signer != NULL) {
862
0
        if (!X509_up_ref(signer))
863
0
            return;
864
0
        EVP_PKEY_free(si->pkey);
865
0
        si->pkey = X509_get_pubkey(signer);
866
0
    }
867
0
    X509_free(si->signer);
868
0
    si->signer = signer;
869
0
}
870
871
int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si,
872
    ASN1_OCTET_STRING **keyid,
873
    X509_NAME **issuer, ASN1_INTEGER **sno)
874
0
{
875
0
    return ossl_cms_SignerIdentifier_get0_signer_id(si->sid, keyid, issuer, sno);
876
0
}
877
878
int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert)
879
0
{
880
0
    return ossl_cms_SignerIdentifier_cert_cmp(si->sid, cert);
881
0
}
882
883
int CMS_set1_signers_certs(CMS_ContentInfo *cms, const STACK_OF(X509) *scerts,
884
    unsigned int flags)
885
0
{
886
0
    CMS_SignedData *sd;
887
0
    CMS_SignerInfo *si;
888
0
    CMS_CertificateChoices *cch;
889
0
    STACK_OF(CMS_CertificateChoices) *certs;
890
0
    X509 *x;
891
0
    int i, j;
892
0
    int ret = 0;
893
894
0
    sd = cms_get0_signed(cms);
895
0
    if (sd == NULL)
896
0
        return -1;
897
0
    certs = sd->certificates;
898
0
    for (i = 0; i < sk_CMS_SignerInfo_num(sd->signerInfos); i++) {
899
0
        si = sk_CMS_SignerInfo_value(sd->signerInfos, i);
900
0
        if (si->signer != NULL)
901
0
            continue;
902
903
0
        for (j = 0; j < sk_X509_num(scerts); j++) {
904
0
            x = sk_X509_value(scerts, j);
905
0
            if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
906
0
                CMS_SignerInfo_set1_signer_cert(si, x);
907
0
                ret++;
908
0
                break;
909
0
            }
910
0
        }
911
912
0
        if (si->signer != NULL || (flags & CMS_NOINTERN))
913
0
            continue;
914
915
0
        for (j = 0; j < sk_CMS_CertificateChoices_num(certs); j++) {
916
0
            cch = sk_CMS_CertificateChoices_value(certs, j);
917
0
            if (cch->type != CMS_CERTCHOICE_CERT)
918
0
                continue;
919
0
            x = cch->d.certificate;
920
0
            if (CMS_SignerInfo_cert_cmp(si, x) == 0) {
921
0
                CMS_SignerInfo_set1_signer_cert(si, x);
922
0
                ret++;
923
0
                break;
924
0
            }
925
0
        }
926
0
    }
927
0
    return ret;
928
0
}
929
930
void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk,
931
    X509 **signer, X509_ALGOR **pdig,
932
    X509_ALGOR **psig)
933
0
{
934
0
    if (pk != NULL)
935
0
        *pk = si->pkey;
936
0
    if (signer != NULL)
937
0
        *signer = si->signer;
938
0
    if (pdig != NULL)
939
0
        *pdig = si->digestAlgorithm;
940
0
    if (psig != NULL)
941
0
        *psig = si->signatureAlgorithm;
942
0
}
943
944
ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si)
945
0
{
946
0
    return si->signature;
947
0
}
948
949
static int cms_bio_read(BIO *in,
950
    unsigned char **buffer, size_t *buffer_len)
951
0
{
952
0
    unsigned char *tmp;
953
0
    size_t offset = 0;
954
0
    int n;
955
956
0
    if (BIO_seek(in, 0) < 0)
957
0
        return -1;
958
959
0
    *buffer = NULL;
960
0
    *buffer_len = 0;
961
962
    /* read data from BIO into memory */
963
0
    do {
964
0
        *buffer_len += 10240;
965
0
        tmp = OPENSSL_realloc(*buffer, *buffer_len);
966
0
        if (!tmp)
967
0
            goto err;
968
0
        *buffer = tmp;
969
970
0
        if ((n = BIO_read(in, &(*buffer)[offset], 10240)) <= 0)
971
0
            goto err;
972
0
        offset += n;
973
0
    } while (BIO_eof(in) != 1);
974
975
0
    *buffer_len = offset;
976
977
0
    return 1;
978
979
0
err:
980
0
    OPENSSL_free(*buffer);
981
0
    *buffer = NULL;
982
0
    return -1;
983
0
}
984
985
static int cms_EVP_PKEY_sign(EVP_PKEY_CTX *pctx, BIO *in,
986
    unsigned char *sig, size_t *sig_len,
987
    int has_msg_update)
988
0
{
989
0
    size_t buffer_len;
990
0
    int ret;
991
992
0
    if (!has_msg_update) {
993
0
        unsigned char *buffer = NULL;
994
995
0
        if (cms_bio_read(in, &buffer, &buffer_len) != 1)
996
0
            return 0;
997
0
        ret = EVP_PKEY_sign(pctx, sig, sig_len, buffer, buffer_len);
998
0
        OPENSSL_free(buffer);
999
0
    } else {
1000
0
        unsigned char buffer[1024];
1001
0
        int n;
1002
1003
0
        if (BIO_seek(in, 0) < 0)
1004
0
            return 0;
1005
1006
0
        do {
1007
0
            n = BIO_read(in, buffer, sizeof(buffer));
1008
0
            if (n <= 0)
1009
0
                break;
1010
0
            if (EVP_PKEY_sign_message_update(pctx, buffer, n) != 1)
1011
0
                return 0;
1012
0
        } while (!BIO_eof(in));
1013
0
        ret = EVP_PKEY_sign_message_final(pctx, sig, sig_len);
1014
0
    }
1015
0
    return ret;
1016
0
}
1017
1018
static int cms_EVP_PKEY_verify(EVP_PKEY_CTX *pctx, BIO *in, unsigned char *sig,
1019
    size_t siglen, int has_msg_update)
1020
0
{
1021
0
    size_t buffer_len;
1022
0
    int ret;
1023
1024
0
    if (!has_msg_update) {
1025
0
        unsigned char *buffer = NULL;
1026
1027
0
        if (cms_bio_read(in, &buffer, &buffer_len) != 1)
1028
0
            return 0;
1029
1030
0
        ret = EVP_PKEY_verify(pctx, sig, siglen, buffer, buffer_len);
1031
0
        OPENSSL_free(buffer);
1032
0
    } else {
1033
0
        unsigned char buffer[1024];
1034
0
        int n;
1035
1036
0
        if (BIO_seek(in, 0) < 0)
1037
0
            return 0;
1038
1039
0
        do {
1040
0
            n = BIO_read(in, buffer, sizeof(buffer));
1041
0
            if (n <= 0)
1042
0
                break;
1043
0
            if (EVP_PKEY_verify_message_update(pctx, buffer, n) != 1)
1044
0
                return 0;
1045
0
        } while (!BIO_eof(in));
1046
0
        if (EVP_PKEY_CTX_set_signature(pctx, sig, siglen) != 1)
1047
0
            return 0;
1048
0
        ret = EVP_PKEY_verify_message_final(pctx);
1049
0
    }
1050
0
    return ret;
1051
0
}
1052
1053
static int cms_SignerInfo_content_sign(CMS_ContentInfo *cms,
1054
    CMS_SignerInfo *si, BIO *chain,
1055
    BIO *data,
1056
    const unsigned char *md,
1057
    unsigned int mdlen)
1058
0
{
1059
0
    EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1060
0
    int r = 0;
1061
0
    EVP_PKEY_CTX *pctx = NULL;
1062
0
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
1063
0
    EVP_SIGNATURE *sig_alg = NULL;
1064
0
    unsigned char *sig = NULL;
1065
1066
0
    if (mctx == NULL) {
1067
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
1068
0
        return 0;
1069
0
    }
1070
1071
0
    if (si->pkey == NULL) {
1072
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_PRIVATE_KEY);
1073
0
        goto err;
1074
0
    }
1075
1076
0
    if (!ossl_cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
1077
0
        goto err;
1078
    /* Set SignerInfo algorithm details if we used custom parameter */
1079
0
    if (si->pctx && !cms_sd_asn1_ctrl(si, 0))
1080
0
        goto err;
1081
1082
    /*
1083
     * If any signed attributes calculate and add messageDigest attribute
1084
     */
1085
0
    if (CMS_signed_get_attr_count(si) >= 0) {
1086
0
        unsigned char computed_md[EVP_MAX_MD_SIZE];
1087
1088
0
        if (md == NULL) {
1089
0
            if (!EVP_DigestFinal_ex(mctx, computed_md, &mdlen))
1090
0
                goto err;
1091
0
            md = computed_md;
1092
0
        }
1093
0
        if (!CMS_signed_add1_attr_by_NID(si, NID_pkcs9_messageDigest,
1094
0
                V_ASN1_OCTET_STRING, md, mdlen))
1095
0
            goto err;
1096
        /* Copy content type across */
1097
0
        if (!cms_set_si_contentType_attr(cms, si))
1098
0
            goto err;
1099
1100
0
        if (!CMS_SignerInfo_sign(si))
1101
0
            goto err;
1102
0
    } else if (si->pctx) {
1103
0
        size_t siglen;
1104
0
        unsigned char computed_md[EVP_MAX_MD_SIZE];
1105
1106
0
        pctx = si->pctx;
1107
0
        si->pctx = NULL;
1108
0
        if (md == NULL) {
1109
0
            if (!EVP_DigestFinal_ex(mctx, computed_md, &mdlen))
1110
0
                goto err;
1111
0
            md = computed_md;
1112
0
        }
1113
0
        siglen = EVP_PKEY_get_size(si->pkey);
1114
0
        if (siglen == 0 || (sig = OPENSSL_malloc(siglen)) == NULL)
1115
0
            goto err;
1116
0
        if (EVP_PKEY_sign(pctx, sig, &siglen, md, mdlen) <= 0)
1117
0
            goto err;
1118
0
        ASN1_STRING_set0(si->signature, sig, (int)siglen);
1119
0
        sig = NULL;
1120
0
    } else {
1121
0
        OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx);
1122
0
        const char *algorithm;
1123
0
        unsigned int siglen;
1124
0
        int has_msg_update;
1125
1126
0
        if (md != NULL) {
1127
0
            ERR_raise(ERR_LIB_CMS, CMS_R_OPERATION_UNSUPPORTED);
1128
0
            goto err;
1129
0
        }
1130
0
        siglen = EVP_PKEY_get_size(si->pkey);
1131
0
        if (siglen == 0 || (sig = OPENSSL_malloc(siglen)) == NULL)
1132
0
            goto err;
1133
1134
0
        if ((algorithm = cms_mdless_signing(si->pkey)) != NULL) {
1135
0
            size_t sig_len;
1136
1137
0
            if (!data) {
1138
0
                ERR_raise(ERR_LIB_CMS, CMS_R_NO_CONTENT);
1139
0
                goto err;
1140
0
            }
1141
1142
0
            pctx = EVP_PKEY_CTX_new(si->pkey, NULL);
1143
0
            if (!pctx)
1144
0
                goto err;
1145
1146
0
            sig_alg = EVP_SIGNATURE_fetch(libctx, algorithm, NULL);
1147
0
            if (!sig_alg)
1148
0
                goto err;
1149
1150
0
            if (EVP_PKEY_sign_message_init(pctx, sig_alg, NULL) != 1)
1151
0
                goto err;
1152
1153
0
            sig_len = siglen;
1154
0
            has_msg_update = EVP_SIGNATURE_has_message_update(sig_alg);
1155
0
            if (cms_EVP_PKEY_sign(pctx, data, sig, &sig_len,
1156
0
                    has_msg_update)
1157
0
                != 1)
1158
0
                goto err;
1159
0
            siglen = (unsigned int)sig_len;
1160
0
        } else {
1161
0
            if (!EVP_SignFinal_ex(mctx, sig, &siglen, si->pkey, libctx,
1162
0
                    ossl_cms_ctx_get0_propq(ctx))) {
1163
0
                ERR_raise(ERR_LIB_CMS, CMS_R_SIGNFINAL_ERROR);
1164
0
                goto err;
1165
0
            }
1166
0
        }
1167
0
        ASN1_STRING_set0(si->signature, sig, siglen);
1168
0
        sig = NULL;
1169
0
    }
1170
1171
0
    r = 1;
1172
1173
0
err:
1174
0
    OPENSSL_free(sig);
1175
0
    EVP_MD_CTX_free(mctx);
1176
0
    EVP_PKEY_CTX_free(pctx);
1177
0
    EVP_SIGNATURE_free(sig_alg);
1178
0
    return r;
1179
0
}
1180
1181
int ossl_cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain, BIO *data,
1182
    const unsigned char *precomp_md,
1183
    unsigned int precomp_mdlen)
1184
0
{
1185
0
    STACK_OF(CMS_SignerInfo) *sinfos;
1186
0
    CMS_SignerInfo *si;
1187
0
    int i;
1188
1189
0
    sinfos = CMS_get0_SignerInfos(cms);
1190
0
    for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
1191
0
        si = sk_CMS_SignerInfo_value(sinfos, i);
1192
0
        if (!cms_SignerInfo_content_sign(cms, si, chain, data,
1193
0
                precomp_md, precomp_mdlen))
1194
0
            return 0;
1195
0
    }
1196
0
    cms->d.signedData->encapContentInfo->partial = 0;
1197
0
    return 1;
1198
0
}
1199
1200
int CMS_SignerInfo_sign(CMS_SignerInfo *si)
1201
0
{
1202
0
    EVP_MD_CTX *mctx = si->mctx;
1203
0
    EVP_PKEY_CTX *pctx = NULL;
1204
0
    unsigned char *abuf = NULL;
1205
0
    int alen;
1206
0
    size_t siglen;
1207
0
    const CMS_CTX *ctx = si->cms_ctx;
1208
0
    char md_name_buf[OSSL_MAX_NAME_SIZE], *md_name;
1209
1210
0
    if (OBJ_obj2txt(md_name_buf, sizeof(md_name_buf),
1211
0
            si->digestAlgorithm->algorithm, 0)
1212
0
        <= 0)
1213
0
        return 0;
1214
0
    md_name = cms_signature_nomd(si->pkey) ? NULL : md_name_buf;
1215
1216
0
    if (!si->omit_signing_time
1217
0
        && CMS_signed_get_attr_by_NID(si, NID_pkcs9_signingTime, -1) < 0) {
1218
0
        if (!cms_add1_signingTime(si, NULL))
1219
0
            goto err;
1220
0
    }
1221
1222
0
    if (!ossl_cms_si_check_attributes(si))
1223
0
        goto err;
1224
1225
0
    if (si->pctx) {
1226
0
        pctx = si->pctx;
1227
0
    } else {
1228
0
        EVP_MD_CTX_reset(mctx);
1229
0
        if (EVP_DigestSignInit_ex(mctx, &pctx, md_name,
1230
0
                ossl_cms_ctx_get0_libctx(ctx),
1231
0
                ossl_cms_ctx_get0_propq(ctx), si->pkey,
1232
0
                NULL)
1233
0
            <= 0)
1234
0
            goto err;
1235
0
        EVP_MD_CTX_set_flags(mctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX);
1236
0
        si->pctx = pctx;
1237
0
    }
1238
1239
0
    if (md_name == NULL) {
1240
0
        if (ASN1_item_sign_ctx(ASN1_ITEM_rptr(CMS_Attributes_Sign), NULL,
1241
0
                NULL, si->signature, si->signedAttrs, mctx)
1242
0
            <= 0)
1243
0
            goto err;
1244
0
        return 1;
1245
0
    }
1246
1247
0
    alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf,
1248
0
        ASN1_ITEM_rptr(CMS_Attributes_Sign));
1249
0
    if (alen < 0 || abuf == NULL)
1250
0
        goto err;
1251
0
    if (EVP_DigestSignUpdate(mctx, abuf, alen) <= 0)
1252
0
        goto err;
1253
0
    if (EVP_DigestSignFinal(mctx, NULL, &siglen) <= 0)
1254
0
        goto err;
1255
0
    OPENSSL_free(abuf);
1256
0
    abuf = OPENSSL_malloc(siglen);
1257
0
    if (abuf == NULL)
1258
0
        goto err;
1259
0
    if (EVP_DigestSignFinal(mctx, abuf, &siglen) <= 0)
1260
0
        goto err;
1261
1262
0
    EVP_MD_CTX_reset(mctx);
1263
1264
0
    ASN1_STRING_set0(si->signature, abuf, (int)siglen);
1265
1266
0
    return 1;
1267
1268
0
err:
1269
0
    OPENSSL_free(abuf);
1270
0
    EVP_MD_CTX_reset(mctx);
1271
0
    return 0;
1272
0
}
1273
1274
int CMS_SignerInfo_verify(CMS_SignerInfo *si)
1275
0
{
1276
0
    EVP_MD_CTX *mctx = NULL;
1277
0
    unsigned char *abuf = NULL;
1278
0
    int alen, r = -1;
1279
0
    char name[OSSL_MAX_NAME_SIZE];
1280
0
    const EVP_MD *md;
1281
0
    EVP_MD *fetched_md = NULL;
1282
0
    const CMS_CTX *ctx = si->cms_ctx;
1283
0
    OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx);
1284
0
    const char *propq = ossl_cms_ctx_get0_propq(ctx);
1285
1286
0
    if (si->pkey == NULL) {
1287
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_PUBLIC_KEY);
1288
0
        return -1;
1289
0
    }
1290
1291
0
    if (!ossl_cms_si_check_attributes(si))
1292
0
        return -1;
1293
1294
0
    if (cms_signature_nomd(si->pkey)) {
1295
0
        r = ASN1_item_verify_ex(ASN1_ITEM_rptr(CMS_Attributes_Sign),
1296
0
            si->signatureAlgorithm, si->signature,
1297
0
            si->signedAttrs, NULL, si->pkey,
1298
0
            libctx, propq);
1299
0
        if (r <= 0)
1300
0
            ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE);
1301
0
        return r;
1302
0
    }
1303
1304
0
    OBJ_obj2txt(name, sizeof(name), si->digestAlgorithm->algorithm, 0);
1305
1306
0
    (void)ERR_set_mark();
1307
0
    fetched_md = EVP_MD_fetch(libctx, name, propq);
1308
1309
0
    if (fetched_md != NULL)
1310
0
        md = fetched_md;
1311
0
    else
1312
0
        md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm);
1313
0
    if (md == NULL) {
1314
0
        (void)ERR_clear_last_mark();
1315
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_DIGEST_ALGORITHM);
1316
0
        return -1;
1317
0
    }
1318
0
    (void)ERR_pop_to_mark();
1319
1320
0
    if (si->mctx == NULL && (si->mctx = EVP_MD_CTX_new()) == NULL) {
1321
0
        ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
1322
0
        goto err;
1323
0
    }
1324
0
    mctx = si->mctx;
1325
0
    if (si->pctx != NULL) {
1326
0
        EVP_PKEY_CTX_free(si->pctx);
1327
0
        si->pctx = NULL;
1328
0
    }
1329
0
    if (EVP_DigestVerifyInit_ex(mctx, &si->pctx, EVP_MD_get0_name(md), libctx,
1330
0
            propq, si->pkey, NULL)
1331
0
        <= 0) {
1332
0
        si->pctx = NULL;
1333
0
        goto err;
1334
0
    }
1335
0
    EVP_MD_CTX_set_flags(mctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX);
1336
1337
0
    if (!cms_sd_asn1_ctrl(si, 1))
1338
0
        goto err;
1339
1340
0
    alen = ASN1_item_i2d((ASN1_VALUE *)si->signedAttrs, &abuf,
1341
0
        ASN1_ITEM_rptr(CMS_Attributes_Verify));
1342
0
    if (abuf == NULL || alen < 0)
1343
0
        goto err;
1344
0
    r = EVP_DigestVerifyUpdate(mctx, abuf, alen);
1345
0
    OPENSSL_free(abuf);
1346
0
    if (r <= 0) {
1347
0
        r = -1;
1348
0
        goto err;
1349
0
    }
1350
0
    r = EVP_DigestVerifyFinal(mctx,
1351
0
        si->signature->data, si->signature->length);
1352
0
    if (r <= 0)
1353
0
        ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE);
1354
0
err:
1355
0
    EVP_MD_free(fetched_md);
1356
0
    EVP_MD_CTX_reset(mctx);
1357
0
    return r;
1358
0
}
1359
1360
/* Create a chain of digest BIOs from a CMS ContentInfo */
1361
BIO *ossl_cms_SignedData_init_bio(CMS_ContentInfo *cms)
1362
0
{
1363
0
    int i;
1364
0
    CMS_SignedData *sd;
1365
0
    BIO *chain = NULL;
1366
1367
0
    sd = cms_get0_signed(cms);
1368
0
    if (sd == NULL)
1369
0
        return NULL;
1370
0
    if (cms->d.signedData->encapContentInfo->partial)
1371
0
        cms_sd_set_version(sd);
1372
0
    for (i = 0; i < sk_X509_ALGOR_num(sd->digestAlgorithms); i++) {
1373
0
        X509_ALGOR *digestAlgorithm;
1374
0
        BIO *mdbio;
1375
1376
0
        digestAlgorithm = sk_X509_ALGOR_value(sd->digestAlgorithms, i);
1377
0
        mdbio = ossl_cms_DigestAlgorithm_init_bio(digestAlgorithm,
1378
0
            ossl_cms_get0_cmsctx(cms));
1379
0
        if (mdbio == NULL)
1380
0
            goto err;
1381
0
        if (chain != NULL)
1382
0
            BIO_push(chain, mdbio);
1383
0
        else
1384
0
            chain = mdbio;
1385
0
    }
1386
0
    return chain;
1387
0
err:
1388
0
    BIO_free_all(chain);
1389
0
    return NULL;
1390
0
}
1391
1392
int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain)
1393
0
{
1394
0
    return CMS_SignerInfo_verify_ex(si, chain, NULL);
1395
0
}
1396
1397
int CMS_SignerInfo_verify_ex(CMS_SignerInfo *si, BIO *chain, BIO *data)
1398
0
{
1399
0
    const ASN1_OCTET_STRING *os = NULL;
1400
0
    EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1401
0
    EVP_PKEY_CTX *pkctx = NULL;
1402
0
    int r = -1;
1403
0
    unsigned char mval[EVP_MAX_MD_SIZE];
1404
0
    unsigned int mlen;
1405
0
    EVP_SIGNATURE *sig_alg = NULL;
1406
0
    unsigned char *buffer = NULL;
1407
1408
0
    if (mctx == NULL) {
1409
0
        ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
1410
0
        goto err;
1411
0
    }
1412
    /* If we have any signed attributes look for messageDigest value */
1413
0
    if (CMS_signed_get_attr_count(si) >= 0) {
1414
0
        os = CMS_signed_get0_data_by_OBJ(si,
1415
0
            OBJ_nid2obj(NID_pkcs9_messageDigest),
1416
0
            -3, V_ASN1_OCTET_STRING);
1417
0
        if (os == NULL) {
1418
0
            ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE);
1419
0
            goto err;
1420
0
        }
1421
0
    }
1422
1423
0
    if (!ossl_cms_DigestAlgorithm_find_ctx(mctx, chain, si->digestAlgorithm))
1424
0
        goto err;
1425
1426
0
    if (EVP_DigestFinal_ex(mctx, mval, &mlen) <= 0) {
1427
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNABLE_TO_FINALIZE_CONTEXT);
1428
0
        goto err;
1429
0
    }
1430
1431
    /* If messageDigest found compare it */
1432
0
    if (os != NULL) {
1433
0
        if (mlen != (unsigned int)os->length) {
1434
0
            ERR_raise(ERR_LIB_CMS, CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH);
1435
0
            goto err;
1436
0
        }
1437
1438
0
        if (memcmp(mval, os->data, mlen)) {
1439
0
            ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE);
1440
0
            r = 0;
1441
0
        } else {
1442
0
            r = 1;
1443
0
        }
1444
0
    } else {
1445
0
        const EVP_MD *md = EVP_MD_CTX_get0_md(mctx);
1446
0
        const CMS_CTX *ctx = si->cms_ctx;
1447
0
        OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx);
1448
0
        const char *algorithm;
1449
0
        int has_msg_update;
1450
1451
0
        pkctx = EVP_PKEY_CTX_new_from_pkey(libctx, si->pkey,
1452
0
            ossl_cms_ctx_get0_propq(ctx));
1453
0
        if (pkctx == NULL)
1454
0
            goto err;
1455
1456
0
        if ((algorithm = cms_mdless_signing(si->pkey)) != NULL) {
1457
0
            if (!data) {
1458
0
                ERR_raise(ERR_LIB_CMS, CMS_R_NO_CONTENT);
1459
0
                goto err;
1460
0
            }
1461
1462
0
            sig_alg = EVP_SIGNATURE_fetch(libctx, algorithm, NULL);
1463
0
            if (!sig_alg)
1464
0
                goto err;
1465
0
            if (EVP_PKEY_verify_message_init(pkctx, sig_alg, NULL) != 1)
1466
0
                goto err;
1467
1468
0
            has_msg_update = EVP_SIGNATURE_has_message_update(sig_alg);
1469
0
            r = cms_EVP_PKEY_verify(pkctx, data, si->signature->data,
1470
0
                si->signature->length, has_msg_update);
1471
0
        } else {
1472
0
            if (EVP_PKEY_verify_init(pkctx) <= 0)
1473
0
                goto err;
1474
0
            if (EVP_PKEY_CTX_set_signature_md(pkctx, md) <= 0)
1475
0
                goto err;
1476
0
            si->pctx = pkctx;
1477
0
            if (!cms_sd_asn1_ctrl(si, 1)) {
1478
0
                si->pctx = NULL;
1479
0
                goto err;
1480
0
            }
1481
0
            si->pctx = NULL;
1482
1483
0
            r = EVP_PKEY_verify(pkctx, si->signature->data,
1484
0
                si->signature->length, mval, mlen);
1485
0
        }
1486
0
        if (r <= 0) {
1487
0
            ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE);
1488
0
            r = 0;
1489
0
        }
1490
0
    }
1491
1492
0
err:
1493
0
    EVP_PKEY_CTX_free(pkctx);
1494
0
    EVP_MD_CTX_free(mctx);
1495
0
    EVP_SIGNATURE_free(sig_alg);
1496
0
    OPENSSL_free(buffer);
1497
0
    return r;
1498
0
}
1499
1500
BIO *CMS_SignedData_verify(CMS_SignedData *sd, BIO *detached_data,
1501
    const STACK_OF(X509) *scerts, X509_STORE *store,
1502
    const STACK_OF(X509) *extra,
1503
    const STACK_OF(X509_CRL) *crls,
1504
    unsigned int flags,
1505
    OSSL_LIB_CTX *libctx, const char *propq)
1506
0
{
1507
0
    CMS_ContentInfo *ci;
1508
0
    BIO *bio = NULL;
1509
0
    int i, res = 0;
1510
1511
0
    if (sd == NULL) {
1512
0
        ERR_raise(ERR_LIB_CMS, ERR_R_PASSED_NULL_PARAMETER);
1513
0
        return NULL;
1514
0
    }
1515
1516
0
    if ((ci = CMS_ContentInfo_new_ex(libctx, propq)) == NULL)
1517
0
        return NULL;
1518
0
    if ((bio = BIO_new(BIO_s_mem())) == NULL)
1519
0
        goto end;
1520
0
    ci->contentType = OBJ_nid2obj(NID_pkcs7_signed);
1521
0
    ci->d.signedData = sd;
1522
1523
0
    for (i = 0; i < sk_X509_num(extra); i++)
1524
0
        if (!CMS_add1_cert(ci, sk_X509_value(extra, i)))
1525
0
            goto end;
1526
0
    for (i = 0; i < sk_X509_CRL_num(crls); i++)
1527
0
        if (!CMS_add1_crl(ci, sk_X509_CRL_value(crls, i)))
1528
0
            goto end;
1529
0
    res = CMS_verify(ci, scerts, store, detached_data, bio, flags);
1530
1531
0
end:
1532
0
    if (ci != NULL)
1533
0
        ci->d.signedData = NULL; /* do not indirectly free |sd| */
1534
0
    CMS_ContentInfo_free(ci);
1535
0
    if (!res) {
1536
0
        BIO_free(bio);
1537
0
        bio = NULL;
1538
0
    }
1539
0
    return bio;
1540
0
}
1541
1542
int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs)
1543
0
{
1544
0
    unsigned char *smder = NULL;
1545
0
    int smderlen, r;
1546
1547
0
    smderlen = i2d_X509_ALGORS(algs, &smder);
1548
0
    if (smderlen <= 0)
1549
0
        return 0;
1550
0
    r = CMS_signed_add1_attr_by_NID(si, NID_SMIMECapabilities,
1551
0
        V_ASN1_SEQUENCE, smder, smderlen);
1552
0
    OPENSSL_free(smder);
1553
0
    return r;
1554
0
}
1555
1556
int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs,
1557
    int algnid, int keysize)
1558
0
{
1559
0
    X509_ALGOR *alg;
1560
0
    ASN1_INTEGER *key = NULL;
1561
1562
0
    if (keysize > 0) {
1563
0
        key = ASN1_INTEGER_new();
1564
0
        if (key == NULL || !ASN1_INTEGER_set(key, keysize)) {
1565
0
            ASN1_INTEGER_free(key);
1566
0
            return 0;
1567
0
        }
1568
0
    }
1569
0
    alg = ossl_X509_ALGOR_from_nid(algnid, key != NULL ? V_ASN1_INTEGER : V_ASN1_UNDEF, key);
1570
0
    if (alg == NULL) {
1571
0
        ASN1_INTEGER_free(key);
1572
0
        return 0;
1573
0
    }
1574
1575
0
    if (*algs == NULL)
1576
0
        *algs = sk_X509_ALGOR_new_null();
1577
0
    if (*algs == NULL || !sk_X509_ALGOR_push(*algs, alg)) {
1578
0
        X509_ALGOR_free(alg);
1579
0
        return 0;
1580
0
    }
1581
0
    return 1;
1582
0
}
1583
1584
/* Check to see if a cipher exists and if so add S/MIME capabilities */
1585
static int cms_add_cipher_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
1586
0
{
1587
0
    if (EVP_get_cipherbynid(nid))
1588
0
        return CMS_add_simple_smimecap(sk, nid, arg);
1589
0
    return 1;
1590
0
}
1591
1592
static int cms_add_digest_smcap(STACK_OF(X509_ALGOR) **sk, int nid, int arg)
1593
0
{
1594
0
    if (EVP_get_digestbynid(nid))
1595
0
        return CMS_add_simple_smimecap(sk, nid, arg);
1596
0
    return 1;
1597
0
}
1598
1599
int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap)
1600
0
{
1601
0
    if (!cms_add_cipher_smcap(smcap, NID_aes_256_cbc, -1)
1602
0
        || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_256, -1)
1603
0
        || !cms_add_digest_smcap(smcap, NID_id_GostR3411_2012_512, -1)
1604
0
        || !cms_add_digest_smcap(smcap, NID_id_GostR3411_94, -1)
1605
0
        || !cms_add_cipher_smcap(smcap, NID_id_Gost28147_89, -1)
1606
0
        || !cms_add_cipher_smcap(smcap, NID_aes_192_cbc, -1)
1607
0
        || !cms_add_cipher_smcap(smcap, NID_aes_128_cbc, -1)
1608
0
        || !cms_add_cipher_smcap(smcap, NID_des_ede3_cbc, -1)
1609
0
        || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 128)
1610
0
        || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 64)
1611
0
        || !cms_add_cipher_smcap(smcap, NID_des_cbc, -1)
1612
0
        || !cms_add_cipher_smcap(smcap, NID_rc2_cbc, 40))
1613
0
        return 0;
1614
0
    return 1;
1615
0
}