Coverage Report

Created: 2023-09-25 06:45

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