Coverage Report

Created: 2026-02-14 07:20

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
3.80k
{
20
3.80k
    OSSL_CMP_PROTECTEDPART prot_part;
21
3.80k
    EVP_PKEY *pubkey = NULL;
22
3.80k
    BIO *bio;
23
3.80k
    int res = 0;
24
25
3.80k
    if (!ossl_assert(cmp_ctx != NULL && msg != NULL && cert != NULL))
26
0
        return 0;
27
28
3.80k
    bio = BIO_new(BIO_s_mem()); /* may be NULL */
29
3.80k
    if (bio == NULL)
30
0
        return 0;
31
    /* verify that keyUsage, if present, contains digitalSignature */
32
3.80k
    if (!cmp_ctx->ignore_keyusage
33
3.80k
        && (X509_get_key_usage(cert) & X509v3_KU_DIGITAL_SIGNATURE) == 0) {
34
512
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE);
35
512
        goto sig_err;
36
512
    }
37
38
3.29k
    pubkey = X509_get_pubkey(cert);
39
3.29k
    if (pubkey == NULL) {
40
1.43k
        ERR_raise(ERR_LIB_CMP, CMP_R_FAILED_EXTRACTING_PUBKEY);
41
1.43k
        goto sig_err;
42
1.43k
    }
43
44
1.86k
    prot_part.header = msg->header;
45
1.86k
    prot_part.body = msg->body;
46
47
1.86k
    if (ASN1_item_verify_ex(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART),
48
1.86k
            msg->header->protectionAlg, msg->protection,
49
1.86k
            &prot_part, NULL, pubkey, cmp_ctx->libctx,
50
1.86k
            cmp_ctx->propq)
51
1.86k
        > 0) {
52
59
        res = 1;
53
59
        goto end;
54
59
    }
55
56
3.74k
sig_err:
57
3.74k
    res = ossl_x509_print_ex_brief(bio, cert, X509_FLAG_NO_EXTENSIONS);
58
3.74k
    ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_SIGNATURE);
59
3.74k
    if (res)
60
3.74k
        ERR_add_error_mem_bio("\n", bio);
61
3.74k
    res = 0;
62
63
3.80k
end:
64
3.80k
    EVP_PKEY_free(pubkey);
65
3.80k
    BIO_free(bio);
66
67
3.80k
    return res;
