Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl30/crypto/cmp/cmp_client.c
Line
Count
Source
1
/*
2
 * Copyright 2007-2025 The OpenSSL Project Authors. All Rights Reserved.
3
 * Copyright Nokia 2007-2019
4
 * Copyright Siemens AG 2015-2019
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
#include "cmp_local.h"
13
#include "internal/cryptlib.h"
14
#include "e_os.h" /* ossl_sleep() */
15
16
/* explicit #includes not strictly needed since implied by the above: */
17
#include <openssl/bio.h>
18
#include <openssl/cmp.h>
19
#include <openssl/err.h>
20
#include <openssl/evp.h>
21
#include <openssl/x509v3.h>
22
#include <openssl/cmp_util.h>
23
24
0
#define IS_CREP(t) ((t) == OSSL_CMP_PKIBODY_IP || (t) == OSSL_CMP_PKIBODY_CP \
25
0
    || (t) == OSSL_CMP_PKIBODY_KUP)
26
27
/*-
28
 * Evaluate whether there's an exception (violating the standard) configured for
29
 * handling negative responses without protection or with invalid protection.
30
 * Returns 1 on acceptance, 0 on rejection, or -1 on (internal) error.
31
 */
32
static int unprotected_exception(const OSSL_CMP_CTX *ctx,
33
    const OSSL_CMP_MSG *rep,
34
    int invalid_protection,
35
    int expected_type /* ignored here */)
36
0
{
37
0
    int rcvd_type = OSSL_CMP_MSG_get_bodytype(rep /* may be NULL */);
38
0
    const char *msg_type = NULL;
39
40
0
    if (!ossl_assert(ctx != NULL && rep != NULL))
41
0
        return -1;
42
43
0
    if (!ctx->unprotectedErrors)
44
0
        return 0;
45
46
0
    switch (rcvd_type) {
47
0
    case OSSL_CMP_PKIBODY_ERROR:
48
0
        msg_type = "error response";
49
0
        break;
50
0
    case OSSL_CMP_PKIBODY_RP: {
51
0
        OSSL_CMP_PKISI *si = ossl_cmp_revrepcontent_get_pkisi(rep->body->value.rp,
52
0
            OSSL_CMP_REVREQSID);
53
54
0
        if (si == NULL)
55
0
            return -1;
56
0
        if (ossl_cmp_pkisi_get_status(si) == OSSL_CMP_PKISTATUS_rejection)
57
0
            msg_type = "revocation response message with rejection status";
58
0
        break;
59
0
    }
60
0
    case OSSL_CMP_PKIBODY_PKICONF:
61
0
        msg_type = "PKI Confirmation message";
62
0
        break;
63
0
    default:
64
0
        if (IS_CREP(rcvd_type)) {
65
0
            int any_rid = OSSL_CMP_CERTREQID_NONE;
66
0
            OSSL_CMP_CERTREPMESSAGE *crepmsg = rep->body->value.ip;
67
0
            OSSL_CMP_CERTRESPONSE *crep = ossl_cmp_certrepmessage_get0_certresponse(crepmsg, any_rid);
68
69
0
            if (sk_OSSL_CMP_CERTRESPONSE_num(crepmsg->response) > 1)
70
0
                return -1;
71
0
            if (crep == NULL)
72
0
                return -1;
73
0
            if (ossl_cmp_pkisi_get_status(crep->status)
74
0
                == OSSL_CMP_PKISTATUS_rejection)
75
0
                msg_type = "CertRepMessage with rejection status";
76
0
        }
77
0
    }
78
0
    if (msg_type == NULL)
79
0
        return 0;
80
0
    ossl_cmp_log2(WARN, ctx, "ignoring %s protection of %s",
81
0
        invalid_protection ? "invalid" : "missing", msg_type);
82
0
    return 1;
83
0
}
84
85
/* Save error info from PKIStatusInfo field of a certresponse into ctx */
86
static int save_statusInfo(OSSL_CMP_CTX *ctx, OSSL_CMP_PKISI *si)
87
0
{
88
0
    int i;
89
0
    OSSL_CMP_PKIFREETEXT *ss;
90
91
0
    if (!ossl_assert(ctx != NULL && si != NULL))
92
0
        return 0;
93
94
0
    ctx->status = ossl_cmp_pkisi_get_status(si);
95
0
    if (ctx->status < OSSL_CMP_PKISTATUS_accepted)
96
0
        return 0;
97
98
0
    ctx->failInfoCode = ossl_cmp_pkisi_get_pkifailureinfo(si);
99
100
0
    if (!ossl_cmp_ctx_set0_statusString(ctx, sk_ASN1_UTF8STRING_new_null())
101
0
        || (ctx->statusString == NULL))
102
0
        return 0;
103
104
0
    ss = si->statusString; /* may be NULL */
105
0
    for (i = 0; i < sk_ASN1_UTF8STRING_num(ss); i++) {
106
0
        ASN1_UTF8STRING *str = sk_ASN1_UTF8STRING_value(ss, i);
107
0
        ASN1_UTF8STRING *dup = ASN1_STRING_dup(str);
108
109
0
        if (dup == NULL || !sk_ASN1_UTF8STRING_push(ctx->statusString, dup)) {
110
0
            ASN1_UTF8STRING_free(dup);
111
0
            return 0;
112
0
        }
113
0
    }
114
0
    return 1;
115
0
}
116
117
/*-
118
 * Perform the generic aspects of sending a request and receiving a response.
119
 * Returns 1 on success and provides the received PKIMESSAGE in *rep.
120
 * Returns 0 on error.
121
 * Regardless of success, caller is responsible for freeing *rep (unless NULL).
122
 */
