Coverage Report

Created: 2026-09-12 06:55

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
3.66k
{
20
3.66k
    OSSL_CMP_PROTECTEDPART prot_part;
21
3.66k
    EVP_PKEY *pubkey = NULL;
22
3.66k
    BIO *bio;
23
3.66k
    int res = 0;
24
25
3.66k
    if (!ossl_assert(cmp_ctx != NULL && msg != NULL && cert != NULL))
26
0
        return 0;
27
28
3.66k
    bio = BIO_new(BIO_s_mem()); /* may be NULL */
29
3.66k
    if (bio == NULL)
30
0
        return 0;
31
    /* verify that keyUsage, if present, contains digitalSignature */
32
3.66k
    if (!cmp_ctx->ignore_keyusage
33
3.66k
        && (X509_get_key_usage(cert) & X509v3_KU_DIGITAL_SIGNATURE) == 0) {
34
381
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE);
35
381
        goto sig_err;
36
381
    }
37
38
3.28k
    pubkey = X509_get_pubkey(cert);
39
3.28k
    if (pubkey == NULL) {
40
1.57k
        ERR_raise(ERR_LIB_CMP, CMP_R_FAILED_EXTRACTING_PUBKEY);
41
1.57k
        goto sig_err;
42
1.57k
    }
43
44
1.70k
    prot_part.header = msg->header;
45
1.70k
    prot_part.body = msg->body;
46
47
1.70k
    if (ASN1_item_verify_ex(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART),
48
1.70k
            msg->header->protectionAlg, msg->protection,
49
1.70k
            &prot_part, NULL, pubkey, cmp_ctx->libctx,
50
1.70k
            cmp_ctx->propq)
51
1.70k
        > 0) {
52
55
        res = 1;
53
55
        goto end;
54
55
    }
55
56
3.60k
sig_err:
57
3.60k
    res = ossl_x509_print_ex_brief(bio, cert, X509_FLAG_NO_EXTENSIONS);
58
3.60k
    ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_SIGNATURE);
59
3.60k
    if (res) {
60
3.60k
        ERR_add_error_txt(NULL, "\n");
61
3.60k
        ERR_add_error_mem_bio(NULL, bio);
62
3.60k
    }
63
3.60k
    res = 0;
64
65
3.66k
end:
66
3.66k
    EVP_PKEY_free(pubkey);
67
3.66k
    BIO_free(bio);
68
69
3.66k
    return res;
