Coverage Report

Created: 2026-07-23 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
3.85k
{
20
3.85k
    OSSL_CMP_PROTECTEDPART prot_part;
21
3.85k
    EVP_PKEY *pubkey = NULL;
22
3.85k
    BIO *bio;
23
3.85k
    int res = 0;
24
25
3.85k
    if (!ossl_assert(cmp_ctx != NULL && msg != NULL && cert != NULL))
26
0
        return 0;
27
28
3.85k
    bio = BIO_new(BIO_s_mem()); /* may be NULL */
29
3.85k
    if (bio == NULL)
30
0
        return 0;
31
    /* verify that keyUsage, if present, contains digitalSignature */
32
3.85k
    if (!cmp_ctx->ignore_keyusage
33
3.85k
        && (X509_get_key_usage(cert) & X509v3_KU_DIGITAL_SIGNATURE) == 0) {
34
404
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE);
35
404
        goto sig_err;
36
404
    }
37
38
3.44k
    pubkey = X509_get_pubkey(cert);
39
3.44k
    if (pubkey == NULL) {
40
1.80k
        ERR_raise(ERR_LIB_CMP, CMP_R_FAILED_EXTRACTING_PUBKEY);
41
1.80k
        goto sig_err;
42
1.80k
    }
43
44
1.64k
    prot_part.header = msg->header;
45
1.64k
    prot_part.body = msg->body;
46
47
1.64k
    if (ASN1_item_verify_ex(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART),
48
1.64k
            msg->header->protectionAlg, msg->protection,
49
1.64k
            &prot_part, NULL, pubkey, cmp_ctx->libctx,
50
1.64k
            cmp_ctx->propq)
51
1.64k
        > 0) {
52
51
        res = 1;
53
51
        goto end;
54
51
    }
55
56
3.80k
sig_err:
57
3.80k
    res = ossl_x509_print_ex_brief(bio, cert, X509_FLAG_NO_EXTENSIONS);
58
3.80k
    ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_SIGNATURE);
59
3.80k
    if (res) {
60
3.80k
        ERR_add_error_txt(NULL, "\n");
61
3.80k
        ERR_add_error_mem_bio(NULL, bio);
62
3.80k
    }
63
3.80k
    res = 0;
64
65
3.85k
end:
66
3.85k
    EVP_PKEY_free(pubkey);
67
3.85k
    BIO_free(bio);
68
69
3.85k
    return res;