123
static int send_receive_check(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req,
124
    OSSL_CMP_MSG **rep, int expected_type)
125
0
{
126
0
    int begin_transaction = expected_type != OSSL_CMP_PKIBODY_POLLREP
127
0
        && expected_type != OSSL_CMP_PKIBODY_PKICONF;
128
0
    const char *req_type_str = ossl_cmp_bodytype_to_string(OSSL_CMP_MSG_get_bodytype(req));
129
0
    const char *expected_type_str = ossl_cmp_bodytype_to_string(expected_type);
130
0
    int bak_msg_timeout = ctx->msg_timeout;
131
0
    int bt;
132
0
    time_t now = time(NULL);
133
0
    int time_left;
134
0
    OSSL_CMP_transfer_cb_t transfer_cb = ctx->transfer_cb;
135
136
0
    if (transfer_cb == NULL)
137
0
        transfer_cb = OSSL_CMP_MSG_http_perform;
138
0
    *rep = NULL;
139
140
0
    if (ctx->total_timeout != 0 /* not waiting indefinitely */) {
141
0
        if (begin_transaction)
142
0
            ctx->end_time = now + ctx->total_timeout;
143
0
        if (now >= ctx->end_time) {
144
0
            ERR_raise(ERR_LIB_CMP, CMP_R_TOTAL_TIMEOUT);
145
0
            return 0;
146
0
        }
147
0
        if (!ossl_assert(ctx->end_time - now < INT_MAX)) {
148
            /* actually cannot happen due to assignment in initial_certreq() */
149
0
            ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS);
150
0
            return 0;
151
0
        }
152
0
        time_left = (int)(ctx->end_time - now);
153
0
        if (ctx->msg_timeout == 0 || time_left < ctx->msg_timeout)
154
0
            ctx->msg_timeout = time_left;
155
0
    }
156
157
    /* should print error queue since transfer_cb may call ERR_clear_error() */
158
0
    OSSL_CMP_CTX_print_errors(ctx);
159
160
0
    ossl_cmp_log1(INFO, ctx, "sending %s", req_type_str);
161
162
0
    *rep = (*transfer_cb)(ctx, req);
163
0
    ctx->msg_timeout = bak_msg_timeout;
164
165
0
    if (*rep == NULL) {
166
0
        ERR_raise_data(ERR_LIB_CMP,
167
0
            ctx->total_timeout != 0 && time(NULL) >= ctx->end_time ? CMP_R_TOTAL_TIMEOUT : CMP_R_TRANSFER_ERROR,
168
0
            "request sent: %s, expected response: %s",
169
0
            req_type_str, expected_type_str);
170
0
        return 0;
171
0
    }
172
173
0
    bt = OSSL_CMP_MSG_get_bodytype(*rep);
174
    /*
175
     * The body type in the 'bt' variable is not yet verified.
176
     * Still we use this preliminary value already for a progress report because
177
     * the following msg verification may also produce log entries and may fail.
178
     */
179
0
    ossl_cmp_log1(INFO, ctx, "received %s", ossl_cmp_bodytype_to_string(bt));
180
181
    /* copy received extraCerts to ctx->extraCertsIn so they can be retrieved */
182
0
    if (bt != OSSL_CMP_PKIBODY_POLLREP && bt != OSSL_CMP_PKIBODY_PKICONF
183
0
        && !ossl_cmp_ctx_set1_extraCertsIn(ctx, (*rep)->extraCerts))
184
0
        return 0;
185
186
0
    if (!ossl_cmp_msg_check_update(ctx, *rep, unprotected_exception,
187
0
            expected_type))
188
0
        return 0;
189
190
0
    if (bt == expected_type
191
        /* as an answer to polling, there could be IP/CP/KUP: */
192
0
        || (IS_CREP(bt) && expected_type == OSSL_CMP_PKIBODY_POLLREP))
193
0
        return 1;
194
195
    /* received message type is not one of the expected ones (e.g., error) */
196
0
    ERR_raise(ERR_LIB_CMP, bt == OSSL_CMP_PKIBODY_ERROR ? CMP_R_RECEIVED_ERROR : CMP_R_UNEXPECTED_PKIBODY); /* in next line for mkerr.pl */
197
198
0
    if (bt != OSSL_CMP_PKIBODY_ERROR) {
199
0
        ERR_add_error_data(3, "message type is '",
200
0
            ossl_cmp_bodytype_to_string(bt), "'");
201
0
    } else {
202
0
        OSSL_CMP_ERRORMSGCONTENT *emc = (*rep)->body->value.error;
203
0
        OSSL_CMP_PKISI *si = emc->pKIStatusInfo;
204
0
        char buf[OSSL_CMP_PKISI_BUFLEN];
205
206
0
        if (save_statusInfo(ctx, si)
207
0
            && OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf,
208
0
                   sizeof(buf))
209
0
                != NULL)
210
0
            ERR_add_error_data(1, buf);
211
0
        if (emc->errorCode != NULL
212
0
            && BIO_snprintf(buf, sizeof(buf), "; errorCode: %08lX",
213
0
                   ASN1_INTEGER_get(emc->errorCode))
214
0
                > 0)
215
0
            ERR_add_error_data(1, buf);
216
0
        if (emc->errorDetails != NULL) {
217
0
            char *text = ossl_sk_ASN1_UTF8STRING2text(emc->errorDetails, ", ",
218
0
                OSSL_CMP_PKISI_BUFLEN - 1);
219
220
0
            if (text != NULL && *text != '\0')
221
0
                ERR_add_error_data(2, "; errorDetails: ", text);
222
0
            OPENSSL_free(text);
223
0
        }
224
0
        if (ctx->status != OSSL_CMP_PKISTATUS_rejection) {
225
0
            ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKISTATUS);