70
3.60k
}
71
72
/* Verify a message protected with PBMAC */
73
static int verify_PBMAC(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
74
1.27k
{
75
1.27k
    ASN1_BIT_STRING *protection = NULL;
76
1.27k
    int valid = 0;
77
78
    /* generate expected protection for the message */
79
1.27k
    if ((protection = ossl_cmp_calc_protection(ctx, msg)) == NULL)
80
883
        return 0; /* failed to generate protection string! */
81
82
394
    valid = msg->protection != NULL && msg->protection->length >= 0
83
394
        && msg->protection->type == protection->type
84
394
        && msg->protection->length == protection->length
85
307
        && CRYPTO_memcmp(msg->protection->data, protection->data,
86
307
               protection->length)
87
307
            == 0;
88
394
    ASN1_BIT_STRING_free(protection);
89
394
    if (!valid)
90
394
        ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_PBM_VALUE);
91
92
394
    return valid;
93
1.27k
}
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
55
{
105
55
    int valid = 0;
106
55
    X509_STORE_CTX *csc = NULL;
107
55
    int err;
108
109
55
    if (ctx == NULL || cert == NULL) {
110
0
        ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
111
0
        return 0;
112
0
    }
113
114
55
    if (trusted_store == NULL) {
115
55
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_STORE);
116
55
        return 0;
117
55
    }
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
4.66k
{
140
4.66k
    X509_STORE_CTX_verify_cb verify_cb;
141
4.66k
    X509_STORE_CTX *csc;
142
4.66k
    int ok = 0;
143
144
4.66k
    if (ts == NULL || (verify_cb = X509_STORE_get_verify_cb(ts)) == NULL)
145
4.66k
        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
4.66k
}
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
9.57k
{
161
9.57k
    char *str;
162
163
9.57k
    if (expect_name == NULL)
164
0
        return 1; /* no expectation, thus trivially fulfilled */
165
166
    /* make sure that a matching name is there */
167
9.57k
    if (actual_name == NULL) {
168
0
        ossl_cmp_log1(WARN, ctx, "missing %s", actual_desc);
169
0
        return 0;
170
0
    }
171
9.57k
    str = X509_NAME_oneline(actual_name, NULL, 0);
172
9.57k
    if (X509_NAME_cmp(actual_name, expect_name) == 0) {
173
4.21k
        if (log_success && str != NULL)
174
4.21k
            ossl_cmp_log3(INFO, ctx, " %s matches %s: %s",
175
4.21k
                actual_desc, expect_desc, str);
176
4.21k
        OPENSSL_free(str);
177
4.21k
        return 1;
178
4.21k
    }
179
180
5.36k
    if (str != NULL)
181
5.36k
        ossl_cmp_log2(INFO, ctx, " actual name in %s = %s", actual_desc, str);
182
5.36k
    OPENSSL_free(str);
183
5.36k
    if ((str = X509_NAME_oneline(expect_name, NULL, 0)) != NULL)
184
5.36k
        ossl_cmp_log2(INFO, ctx, " does not match %s = %s", expect_desc, str);
185
5.36k
    OPENSSL_free(str);
186
5.36k
    return 0;
187
9.57k
}
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
4.21k
{
194
4.21k
    char *str;
195
196
4.21k
    if (skid == NULL)
197
1.63k
        return 1; /* no expectation, thus trivially fulfilled */
198
199
    /* make sure that the expected subject key identifier is there */
200
2.57k
    if (ckid == NULL) {
201
183
        ossl_cmp_warn(ctx, "missing Subject Key Identifier in certificate");
202
183
        return 0;
203
183
    }
204
2.39k
    str = i2s_ASN1_OCTET_STRING(NULL, ckid);
205
2.39k
    if (ASN1_OCTET_STRING_cmp(ckid, skid) == 0) {
206
2.22k
        if (str != NULL)
207
2.22k
            ossl_cmp_log1(INFO, ctx, " subjectKID matches senderKID: %s", str);
208
2.22k
        OPENSSL_free(str);
209
2.22k
        return 1;
210
2.22k
    }
211
212
166
    if (str != NULL)
213
166
        ossl_cmp_log1(INFO, ctx, " cert Subject Key Identifier = %s", str);
214
166
    OPENSSL_free(str);
215
166
    if ((str = i2s_ASN1_OCTET_STRING(NULL, skid)) != NULL)
216
166
        ossl_cmp_log1(INFO, ctx, " does not match senderKID    = %s", str);
217
166
    OPENSSL_free(str);
218
166
    return 0;
219
2.39k
}
220
221
static int already_checked(const X509 *cert,
222
    const STACK_OF(X509) *already_checked)
223
42.7k
{
224
42.7k
    int i;
225
226
64.7k
    for (i = sk_X509_num(already_checked /* may be NULL */); i > 0; i--)
227
36.2k
        if (X509_cmp(sk_X509_value(already_checked, i - 1), cert) == 0)
228
14.2k
            return 1;
229
28.4k
    return 0;
230
42.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.6k
        str = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
259
15.6k
        if (str != NULL)
260
15.6k
            ossl_cmp_log1(INFO, ctx, "  issuer  = %s", str);
261
15.6k
        OPENSSL_free(str);
262
15.6k
    }
263
264
17.5k
    if (already_checked(cert, already_checked1)
265
8.78k
        || already_checked(cert, already_checked2)) {
266
8.78k
        ossl_cmp_info(ctx, " cert has already been checked");
267
8.78k
        return 0;
268
8.78k
    }
269
270
8.78k
    time_cmp = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
271
8.78k
        X509_get0_notAfter(cert));
272
8.78k
    if (time_cmp != 0) {
273
4.63k
        int err = time_cmp > 0 ? X509_V_ERR_CERT_HAS_EXPIRED
274
4.63k
                               : X509_V_ERR_CERT_NOT_YET_VALID;
275
276
4.63k
        ossl_cmp_warn(ctx, time_cmp > 0 ? "cert has expired" : "cert is not yet valid");
277
4.63k
        if (ctx->log_cb != NULL /* logging not temporarily disabled */
278
2.31k
            && verify_cb_cert(ts, cert, err) <= 0)
279
2.31k
            return 0;
280
4.63k
    }
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.87k
    if (!check_kid(ctx, X509_get0_subject_key_id(cert), msg->header->senderKID))
288
209
        return 0;
289
    /* prevent misleading error later in case x509v3_cache_extensions() fails */
290
2.66k
    if (!ossl_x509v3_cache_extensions(cert)) {
291
155
        ossl_cmp_warn(ctx, "cert appears to be invalid");
292
155
        return 0;
293
155
    }
294
2.51k
    if (!verify_signature(ctx, msg, cert)) {
295
2.47k
        ossl_cmp_warn(ctx, "msg signature verification failed");
296
2.47k
        return 0;
297
2.47k
    }
