Coverage Report

Created: 2026-04-01 06:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl36/crypto/cmp/cmp_vfy.c
Line
Count
Source
1
/*
2
 * Copyright 2007-2025 The OpenSSL Project Authors. All Rights Reserved.
3
 * Copyright Nokia 2007-2020
4
 * Copyright Siemens AG 2015-2020
5
 *
6
 * Licensed under the Apache License 2.0 (the "License").  You may not use
7
 * this file except in compliance with the License.  You can obtain a copy
8
 * in the file LICENSE in the source distribution or at
9
 * https://www.openssl.org/source/license.html
10
 */
11
12
/* CMP functions for PKIMessage checking */
13
14
#include "cmp_local.h"
15
16
/* Verify a message protected by signature according to RFC section 5.1.3.3 */
17
static int verify_signature(const OSSL_CMP_CTX *cmp_ctx,
18
    const OSSL_CMP_MSG *msg, X509 *cert)
19
4.05k
{
20
4.05k
    OSSL_CMP_PROTECTEDPART prot_part;
21
4.05k
    EVP_PKEY *pubkey = NULL;
22
4.05k
    BIO *bio;
23
4.05k
    int res = 0;
24
25
4.05k
    if (!ossl_assert(cmp_ctx != NULL && msg != NULL && cert != NULL))
26
0
        return 0;
27
28
4.05k
    bio = BIO_new(BIO_s_mem()); /* may be NULL */
29
4.05k
    if (bio == NULL)
30
0
        return 0;
31
    /* verify that keyUsage, if present, contains digitalSignature */
32
4.05k
    if (!cmp_ctx->ignore_keyusage
33
4.05k
        && (X509_get_key_usage(cert) & X509v3_KU_DIGITAL_SIGNATURE) == 0) {
34
500
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE);
35
500
        goto sig_err;
36
500
    }
37
38
3.55k
    pubkey = X509_get_pubkey(cert);
39
3.55k
    if (pubkey == NULL) {
40
1.63k
        ERR_raise(ERR_LIB_CMP, CMP_R_FAILED_EXTRACTING_PUBKEY);
41
1.63k
        goto sig_err;
42
1.63k
    }
43
44
1.92k
    prot_part.header = msg->header;
45
1.92k
    prot_part.body = msg->body;
46
47
1.92k
    if (ASN1_item_verify_ex(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART),
48
1.92k
            msg->header->protectionAlg, msg->protection,
49
1.92k
            &prot_part, NULL, pubkey, cmp_ctx->libctx,
50
1.92k
            cmp_ctx->propq)
51
1.92k
        > 0) {
52
49
        res = 1;
53
49
        goto end;
54
49
    }
55
56
4.00k
sig_err:
57
4.00k
    res = ossl_x509_print_ex_brief(bio, cert, X509_FLAG_NO_EXTENSIONS);
58
4.00k
    ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_SIGNATURE);
59
4.00k
    if (res)
60
4.00k
        ERR_add_error_mem_bio("\n", bio);
61
4.00k
    res = 0;
62
63
4.05k
end:
64
4.05k
    EVP_PKEY_free(pubkey);
65
4.05k
    BIO_free(bio);
66
67
4.05k
    return res;
68
4.00k
}
69
70
/* Verify a message protected with PBMAC */
71
static int verify_PBMAC(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
72
1.73k
{
73
1.73k
    ASN1_BIT_STRING *protection = NULL;
74
1.73k
    int valid = 0;
75
76
    /* generate expected protection for the message */
77
1.73k
    if ((protection = ossl_cmp_calc_protection(ctx, msg)) == NULL)
78
1.21k
        return 0; /* failed to generate protection string! */
79
80
516
    valid = msg->protection != NULL && msg->protection->length >= 0
81
516
        && msg->protection->type == protection->type
82
516
        && msg->protection->length == protection->length
83
363
        && CRYPTO_memcmp(msg->protection->data, protection->data,
84
363
               protection->length)
85
363
            == 0;
86
516
    ASN1_BIT_STRING_free(protection);
87
516
    if (!valid)
88
516
        ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_PBM_VALUE);
89
90
516
    return valid;
91
1.73k
}
92
93
/*-
94
 * Attempt to validate certificate and path using any given store with trusted
95
 * certs (possibly including CRLs and a cert verification callback function)
96
 * and non-trusted intermediate certs from the given ctx.
97
 *
98
 * Returns 1 on successful validation and 0 otherwise.
99
 */
100
int OSSL_CMP_validate_cert_path(const OSSL_CMP_CTX *ctx,
101
    X509_STORE *trusted_store, X509 *cert)
102
53
{
103
53
    int valid = 0;
104
53
    X509_STORE_CTX *csc = NULL;
105
53
    int err;
106
107
53
    if (ctx == NULL || cert == NULL) {
108
0
        ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
109
0
        return 0;
110
0
    }
111
112
53
    if (trusted_store == NULL) {
113
53
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_STORE);
114
53
        return 0;
115
53
    }
116
117
0
    if ((csc = X509_STORE_CTX_new_ex(ctx->libctx, ctx->propq)) == NULL
118
0
        || !X509_STORE_CTX_init(csc, trusted_store,
119
0
            cert, ctx->untrusted))
120
0
        goto err;
121
122
0
    valid = X509_verify_cert(csc) > 0;