226
0
            if (ctx->status == OSSL_CMP_PKISTATUS_waiting)
227
0
                ctx->status = OSSL_CMP_PKISTATUS_rejection;
228
0
        }
229
0
    }
230
0
    return 0;
231
0
}
232
233
/*-
234
 * When a 'waiting' PKIStatus has been received, this function is used to
235
 * poll, which should yield a pollRep or finally a CertRepMessage in ip/cp/kup.
236
 * On receiving a pollRep, which includes a checkAfter value, it return this
237
 * value if sleep == 0, else it sleeps as long as indicated and retries.
238
 *
239
 * A transaction timeout is enabled if ctx->total_timeout is != 0.
240
 * In this case polling will continue until the timeout is reached and then
241
 * polling is done a last time even if this is before the "checkAfter" time.
242
 *
243
 * Returns -1 on receiving pollRep if sleep == 0, setting the checkAfter value.
244
 * Returns 1 on success and provides the received PKIMESSAGE in *rep.
245
 *           In this case the caller is responsible for freeing *rep.
246
 * Returns 0 on error (which includes the case that timeout has been reached).
247
 */
248
static int poll_for_response(OSSL_CMP_CTX *ctx, int sleep, int rid,
249
    OSSL_CMP_MSG **rep, int *checkAfter)
250
181
{
251
181
    OSSL_CMP_MSG *preq = NULL;
252
181
    OSSL_CMP_MSG *prep = NULL;
253
254
181
    ossl_cmp_info(ctx,
255
181
        "received 'waiting' PKIStatus, starting to poll for response");
256
181
    *rep = NULL;
257
181
    for (;;) {
258
181
        if ((preq = ossl_cmp_pollReq_new(ctx, rid)) == NULL)
259
181
            goto err;
260
261
0
        if (!send_receive_check(ctx, preq, &prep, OSSL_CMP_PKIBODY_POLLREP))
262
0
            goto err;
263
264
        /* handle potential pollRep */
265
0
        if (OSSL_CMP_MSG_get_bodytype(prep) == OSSL_CMP_PKIBODY_POLLREP) {
266
0
            OSSL_CMP_POLLREPCONTENT *prc = prep->body->value.pollRep;
267
0
            OSSL_CMP_POLLREP *pollRep = NULL;
268
0
            int64_t check_after;
269
0
            char str[OSSL_CMP_PKISI_BUFLEN];
270
0
            int len;
271
272
0
            if (sk_OSSL_CMP_POLLREP_num(prc) > 1) {
273
0
                ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED);
274
0
                goto err;
275
0
            }
276
0
            pollRep = ossl_cmp_pollrepcontent_get0_pollrep(prc, rid);
277
0
            if (pollRep == NULL)
278
0
                goto err;
279
280
0
            if (!ASN1_INTEGER_get_int64(&check_after, pollRep->checkAfter)) {
281
0
                ERR_raise(ERR_LIB_CMP, CMP_R_BAD_CHECKAFTER_IN_POLLREP);
282
0
                goto err;
283
0
            }
284
0
            if (check_after < 0 || (uint64_t)check_after > (sleep ? ULONG_MAX / 1000 : INT_MAX)) {
285
0
                ERR_raise(ERR_LIB_CMP, CMP_R_CHECKAFTER_OUT_OF_RANGE);
286
0
                if (BIO_snprintf(str, OSSL_CMP_PKISI_BUFLEN, "value = %jd",
287
0
                        check_after)
288
0
                    >= 0)
289
0
                    ERR_add_error_data(1, str);
290
0
                goto err;
291
0
            }
292
293
0
            if (pollRep->reason == NULL
294
0
                || (len = BIO_snprintf(str, OSSL_CMP_PKISI_BUFLEN,
295
0
                        " with reason = '"))
296
0
                    < 0) {
297
0
                *str = '\0';
298
0
            } else {
299
0
                char *text = ossl_sk_ASN1_UTF8STRING2text(pollRep->reason, ", ",
300
0
                    sizeof(str) - len - 2);
301
302
0
                if (text == NULL
303
0
                    || BIO_snprintf(str + len, sizeof(str) - len,
304
0
                           "%s'", text)
305
0
                        < 0)
306
0
                    *str = '\0';
307
0
                OPENSSL_free(text);
308
0
            }
309
0
            ossl_cmp_log2(INFO, ctx,
310
0
                "received polling response%s; checkAfter = %ld seconds",
311
0
                str, check_after);
312
313
0
            if (ctx->total_timeout != 0) { /* timeout is not infinite */
314
0
                const int exp = 5; /* expected max time per msg round trip */
315
0
                int64_t time_left = (int64_t)(ctx->end_time - exp - time(NULL));
316
317
0
                if (time_left <= 0) {
318
0
                    ERR_raise(ERR_LIB_CMP, CMP_R_TOTAL_TIMEOUT);
319
0
                    goto err;
320
0
                }
321
0
                if (time_left < check_after)
322
0
                    check_after = time_left;
323
                /* poll one last time just when timeout was reached */
324
0
            }
325
326
0
            OSSL_CMP_MSG_free(preq);
327
0
            preq = NULL;
328
0
            OSSL_CMP_MSG_free(prep);
329
0
            prep = NULL;
330
0
            if (sleep) {
331
0
                ossl_sleep((unsigned long)(1000 * check_after));
332
0
            } else {
333
0
                if (checkAfter != NULL)
334
0
                    *checkAfter = (int)check_after;
335
0
                return -1; /* exits the loop */
336
0
            }
337
0
        } else {
338
0
            ossl_cmp_info(ctx, "received ip/cp/kup after polling");
339
            /* any other body type has been rejected by send_receive_check() */
340
0
            break;
341
0
        }
342
0
    }