298
    /* acceptable also if there is no senderKID in msg header */
299
34
    ossl_cmp_info(ctx, " cert seems acceptable");
300
34
    return 1;
301
2.51k
}
302
303
static int check_cert_path(const OSSL_CMP_CTX *ctx, X509_STORE *store,
304
    X509 *scrt)
305
55
{
306
55
    if (OSSL_CMP_validate_cert_path(ctx, store, scrt))
307
0
        return 1;
308
309
55
    ossl_cmp_warn(ctx,
310
55
        "msg signature validates but cert path validation failed");
311
55
    return 0;
312
55
}
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
14.6k
{
379
14.6k
    int in_extraCerts = already_checked1 == NULL;
380
14.6k
    int n_acceptable_certs = 0;
381
14.6k
    int i;
382
383
14.6k
    if (sk_X509_num(certs) <= 0) {
384
1.96k
        ossl_cmp_log1(INFO, ctx, "no %s", desc);
385
1.96k
        return 0;
386
1.96k
    }
387
388
41.1k
    for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
389
28.4k
        X509 *cert = sk_X509_value(certs, i);
390
391
28.4k
        if (!ossl_assert(cert != NULL))
392
0
            return 0;
393
28.4k
        if (!cert_acceptable(ctx, "cert from", desc, cert,
394
28.4k
                already_checked1, already_checked2, msg))
395
28.4k
            continue;
396
55
        n_acceptable_certs++;
397
55
        if (mode_3gpp ? check_cert_path_3gpp(ctx, msg, cert)
398
55
                      : 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
55
    }
403
12.7k
    if (in_extraCerts && n_acceptable_certs == 0)
404
6.29k
        ossl_cmp_log1(WARN, ctx, "no acceptable %s", desc);
405
12.7k
    return 0;
406
12.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
14.6k
{
416
14.6k
    int ret = 0;
417
418
14.6k
    if (ctx->permitTAInExtraCertsForIR
419
0
        && OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_IP)
420
14.6k
        ossl_cmp_info(ctx, mode_3gpp ? "normal mode failed; trying now 3GPP mode trusting extraCerts" : "trying first normal mode using trust store");
421
14.6k
    else if (mode_3gpp)
422
7.33k
        return 0;
423
424
7.33k
    if (check_msg_with_certs(ctx, msg->extraCerts, "extraCerts",
425
7.33k
            NULL, NULL, msg, mode_3gpp))
426
0
        return 1;
427
7.33k
    if (check_msg_with_certs(ctx, ctx->untrusted, "untrusted certs",
428
7.33k
            msg->extraCerts, NULL, msg, mode_3gpp))
429
0
        return 1;
430
431
7.33k
    if (ctx->trusted == NULL) {
432
7.33k
        ossl_cmp_warn(ctx, mode_3gpp ? "no self-issued extraCerts" : "no trusted store");
433
7.33k
    } 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
7.33k
    return ret;
444
7.33k
}
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
3.66k
{
452
3.66k
    X509 *scrt = ctx->validatedSrvCert; /* previous successful sender cert */
453
3.66k
    GENERAL_NAME *sender = msg->header->sender;
454
3.66k
    char *sname = NULL;
455
3.66k
    char *skid_str = NULL;
456
3.66k
    const ASN1_OCTET_STRING *skid = msg->header->senderKID;
457
3.66k
    OSSL_CMP_log_cb_t backup_log_cb = ctx->log_cb;
458
3.66k
    int res = 0;
459
460
3.66k
    if (sender == NULL || msg->body == NULL)
461
0
        return 0; /* other NULL cases already have been checked */
462
3.66k
    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
3.66k
    OSSL_CMP_CTX_print_errors(ctx);
470
471
    /* enable clearing irrelevant errors in attempts to validate sender certs */
472
3.66k
    (void)ERR_set_mark();
473
3.66k
    ctx->log_cb = NULL; /* temporarily disable logging */
474
475
3.66k
    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
3.66k
    res = check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */)
498
3.66k
        || check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
499
500
3.66k
    ctx->log_cb = backup_log_cb; /* re-enable logging */
501
    /* discard any previous diagnostic information on trying to use certs */
502
3.66k
    (void)ERR_pop_to_mark();
503
504
3.66k
    if (res)
505
0
        goto end;
506
    /* failed finding a sender cert that verifies the message signature */
507
508
3.66k
    sname = X509_NAME_oneline(sender->d.directoryName, NULL, 0);
509
3.66k
    skid_str = skid == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, skid);