123
124
    /* make sure suitable error is queued even if callback did not do */
125
0
    err = ERR_peek_last_error();
126
0
    if (!valid && ERR_GET_REASON(err) != CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
127
0
        ERR_raise(ERR_LIB_CMP, CMP_R_POTENTIALLY_INVALID_CERTIFICATE);
128
129
0
err:
130
    /* directly output any fresh errors, needed for check_msg_find_cert() */
131
0
    OSSL_CMP_CTX_print_errors(ctx);
132
0
    X509_STORE_CTX_free(csc);
133
0
    return valid;
134
0
}
135
136
static int verify_cb_cert(X509_STORE *ts, X509 *cert, int err)
137
4.43k
{
138
4.43k
    X509_STORE_CTX_verify_cb verify_cb;
139
4.43k
    X509_STORE_CTX *csc;
140
4.43k
    int ok = 0;
141
142
4.43k
    if (ts == NULL || (verify_cb = X509_STORE_get_verify_cb(ts)) == NULL)
143
4.43k
        return ok;
144
0
    if ((csc = X509_STORE_CTX_new()) != NULL
145
0
        && X509_STORE_CTX_init(csc, ts, cert, NULL)) {
146
0
        X509_STORE_CTX_set_error(csc, err);
147
0
        X509_STORE_CTX_set_current_cert(csc, cert);
148
0
        ok = (*verify_cb)(0, csc);
149
0
    }
150
0
    X509_STORE_CTX_free(csc);
151
0
    return ok;
152
4.43k
}
153
154
/* Return 0 if expect_name != NULL and there is no matching actual_name */
155
static int check_name(const OSSL_CMP_CTX *ctx, int log_success,
156
    const char *actual_desc, const X509_NAME *actual_name,
157
    const char *expect_desc, const X509_NAME *expect_name)
158
16.8k
{
159
16.8k
    char *str;
160
161
16.8k
    if (expect_name == NULL)
162
4.99k
        return 1; /* no expectation, thus trivially fulfilled */
163
164
    /* make sure that a matching name is there */
165
11.8k
    if (actual_name == NULL) {
166
0
        ossl_cmp_log1(WARN, ctx, "missing %s", actual_desc);
167
0
        return 0;
168
0
    }
169
11.8k
    str = X509_NAME_oneline(actual_name, NULL, 0);
170
11.8k
    if (X509_NAME_cmp(actual_name, expect_name) == 0) {
171
5.33k
        if (log_success && str != NULL)
172
5.33k
            ossl_cmp_log3(INFO, ctx, " %s matches %s: %s",
173
5.33k
                actual_desc, expect_desc, str);
174
5.33k
        OPENSSL_free(str);
175
5.33k
        return 1;
176
5.33k
    }
177
178
6.53k
    if (str != NULL)
179
6.53k
        ossl_cmp_log2(INFO, ctx, " actual name in %s = %s", actual_desc, str);
180
6.53k
    OPENSSL_free(str);
181
6.53k
    if ((str = X509_NAME_oneline(expect_name, NULL, 0)) != NULL)
182
6.53k
        ossl_cmp_log2(INFO, ctx, " does not match %s = %s", expect_desc, str);
183
6.53k
    OPENSSL_free(str);
184
6.53k
    return 0;
185
11.8k
}
186
187
/* Return 0 if skid != NULL and there is no matching subject key ID in cert */
188
static int check_kid(const OSSL_CMP_CTX *ctx,
189
    const ASN1_OCTET_STRING *ckid,
190
    const ASN1_OCTET_STRING *skid)
191
5.33k
{
192
5.33k
    char *str;
193
194
5.33k
    if (skid == NULL)
195
1.99k
        return 1; /* no expectation, thus trivially fulfilled */
196
197
    /* make sure that the expected subject key identifier is there */
198
3.34k
    if (ckid == NULL) {
199
279
        ossl_cmp_warn(ctx, "missing Subject Key Identifier in certificate");
200
279
        return 0;
201
279
    }
202
3.06k
    str = i2s_ASN1_OCTET_STRING(NULL, ckid);
203
3.06k
    if (ASN1_OCTET_STRING_cmp(ckid, skid) == 0) {
204
2.85k
        if (str != NULL)
205
2.85k
            ossl_cmp_log1(INFO, ctx, " subjectKID matches senderKID: %s", str);
206
2.85k
        OPENSSL_free(str);
207
2.85k
        return 1;
208
2.85k
    }
209
210
205
    if (str != NULL)
211
205
        ossl_cmp_log1(INFO, ctx, " cert Subject Key Identifier = %s", str);
212
205
    OPENSSL_free(str);
213
205
    if ((str = i2s_ASN1_OCTET_STRING(NULL, skid)) != NULL)
214
205
        ossl_cmp_log1(INFO, ctx, " does not match senderKID    = %s", str);
215
205
    OPENSSL_free(str);
216
205
    return 0;
217
3.06k
}
218
219
static int already_checked(const X509 *cert,
220
    const STACK_OF(X509) *already_checked)