68
3.74k
}
69
70
/* Verify a message protected with PBMAC */
71
static int verify_PBMAC(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
72
1.72k
{
73
1.72k
    ASN1_BIT_STRING *protection = NULL;
74
1.72k
    int valid = 0;
75
76
    /* generate expected protection for the message */
77
1.72k
    if ((protection = ossl_cmp_calc_protection(ctx, msg)) == NULL)
78
1.20k
        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
370
        && CRYPTO_memcmp(msg->protection->data, protection->data,
84
370
               protection->length)
85
370
            == 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.72k
}
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
65
{
103
65
    int valid = 0;
104
65
    X509_STORE_CTX *csc = NULL;
105
65
    int err;
106
107
65
    if (ctx == NULL || cert == NULL) {
108
0
        ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
109
0
        return 0;
110
0
    }
111
112
65
    if (trusted_store == NULL) {
113
65
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_STORE);
114
65
        return 0;
115
65
    }
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.44k
{
138
4.44k
    X509_STORE_CTX_verify_cb verify_cb;
139
4.44k
    X509_STORE_CTX *csc;
140
4.44k
    int ok = 0;
141
142
4.44k
    if (ts == NULL || (verify_cb = X509_STORE_get_verify_cb(ts)) == NULL)
143
4.44k
        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.44k
}
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.5k
{
159
16.5k
    char *str;
160
161
16.5k
    if (expect_name == NULL)
162
5.15k
        return 1; /* no expectation, thus trivially fulfilled */
163
164
    /* make sure that a matching name is there */
165
11.4k
    if (actual_name == NULL) {
166
0
        ossl_cmp_log1(WARN, ctx, "missing %s", actual_desc);
167
0
        return 0;
168
0
    }
169
11.4k
    str = X509_NAME_oneline(actual_name, NULL, 0);
170
11.4k
    if (X509_NAME_cmp(actual_name, expect_name) == 0) {
171
5.05k
        if (log_success && str != NULL)
172
5.05k
            ossl_cmp_log3(INFO, ctx, " %s matches %s: %s",
173
5.05k
                actual_desc, expect_desc, str);
174
5.05k
        OPENSSL_free(str);
175
5.05k
        return 1;
176
5.05k
    }
177
178
6.36k
    if (str != NULL)
179
6.36k
        ossl_cmp_log2(INFO, ctx, " actual name in %s = %s", actual_desc, str);
180
6.36k
    OPENSSL_free(str);
181
6.36k
    if ((str = X509_NAME_oneline(expect_name, NULL, 0)) != NULL)
182
6.36k
        ossl_cmp_log2(INFO, ctx, " does not match %s = %s", expect_desc, str);
183
6.36k
    OPENSSL_free(str);
184
6.36k
    return 0;
185
11.4k
}
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.05k
{
192
5.05k
    char *str;
193
194
5.05k
    if (skid == NULL)
195
1.85k
        return 1; /* no expectation, thus trivially fulfilled */
196
197
    /* make sure that the expected subject key identifier is there */
198
3.19k
    if (ckid == NULL) {
199
297
        ossl_cmp_warn(ctx, "missing Subject Key Identifier in certificate");
200
297
        return 0;
201
297
    }
202
2.90k
    str = i2s_ASN1_OCTET_STRING(NULL, ckid);
203
2.90k
    if (ASN1_OCTET_STRING_cmp(ckid, skid) == 0) {
204
2.74k
        if (str != NULL)
205
2.74k
            ossl_cmp_log1(INFO, ctx, " subjectKID matches senderKID: %s", str);
206
2.74k
        OPENSSL_free(str);
207
2.74k
        return 1;
208
2.74k
    }
209
210
161
    if (str != NULL)
211
161
        ossl_cmp_log1(INFO, ctx, " cert Subject Key Identifier = %s", str);
212
161
    OPENSSL_free(str);
213
161
    if ((str = i2s_ASN1_OCTET_STRING(NULL, skid)) != NULL)
214
161
        ossl_cmp_log1(INFO, ctx, " does not match senderKID    = %s", str);
215
161
    OPENSSL_free(str);
216
161
    return 0;
217
2.90k
}
218
219
static int already_checked(const X509 *cert,
220
    const STACK_OF(X509) *already_checked)
221
50.5k
{
222
50.5k
    int i;
223
224
76.3k
    for (i = sk_X509_num(already_checked /* may be NULL */); i > 0; i--)
225
42.6k
        if (X509_cmp(sk_X509_value(already_checked, i - 1), cert) == 0)
226
16.8k
            return 1;
227
33.6k
    return 0;
228
50.5k
}
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
24.1k
{
244
24.1k
    X509_STORE *ts = ctx->trusted;
245
24.1k
    int self_issued = X509_check_issued(cert, cert) == X509_V_OK;
246
24.1k
    char *str;
247
24.1k
    X509_VERIFY_PARAM *vpm = ts != NULL ? X509_STORE_get0_param(ts) : NULL;
248
24.1k
    int time_cmp;
249
250
24.1k
    ossl_cmp_log3(INFO, ctx, " considering %s%s %s with..",
251
24.1k
        self_issued ? "self-issued " : "", desc1, desc2);
252
24.1k
    if ((str = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0)) != NULL)
253
24.1k
        ossl_cmp_log1(INFO, ctx, "  subject = %s", str);
254
24.1k
    OPENSSL_free(str);
255
24.1k
    if (!self_issued) {
256
21.3k
        str = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
257
21.3k
        if (str != NULL)
258
21.3k
            ossl_cmp_log1(INFO, ctx, "  issuer  = %s", str);
259
21.3k
        OPENSSL_free(str);
260
21.3k
    }
261
262
24.1k
    if (already_checked(cert, already_checked1)
263
12.0k
        || already_checked(cert, already_checked2)) {
264
12.0k
        ossl_cmp_info(ctx, " cert has already been checked");
265
12.0k
        return 0;
266
12.0k
    }
267
268
12.0k
    time_cmp = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
269
12.0k
        X509_get0_notAfter(cert));
270
12.0k
    if (time_cmp != 0) {
271
6.56k
        int err = time_cmp > 0 ? X509_V_ERR_CERT_HAS_EXPIRED
272
6.56k
                               : X509_V_ERR_CERT_NOT_YET_VALID;
273
274
6.56k
        ossl_cmp_warn(ctx, time_cmp > 0 ? "cert has expired" : "cert is not yet valid");
275
6.56k
        if (ctx->log_cb != NULL /* logging not temporarily disabled */
276
3.28k
            && verify_cb_cert(ts, cert, err) <= 0)
277
3.28k
            return 0;
278
6.56k
    }
