Coverage Report

Created: 2025-12-31 06:58

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