221
51.7k
{
222
51.7k
    int i;
223
224
77.5k
    for (i = sk_X509_num(already_checked /* may be NULL */); i > 0; i--)
225
43.0k
        if (X509_cmp(sk_X509_value(already_checked, i - 1), cert) == 0)
226
17.2k
            return 1;
227
34.4k
    return 0;
228
51.7k
}
229
230
/*-
231
 * Check if the given cert is acceptable as sender cert of the given message.
232
 * The subject DN must match, the subject key ID as well if present in the msg,
233
 * and the cert must be current (checked if ctx->trusted is not NULL).
234
 * Note that cert revocation etc. is checked by OSSL_CMP_validate_cert_path().
235
 *
236
 * Returns 0 on error or not acceptable, else 1.
237
 */
238
static int cert_acceptable(const OSSL_CMP_CTX *ctx,
239
    const char *desc1, const char *desc2, X509 *cert,
240
    const STACK_OF(X509) *already_checked1,
241
    const STACK_OF(X509) *already_checked2,
242
    const OSSL_CMP_MSG *msg)
243
25.1k
{
244
25.1k
    X509_STORE *ts = ctx->trusted;
245
25.1k
    int self_issued = X509_check_issued(cert, cert) == X509_V_OK;
246
25.1k
    char *str;
247
25.1k
    X509_VERIFY_PARAM *vpm = ts != NULL ? X509_STORE_get0_param(ts) : NULL;
248
25.1k
    int time_cmp;
249
250
25.1k
    ossl_cmp_log3(INFO, ctx, " considering %s%s %s with..",
251
25.1k
        self_issued ? "self-issued " : "", desc1, desc2);
252
25.1k
    if ((str = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0)) != NULL)
253
25.1k
        ossl_cmp_log1(INFO, ctx, "  subject = %s", str);
254
25.1k
    OPENSSL_free(str);
255
25.1k
    if (!self_issued) {
256
22.3k
        str = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
257
22.3k
        if (str != NULL)
258
22.3k
            ossl_cmp_log1(INFO, ctx, "  issuer  = %s", str);
259
22.3k
        OPENSSL_free(str);
260
22.3k
    }
261
262
25.1k
    if (already_checked(cert, already_checked1)
263
12.5k
        || already_checked(cert, already_checked2)) {
264
12.5k
        ossl_cmp_info(ctx, " cert has already been checked");
265
12.5k
        return 0;
266
12.5k
    }
267
268
12.5k
    time_cmp = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
269
12.5k
        X509_get0_notAfter(cert));
270
12.5k
    if (time_cmp != 0) {
271
6.67k
        int err = time_cmp > 0 ? X509_V_ERR_CERT_HAS_EXPIRED
272
6.67k
                               : X509_V_ERR_CERT_NOT_YET_VALID;
273
274
6.67k
        ossl_cmp_warn(ctx, time_cmp > 0 ? "cert has expired" : "cert is not yet valid");
275
6.67k
        if (ctx->log_cb != NULL /* logging not temporarily disabled */
276
3.33k
            && verify_cb_cert(ts, cert, err) <= 0)
277
3.33k
            return 0;
278
6.67k
    }
279
280
9.25k
    if (!check_name(ctx, 1,
281
9.25k
            "cert subject", X509_get_subject_name(cert),
282
9.25k
            "sender field", msg->header->sender->d.directoryName))
283
5.11k
        return 0;
284
285
4.13k
    if (!check_kid(ctx, X509_get0_subject_key_id(cert), msg->header->senderKID))
286
387
        return 0;
287
    /* prevent misleading error later in case x509v3_cache_extensions() fails */
288
3.74k
    if (!ossl_x509v3_cache_extensions(cert)) {
289
219
        ossl_cmp_warn(ctx, "cert appears to be invalid");
290
219
        return 0;
291
219
    }
292
3.52k
    if (!verify_signature(ctx, msg, cert)) {
293
3.48k
        ossl_cmp_warn(ctx, "msg signature verification failed");
294
3.48k
        return 0;
295
3.48k
    }
296
    /* acceptable also if there is no senderKID in msg header */
297
41
    ossl_cmp_info(ctx, " cert seems acceptable");
298
41
    return 1;
299
3.52k
}
300
301
static int check_cert_path(const OSSL_CMP_CTX *ctx, X509_STORE *store,
302
    X509 *scrt)
303
53
{
304
53
    if (OSSL_CMP_validate_cert_path(ctx, store, scrt))
305
0
        return 1;
306
307
53
    ossl_cmp_warn(ctx,
308
53
        "msg signature validates but cert path validation failed");
309
53
    return 0;
310
53
}
311
312
/*
313
 * Exceptional handling for 3GPP TS 33.310 [3G/LTE Network Domain Security
314
 * (NDS); Authentication Framework (AF)], only to use for IP messages
315
 * and if the ctx option is explicitly set: use self-issued certificates
316
 * from extraCerts as trust anchor to validate sender cert -
317
 * provided it also can validate the newly enrolled certificate
318
 */
319
static int check_cert_path_3gpp(const OSSL_CMP_CTX *ctx,
320
    const OSSL_CMP_MSG *msg, X509 *scrt)