279
280
8.78k
    if (!check_name(ctx, 1,
281
8.78k
            "cert subject", X509_get_subject_name(cert),
282
8.78k
            "sender field", msg->header->sender->d.directoryName))
283
4.90k
        return 0;
284
285
3.88k
    if (!check_kid(ctx, X509_get0_subject_key_id(cert), msg->header->senderKID))
286
366
        return 0;
287
    /* prevent misleading error later in case x509v3_cache_extensions() fails */
288
3.51k
    if (!ossl_x509v3_cache_extensions(cert)) {
289
208
        ossl_cmp_warn(ctx, "cert appears to be invalid");
290
208
        return 0;
291
208
    }
292
3.30k
    if (!verify_signature(ctx, msg, cert)) {
293
3.25k
        ossl_cmp_warn(ctx, "msg signature verification failed");
294
3.25k
        return 0;
295
3.25k
    }
296
    /* acceptable also if there is no senderKID in msg header */
297
49
    ossl_cmp_info(ctx, " cert seems acceptable");
298
49
    return 1;
299
3.30k
}
300
301
static int check_cert_path(const OSSL_CMP_CTX *ctx, X509_STORE *store,
302
    X509 *scrt)
303
65
{
304
65
    if (OSSL_CMP_validate_cert_path(ctx, store, scrt))
305
0
        return 1;
306
307
65
    ossl_cmp_warn(ctx,
308
65
        "msg signature validates but cert path validation failed");
309
65
    return 0;
310
65
}
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
static int check_msg_given_cert(const OSSL_CMP_CTX *ctx, X509 *cert,
359
    const OSSL_CMP_MSG *msg)
360
0
{
361
0
    return cert_acceptable(ctx, "previously validated", "sender cert",
362
0
               cert, NULL, NULL, msg)
363
0
        && (check_cert_path(ctx, ctx->trusted, cert)
364
0
            || check_cert_path_3gpp(ctx, msg, cert));
365
0
}
366
367
/*-
368
 * Try all certs in given list for verifying msg, normally or in 3GPP mode.
369
 * If already_checked1 == NULL then certs are assumed to be the msg->extraCerts.
370
 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
371
 */
372
static int check_msg_with_certs(OSSL_CMP_CTX *ctx, const STACK_OF(X509) *certs,
373
    const char *desc,
374
    const STACK_OF(X509) *already_checked1,
375
    const STACK_OF(X509) *already_checked2,
376
    const OSSL_CMP_MSG *msg, int mode_3gpp)
377
15.6k
{
378
15.6k
    int in_extraCerts = already_checked1 == NULL;
379
15.6k
    int n_acceptable_certs = 0;
380
15.6k
    int i;
381
382
15.6k
    if (sk_X509_num(certs) <= 0) {
383
2.39k
        ossl_cmp_log1(WARN, ctx, "no %s", desc);
384
2.39k
        return 0;
385
2.39k
    }
386
387
42.5k
    for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
388
29.2k
        X509 *cert = sk_X509_value(certs, i);
389
390
29.2k
        if (!ossl_assert(cert != NULL))
391
0
            return 0;
392
29.2k
        if (!cert_acceptable(ctx, "cert from", desc, cert,
393
29.2k
                already_checked1, already_checked2, msg))
394
29.2k
            continue;
395
59
        n_acceptable_certs++;
396
59
        if (mode_3gpp ? check_cert_path_3gpp(ctx, msg, cert)
397
59
                      : check_cert_path(ctx, ctx->trusted, cert)) {
398
            /* store successful sender cert for further msgs in transaction */
399
0
            return ossl_cmp_ctx_set1_validatedSrvCert(ctx, cert);
400
0
        }
401
59
    }
402
13.2k
    if (in_extraCerts && n_acceptable_certs == 0)
403
13.2k
        ossl_cmp_warn(ctx, "no acceptable cert in extraCerts");
404
13.2k
    return 0;
405
13.2k
}
406
407
/*-
408
 * Verify msg trying first ctx->untrusted, which should include extraCerts
409
 * at its front, then trying the trusted certs in truststore (if any) of ctx.
410
 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
411
 */
412
static int check_msg_all_certs(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
413
    int mode_3gpp)
