Coverage Report

Created: 2025-12-31 06:58

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