321
0
{
322
0
    int valid = 0;
323
0
    X509_STORE *store;
324
325
0
    if (!ctx->permitTAInExtraCertsForIR)
326
0
        return 0;
327
328
0
    if ((store = X509_STORE_new()) == NULL
329
0
        || !ossl_cmp_X509_STORE_add1_certs(store, msg->extraCerts,
330
0
            1 /* self-issued only */))
331
0
        goto err;
332
333
    /* store does not include CRLs */
334
0
    valid = OSSL_CMP_validate_cert_path(ctx, store, scrt);
335
0
    if (!valid) {
336
0
        ossl_cmp_warn(ctx,
337
0
            "also exceptional 3GPP mode cert path validation failed");
338
0
    } else if (OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_IP) {
339
        /*
340
         * verify that the newly enrolled certificate (which assumed rid ==
341
         * OSSL_CMP_CERTREQID) can also be validated with the same trusted store
342
         */
343
0
        OSSL_CMP_CERTRESPONSE *crep = ossl_cmp_certrepmessage_get0_certresponse(msg->body->value.ip,
344
0
            OSSL_CMP_CERTREQID);
345
0
        X509 *newcrt = NULL;
346
347
0
        valid = crep != NULL
348
0
            && (newcrt = ossl_cmp_certresponse_get1_cert(ctx, crep)) != NULL
349
0
            && OSSL_CMP_validate_cert_path(ctx, store, newcrt);
350
0
        X509_free(newcrt);
351
0
    }
352
353
0
err:
354
0
    X509_STORE_free(store);
355
0
    return valid;
356
0
}
357
358
/* checks protection of msg but not cert revocation nor cert chain */
359
static int check_msg_given_cert(const OSSL_CMP_CTX *ctx, X509 *cert,
360
    const OSSL_CMP_MSG *msg)
361
0
{
362
0
    return cert_acceptable(ctx, "previously validated", "sender cert",
363
0
        cert, NULL, NULL, msg);
364
0
}
365
366
/*-
367
 * Try all certs in given list for verifying msg, normally or in 3GPP mode.
368
 * If already_checked1 == NULL then certs are assumed to be the msg->extraCerts.
369
 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
370
 */
371
static int check_msg_with_certs(OSSL_CMP_CTX *ctx, const STACK_OF(X509) *certs,
372
    const char *desc,
373
    const STACK_OF(X509) *already_checked1,
374
    const STACK_OF(X509) *already_checked2,
375
    const OSSL_CMP_MSG *msg, int mode_3gpp)
376
16.1k
{
377
16.1k
    int in_extraCerts = already_checked1 == NULL;
378
16.1k
    int n_acceptable_certs = 0;
379
16.1k
    int i;
380
381
16.1k
    if (sk_X509_num(certs) <= 0) {
382
2.25k
        ossl_cmp_log1(WARN, ctx, "no %s", desc);
383
2.25k
        return 0;
384
2.25k
    }
385
386
44.0k
    for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
387
30.1k
        X509 *cert = sk_X509_value(certs, i);
388
389
30.1k
        if (!ossl_assert(cert != NULL))
390
0
            return 0;
391
30.1k
        if (!cert_acceptable(ctx, "cert from", desc, cert,
392
30.1k
                already_checked1, already_checked2, msg))
393
30.0k
            continue;
394
49
        n_acceptable_certs++;
395
49
        if (mode_3gpp ? check_cert_path_3gpp(ctx, msg, cert)
396
49
                      : check_cert_path(ctx, ctx->trusted, cert)) {
397
            /* store successful sender cert for further msgs in transaction */
398
0
            return ossl_cmp_ctx_set1_validatedSrvCert(ctx, cert);
399
0
        }
400
49
    }
401
13.9k
    if (in_extraCerts && n_acceptable_certs == 0)
402
13.9k
        ossl_cmp_warn(ctx, "no acceptable cert in extraCerts");
403
13.9k
    return 0;
404
13.9k
}
405
406
/*-
407
 * Verify msg trying first ctx->untrusted, which should include extraCerts
408
 * at its front, then trying the trusted certs in truststore (if any) of ctx.
409
 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
410
 */
411
static int check_msg_all_certs(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
412
    int mode_3gpp)
413
16.1k
{
414
16.1k
    int ret = 0;
415
416
16.1k
    if (ctx->permitTAInExtraCertsForIR
417
0
        && OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_IP)
418
16.1k
        ossl_cmp_info(ctx, mode_3gpp ? "normal mode failed; trying now 3GPP mode trusting extraCerts" : "trying first normal mode using trust store");
419
16.1k
    else if (mode_3gpp)
420
8.09k
        return 0;
421
422
8.09k
    if (check_msg_with_certs(ctx, msg->extraCerts, "extraCerts",
423
8.09k
            NULL, NULL, msg, mode_3gpp))
424
0
        return 1;
425
8.09k
    if (check_msg_with_certs(ctx, ctx->untrusted, "untrusted certs",
426
8.09k
            msg->extraCerts, NULL, msg, mode_3gpp))
427
0
        return 1;
428
429
8.09k
    if (ctx->trusted == NULL) {
430
8.09k
        ossl_cmp_warn(ctx, mode_3gpp ? "no self-issued extraCerts" : "no trusted store");
431
8.09k
    } else {
432
0
        STACK_OF(X509) *trusted = X509_STORE_get1_all_certs(ctx->trusted);
433
434
0
        ret = check_msg_with_certs(ctx, trusted,
435
0
            mode_3gpp ? "self-issued extraCerts"
436
0
                      : "certs in trusted store",
437
0
            msg->extraCerts, ctx->untrusted,
438
0
            msg, mode_3gpp);
439
0
        OSSL_STACK_OF_X509_free(trusted);
440
0
    }
441
8.09k
    return ret;
442
8.09k
}
443
444
/*-
445
 * Verify message signature with any acceptable and valid candidate cert.
446
 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
447
 */
