Coverage Report

Created: 2026-04-01 06:39

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