343
0
    if (prep == NULL)
344
0
        goto err;
345
346
0
    OSSL_CMP_MSG_free(preq);
347
0
    *rep = prep;
348
349
0
    return 1;
350
181
err:
351
181
    OSSL_CMP_MSG_free(preq);
352
181
    OSSL_CMP_MSG_free(prep);
353
181
    return 0;
354
0
}
355
356
/*
357
 * Send certConf for IR, CR or KUR sequences and check response,
358
 * not modifying ctx->status during the certConf exchange
359
 */
360
int ossl_cmp_exchange_certConf(OSSL_CMP_CTX *ctx, int certReqId,
361
    int fail_info, const char *txt)
362
0
{
363
0
    OSSL_CMP_MSG *certConf;
364
0
    OSSL_CMP_MSG *PKIconf = NULL;
365
0
    int res = 0;
366
367
    /* OSSL_CMP_certConf_new() also checks if all necessary options are set */
368
0
    certConf = ossl_cmp_certConf_new(ctx, certReqId, fail_info, txt);
369
0
    if (certConf == NULL)
370
0
        goto err;
371
372
0
    res = send_receive_check(ctx, certConf, &PKIconf, OSSL_CMP_PKIBODY_PKICONF);
373
374
0
err:
375
0
    OSSL_CMP_MSG_free(certConf);
376
0
    OSSL_CMP_MSG_free(PKIconf);
377
0
    return res;
378
0
}
379
380
/* Send given error and check response */
381
int ossl_cmp_exchange_error(OSSL_CMP_CTX *ctx, int status, int fail_info,
382
    const char *txt, int errorCode, const char *details)
383
0
{
384
0
    OSSL_CMP_MSG *error = NULL;
385
0
    OSSL_CMP_PKISI *si = NULL;
386
0
    OSSL_CMP_MSG *PKIconf = NULL;
387
0
    int res = 0;
388
389
    /* not overwriting ctx->status on error exchange */
390
0
    if ((si = OSSL_CMP_STATUSINFO_new(status, fail_info, txt)) == NULL)
391
0
        goto err;
392
    /* ossl_cmp_error_new() also checks if all necessary options are set */
393
0
    if ((error = ossl_cmp_error_new(ctx, si, errorCode, details, 0)) == NULL)
394
0
        goto err;
395
396
0
    res = send_receive_check(ctx, error, &PKIconf, OSSL_CMP_PKIBODY_PKICONF);
397
398
0
err:
399
0
    OSSL_CMP_MSG_free(error);
400
0
    OSSL_CMP_PKISI_free(si);
401
0
    OSSL_CMP_MSG_free(PKIconf);
402
0
    return res;
403
0
}
404
405
/*-
406
 * Retrieve a copy of the certificate, if any, from the given CertResponse.
407
 * Take into account PKIStatusInfo of CertResponse in ctx, report it on error.
408
 * Returns NULL if not found or on error.
409
 */
410
static X509 *get1_cert_status(OSSL_CMP_CTX *ctx, int bodytype,
411
    OSSL_CMP_CERTRESPONSE *crep)
412
0
{
413
0
    char buf[OSSL_CMP_PKISI_BUFLEN];
414
0
    X509 *crt = NULL;
415
416
0
    if (!ossl_assert(ctx != NULL && crep != NULL))
417
0
        return NULL;
418
419
0
    switch (ossl_cmp_pkisi_get_status(crep->status)) {
420
0
    case OSSL_CMP_PKISTATUS_waiting:
421
0
        ossl_cmp_err(ctx,
422
0
            "received \"waiting\" status for cert when actually aiming to extract cert");
423
0
        ERR_raise(ERR_LIB_CMP, CMP_R_ENCOUNTERED_WAITING);
424
0
        goto err;
425
0
    case OSSL_CMP_PKISTATUS_grantedWithMods:
426
0
        ossl_cmp_warn(ctx, "received \"grantedWithMods\" for certificate");
427
0
        break;
428
0
    case OSSL_CMP_PKISTATUS_accepted:
429
0
        break;
430
        /* get all information in case of a rejection before going to error */
431
0
    case OSSL_CMP_PKISTATUS_rejection:
432
0
        ossl_cmp_err(ctx, "received \"rejection\" status rather than cert");
433
0
        ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_REJECTED_BY_SERVER);
434
0
        goto err;
435
0
    case OSSL_CMP_PKISTATUS_revocationWarning:
436
0
        ossl_cmp_warn(ctx,
437
0
            "received \"revocationWarning\" - a revocation of the cert is imminent");
438
0
        break;
439
0
    case OSSL_CMP_PKISTATUS_revocationNotification:
440
0
        ossl_cmp_warn(ctx,
441
0
            "received \"revocationNotification\" - a revocation of the cert has occurred");
442
0
        break;
443
0
    case OSSL_CMP_PKISTATUS_keyUpdateWarning:
444
0
        if (bodytype != OSSL_CMP_PKIBODY_KUR) {
445
0
            ERR_raise(ERR_LIB_CMP, CMP_R_ENCOUNTERED_KEYUPDATEWARNING);
446
0
            goto err;
447
0
        }
448
0
        break;
449
0
    default:
450
0
        ossl_cmp_log1(ERROR, ctx,
451
0
            "received unsupported PKIStatus %d for certificate",
452
0
            ctx->status);
453
0
        ERR_raise(ERR_LIB_CMP, CMP_R_UNKNOWN_PKISTATUS);
454
0
        goto err;
455
0
    }
456
0
    crt = ossl_cmp_certresponse_get1_cert(ctx, crep);
457
0
    if (crt == NULL) /* according to PKIStatus, we can expect a cert */