70
3.80k
}
71
72
/* Verify a message protected with PBMAC */
73
static int verify_PBMAC(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
74
1.30k
{
75
1.30k
    ASN1_BIT_STRING *protection = NULL;
76
1.30k
    int valid = 0;
77
78
    /* generate expected protection for the message */
79
1.30k
    if ((protection = ossl_cmp_calc_protection(ctx, msg)) == NULL)
80
946
        return 0; /* failed to generate protection string! */
81
82
361
    valid = msg->protection != NULL && msg->protection->length >= 0
83
361
        && msg->protection->type == protection->type
84
361
        && msg->protection->length == protection->length
85
235
        && CRYPTO_memcmp(msg->protection->data, protection->data,
86
235
               protection->length)
87
235
            == 0;
88
361
    ASN1_BIT_STRING_free(protection);
89
361
    if (!valid)
90
361
        ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_PBM_VALUE);
91
92
361
    return valid;
93
1.30k
}
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
57
{
105
57
    int valid = 0;
106
57
    X509_STORE_CTX *csc = NULL;
107
57
    int err;
108
109
57
    if (ctx == NULL || cert == NULL) {
110
0
        ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
111
0
        return 0;
112
0
    }
113
114
57
    if (trusted_store == NULL) {
115
57
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_STORE);
116
57
        return 0;
117
57
    }
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.22k
{
140
4.22k
    X509_STORE_CTX_verify_cb verify_cb;
141
4.22k
    X509_STORE_CTX *csc;
142
4.22k
    int ok = 0;
143
144
4.22k
    if (ts == NULL || (verify_cb = X509_STORE_get_verify_cb(ts)) == NULL)
145
4.22k
        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.22k
}
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
15.8k
{
161
15.8k
    char *str;
162
163
15.8k
    if (expect_name == NULL)
164
4.67k
        return 1; /* no expectation, thus trivially fulfilled */
165
166
    /* make sure that a matching name is there */
167
11.1k
    if (actual_name == NULL) {
168
0
        ossl_cmp_log1(WARN, ctx, "missing %s", actual_desc);
169
0
        return 0;
170
0
    }
171
11.1k
    str = X509_NAME_oneline(actual_name, NULL, 0);
172
11.1k
    if (X509_NAME_cmp(actual_name, expect_name) == 0) {
173
5.02k
        if (log_success && str != NULL)
174
5.02k
            ossl_cmp_log3(INFO, ctx, " %s matches %s: %s",
175
5.02k
                actual_desc, expect_desc, str);
176
5.02k
        OPENSSL_free(str);
177
5.02k
        return 1;
178
5.02k
    }
179
180
6.17k
    if (str != NULL)
181
6.17k
        ossl_cmp_log2(INFO, ctx, " actual name in %s = %s", actual_desc, str);
182
6.17k
    OPENSSL_free(str);
183
6.17k
    if ((str = X509_NAME_oneline(expect_name, NULL, 0)) != NULL)
184
6.17k
        ossl_cmp_log2(INFO, ctx, " does not match %s = %s", expect_desc, str);
185
6.17k
    OPENSSL_free(str);
186
6.17k
    return 0;
187
11.1k
}
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.02k
{
194
5.02k
    char *str;
195
196
5.02k
    if (skid == NULL)
197
2.10k
        return 1; /* no expectation, thus trivially fulfilled */
198
199
    /* make sure that the expected subject key identifier is there */
200
2.91k
    if (ckid == NULL) {
201
216
        ossl_cmp_warn(ctx, "missing Subject Key Identifier in certificate");
202
216
        return 0;
203
216
    }
204
2.70k
    str = i2s_ASN1_OCTET_STRING(NULL, ckid);
205
2.70k
    if (ASN1_OCTET_STRING_cmp(ckid, skid) == 0) {
206
2.52k
        if (str != NULL)
207
2.52k
            ossl_cmp_log1(INFO, ctx, " subjectKID matches senderKID: %s", str);
208
2.52k
        OPENSSL_free(str);
209
2.52k
        return 1;
210
2.52k
    }
211
212
174
    if (str != NULL)
213
174
        ossl_cmp_log1(INFO, ctx, " cert Subject Key Identifier = %s", str);
214
174
    OPENSSL_free(str);
215
174
    if ((str = i2s_ASN1_OCTET_STRING(NULL, skid)) != NULL)
216
174
        ossl_cmp_log1(INFO, ctx, " does not match senderKID    = %s", str);
217
174
    OPENSSL_free(str);
218
174
    return 0;
219
2.70k
}
220
221
static int already_checked(const X509 *cert,
222
    const STACK_OF(X509) *already_checked)
223
49.1k
{
224
49.1k
    int i;
225
226
74.7k
    for (i = sk_X509_num(already_checked /* may be NULL */); i > 0; i--)
227
42.0k
        if (X509_cmp(sk_X509_value(already_checked, i - 1), cert) == 0)
228
16.3k
            return 1;
229
32.7k
    return 0;
230
49.1k
}
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
23.2k
{
246
23.2k
    X509_STORE *ts = ctx->trusted;
247
23.2k
    int self_issued = X509_check_issued(cert, cert) == X509_V_OK;
248
23.2k
    char *str;
249
23.2k
    X509_VERIFY_PARAM *vpm = ts != NULL ? X509_STORE_get0_param(ts) : NULL;
250
23.2k
    int time_cmp;
251
252
23.2k
    ossl_cmp_log3(INFO, ctx, " considering %s%s %s with..",
253
23.2k
        self_issued ? "self-issued " : "", desc1, desc2);
254
23.2k
    if ((str = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0)) != NULL)
255
23.2k
        ossl_cmp_log1(INFO, ctx, "  subject = %s", str);
256
23.2k
    OPENSSL_free(str);
257
23.2k
    if (!self_issued) {
258
20.8k
        str = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
259
20.8k
        if (str != NULL)
260
20.8k
            ossl_cmp_log1(INFO, ctx, "  issuer  = %s", str);
261
20.8k
        OPENSSL_free(str);
262
20.8k
    }
263
264
23.2k
    if (already_checked(cert, already_checked1)
265
11.6k
        || already_checked(cert, already_checked2)) {
266
11.6k
        ossl_cmp_info(ctx, " cert has already been checked");
267
11.6k
        return 0;
268
11.6k
    }
269
270
11.6k
    time_cmp = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
