Coverage Report

Created: 2025-08-28 07:07

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