458
0
        ERR_raise(ERR_LIB_CMP, CMP_R_CERTIFICATE_NOT_FOUND);
459
460
0
    return crt;
461
462
0
err:
463
0
    if (OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf, sizeof(buf)) != NULL)
464
0
        ERR_add_error_data(1, buf);
465
0
    return NULL;
466
0
}
467
468
/*-
469
 * Callback fn validating that the new certificate can be verified, using
470
 * ctx->certConf_cb_arg, which has been initialized using opt_out_trusted, and
471
 * ctx->untrusted, which at this point already contains msg->extraCerts.
472
 * Returns 0 on acceptance, else a bit field reflecting PKIFailureInfo.
473
 * Quoting from RFC 4210 section 5.1. Overall PKI Message:
474
 *     The extraCerts field can contain certificates that may be useful to
475
 *     the recipient.  For example, this can be used by a CA or RA to
476
 *     present an end entity with certificates that it needs to verify its
477
 *     own new certificate (if, for example, the CA that issued the end
478
 *     entity's certificate is not a root CA for the end entity).  Note that
479
 *     this field does not necessarily contain a certification path; the
480
 *     recipient may have to sort, select from, or otherwise process the
481
 *     extra certificates in order to use them.
482
 * Note: While often handy, there is no hard requirement by CMP that
483
 * an EE must be able to validate the certificates it gets enrolled.
484
 */
485
int OSSL_CMP_certConf_cb(OSSL_CMP_CTX *ctx, X509 *cert, int fail_info,
486
    const char **text)
487
0
{
488
0
    X509_STORE *out_trusted = OSSL_CMP_CTX_get_certConf_cb_arg(ctx);
489
0
    STACK_OF(X509) *chain = NULL;
490
0
    (void)text; /* make (artificial) use of var to prevent compiler warning */
491
492
0
    if (fail_info != 0) /* accept any error flagged by CMP core library */
493
0
        return fail_info;
494
495
0
    if (out_trusted == NULL) {
496
0
        ossl_cmp_debug(ctx, "trying to build chain for newly enrolled cert");
497
0
        chain = X509_build_chain(cert, ctx->untrusted, out_trusted,
498
0
            0, ctx->libctx, ctx->propq);
499
0
    } else {
500
0
        X509_STORE_CTX *csc = X509_STORE_CTX_new_ex(ctx->libctx, ctx->propq);
501
502
0
        ossl_cmp_debug(ctx, "validating newly enrolled cert");
503
0
        if (csc == NULL)
504
0
            goto err;
505
0
        if (!X509_STORE_CTX_init(csc, out_trusted, cert, ctx->untrusted))
506
0
            goto err;
507
        /* disable any cert status/revocation checking etc. */
508
0
        X509_VERIFY_PARAM_clear_flags(X509_STORE_CTX_get0_param(csc),
509
0
            ~(X509_V_FLAG_USE_CHECK_TIME
510
0
                | X509_V_FLAG_NO_CHECK_TIME
511
0
                | X509_V_FLAG_PARTIAL_CHAIN
512
0
                | X509_V_FLAG_POLICY_CHECK));
513
0
        if (X509_verify_cert(csc) <= 0)
514
0
            goto err;
515
516
0
        if (!ossl_x509_add_certs_new(&chain, X509_STORE_CTX_get0_chain(csc),
517
0
                X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
518
0
                    | X509_ADD_FLAG_NO_SS)) {
519
0
            sk_X509_free(chain);
520
0
            chain = NULL;
521
0
        }
522
0
    err:
523
0
        X509_STORE_CTX_free(csc);
524
0
    }
525
526
0
    if (sk_X509_num(chain) > 0)
527
0
        X509_free(sk_X509_shift(chain)); /* remove leaf (EE) cert */
528
0
    if (out_trusted != NULL) {
529
0
        if (chain == NULL) {
530
0
            ossl_cmp_err(ctx, "failed to validate newly enrolled cert");
531
0
            fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_incorrectData;
532
0
        } else {
533
0
            ossl_cmp_debug(ctx,
534
0
                "success validating newly enrolled cert");
535
0
        }
536
0
    } else if (chain == NULL) {
537
0
        ossl_cmp_warn(ctx, "could not build approximate chain for newly enrolled cert, resorting to received extraCerts");
538
0
        chain = OSSL_CMP_CTX_get1_extraCertsIn(ctx);
539
0
    } else {
540
0
        ossl_cmp_debug(ctx,
541
0
            "success building approximate chain for newly enrolled cert");
542
0
    }
543
0
    (void)ossl_cmp_ctx_set1_newChain(ctx, chain);
544
0
    sk_X509_pop_free(chain, X509_free);
545
546
0
    return fail_info;
547
0
}
548
549
/*-
550
 * Perform the generic handling of certificate responses for IR/CR/KUR/P10CR.
551
 * |rid| must be OSSL_CMP_CERTREQID_NONE if not available, namely for p10cr
552
 * Returns -1 on receiving pollRep if sleep == 0, setting the checkAfter value.
553
 * Returns 1 on success and provides the received PKIMESSAGE in *resp.
554
 * Returns 0 on error (which includes the case that timeout has been reached).
555
 * Regardless of success, caller is responsible for freeing *resp (unless NULL).
556
 */
557
static int cert_response(OSSL_CMP_CTX *ctx, int sleep, int rid,
558
    OSSL_CMP_MSG **resp, int *checkAfter,
559
    int req_type, int expected_type)