271
11.6k
        X509_get0_notAfter(cert));
272
11.6k
    if (time_cmp != 0) {
273
6.22k
        int err = time_cmp > 0 ? X509_V_ERR_CERT_HAS_EXPIRED
274
6.22k
                               : X509_V_ERR_CERT_NOT_YET_VALID;
275
276
6.22k
        ossl_cmp_warn(ctx, time_cmp > 0 ? "cert has expired" : "cert is not yet valid");
277
6.22k
        if (ctx->log_cb != NULL /* logging not temporarily disabled */
278
3.11k
            && verify_cb_cert(ts, cert, err) <= 0)
279
3.11k
            return 0;
280
6.22k
    }
281
282
8.51k
    if (!check_name(ctx, 1,
283
8.51k
            "cert subject", X509_get_subject_name(cert),
284
8.51k
            "sender field", msg->header->sender->d.directoryName))
285
4.72k
        return 0;
286
287
3.79k
    if (!check_kid(ctx, X509_get0_subject_key_id(cert), msg->header->senderKID))
288
292
        return 0;
289
    /* prevent misleading error later in case x509v3_cache_extensions() fails */
290
3.50k
    if (!ossl_x509v3_cache_extensions(cert)) {
291
212
        ossl_cmp_warn(ctx, "cert appears to be invalid");
292
212
        return 0;
293
212
    }
294
3.28k
    if (!verify_signature(ctx, msg, cert)) {
295
3.24k
        ossl_cmp_warn(ctx, "msg signature verification failed");
296
3.24k
        return 0;
297
3.24k
    }
298
    /* acceptable also if there is no senderKID in msg header */
299
41
    ossl_cmp_info(ctx, " cert seems acceptable");
300
41
    return 1;
301
3.28k
}
302
303
static int check_cert_path(const OSSL_CMP_CTX *ctx, X509_STORE *store,
304
    X509 *scrt)
305
57
{
306
57
    if (OSSL_CMP_validate_cert_path(ctx, store, scrt))
307
0
        return 1;
308
309
57
    ossl_cmp_warn(ctx,
310
57
        "msg signature validates but cert path validation failed");
311
57
    return 0;
312
57
}
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.2k
{
379
14.2k
    int in_extraCerts = already_checked1 == NULL;
380
14.2k
    int n_acceptable_certs = 0;
381
14.2k
    int i;
382
383
14.2k
    if (sk_X509_num(certs) <= 0) {
384
1.44k
        ossl_cmp_log1(INFO, ctx, "no %s", desc);
385
1.44k
        return 0;
386
1.44k
    }
387
388
41.1k
    for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
389
28.3k
        X509 *cert = sk_X509_value(certs, i);
390
391
28.3k
        if (!ossl_assert(cert != NULL))
392
0
            return 0;
393
28.3k
        if (!cert_acceptable(ctx, "cert from", desc, cert,
394
28.3k
                already_checked1, already_checked2, msg))
395
28.2k
            continue;
396
51
        n_acceptable_certs++;
397
51
        if (mode_3gpp ? check_cert_path_3gpp(ctx, msg, cert)
398
51
                      : 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
51
    }
403
12.8k
    if (in_extraCerts && n_acceptable_certs == 0)
404
6.37k
        ossl_cmp_log1(WARN, ctx, "no acceptable %s", desc);
405
12.8k
    return 0;
406
12.8k
}
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.2k
{
416
14.2k
    int ret = 0;
417
418
14.2k
    if (ctx->permitTAInExtraCertsForIR
419
0
        && OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_IP)
420
14.2k
        ossl_cmp_info(ctx, mode_3gpp ? "normal mode failed; trying now 3GPP mode trusting extraCerts" : "trying first normal mode using trust store");
421
14.2k
    else if (mode_3gpp)
422
7.14k
        return 0;
423
424
7.14k
    if (check_msg_with_certs(ctx, msg->extraCerts, "extraCerts",
425
7.14k
            NULL, NULL, msg, mode_3gpp))
426
0
        return 1;
427
7.14k
    if (check_msg_with_certs(ctx, ctx->untrusted, "untrusted certs",
428
7.14k
            msg->extraCerts, NULL, msg, mode_3gpp))
429
0
        return 1;
430
431
7.14k
    if (ctx->trusted == NULL) {
432
7.14k
        ossl_cmp_warn(ctx, mode_3gpp ? "no self-issued extraCerts" : "no trusted store");
433
7.14k
    } 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.14k
    return ret;
444
7.14k
}
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.07k
{
452
4.07k
    X509 *scrt = ctx->validatedSrvCert; /* previous successful sender cert */
453
4.07k
    GENERAL_NAME *sender = msg->header->sender;
454
4.07k
    char *sname = NULL;
455
4.07k
    char *skid_str = NULL;
456
4.07k
    const ASN1_OCTET_STRING *skid = msg->header->senderKID;
457
4.07k
    OSSL_CMP_log_cb_t backup_log_cb = ctx->log_cb;
458
4.07k
    int res = 0;
459
460
4.07k
    if (sender == NULL || msg->body == NULL)
461
0
        return 0; /* other NULL cases already have been checked */
462
4.07k
    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.07k
    OSSL_CMP_CTX_print_errors(ctx);
470
471
    /* enable clearing irrelevant errors in attempts to validate sender certs */
472
4.07k
    (void)ERR_set_mark();
473
4.07k
    ctx->log_cb = NULL; /* temporarily disable logging */
474
475
4.07k
    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.07k
    res = check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */)