510
3.66k
    if (ctx->log_cb != NULL) {
511
3.66k
        ossl_cmp_info(ctx, "trying to verify msg signature with a valid cert that..");
512
3.66k
        if (sname != NULL)
513
3.66k
            ossl_cmp_log1(INFO, ctx, "matches msg sender    = %s", sname);
514
3.66k
        if (skid_str != NULL)
515
2.14k
            ossl_cmp_log1(INFO, ctx, "matches msg senderKID = %s", skid_str);
516
1.52k
        else
517
3.66k
            ossl_cmp_info(ctx, "while msg header does not contain senderKID");
518
        /* re-do the above checks (just) for adding diagnostic information */
519
3.66k
        (void)check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */);
520
3.66k
        (void)check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
521
3.66k
    }
522
523
3.66k
    ERR_raise(ERR_LIB_CMP, CMP_R_NO_SUITABLE_SENDER_CERT);
524
3.66k
    if (sname != NULL) {
525
3.66k
        ERR_add_error_txt(NULL, "for msg sender name = ");
526
3.66k
        ERR_add_error_txt(NULL, sname);
527
3.66k
    }
528
3.66k
    if (skid_str != NULL) {
529
2.14k
        ERR_add_error_txt(" and ", "for msg senderKID = ");
530
2.14k
        ERR_add_error_txt(NULL, skid_str);
531
2.14k
    }
532
533
3.66k
end:
534
3.66k
    OPENSSL_free(sname);
535
3.66k
    OPENSSL_free(skid_str);
536
3.66k
    return res;
537
3.66k
}
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
8.73k
{
557
8.73k
    X509 *scrt;
558
559
8.73k
    ossl_cmp_debug(ctx, "validating CMP message");
560
8.73k
    if (ctx == NULL || msg == NULL
561
8.73k
        || 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
8.73k
    if (msg->header->protectionAlg == NULL /* unprotected message */
567
8.73k
        || msg->protection == NULL || msg->protection->data == NULL) {
568
1.74k
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
569
1.74k
        return 0;
570
1.74k
    }
571
572
6.99k
    switch (ossl_cmp_hdr_get_protection_nid(msg->header)) {
573
        /* 5.1.3.1.  Shared Secret Information */
574
2.00k
    case NID_id_PasswordBasedMAC:
575
2.00k
        if (ctx->secretValue == NULL) {
576
973
            ossl_cmp_info(ctx, "no secret available for verifying PBM-based CMP message protection");
577
973
            ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SECRET);
578
973
            return 0;
579
973
        }
580
1.03k
        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
5
            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
2
            case OSSL_CMP_PKIBODY_CCP:
594
2
                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
2
                break;
603
3
            default:
604
3
                break;
605
5
            }
606
5
            ossl_cmp_debug(ctx,
607
5
                "successfully validated PBM-based CMP message protection");
608
5
            return 1;
609
5
        }
610
1.02k
        ossl_cmp_warn(ctx, "verifying PBM-based CMP message protection failed");
611
1.02k
        break;
612
613
        /*
614
         * 5.1.3.2 DH Key Pairs
615
         * Not yet supported
616
         */
617
31
    case NID_id_DHBasedMac:
618
31
        ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC);
619
31
        break;
620
621
        /*
622
         * 5.1.3.3.  Signature
623
         */
624
4.95k
    default:
625
4.95k
        scrt = ctx->srvCert;
626
4.95k
        if (scrt == NULL) {
627
4.95k
            if (ctx->trusted == NULL && ctx->secretValue != NULL) {
628
1.99k
                ossl_cmp_info(ctx, "no trust store nor pinned sender cert available for verifying signature-based CMP message protection");
629
1.99k
                ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_ANCHOR);
630
1.99k
                return 0;
631
1.99k
            }
632
2.96k
            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
2.96k
        } 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
2.96k
        break;
649
6.99k
    }
650
4.02k
    return 0;
651
6.99k
}
652
653
static int check_transactionID_or_nonce(ASN1_OCTET_STRING *expected,
654
    ASN1_OCTET_STRING *actual, int reason)
