Coverage Report

Created: 2025-12-31 06:58

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