414
15.6k
{
415
15.6k
    int ret = 0;
416
417
15.6k
    if (ctx->permitTAInExtraCertsForIR
418
0
        && OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_IP)
419
15.6k
        ossl_cmp_info(ctx, mode_3gpp ? "normal mode failed; trying now 3GPP mode trusting extraCerts" : "trying first normal mode using trust store");
420
15.6k
    else if (mode_3gpp)
421
7.83k
        return 0;
422
423
7.83k
    if (check_msg_with_certs(ctx, msg->extraCerts, "extraCerts",
424
7.83k
            NULL, NULL, msg, mode_3gpp))
425
0
        return 1;
426
7.83k
    if (check_msg_with_certs(ctx, ctx->untrusted, "untrusted certs",
427
7.83k
            msg->extraCerts, NULL, msg, mode_3gpp))
428
0
        return 1;
429
430
7.83k
    if (ctx->trusted == NULL) {
431
7.83k
        ossl_cmp_warn(ctx, mode_3gpp ? "no self-issued extraCerts" : "no trusted store");
432
7.83k
    } else {
433
0
        STACK_OF(X509) *trusted = X509_STORE_get1_all_certs(ctx->trusted);
434
435
0
        ret = check_msg_with_certs(ctx, trusted,
436
0
            mode_3gpp ? "self-issued extraCerts"
437
0
                      : "certs in trusted store",
438
0
            msg->extraCerts, ctx->untrusted,
439
0
            msg, mode_3gpp);
440
0
        OSSL_STACK_OF_X509_free(trusted);
441
0
    }
442
7.83k
    return ret;
443
7.83k
}
444
445
/*-
446
 * Verify message signature with any acceptable and valid candidate cert.
447
 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
448
 */
449
static int check_msg_find_cert(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
450
4.43k
{
451
4.43k
    X509 *scrt = ctx->validatedSrvCert; /* previous successful sender cert */
452
4.43k
    GENERAL_NAME *sender = msg->header->sender;
453
4.43k
    char *sname = NULL;
454
4.43k
    char *skid_str = NULL;
455
4.43k
    const ASN1_OCTET_STRING *skid = msg->header->senderKID;
456
4.43k
    OSSL_CMP_log_cb_t backup_log_cb = ctx->log_cb;
457
4.43k
    int res = 0;
458
459
4.43k
    if (sender == NULL || msg->body == NULL)
460
0
        return 0; /* other NULL cases already have been checked */
461
4.43k
    if (sender->type != GEN_DIRNAME) {
462
        /* So far, only X509_NAME is supported */
463
0
        ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
464
0
        return 0;
465
0
    }
466
467
    /* dump any hitherto errors to avoid confusion when printing further ones */
468
4.43k
    OSSL_CMP_CTX_print_errors(ctx);
469
470
    /* enable clearing irrelevant errors in attempts to validate sender certs */
471
4.43k
    (void)ERR_set_mark();
472
4.43k
    ctx->log_cb = NULL; /* temporarily disable logging */
473
474
    /*
475
     * try first cached scrt, used successfully earlier in same transaction,
476
     * for validating this and any further msgs where extraCerts may be left out
477
     */
478
4.43k
    if (scrt != NULL) {
479
0
        if (check_msg_given_cert(ctx, scrt, msg)) {
480
0
            ctx->log_cb = backup_log_cb;
481
0
            (void)ERR_pop_to_mark();
482
0
            return 1;
483
0
        }
484
        /* cached sender cert has shown to be no more successfully usable */
485
0
        (void)ossl_cmp_ctx_set1_validatedSrvCert(ctx, NULL);
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
        (void)check_msg_given_cert(ctx, scrt, msg);
490
0
    }
491
492
4.43k
    res = check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */)
493
4.43k
        || check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
494
4.43k
    ctx->log_cb = backup_log_cb;
495
4.43k
    if (res) {
496
        /* discard any diagnostic information on trying to use certs */
497
0
        (void)ERR_pop_to_mark();
498
0
        goto end;
499
0
    }
500
    /* failed finding a sender cert that verifies the message signature */
501
4.43k
    (void)ERR_clear_last_mark();
502
503
4.43k
    sname = X509_NAME_oneline(sender->d.directoryName, NULL, 0);
504
4.43k
    skid_str = skid == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, skid);
