Coverage Report

Created: 2026-10-28 06:28

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