448
static int check_msg_find_cert(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
449
4.56k
{
450
4.56k
    X509 *scrt = ctx->validatedSrvCert; /* previous successful sender cert */
451
4.56k
    GENERAL_NAME *sender = msg->header->sender;
452
4.56k
    char *sname = NULL;
453
4.56k
    char *skid_str = NULL;
454
4.56k
    const ASN1_OCTET_STRING *skid = msg->header->senderKID;
455
4.56k
    OSSL_CMP_log_cb_t backup_log_cb = ctx->log_cb;
456
4.56k
    int res = 0;
457
458
4.56k
    if (sender == NULL || msg->body == NULL)
459
0
        return 0; /* other NULL cases already have been checked */
460
4.56k
    if (sender->type != GEN_DIRNAME) {
461
        /* So far, only X509_NAME is supported */
462
0
        ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
463
0
        return 0;
464
0
    }
465
466
    /* dump any hitherto errors to avoid confusion when printing further ones */
467
4.56k
    OSSL_CMP_CTX_print_errors(ctx);
468
469
    /* enable clearing irrelevant errors in attempts to validate sender certs */
470
4.56k
    (void)ERR_set_mark();
471
4.56k
    ctx->log_cb = NULL; /* temporarily disable logging */
472
473
4.56k
    if (scrt != NULL) {
474
        /*-
475
         * try first using cached message sender cert (in 'scrt' variable),
476
         * which was used successfully earlier in the same transaction
477
         * (assuming that the certificate itself was not revoked meanwhile and
478
         *  is a good guess for use in validating also the current message)
479
         */
480
0
        if (check_msg_given_cert(ctx, scrt, msg)) {
481
0
            ctx->log_cb = backup_log_cb;
482
0
            (void)ERR_pop_to_mark();
483
0
            return 1;
484
0
        }
485
        /* cached sender cert has shown to be no more successfully usable */
486
        /* re-do the above check (just) for adding diagnostic information */
487
0
        ossl_cmp_info(ctx,
488
0
            "trying to verify msg signature with previously validated cert");
489
0
        ctx->log_cb = backup_log_cb;
490
0
        (void)check_msg_given_cert(ctx, scrt, msg);
491
0
        ctx->log_cb = NULL;
492
0
        (void)ossl_cmp_ctx_set1_validatedSrvCert(ctx, NULL); /* this invalidates scrt */
493
0
    }
494
495
4.56k
    res = check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */)
496
4.56k
        || check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
497
4.56k
    ctx->log_cb = backup_log_cb;
498
4.56k
    if (res) {
499
        /* discard any diagnostic information on trying to use certs */
500
0
        (void)ERR_pop_to_mark();
501
0
        goto end;
502
0
    }
503
    /* failed finding a sender cert that verifies the message signature */
504
4.56k
    (void)ERR_clear_last_mark();
505
506
4.56k
    sname = X509_NAME_oneline(sender->d.directoryName, NULL, 0);
507
4.56k
    skid_str = skid == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, skid);
508
4.56k
    if (ctx->log_cb != NULL) {
509
4.56k
        ossl_cmp_info(ctx, "trying to verify msg signature with a valid cert that..");
510
4.56k
        if (sname != NULL)
511
4.56k
            ossl_cmp_log1(INFO, ctx, "matches msg sender    = %s", sname);
512
4.56k
        if (skid_str != NULL)
513
2.63k
            ossl_cmp_log1(INFO, ctx, "matches msg senderKID = %s", skid_str);
514
1.92k
        else
515
4.56k
            ossl_cmp_info(ctx, "while msg header does not contain senderKID");
516
        /* re-do the above checks (just) for adding diagnostic information */
517
4.56k
        (void)check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */);
518
4.56k
        (void)check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
519
4.56k
    }
520
521
4.56k
    ERR_raise(ERR_LIB_CMP, CMP_R_NO_SUITABLE_SENDER_CERT);
522
4.56k
    if (sname != NULL) {
523
4.56k
        ERR_add_error_txt(NULL, "for msg sender name = ");
524
4.56k
        ERR_add_error_txt(NULL, sname);
525
4.56k
    }
526
4.56k
    if (skid_str != NULL) {
527
2.63k
        ERR_add_error_txt(" and ", "for msg senderKID = ");
528
2.63k
        ERR_add_error_txt(NULL, skid_str);
529
2.63k
    }
530
531
4.56k
end:
532
4.56k
    OPENSSL_free(sname);
533
4.56k
    OPENSSL_free(skid_str);
534
4.56k
    return res;
535
4.56k
}
536
537
/*-
538
 * Validate the protection of the given PKIMessage using either password-
539
 * based mac (PBM) or a signature algorithm. In the case of signature algorithm,
540
 * the sender certificate can have been pinned by providing it in ctx->srvCert,
541
 * else it is searched in msg->extraCerts, ctx->untrusted, in ctx->trusted
542
 * (in this order) and is path is validated against ctx->trusted.
543
 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
544
 *
545
 * If ctx->permitTAInExtraCertsForIR is true and when validating a CMP IP msg,
546
 * the trust anchor for validating the IP msg may be taken from msg->extraCerts
547
 * if a self-issued certificate is found there that can be used to
548
 * validate the enrolled certificate returned in the IP.
549
 * This is according to the need given in 3GPP TS 33.310.
550
 *
551
 * Returns 1 on success, 0 on error or validation failed.
552
 */