505
4.43k
    if (ctx->log_cb != NULL) {
506
4.43k
        ossl_cmp_info(ctx, "trying to verify msg signature with a valid cert that..");
507
4.43k
        if (sname != NULL)
508
4.43k
            ossl_cmp_log1(INFO, ctx, "matches msg sender    = %s", sname);
509
4.43k
        if (skid_str != NULL)
510
2.60k
            ossl_cmp_log1(INFO, ctx, "matches msg senderKID = %s", skid_str);
511
1.83k
        else
512
4.43k
            ossl_cmp_info(ctx, "while msg header does not contain senderKID");
513
        /* re-do the above checks (just) for adding diagnostic information */
514
4.43k
        (void)check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */);
515
4.43k
        (void)check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
516
4.43k
    }
517
518
4.43k
    ERR_raise(ERR_LIB_CMP, CMP_R_NO_SUITABLE_SENDER_CERT);
519
4.43k
    if (sname != NULL) {
520
4.43k
        ERR_add_error_txt(NULL, "for msg sender name = ");
521
4.43k
        ERR_add_error_txt(NULL, sname);
522
4.43k
    }
523
4.43k
    if (skid_str != NULL) {
524
2.60k
        ERR_add_error_txt(" and ", "for msg senderKID = ");
525
2.60k
        ERR_add_error_txt(NULL, skid_str);
526
2.60k
    }
527
528
4.43k
end:
529
4.43k
    OPENSSL_free(sname);
530
4.43k
    OPENSSL_free(skid_str);
531
4.43k
    return res;
532
4.43k
}
533
534
/*-
535
 * Validate the protection of the given PKIMessage using either password-
536
 * based mac (PBM) or a signature algorithm. In the case of signature algorithm,
537
 * the sender certificate can have been pinned by providing it in ctx->srvCert,
538
 * else it is searched in msg->extraCerts, ctx->untrusted, in ctx->trusted
539
 * (in this order) and is path is validated against ctx->trusted.
540
 * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
541
 *
542
 * If ctx->permitTAInExtraCertsForIR is true and when validating a CMP IP msg,
543
 * the trust anchor for validating the IP msg may be taken from msg->extraCerts
544
 * if a self-issued certificate is found there that can be used to
545
 * validate the enrolled certificate returned in the IP.
546
 * This is according to the need given in 3GPP TS 33.310.
547
 *
548
 * Returns 1 on success, 0 on error or validation failed.
549
 */
550
int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
551
8.08k
{
552
8.08k
    X509 *scrt;
553
554
8.08k
    ossl_cmp_debug(ctx, "validating CMP message");
555
8.08k
    if (ctx == NULL || msg == NULL
556
8.08k
        || msg->header == NULL || msg->body == NULL) {
557
0
        ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
558
0
        return 0;
559
0
    }
560
561
8.08k
    if (msg->header->protectionAlg == NULL /* unprotected message */
562
8.08k
        || msg->protection == NULL || msg->protection->data == NULL) {
563
2.36k
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
564
2.36k
        return 0;
565
2.36k
    }
566
567
5.72k
    switch (ossl_cmp_hdr_get_protection_nid(msg->header)) {
568
        /* 5.1.3.1.  Shared Secret Information */
569
1.61k
    case NID_id_PasswordBasedMAC:
570
1.61k
        if (ctx->secretValue == NULL) {
571
748
            ossl_cmp_info(ctx, "no secret available for verifying PBM-based CMP message protection");
572
748
            ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SECRET);
573
748
            return 0;
574
748
        }
575
868
        if (verify_PBMAC(ctx, msg)) {
576
            /*
577
             * RFC 9810, 5.3.2: 'Note that if the PKI message protection is
578
             * "shared secret information", then any certificate transported in
579
             * the caPubs field may be directly trusted as a root CA
580
             * certificate by the initiator.'
581
             */
582
6
            switch (OSSL_CMP_MSG_get_bodytype(msg)) {
583
0
            case -1:
584
0
                return 0;
585
0
            case OSSL_CMP_PKIBODY_IP:
586
0
            case OSSL_CMP_PKIBODY_CP:
587
0
            case OSSL_CMP_PKIBODY_KUP:
588
3
            case OSSL_CMP_PKIBODY_CCP:
589
3
                if (ctx->trusted != NULL) {
590
0
                    STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
591
                    /* value.ip is same for cp, kup, and ccp */
592
593
0
                    if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
594
                        /* adds both self-issued and not self-issued certs */
595
0
                        return 0;
596
0
                }
597
3
                break;
598
3
            default:
599
3
                break;
600
6
            }
601
6
            ossl_cmp_debug(ctx,
602
6
                "successfully validated PBM-based CMP message protection");
603
6
            return 1;
604
6
        }
605
862
        ossl_cmp_warn(ctx, "verifying PBM-based CMP message protection failed");
606
862
        break;
607
608
        /*
609
         * 5.1.3.2 DH Key Pairs
610
         * Not yet supported
611
         */
612
24
    case NID_id_DHBasedMac:
613
24
        ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC);