498
4.07k
        || check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
499
500
4.07k
    ctx->log_cb = backup_log_cb; /* re-enable logging */
501
    /* discard any previous diagnostic information on trying to use certs */
502
4.07k
    (void)ERR_pop_to_mark();
503
504
4.07k
    if (res)
505
0
        goto end;
506
    /* failed finding a sender cert that verifies the message signature */
507
508
4.07k
    sname = X509_NAME_oneline(sender->d.directoryName, NULL, 0);
509
4.07k
    skid_str = skid == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, skid);
510
4.07k
    if (ctx->log_cb != NULL) {
511
4.07k
        ossl_cmp_info(ctx, "trying to verify msg signature with a valid cert that..");
512
4.07k
        if (sname != NULL)
513
4.07k
            ossl_cmp_log1(INFO, ctx, "matches msg sender    = %s", sname);
514
4.07k
        if (skid_str != NULL)
515
2.16k
            ossl_cmp_log1(INFO, ctx, "matches msg senderKID = %s", skid_str);
516
1.90k
        else
517
4.07k
            ossl_cmp_info(ctx, "while msg header does not contain senderKID");
518
        /* re-do the above checks (just) for adding diagnostic information */
519
4.07k
        (void)check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */);
520
4.07k
        (void)check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
521
4.07k
    }
522
523
4.07k
    ERR_raise(ERR_LIB_CMP, CMP_R_NO_SUITABLE_SENDER_CERT);
524
4.07k
    if (sname != NULL) {
525
4.07k
        ERR_add_error_txt(NULL, "for msg sender name = ");
526
4.07k
        ERR_add_error_txt(NULL, sname);
527
4.07k
    }
528
4.07k
    if (skid_str != NULL) {
529
2.16k
        ERR_add_error_txt(" and ", "for msg senderKID = ");
530
2.16k
        ERR_add_error_txt(NULL, skid_str);
531
2.16k
    }
532
533
4.07k
end:
534
4.07k
    OPENSSL_free(sname);
535
4.07k
    OPENSSL_free(skid_str);
536
4.07k
    return res;
537
4.07k
}
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
5.61k
{
557
5.61k
    X509 *scrt;
558
559
5.61k
    ossl_cmp_debug(ctx, "validating CMP message");
560
5.61k
    if (ctx == NULL || msg == NULL
561
5.61k
        || 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
5.61k
    if (msg->header->protectionAlg == NULL /* unprotected message */
567
5.61k
        || msg->protection == NULL || msg->protection->data == NULL) {
568
1.24k
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
569
1.24k
        return 0;
570
1.24k
    }
571
572
4.37k
    switch (ossl_cmp_hdr_get_protection_nid(msg->header)) {
573
        /* 5.1.3.1.  Shared Secret Information */
574
983
    case NID_id_PasswordBasedMAC:
575
983
        if (ctx->secretValue == NULL) {
576
434
            ossl_cmp_info(ctx, "no secret available for verifying PBM-based CMP message protection");
577
434
            ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SECRET);
578
434
            return 0;
579
434
        }
580
549
        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
4
            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
2
            default:
604
2
                break;
605
4
            }
606
4
            ossl_cmp_debug(ctx,
607
4
                "successfully validated PBM-based CMP message protection");
608
4
            return 1;
609
4
        }