560
0
{
561
0
    EVP_PKEY *rkey = ossl_cmp_ctx_get0_newPubkey(ctx);
562
0
    int fail_info = 0; /* no failure */
563
0
    const char *txt = NULL;
564
0
    OSSL_CMP_CERTREPMESSAGE *crepmsg;
565
0
    OSSL_CMP_CERTRESPONSE *crep;
566
0
    OSSL_CMP_certConf_cb_t cb;
567
0
    X509 *cert;
568
0
    char *subj = NULL;
569
0
    int ret = 1;
570
571
0
    if (!ossl_assert(ctx != NULL))
572
0
        return 0;
573
574
0
retry:
575
0
    crepmsg = (*resp)->body->value.ip; /* same for cp and kup */
576
0
    if (sk_OSSL_CMP_CERTRESPONSE_num(crepmsg->response) > 1) {
577
0
        ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED);
578
0
        return 0;
579
0
    }
580
0
    crep = ossl_cmp_certrepmessage_get0_certresponse(crepmsg, rid);
581
0
    if (crep == NULL)
582
0
        return 0;
583
0
    if (!save_statusInfo(ctx, crep->status))
584
0
        return 0;
585
0
    if (rid == OSSL_CMP_CERTREQID_NONE) { /* used for OSSL_CMP_PKIBODY_P10CR */
586
0
        rid = ossl_cmp_asn1_get_int(crep->certReqId);
587
0
        if (rid < OSSL_CMP_CERTREQID_NONE) {
588
0
            ERR_raise(ERR_LIB_CMP, CMP_R_BAD_REQUEST_ID);
589
0
            return 0;
590
0
        }
591
0
    }
592
593
0
    if (ossl_cmp_pkisi_get_status(crep->status) == OSSL_CMP_PKISTATUS_waiting) {
594
0
        OSSL_CMP_MSG_free(*resp);
595
0
        *resp = NULL;
596
0
        if ((ret = poll_for_response(ctx, sleep, rid, resp, checkAfter)) != 0) {
597
0
            if (ret == -1) /* at this point implies sleep == 0 */
598
0
                return ret; /* waiting */
599
0
            goto retry; /* got ip/cp/kup, which may still indicate 'waiting' */
600
0
        } else {
601
0
            ERR_raise(ERR_LIB_CMP, CMP_R_POLLING_FAILED);
602
0
            return 0;
603
0
        }
604
0
    }
605
606
0
    cert = get1_cert_status(ctx, (*resp)->body->type, crep);
607
0
    if (cert == NULL) {
608
0
        ERR_add_error_data(1, "; cannot extract certificate from response");
609
0
        return 0;
610
0
    }
611
0
    if (!ossl_cmp_ctx_set0_newCert(ctx, cert)) {
612
0
        X509_free(cert);
613
0
        return 0;
614
0
    }
615
616
    /*
617
     * if the CMP server returned certificates in the caPubs field, copy them
618
     * to the context so that they can be retrieved if necessary
619
     */
620
0
    if (crepmsg->caPubs != NULL
621
0
        && !ossl_cmp_ctx_set1_caPubs(ctx, crepmsg->caPubs))
622
0
        return 0;
623
624
0
    subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
625
0
    if (rkey != NULL
626
        /* X509_check_private_key() also works if rkey is just public key */
627
0
        && !(X509_check_private_key(ctx->newCert, rkey))) {
628
0
        fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_incorrectData;
629
0
        txt = "public key in new certificate does not match our enrollment key";
630
        /*-
631
         * not calling (void)ossl_cmp_exchange_error(ctx,
632
         *                   OSSL_CMP_PKISTATUS_rejection, fail_info, txt)
633
         * not throwing CMP_R_CERTIFICATE_NOT_ACCEPTED with txt
634
         * not returning 0
635
         * since we better leave this for the certConf_cb to decide
636
         */
637
0
    }
638
639
    /*
640
     * Execute the certification checking callback function,
641
     * which can determine whether to accept a newly enrolled certificate.
642
     * It may overrule the pre-decision reflected in 'fail_info' and '*txt'.
643
     */
644
0
    cb = ctx->certConf_cb != NULL ? ctx->certConf_cb : OSSL_CMP_certConf_cb;
645
0
    if ((fail_info = cb(ctx, ctx->newCert, fail_info, &txt)) != 0
646
0
        && txt == NULL)
647
0
        txt = "CMP client did not accept it";
648
0
    if (fail_info != 0) /* immediately log error before any certConf exchange */
649
0
        ossl_cmp_log1(ERROR, ctx,
650
0
            "rejecting newly enrolled cert with subject: %s", subj);
651
0
    if (!ctx->disableConfirm
652
0
        && !ossl_cmp_hdr_has_implicitConfirm((*resp)->header)) {
653
0
        if (!ossl_cmp_exchange_certConf(ctx, rid, fail_info, txt))
654
0
            ret = 0;
655
0
    }
656
657
    /* not throwing failure earlier as transfer_cb may call ERR_clear_error() */
658
0
    if (fail_info != 0) {
659
0
        ERR_raise_data(ERR_LIB_CMP, CMP_R_CERTIFICATE_NOT_ACCEPTED,
660
0
            "rejecting newly enrolled cert with subject: %s; %s",
661
0
            subj, txt);
662
0
        ctx->status = OSSL_CMP_PKISTATUS_rejection;
663
0
        ret = 0;
664
0
    }
665
0
    OPENSSL_free(subj);
666
0
    return ret;
667
0
}
668
669
static int initial_certreq(OSSL_CMP_CTX *ctx,
670
    int req_type, const OSSL_CRMF_MSG *crm,
671
    OSSL_CMP_MSG **p_rep, int rep_type)