614
24
        break;
615
616
        /*
617
         * 5.1.3.3.  Signature
618
         */
619
4.08k
    default:
620
4.08k
        scrt = ctx->srvCert;
621
4.08k
        if (scrt == NULL) {
622
4.08k
            if (ctx->trusted == NULL && ctx->secretValue != NULL) {
623
1.65k
                ossl_cmp_info(ctx, "no trust store nor pinned server cert available for verifying signature-based CMP message protection");
624
1.65k
                ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_ANCHOR);
625
1.65k
                return 0;
626
1.65k
            }
627
2.43k
            if (check_msg_find_cert(ctx, msg)) {
628
0
                ossl_cmp_log1(DEBUG, ctx,
629
0
                    "successfully validated signature-based CMP message protection using trust store%s",
630
0
                    ctx->permitTAInExtraCertsForIR ? " or 3GPP mode" : "");
631
0
                return 1;
632
0
            }
633
2.43k
        } else { /* use pinned sender cert */
634
            /* use ctx->srvCert for signature check even if not acceptable */
635
0
            if (verify_signature(ctx, msg, scrt)) {
636
0
                ossl_cmp_debug(ctx,
637
0
                    "successfully validated signature-based CMP message protection using pinned server cert");
638
0
                return ossl_cmp_ctx_set1_validatedSrvCert(ctx, scrt);
639
0
            }
640
0
            ossl_cmp_warn(ctx, "CMP message signature verification failed");
641
0
            ERR_raise(ERR_LIB_CMP, CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG);
642
0
        }
643
2.43k
        break;
644
5.72k
    }
645
3.31k
    return 0;
646
5.72k
}
647
648
static int check_transactionID_or_nonce(ASN1_OCTET_STRING *expected,
649
    ASN1_OCTET_STRING *actual, int reason)
650
81.4k
{
651
81.4k
    if (expected != NULL
652
0
        && (actual == NULL || ASN1_OCTET_STRING_cmp(expected, actual) != 0)) {
653
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
654
        char *expected_str, *actual_str;
655
656
        expected_str = i2s_ASN1_OCTET_STRING(NULL, expected);
657
        actual_str = actual == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, actual);
658
        ERR_raise_data(ERR_LIB_CMP, reason,
659
            "expected = %s, actual = %s",
660
            expected_str == NULL ? "?" : expected_str,
661
            actual == NULL ? "(none)" : actual_str == NULL ? "?"
662
                                                           : actual_str);
663
        OPENSSL_free(expected_str);
664
        OPENSSL_free(actual_str);
665
        return 0;
666
#endif
667
0
    }
668
81.4k
    return 1;
669
81.4k
}
670
671
/*-
672
 * Check received message (i.e., response by server or request from client)
673
 * Any msg->extraCerts are prepended to ctx->untrusted.
674
 *
675
 * Ensures that:
676
 * its sender is of appropriate type (currently only X509_NAME) and
677
 *     matches any expected sender or srvCert subject given in the ctx
678
 * it has a valid body type
679
 * its protection is valid (or invalid/absent, but only if a callback function
680
 *     is present and yields a positive result using also the supplied argument)
681
 * its transaction ID matches the previous transaction ID stored in ctx (if any)
682
 * its recipNonce matches the previous senderNonce stored in the ctx (if any)
683
 *
684
 * If everything is fine:
685
 * learns the senderNonce from the received message,
686
 * learns the transaction ID if it is not yet in ctx,
687
 * and makes any certs in caPubs directly trusted.
688
 *
689
 * Returns 1 on success, 0 on error.
690
 */
691
int ossl_cmp_msg_check_update(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
692
    ossl_cmp_allow_unprotected_cb_t cb, int cb_arg)