655
76.1k
{
656
76.1k
    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
76.1k
    return 1;
674
76.1k
}
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
23.9k
{
699
23.9k
    OSSL_CMP_PKIHEADER *hdr;
700
23.9k
    const X509_NAME *expected_sender;
701
23.9k
    int num_untrusted, num_added, res;
702
703
23.9k
    if (!ossl_assert(ctx != NULL && msg != NULL && msg->header != NULL))
704
0
        return 0;
705
23.9k
    hdr = OSSL_CMP_MSG_get0_header(msg);
706
707
    /* If expected_sender is given, validate sender name of received msg */
708
23.9k
    expected_sender = ctx->expected_sender;
709
23.9k
    if (expected_sender == NULL && ctx->srvCert != NULL)
710
0
        expected_sender = X509_get_subject_name(ctx->srvCert);
711
23.9k
    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
23.9k
    num_added = sk_X509_num(msg->extraCerts);
737
23.9k
    if (num_added > 10)
738
0
        ossl_cmp_log1(WARN, ctx, "received CMP message contains %d extraCerts",
739
23.9k
            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
23.9k
    num_untrusted = ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted);
750
23.9k
    res = ossl_x509_add_certs_new(&ctx->untrusted, msg->extraCerts,
751
        /* this allows self-signed certs */
752
23.9k
        X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
753
23.9k
            | X509_ADD_FLAG_PREPEND);
754
23.9k
    num_added = (ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted))
755
23.9k
        - num_untrusted;
756
23.9k
    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
23.9k
    if (hdr->protectionAlg != NULL)
763
5.93k
        res = OSSL_CMP_validate_msg(ctx, msg)
764
            /* explicitly permitted exceptions for invalid protection: */
765
5.92k
            || (cb != NULL && (*cb)(ctx, msg, 1, cb_arg) > 0);
766
18.0k
    else
767
        /* explicitly permitted exceptions for missing protection: */
768
18.0k
        res = cb != NULL && (*cb)(ctx, msg, 0, cb_arg) > 0;
769
23.9k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
770
23.9k
    res = 1; /* support more aggressive fuzzing by letting invalid msg pass */
771
23.9k
#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
23.9k
    if (ctx->noCacheExtraCerts || res != 1)
780
0
        while (num_added-- > 0)
781
0
            X509_free(sk_X509_shift(ctx->untrusted));
782
783
23.9k
    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
23.9k
    if (ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_2
793
18.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
18.2k
    }
799
800
23.9k
    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
23.9k
    if (!check_transactionID_or_nonce(ctx->transactionID, hdr->transactionID,
809
23.9k
            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
23.9k
    (void)ERR_set_mark();
817
    /* compare received nonce with the one we sent */
818
23.9k
    if (!check_transactionID_or_nonce(ctx->senderNonce, hdr->recipNonce,
819
23.9k
            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
23.9k
    (void)ERR_pop_to_mark();
832
833
    /* if not yet present, learn transactionID */
834
23.9k
    if (ctx->transactionID == NULL
835
23.9k
        && !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
23.9k
    if (!ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce))
844
0
        return 0;
845
846
23.9k
    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.31k
        switch (OSSL_CMP_MSG_get_bodytype(msg)) {
854
5
        case OSSL_CMP_PKIBODY_IP:
855
13
        case OSSL_CMP_PKIBODY_CP:
856
16
        case OSSL_CMP_PKIBODY_KUP:
857
35
        case OSSL_CMP_PKIBODY_CCP:
858
35
            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
35
            break;
867
1.28k
        default:
868
1.28k
            break;
869
1.31k
        }
870
1.31k
    }
871
23.9k
    return 1;
872
23.9k
}
873
874
int ossl_cmp_verify_popo(const OSSL_CMP_CTX *ctx,
875
    const OSSL_CMP_MSG *msg, int acceptRAVerified)
876
5.01k
{
877
5.01k
    if (!ossl_assert(msg != NULL && msg->body != NULL))
878
0
        return 0;
879
5.01k
    switch (msg->body->type) {
880
2.82k
    case OSSL_CMP_PKIBODY_P10CR: {
881
2.82k
        X509_REQ *req = msg->body->value.p10cr;
882
883
2.82k
        if (X509_REQ_verify_ex(req, X509_REQ_get0_pubkey(req), ctx->libctx,
884
2.82k
                ctx->propq)
885
2.82k
            <= 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
2.82k
        }
891
2.82k
    } break;
892
1.14k
    case OSSL_CMP_PKIBODY_IR:
893
1.84k
    case OSSL_CMP_PKIBODY_CR:
894
2.18k
    case OSSL_CMP_PKIBODY_KUR:
895
2.18k
        if (!OSSL_CRMF_MSGS_verify_popo(msg->body->value.ir, OSSL_CMP_CERTREQID,
896
2.18k
                acceptRAVerified,
897
2.18k
                ctx->libctx, ctx->propq)) {
898
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
899
            return 0;
900
#endif
901
2.08k
        }
902
2.18k
        break;
903
0
    default:
904
0
        ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
905
0
        return 0;
906
5.01k
    }
907
5.01k
    return 1;
908
5.01k
}