Coverage Report

Created: 2025-12-04 06:33

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