672
1.25k
{
673
1.25k
    OSSL_CMP_MSG *req;
674
1.25k
    int res;
675
676
1.25k
    ctx->status = OSSL_CMP_PKISTATUS_request;
677
1.25k
    if (!ossl_cmp_ctx_set0_newCert(ctx, NULL))
678
0
        return 0;
679
680
    /* also checks if all necessary options are set */
681
1.25k
    if ((req = ossl_cmp_certreq_new(ctx, req_type, crm)) == NULL)
682
1.25k
        return 0;
683
684
0
    ctx->status = OSSL_CMP_PKISTATUS_trans;
685
0
    res = send_receive_check(ctx, req, p_rep, rep_type);
686
0
    OSSL_CMP_MSG_free(req);
687
0
    return res;
688
1.25k
}
689
690
int OSSL_CMP_try_certreq(OSSL_CMP_CTX *ctx, int req_type,
691
    const OSSL_CRMF_MSG *crm, int *checkAfter)
692
181
{
693
181
    OSSL_CMP_MSG *rep = NULL;
694
181
    int is_p10 = req_type == OSSL_CMP_PKIBODY_P10CR;
695
181
    int rid = is_p10 ? OSSL_CMP_CERTREQID_NONE : OSSL_CMP_CERTREQID;
696
181
    int rep_type = is_p10 ? OSSL_CMP_PKIBODY_CP : req_type + 1;
697
181
    int res = 0;
698
699
181
    if (ctx == NULL) {
700
0
        ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
701
0
        return 0;
702
0
    }
703
704
181
    if (ctx->status != OSSL_CMP_PKISTATUS_waiting) { /* not polling already */
705
0
        if (!initial_certreq(ctx, req_type, crm, &rep, rep_type))
706
0
            goto err;
707
181
    } else {
708
181
        if (req_type < 0)
709
0
            return ossl_cmp_exchange_error(ctx, OSSL_CMP_PKISTATUS_rejection,
710
0
                0, "polling aborted",
711
0
                0 /* errorCode */, "by application");
712
181
        res = poll_for_response(ctx, 0 /* no sleep */, rid, &rep, checkAfter);
713
181
        if (res <= 0) /* waiting or error */
714
181
            return res;
715
181
    }
716
0
    res = cert_response(ctx, 0 /* no sleep */, rid, &rep, checkAfter,
717
0
        req_type, rep_type);
718
719
0
err:
720
0
    OSSL_CMP_MSG_free(rep);
721
0
    return res;
722
0
}
723
724
/*-
725
 * Do the full sequence CR/IR/KUR/P10CR, CP/IP/KUP/CP,
726
 * certConf, PKIconf, and polling if required.
727
 * Will sleep as long as indicated by the server (according to checkAfter).
728
 * All enrollment options need to be present in the context.
729
 * Returns pointer to received certificate, or NULL if none was received.
730
 */
731
X509 *OSSL_CMP_exec_certreq(OSSL_CMP_CTX *ctx, int req_type,
732
    const OSSL_CRMF_MSG *crm)
733
199
{
734
735
199
    OSSL_CMP_MSG *rep = NULL;
736
199
    int is_p10 = req_type == OSSL_CMP_PKIBODY_P10CR;
737
199
    int rid = is_p10 ? OSSL_CMP_CERTREQID_NONE : OSSL_CMP_CERTREQID;
738
199
    int rep_type = is_p10 ? OSSL_CMP_PKIBODY_CP : req_type + 1;
739
199
    X509 *result = NULL;
740
741
199
    if (ctx == NULL) {
742
0
        ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
743
0
        return NULL;
744
0
    }
745
746
199
    if (!initial_certreq(ctx, req_type, crm, &rep, rep_type))
747
199
        goto err;
748
749
0
    if (cert_response(ctx, 1 /* sleep */, rid, &rep, NULL, req_type, rep_type)
750
0
        <= 0)
751
0
        goto err;
752
753
0
    result = ctx->newCert;
754
199
err:
755
199
    OSSL_CMP_MSG_free(rep);
756
199
    return result;
757
0
}
758
759
int OSSL_CMP_exec_RR_ses(OSSL_CMP_CTX *ctx)
760
38
{
761
38
    OSSL_CMP_MSG *rr = NULL;
762
38
    OSSL_CMP_MSG *rp = NULL;
763
38
    const int num_RevDetails = 1;
764
38
    const int rsid = OSSL_CMP_REVREQSID;
765
38
    OSSL_CMP_REVREPCONTENT *rrep = NULL;
766
38
    OSSL_CMP_PKISI *si = NULL;
767
38
    char buf[OSSL_CMP_PKISI_BUFLEN];
768
38
    int ret = 0;
769
770
38
    if (ctx == NULL) {
771
0
        ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS);
772
0
        return 0;
773
0
    }
774
38
    ctx->status = OSSL_CMP_PKISTATUS_request;
775
38
    if (ctx->oldCert == NULL && ctx->p10CSR == NULL) {
776
0
        ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_REFERENCE_CERT);
777
0
        return 0;
778
0
    }
779
780
    /* OSSL_CMP_rr_new() also checks if all necessary options are set */
781
38
    if ((rr = ossl_cmp_rr_new(ctx)) == NULL)
782
38
        goto end;
783
784
0
    ctx->status = OSSL_CMP_PKISTATUS_trans;
785
0
    if (!send_receive_check(ctx, rr, &rp, OSSL_CMP_PKIBODY_RP))
786
0
        goto end;
787
788
0
    rrep = rp->body->value.rp;
789
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
790
    if (sk_OSSL_CMP_PKISI_num(rrep->status) != num_RevDetails) {
791
        ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT);
792
        goto end;
793
    }
794
#else
795
0
    if (sk_OSSL_CMP_PKISI_num(rrep->status) < 1) {
796
0
        ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT);
797
0
        goto end;
798
0
    }
799
0
#endif
800
801
    /* evaluate PKIStatus field */