553
int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
554
8.15k
{
555
8.15k
    X509 *scrt;
556
557
8.15k
    ossl_cmp_debug(ctx, "validating CMP message");
558
8.15k
    if (ctx == NULL || msg == NULL
559
8.15k
        || msg->header == NULL || msg->body == NULL) {
560
0
        ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
561
0
        return 0;
562
0
    }
563
564
8.15k
    if (msg->header->protectionAlg == NULL /* unprotected message */
565
8.15k
        || msg->protection == NULL || msg->protection->data == NULL) {
566
2.39k
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
567
2.39k
        return 0;
568
2.39k
    }
569
570
5.75k
    switch (ossl_cmp_hdr_get_protection_nid(msg->header)) {
571
        /* 5.1.3.1.  Shared Secret Information */
572
1.59k
    case NID_id_PasswordBasedMAC:
573
1.59k
        if (ctx->secretValue == NULL) {
574
720
            ossl_cmp_info(ctx, "no secret available for verifying PBM-based CMP message protection");
575
720
            ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SECRET);
576
720
            return 0;
577
720
        }
578
870
        if (verify_PBMAC(ctx, msg)) {
579
            /*
580
             * RFC 9810, 5.3.2: 'Note that if the PKI message protection is
581
             * "shared secret information", then any certificate transported in
582
             * the caPubs field may be directly trusted as a root CA
583
             * certificate by the initiator.'
584
             */
585
6
            switch (OSSL_CMP_MSG_get_bodytype(msg)) {
586
0
            case -1:
587
0
                return 0;
588
0
            case OSSL_CMP_PKIBODY_IP:
589
0
            case OSSL_CMP_PKIBODY_CP:
590
0
            case OSSL_CMP_PKIBODY_KUP:
591
3
            case OSSL_CMP_PKIBODY_CCP:
592
3
                if (ctx->trusted != NULL) {
593
0
                    STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
594
                    /* value.ip is same for cp, kup, and ccp */
595
596
0
                    if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
597
                        /* adds both self-issued and not self-issued certs */
598
0
                        return 0;
599
0
                }
600
3
                break;
601
3
            default:
602
3
                break;
603
6
            }
604
6
            ossl_cmp_debug(ctx,
605
6
                "successfully validated PBM-based CMP message protection");
606
6
            return 1;
607
6
        }
608
864
        ossl_cmp_warn(ctx, "verifying PBM-based CMP message protection failed");
609
864
        break;
610
611
        /*
612
         * 5.1.3.2 DH Key Pairs
613
         * Not yet supported
614
         */
615
30
    case NID_id_DHBasedMac:
616
30
        ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC);
617
30
        break;
618
619
        /*
620
         * 5.1.3.3.  Signature
621
         */
622
4.13k
    default:
623
4.13k
        scrt = ctx->srvCert;
624
4.13k
        if (scrt == NULL) {
625
4.13k
            if (ctx->trusted == NULL && ctx->secretValue != NULL) {
626
1.66k
                ossl_cmp_info(ctx, "no trust store nor pinned sender cert available for verifying signature-based CMP message protection");
627
1.66k
                ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_ANCHOR);
628
1.66k
                return 0;
629
1.66k
            }
630
2.47k
            if (check_msg_find_cert(ctx, msg)) {
631
0
                ossl_cmp_log1(DEBUG, ctx,
632
0
                    "successfully validated signature-based CMP message protection using trust store%s",
633
0
                    ctx->permitTAInExtraCertsForIR ? " or 3GPP mode" : "");
634
0
                return 1;
635
0
            }
636
2.47k
        } else { /* use pinned sender cert */
637
            /* use ctx->srvCert for signature check even if not acceptable */
638
0
            if (verify_signature(ctx, msg, scrt)) {
639
0
                ossl_cmp_debug(ctx,
640
0
                    "successfully validated signature-based CMP message protection using pinned sender cert");
641
0
                return ossl_cmp_ctx_set1_validatedSrvCert(ctx, scrt);
642
0
            }
643
0
            ossl_cmp_warn(ctx, "CMP message signature verification failed");
644
0
            ERR_raise(ERR_LIB_CMP, CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG);
645
0
        }
646
2.47k
        break;
647
5.75k
    }
648
3.36k
    return 0;
649
5.75k
}
650
651
static int check_transactionID_or_nonce(ASN1_OCTET_STRING *expected,
652
    ASN1_OCTET_STRING *actual, int reason)
653
83.2k
{
654
83.2k
    if (expected != NULL
655
0
        && (actual == NULL || ASN1_OCTET_STRING_cmp(expected, actual) != 0)) {
656
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
657
        char *expected_str, *actual_str;
658
659
        expected_str = i2s_ASN1_OCTET_STRING(NULL, expected);
660
        actual_str = actual == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, actual);
661
        ERR_raise_data(ERR_LIB_CMP, reason,
662
            "expected = %s, actual = %s",
663
            expected_str == NULL ? "?" : expected_str,
664
            actual == NULL ? "(none)" : actual_str == NULL ? "?"
665
                                                           : actual_str);
666
        OPENSSL_free(expected_str);
667
        OPENSSL_free(actual_str);
668
        return 0;
669
#endif
670
0
    }
