Coverage Report

Created: 2025-06-13 06:58

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