Coverage Report

Created: 2026-10-28 06:28

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