671
83.2k
    return 1;
672
83.2k
}
673
674
/*-
675
 * Check received message (i.e., response by server or request from client)
676
 * Any msg->extraCerts are prepended to ctx->untrusted.
677
 *
678
 * Ensures that:
679
 * its sender is of appropriate type (currently only X509_NAME) and
680
 *     matches any expected sender or srvCert subject given in the ctx
681
 * it has a valid body type
682
 * its protection is valid (or invalid/absent, but only if a callback function
683
 *     is present and yields a positive result using also the supplied argument)
684
 * its transaction ID matches the previous transaction ID stored in ctx (if any)
685
 * its recipNonce matches the previous senderNonce stored in the ctx (if any)
686
 *
687
 * If everything is fine:
688
 * learns the senderNonce from the received message,
689
 * learns the transaction ID if it is not yet in ctx,
690
 * and makes any certs in caPubs directly trusted.
691
 *
692
 * Returns 1 on success, 0 on error.
693
 */
694
int ossl_cmp_msg_check_update(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
695
    ossl_cmp_allow_unprotected_cb_t cb, int cb_arg)
696
33.4k
{
697
33.4k
    OSSL_CMP_PKIHEADER *hdr;
698
33.4k
    const X509_NAME *expected_sender;
699
33.4k
    int num_untrusted, num_added, res;
700
701
33.4k
    if (!ossl_assert(ctx != NULL && msg != NULL && msg->header != NULL))
702
0
        return 0;
703
33.4k
    hdr = OSSL_CMP_MSG_get0_header(msg);
704
705
    /* If expected_sender is given, validate sender name of received msg */
706
33.4k
    expected_sender = ctx->expected_sender;
707
33.4k
    if (expected_sender == NULL && ctx->srvCert != NULL)
708
0
        expected_sender = X509_get_subject_name(ctx->srvCert);
709
33.4k
    if (expected_sender != NULL) {
710
0
        const X509_NAME *actual_sender;
711
0
        char *str;
712
713
0
        if (hdr->sender->type != GEN_DIRNAME) {
714
0
            ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
715
0
            return 0;
716
0
        }
717
0
        actual_sender = hdr->sender->d.directoryName;
718
        /*
719
         * Compare actual sender name of response with expected sender name.
720
         * Mitigates risk of accepting misused PBM secret or
721
         * misused certificate of an unauthorized entity of a trusted hierarchy.
722
         */
723
0
        if (!check_name(ctx, 0, "sender DN field", actual_sender,
724
0
                "expected sender", expected_sender)) {
725
0
            str = X509_NAME_oneline(actual_sender, NULL, 0);
726
0
            ERR_raise_data(ERR_LIB_CMP, CMP_R_UNEXPECTED_SENDER,
727
0
                str != NULL ? str : "<unknown>");
728
0
            OPENSSL_free(str);
729
0
            return 0;
730
0
        }
731
0
    }
732
    /* Note: if recipient was NULL-DN it could be learned here if needed */
733
734
33.4k
    num_added = sk_X509_num(msg->extraCerts);
735
33.4k
    if (num_added > 10)
736
0
        ossl_cmp_log1(WARN, ctx, "received CMP message contains %d extraCerts",
737
33.4k
            num_added);
738
    /*
739
     * Store any provided extraCerts in ctx for use in OSSL_CMP_validate_msg()
740
     * and for future use, such that they are available to ctx->certConf_cb and
741
     * the peer does not need to send them again in the same transaction.
742
     * Note that it does not help validating the message before storing the
743
     * extraCerts because they do not belong to the protected msg part anyway.
744
     * The extraCerts are prepended. Allows simple removal if they shall not be
745
     * cached. Also they get used first, which is likely good for efficiency.
746
     */
747
33.4k
    num_untrusted = ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted);
748
33.4k
    res = ossl_x509_add_certs_new(&ctx->untrusted, msg->extraCerts,
749
        /* this allows self-signed certs */
750
33.4k
        X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
751
33.4k
            | X509_ADD_FLAG_PREPEND);
752
33.4k
    num_added = (ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted))
753
33.4k
        - num_untrusted;
754
33.4k
    if (!res) {
755
0
        while (num_added-- > 0)
756
0
            X509_free(sk_X509_shift(ctx->untrusted));
757
0
        return 0;
758
0
    }
759
760
33.4k
    if (hdr->protectionAlg != NULL)
761
13.3k
        res = OSSL_CMP_validate_msg(ctx, msg)
762
            /* explicitly permitted exceptions for invalid protection: */
763
13.3k
            || (cb != NULL && (*cb)(ctx, msg, 1, cb_arg) > 0);
764
20.0k
    else
765
        /* explicitly permitted exceptions for missing protection: */
766
20.0k
        res = cb != NULL && (*cb)(ctx, msg, 0, cb_arg) > 0;
767
33.4k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
768
33.4k
    res = 1; /* support more aggressive fuzzing by letting invalid msg pass */
769
33.4k
#endif
770
771
    /* remove extraCerts again if not caching */
772
33.4k
    if (ctx->noCacheExtraCerts)