802
0
    si = ossl_cmp_revrepcontent_get_pkisi(rrep, rsid);
803
0
    if (!save_statusInfo(ctx, si))
804
0
        goto err;
805
0
    switch (ossl_cmp_pkisi_get_status(si)) {
806
0
    case OSSL_CMP_PKISTATUS_accepted:
807
0
        ossl_cmp_info(ctx, "revocation accepted (PKIStatus=accepted)");
808
0
        ret = 1;
809
0
        break;
810
0
    case OSSL_CMP_PKISTATUS_grantedWithMods:
811
0
        ossl_cmp_info(ctx, "revocation accepted (PKIStatus=grantedWithMods)");
812
0
        ret = 1;
813
0
        break;
814
0
    case OSSL_CMP_PKISTATUS_rejection:
815
0
        ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_REJECTED_BY_SERVER);
816
0
        goto err;
817
0
    case OSSL_CMP_PKISTATUS_revocationWarning:
818
0
        ossl_cmp_info(ctx, "revocation accepted (PKIStatus=revocationWarning)");
819
0
        ret = 1;
820
0
        break;
821
0
    case OSSL_CMP_PKISTATUS_revocationNotification:
822
        /* interpretation as warning or error depends on CA */
823
0
        ossl_cmp_warn(ctx,
824
0
            "revocation accepted (PKIStatus=revocationNotification)");
825
0
        ret = 1;
826
0
        break;
827
0
    case OSSL_CMP_PKISTATUS_waiting:
828
0
    case OSSL_CMP_PKISTATUS_keyUpdateWarning:
829
0
        ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKISTATUS);
830
0
        goto err;
831
0
    default:
832
0
        ERR_raise(ERR_LIB_CMP, CMP_R_UNKNOWN_PKISTATUS);
833
0
        goto err;
834
0
    }
835
836
    /* check any present CertId in optional revCerts field */
837
0
    if (sk_OSSL_CRMF_CERTID_num(rrep->revCerts) >= 1) {
838
0
        OSSL_CRMF_CERTID *cid;
839
0
        OSSL_CRMF_CERTTEMPLATE *tmpl = sk_OSSL_CMP_REVDETAILS_value(rr->body->value.rr, rsid)->certDetails;
840
0
        const X509_NAME *issuer = OSSL_CRMF_CERTTEMPLATE_get0_issuer(tmpl);
841
0
        const ASN1_INTEGER *serial = OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(tmpl);
842
843
0
        if (sk_OSSL_CRMF_CERTID_num(rrep->revCerts) != num_RevDetails) {
844
0
            ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT);
845
0
            ret = 0;
846
0
            goto err;
847
0
        }
848
0
        if ((cid = ossl_cmp_revrepcontent_get_CertId(rrep, rsid)) == NULL) {
849
0
            ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_CERTID);
850
0
            ret = 0;
851
0
            goto err;
852
0
        }
853
0
        if (X509_NAME_cmp(issuer, OSSL_CRMF_CERTID_get0_issuer(cid)) != 0) {
854
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
855
            ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_CERTID_IN_RP);
856
            ret = 0;
857
            goto err;
858
#endif
859
0
        }
860
0
        if (ASN1_INTEGER_cmp(serial,
861
0
                OSSL_CRMF_CERTID_get0_serialNumber(cid))
862
0
            != 0) {
863
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
864
            ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_SERIAL_IN_RP);
865
            ret = 0;
866
            goto err;
867
#endif
868
0
        }
869
0
    }
870
871
    /* check number of any optionally present crls */
872
0
    if (rrep->crls != NULL && sk_X509_CRL_num(rrep->crls) != num_RevDetails) {
873
0
        ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_RP_COMPONENT_COUNT);
874
0
        ret = 0;
875
0
        goto err;
876
0
    }
877
878
0
err:
879
0
    if (ret == 0
880
0
        && OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf, sizeof(buf)) != NULL)
881
0
        ERR_add_error_data(1, buf);
882
883
38
end:
884
38
    OSSL_CMP_MSG_free(rr);
885
38
    OSSL_CMP_MSG_free(rp);
886
38
    return ret;
887
0
}
888
889
STACK_OF(OSSL_CMP_ITAV) *OSSL_CMP_exec_GENM_ses(OSSL_CMP_CTX *ctx)
890
1.04k
{
891
1.04k
    OSSL_CMP_MSG *genm;
892
1.04k
    OSSL_CMP_MSG *genp = NULL;
893
1.04k
    STACK_OF(OSSL_CMP_ITAV) *itavs = NULL;
894
895
1.04k
    if (ctx == NULL) {
896
0
        ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS);
897
0
        return NULL;
898
0
    }
899
1.04k
    ctx->status = OSSL_CMP_PKISTATUS_request;
900
901
1.04k
    if ((genm = ossl_cmp_genm_new(ctx)) == NULL)
902
1.04k
        goto err;
903
904
0
    ctx->status = OSSL_CMP_PKISTATUS_trans;
905
0
    if (!send_receive_check(ctx, genm, &genp, OSSL_CMP_PKIBODY_GENP))
906
0
        goto err;
907
0
    ctx->status = OSSL_CMP_PKISTATUS_accepted;
908
909
0
    itavs = genp->body->value.genp;
910
0
    if (itavs == NULL)
911
0
        itavs = sk_OSSL_CMP_ITAV_new_null();
912
    /* received stack of itavs not to be freed with the genp */
913
0
    genp->body->value.genp = NULL;
914
915
1.04k
err:
916
1.04k
    OSSL_CMP_MSG_free(genm);
917
1.04k
    OSSL_CMP_MSG_free(genp);
918
919
1.04k
    return itavs; /* NULL indicates error case */
920
0
}