610
545
        ossl_cmp_warn(ctx, "verifying PBM-based CMP message protection failed");
611
545
        break;
612
613
        /*
614
         * 5.1.3.2 DH Key Pairs
615
         * Not yet supported
616
         */
617
32
    case NID_id_DHBasedMac:
618
32
        ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC);
619
32
        break;
620
621
        /*
622
         * 5.1.3.3.  Signature
623
         */
624
3.35k
    default:
625
3.35k
        scrt = ctx->srvCert;
626
3.35k
        if (scrt == NULL) {
627
3.35k
            if (ctx->trusted == NULL && ctx->secretValue != NULL) {
628
1.25k
                ossl_cmp_info(ctx, "no trust store nor pinned sender cert available for verifying signature-based CMP message protection");
629
1.25k
                ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_ANCHOR);
630
1.25k
                return 0;
631
1.25k
            }
632
2.10k
            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.10k
        } 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.10k
        break;
649
4.37k
    }
650
2.68k
    return 0;
651
4.37k
}
652
653
static int check_transactionID_or_nonce(ASN1_OCTET_STRING *expected,
654
    ASN1_OCTET_STRING *actual, int reason)
655
82.2k
{
656
82.2k
    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
82.2k
    return 1;
674
82.2k
}
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
33.2k
{
699
33.2k
    OSSL_CMP_PKIHEADER *hdr;
700
33.2k
    const X509_NAME *expected_sender;
701
33.2k
    int num_untrusted, num_added, res;
702
703
33.2k
    if (!ossl_assert(ctx != NULL && msg != NULL && msg->header != NULL))
704
0
        return 0;
705
33.2k
    hdr = OSSL_CMP_MSG_get0_header(msg);
706
707
    /* If expected_sender is given, validate sender name of received msg */
708
33.2k
    expected_sender = ctx->expected_sender;
709
33.2k
    if (expected_sender == NULL && ctx->srvCert != NULL)
710
0
        expected_sender = X509_get_subject_name(ctx->srvCert);
711
33.2k
    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
                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
33.2k
    num_added = sk_X509_num(msg->extraCerts);
737
33.2k
    if (num_added > 10)
738
0
        ossl_cmp_log1(WARN, ctx, "received CMP message contains %d extraCerts",
739
33.2k
            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
33.2k
    num_untrusted = ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted);
750
33.2k
    res = ossl_x509_add_certs_new(&ctx->untrusted, msg->extraCerts,
751
        /* this allows self-signed certs */
752
33.2k
        X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
753
33.2k
            | X509_ADD_FLAG_PREPEND);
754
33.2k
    num_added = (ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted))
755
33.2k
        - num_untrusted;
756
33.2k
    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
33.2k
    if (hdr->protectionAlg != NULL)
763
9.23k
        res = OSSL_CMP_validate_msg(ctx, msg)
764
            /* explicitly permitted exceptions for invalid protection: */
765
9.23k
            || (cb != NULL && (*cb)(ctx, msg, 1, cb_arg) > 0);
766
24.0k
    else
767
        /* explicitly permitted exceptions for missing protection: */
768
24.0k
        res = cb != NULL && (*cb)(ctx, msg, 0, cb_arg) > 0;
769
33.2k
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
770
33.2k
    res = 1; /* support more aggressive fuzzing by letting invalid msg pass */
771
33.2k
#endif
772
773
    /* remove extraCerts again if not caching */
774
33.2k
    if (ctx->noCacheExtraCerts)
775
0
        while (num_added-- > 0)
776
0
            X509_free(sk_X509_shift(ctx->untrusted));
777
778
33.2k
    if (!res) {
779
0
        if (hdr->protectionAlg != NULL)
780
0
            ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_PROTECTION);
781
0
        else
782
0
            ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
783
0
        return 0;
784
0
    }
785
786
    /* check CMP version number in header */
787
33.2k
    if (ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_2
788
25.0k
        && ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_3) {
789
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
790
        ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PVNO);
791
        return 0;
792
#endif
793
25.0k
    }
794
795
33.2k
    if (OSSL_CMP_MSG_get_bodytype(msg) < 0) {
796
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
797
        ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
798
        return 0;
799
#endif
800
0
    }
801
802
    /* compare received transactionID with the expected one in previous msg */
803
33.2k
    if (!check_transactionID_or_nonce(ctx->transactionID, hdr->transactionID,
804
33.2k
            CMP_R_TRANSACTIONID_UNMATCHED))