693
32.5k
{
694
32.5k
    OSSL_CMP_PKIHEADER *hdr;
695
32.5k
    const X509_NAME *expected_sender;
696
32.5k
    int num_untrusted, num_added, res;
697
698
32.5k
    if (!ossl_assert(ctx != NULL && msg != NULL && msg->header != NULL))
699
0
        return 0;
700
32.5k
    hdr = OSSL_CMP_MSG_get0_header(msg);
701
702
    /* If expected_sender is given, validate sender name of received msg */
703
32.5k
    expected_sender = ctx->expected_sender;
704
32.5k
    if (expected_sender == NULL && ctx->srvCert != NULL)
705
0
        expected_sender = X509_get_subject_name(ctx->srvCert);
706
32.5k
    if (expected_sender != NULL) {
707
0
        const X509_NAME *actual_sender;
708
0
        char *str;
709
710
0
        if (hdr->sender->type != GEN_DIRNAME) {
711
0
            ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
712
0
            return 0;
713
0
        }
714
0
        actual_sender = hdr->sender->d.directoryName;
715
        /*
716
         * Compare actual sender name of response with expected sender name.
717
         * Mitigates risk of accepting misused PBM secret or
718
         * misused certificate of an unauthorized entity of a trusted hierarchy.
719
         */
720
0
        if (!check_name(ctx, 0, "sender DN field", actual_sender,
721
0
                "expected sender", expected_sender)) {
722
0
            str = X509_NAME_oneline(actual_sender, NULL, 0);
723
0
            ERR_raise_data(ERR_LIB_CMP, CMP_R_UNEXPECTED_SENDER,
724
0
                str != NULL ? str : "<unknown>");
725
0
            OPENSSL_free(str);
726
0
            return 0;
727
0
        }
728
0
    }
729
    /* Note: if recipient was NULL-DN it could be learned here if needed */
730
731
32.5k
    num_added = sk_X509_num(msg->extraCerts);
732
32.5k
    if (num_added > 10)
733
0
        ossl_cmp_log1(WARN, ctx, "received CMP message contains %d extraCerts",
734
32.5k
            num_added);
735
    /*
736
     * Store any provided extraCerts in ctx for use in OSSL_CMP_validate_msg()
737
     * and for future use, such that they are available to ctx->certConf_cb and
738
     * the peer does not need to send them again in the same transaction.
739
     * Note that it does not help validating the message before storing the
740
     * extraCerts because they do not belong to the protected msg part anyway.
741
     * The extraCerts are prepended. Allows simple removal if they shall not be
742
     * cached. Also they get used first, which is likely good for efficiency.
743
     */
744
32.5k
    num_untrusted = ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted);
745
32.5k
    res = ossl_x509_add_certs_new(&ctx->untrusted, msg->extraCerts,
746
        /* this allows self-signed certs */
747
32.5k
        X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
748
32.5k
            | X509_ADD_FLAG_PREPEND);
749
32.5k
    num_added = (ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted))
750
32.5k
        - num_untrusted;
751
32.5k
    if (!res) {
752
0
        while (num_added-- > 0)
753
0
            X509_free(sk_X509_shift(ctx->untrusted));
754
0
        return 0;
755
0
    }
756
757
32.5k
    if (hdr->protectionAlg != NULL)
758
12.8k
        res = OSSL_CMP_validate_msg(ctx, msg)
759
            /* explicitly permitted exceptions for invalid protection: */
760
12.8k
            || (cb != NULL && (*cb)(ctx, msg, 1, cb_arg) > 0);
761
19.6k
    else
762
        /* explicitly permitted exceptions for missing protection: */
763
19.6k
        res = cb != NULL && (*cb)(ctx, msg, 0, cb_arg) > 0;
764
32.5k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
765
32.5k
    res = 1; /* support more aggressive fuzzing by letting invalid msg pass */
766
32.5k
#endif
767
768
    /* remove extraCerts again if not caching */
769
32.5k
    if (ctx->noCacheExtraCerts)
770
0
        while (num_added-- > 0)
771
0
            X509_free(sk_X509_shift(ctx->untrusted));
772
773
32.5k
    if (!res) {
774
0
        if (hdr->protectionAlg != NULL)
775
0
            ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_PROTECTION);
776
0
        else
777
0
            ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
778
0
        return 0;
779
0
    }
780
781
    /* check CMP version number in header */
782
32.5k
    if (ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_2
783
20.8k
        && ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_3) {
784
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
785
        ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PVNO);
786
        return 0;
787
#endif
788
20.7k
    }
789
790
32.5k
    if (OSSL_CMP_MSG_get_bodytype(msg) < 0) {
791
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
792
        ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
793
        return 0;
794
#endif
795
0
    }
796
797
    /* compare received transactionID with the expected one in previous msg */
