Coverage Report

Created: 2025-06-13 06:58

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