805
0
        return 0;
806
807
    /*
808
     * enable clearing irrelevant errors
809
     * in attempts to validate recipient nonce in case of delayed delivery.
810
     */
811
33.2k
    (void)ERR_set_mark();
812
    /* compare received nonce with the one we sent */
813
33.2k
    if (!check_transactionID_or_nonce(ctx->senderNonce, hdr->recipNonce,
814
33.2k
            CMP_R_RECIPNONCE_UNMATCHED)) {
815
        /* check if we are polling and received final response */
816
0
        if (ctx->first_senderNonce == NULL
817
0
            || OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_POLLREP
818
            /* compare received nonce with our sender nonce at poll start */
819
0
            || !check_transactionID_or_nonce(ctx->first_senderNonce,
820
0
                hdr->recipNonce,
821
0
                CMP_R_RECIPNONCE_UNMATCHED)) {
822
0
            (void)ERR_clear_last_mark();
823
0
            return 0;
824
0
        }
825
0
    }
826
33.2k
    (void)ERR_pop_to_mark();
827
828
    /* if not yet present, learn transactionID */
829
33.2k
    if (ctx->transactionID == NULL
830
33.2k
        && !OSSL_CMP_CTX_set1_transactionID(ctx, hdr->transactionID))
831
0
        return 0;
832
833
    /*
834
     * RFC 9810 section 5.1.1 states: the recipNonce is copied from
835
     * the senderNonce of the previous message in the transaction.
836
     * --> Store for setting in next message
837
     */
838
33.2k
    if (!ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce))
839
0
        return 0;
840
841
33.2k
    if (ossl_cmp_hdr_get_protection_nid(hdr) == NID_id_PasswordBasedMAC) {
842
        /*
843
         * RFC 9810, 5.3.2: 'Note that if the PKI message protection is
844
         * "shared secret information", then any certificate transported in
845
         * the caPubs field may be directly trusted as a root CA
846
         * certificate by the initiator.'
847
         */
848
3.01k
        switch (OSSL_CMP_MSG_get_bodytype(msg)) {
849
9
        case OSSL_CMP_PKIBODY_IP:
850
20
        case OSSL_CMP_PKIBODY_CP:
851
24
        case OSSL_CMP_PKIBODY_KUP:
852
50
        case OSSL_CMP_PKIBODY_CCP:
853
50
            if (ctx->trusted != NULL) {
854
0
                STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
855
                /* value.ip is same for cp, kup, and ccp */
856
857
0
                if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
858
                    /* adds both self-issued and not self-issued certs */
859
0
                    return 0;
860
0
            }
861
50
            break;
862
2.96k
        default:
863
2.96k
            break;
864
3.01k
        }
865
3.01k
    }
866
33.2k
    return 1;
867
33.2k
}
868
869
int ossl_cmp_verify_popo(const OSSL_CMP_CTX *ctx,
870
    const OSSL_CMP_MSG *msg, int acceptRAVerified)
871
5.73k
{
872
5.73k
    if (!ossl_assert(msg != NULL && msg->body != NULL))
873
0
        return 0;
874
5.73k
    switch (msg->body->type) {
875
3.39k
    case OSSL_CMP_PKIBODY_P10CR: {
876
3.39k
        X509_REQ *req = msg->body->value.p10cr;
877
878
3.39k
        if (X509_REQ_verify_ex(req, X509_REQ_get0_pubkey(req), ctx->libctx,
879
3.39k
                ctx->propq)
880
3.39k
            <= 0) {
881
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
882
            ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED);
883
            return 0;
884
#endif
885
3.38k
        }
886
3.39k
    } break;
887
1.26k
    case OSSL_CMP_PKIBODY_IR:
888
2.01k
    case OSSL_CMP_PKIBODY_CR:
889
2.34k
    case OSSL_CMP_PKIBODY_KUR:
890
2.34k
        if (!OSSL_CRMF_MSGS_verify_popo(msg->body->value.ir, OSSL_CMP_CERTREQID,
891
2.34k
                acceptRAVerified,
892
2.34k
                ctx->libctx, ctx->propq)) {
893
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
894
            return 0;
895
#endif
896
2.23k
        }
897
2.34k
        break;
898
0
    default:
899
0
        ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
900
0
        return 0;
901
5.73k
    }
902
5.73k
    return 1;
903
5.73k
}