798
32.5k
    if (!check_transactionID_or_nonce(ctx->transactionID, hdr->transactionID,
799
32.5k
            CMP_R_TRANSACTIONID_UNMATCHED))
800
0
        return 0;
801
802
    /*
803
     * enable clearing irrelevant errors
804
     * in attempts to validate recipient nonce in case of delayed delivery.
805
     */
806
32.5k
    (void)ERR_set_mark();
807
    /* compare received nonce with the one we sent */
808
32.5k
    if (!check_transactionID_or_nonce(ctx->senderNonce, hdr->recipNonce,
809
32.5k
            CMP_R_RECIPNONCE_UNMATCHED)) {
810
        /* check if we are polling and received final response */
811
0
        if (ctx->first_senderNonce == NULL
812
0
            || OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_POLLREP
813
            /* compare received nonce with our sender nonce at poll start */
814
0
            || !check_transactionID_or_nonce(ctx->first_senderNonce,
815
0
                hdr->recipNonce,
816
0
                CMP_R_RECIPNONCE_UNMATCHED)) {
817
0
            (void)ERR_clear_last_mark();
818
0
            return 0;
819
0
        }
820
0
    }
821
32.5k
    (void)ERR_pop_to_mark();
822
823
    /* if not yet present, learn transactionID */
824
32.5k
    if (ctx->transactionID == NULL
825
32.5k
        && !OSSL_CMP_CTX_set1_transactionID(ctx, hdr->transactionID))
826
0
        return 0;
827
828
    /*
829
     * RFC 9810 section 5.1.1 states: the recipNonce is copied from
830
     * the senderNonce of the previous message in the transaction.
831
     * --> Store for setting in next message
832
     */
833
32.5k
    if (!ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce))
834
0
        return 0;
835
836
32.5k
    if (ossl_cmp_hdr_get_protection_nid(hdr) == NID_id_PasswordBasedMAC) {
837
        /*
838
         * RFC 9810, 5.3.2: 'Note that if the PKI message protection is
839
         * "shared secret information", then any certificate transported in
840
         * the caPubs field may be directly trusted as a root CA
841
         * certificate by the initiator.'
842
         */
843
3.59k
        switch (OSSL_CMP_MSG_get_bodytype(msg)) {
844
8
        case OSSL_CMP_PKIBODY_IP:
845
20
        case OSSL_CMP_PKIBODY_CP:
846
24
        case OSSL_CMP_PKIBODY_KUP:
847
44
        case OSSL_CMP_PKIBODY_CCP:
848
44
            if (ctx->trusted != NULL) {
849
0
                STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
850
                /* value.ip is same for cp, kup, and ccp */
851
852
0
                if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
853
                    /* adds both self-issued and not self-issued certs */
854
0
                    return 0;
855
0
            }
856
44
            break;
857
3.54k
        default:
858
3.54k
            break;
859
3.59k
        }
860
3.59k
    }
861
32.5k
    return 1;
862
32.5k
}
863
864
int ossl_cmp_verify_popo(const OSSL_CMP_CTX *ctx,
865
    const OSSL_CMP_MSG *msg, int acceptRAVerified)
866
6.45k
{
867
6.45k
    if (!ossl_assert(msg != NULL && msg->body != NULL))
868
0
        return 0;
869
6.45k
    switch (msg->body->type) {
870
3.81k
    case OSSL_CMP_PKIBODY_P10CR: {
871
3.81k
        X509_REQ *req = msg->body->value.p10cr;
872
873
3.81k
        if (X509_REQ_verify_ex(req, X509_REQ_get0_pubkey(req), ctx->libctx,
874
3.81k
                ctx->propq)
875
3.81k
            <= 0) {
876
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
877
            ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED);
878
            return 0;
879
#endif
880
3.81k
        }
881
3.81k
    } break;
882
1.42k
    case OSSL_CMP_PKIBODY_IR:
883
2.45k
    case OSSL_CMP_PKIBODY_CR:
884
2.63k
    case OSSL_CMP_PKIBODY_KUR:
885
2.63k
        if (!OSSL_CRMF_MSGS_verify_popo(msg->body->value.ir, OSSL_CMP_CERTREQID,
886
2.63k
                acceptRAVerified,
887
2.63k
                ctx->libctx, ctx->propq)) {
888
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
889
            return 0;
890
#endif
891
2.53k
        }
892
2.63k
        break;
893
0
    default:
894
0
        ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
895
0
        return 0;
896
6.45k
    }
897
6.45k
    return 1;
898
6.45k
}