773
0
        while (num_added-- > 0)
774
0
            X509_free(sk_X509_shift(ctx->untrusted));
775
776
33.4k
    if (!res) {
777
0
        if (hdr->protectionAlg != NULL)
778
0
            ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_PROTECTION);
779
0
        else
780
0
            ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
781
0
        return 0;
782
0
    }
783
784
    /* check CMP version number in header */
785
33.4k
    if (ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_2
786
21.3k
        && ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_3) {
787
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
788
        ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PVNO);
789
        return 0;
790
#endif
791
21.3k
    }
792
793
33.4k
    if (OSSL_CMP_MSG_get_bodytype(msg) < 0) {
794
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
795
        ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
796
        return 0;
797
#endif
798
0
    }
799
800
    /* compare received transactionID with the expected one in previous msg */
801
33.4k
    if (!check_transactionID_or_nonce(ctx->transactionID, hdr->transactionID,
802
33.4k
            CMP_R_TRANSACTIONID_UNMATCHED))
803
0
        return 0;
804
805
    /*
806
     * enable clearing irrelevant errors
807
     * in attempts to validate recipient nonce in case of delayed delivery.
808
     */
809
33.4k
    (void)ERR_set_mark();
810
    /* compare received nonce with the one we sent */
811
33.4k
    if (!check_transactionID_or_nonce(ctx->senderNonce, hdr->recipNonce,
812
33.4k
            CMP_R_RECIPNONCE_UNMATCHED)) {
813
        /* check if we are polling and received final response */
814
0
        if (ctx->first_senderNonce == NULL
815
0
            || OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_POLLREP
816
            /* compare received nonce with our sender nonce at poll start */
817
0
            || !check_transactionID_or_nonce(ctx->first_senderNonce,
818
0
                hdr->recipNonce,
819
0
                CMP_R_RECIPNONCE_UNMATCHED)) {
820
0
            (void)ERR_clear_last_mark();
821
0
            return 0;
822
0
        }
823
0
    }
824
33.4k
    (void)ERR_pop_to_mark();
825
826
    /* if not yet present, learn transactionID */
827
33.4k
    if (ctx->transactionID == NULL
828
33.4k
        && !OSSL_CMP_CTX_set1_transactionID(ctx, hdr->transactionID))
829
0
        return 0;
830
831
    /*
832
     * RFC 9810 section 5.1.1 states: the recipNonce is copied from
833
     * the senderNonce of the previous message in the transaction.
834
     * --> Store for setting in next message
835
     */
836
33.4k
    if (!ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce))
837
0
        return 0;
838
839
33.4k
    if (ossl_cmp_hdr_get_protection_nid(hdr) == NID_id_PasswordBasedMAC) {
840
        /*
841
         * RFC 9810, 5.3.2: 'Note that if the PKI message protection is
842
         * "shared secret information", then any certificate transported in
843
         * the caPubs field may be directly trusted as a root CA
844
         * certificate by the initiator.'
845
         */
846
3.56k
        switch (OSSL_CMP_MSG_get_bodytype(msg)) {
847
7
        case OSSL_CMP_PKIBODY_IP:
848
18
        case OSSL_CMP_PKIBODY_CP:
849
23
        case OSSL_CMP_PKIBODY_KUP:
850
44
        case OSSL_CMP_PKIBODY_CCP:
851
44
            if (ctx->trusted != NULL) {
852
0
                STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
853
                /* value.ip is same for cp, kup, and ccp */
854
855
0
                if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
856
                    /* adds both self-issued and not self-issued certs */
857
0
                    return 0;
858
0
            }
859
44
            break;
860
3.51k
        default:
861
3.51k
            break;
862
3.56k
        }
863
3.56k
    }
864
33.4k
    return 1;
865
33.4k
}
866
867
int ossl_cmp_verify_popo(const OSSL_CMP_CTX *ctx,
868
    const OSSL_CMP_MSG *msg, int acceptRAVerified)
869
6.63k
{
870
6.63k
    if (!ossl_assert(msg != NULL && msg->body != NULL))
871
0
        return 0;
872
6.63k
    switch (msg->body->type) {
873
3.99k
    case OSSL_CMP_PKIBODY_P10CR: {
874
3.99k
        X509_REQ *req = msg->body->value.p10cr;
875
876
3.99k
        if (X509_REQ_verify_ex(req, X509_REQ_get0_pubkey(req), ctx->libctx,
877
3.99k
                ctx->propq)
878
3.99k
            <= 0) {
879
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
880
            ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED);
881
            return 0;
882
#endif
883
3.99k
        }
884
3.99k
    } break;
885
1.47k
    case OSSL_CMP_PKIBODY_IR:
886
2.45k
    case OSSL_CMP_PKIBODY_CR:
887
2.64k
    case OSSL_CMP_PKIBODY_KUR:
888
2.64k
        if (!OSSL_CRMF_MSGS_verify_popo(msg->body->value.ir, OSSL_CMP_CERTREQID,
889
2.64k
                acceptRAVerified,
890
2.64k
                ctx->libctx, ctx->propq)) {
891
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
892
            return 0;
893
#endif
894
2.54k
        }
895
2.64k
        break;
896
0
    default:
897
0
        ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
898
0
        return 0;
899
6.63k
    }
900
6.63k
    return 1;
901
6.63k
}