dcad9c89415f508399f44515e5a7eefa933dd44b
[openssl.git] / crypto / cmp / cmp_ctx.c
1 /*
2  * Copyright 2007-2021 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 <openssl/trace.h>
13 #include <openssl/bio.h>
14 #include <openssl/ocsp.h> /* for OCSP_REVOKED_STATUS_* */
15
16 #include "cmp_local.h"
17
18 /* explicit #includes not strictly needed since implied by the above: */
19 #include <openssl/cmp.h>
20 #include <openssl/crmf.h>
21 #include <openssl/err.h>
22
23 #define DEFINE_OSSL_CMP_CTX_get0(FIELD, TYPE) \
24     DEFINE_OSSL_CMP_CTX_get0_NAME(FIELD, FIELD, TYPE)
25 #define DEFINE_OSSL_CMP_CTX_get0_NAME(NAME, FIELD, TYPE) \
26 TYPE *OSSL_CMP_CTX_get0_##NAME(const OSSL_CMP_CTX *ctx) \
27 { \
28     if (ctx == NULL) { \
29         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \
30         return NULL; \
31     } \
32     return ctx->FIELD; \
33 }
34
35 /*
36  * Get current certificate store containing trusted root CA certs
37  */
38 DEFINE_OSSL_CMP_CTX_get0_NAME(trusted, trusted, X509_STORE)
39
40 #define DEFINE_OSSL_set0(PREFIX, FIELD, TYPE) \
41     DEFINE_OSSL_set0_NAME(PREFIX, FIELD, FIELD, TYPE)
42 #define DEFINE_OSSL_set0_NAME(PREFIX, NAME, FIELD, TYPE) \
43 int PREFIX##_set0##_##NAME(OSSL_CMP_CTX *ctx, TYPE *val) \
44 { \
45     if (ctx == NULL) { \
46         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \
47         return 0; \
48     } \
49     TYPE##_free(ctx->FIELD); \
50     ctx->FIELD = val; \
51     return 1; \
52 }
53
54 /*
55  * Set certificate store containing trusted (root) CA certs and possibly CRLs
56  * and a cert verification callback function used for CMP server authentication.
57  * Any already existing store entry is freed. Given NULL, the entry is reset.
58  */
59 DEFINE_OSSL_set0_NAME(OSSL_CMP_CTX, trusted, trusted, X509_STORE)
60
61 DEFINE_OSSL_CMP_CTX_get0(libctx, OSSL_LIB_CTX)
62 DEFINE_OSSL_CMP_CTX_get0(propq, const char)
63
64 /* Get current list of non-trusted intermediate certs */
65 DEFINE_OSSL_CMP_CTX_get0(untrusted, STACK_OF(X509))
66
67 /*
68  * Set untrusted certificates for path construction in authentication of
69  * the CMP server and potentially others (TLS server, newly enrolled cert).
70  */
71 int OSSL_CMP_CTX_set1_untrusted(OSSL_CMP_CTX *ctx, STACK_OF(X509) *certs)
72 {
73     STACK_OF(X509) *untrusted = NULL;
74
75     if (ctx == NULL) {
76         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
77         return 0;
78     }
79     if (!ossl_x509_add_certs_new(&untrusted, certs,
80                                  X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
81         goto err;
82     OSSL_STACK_OF_X509_free(ctx->untrusted);
83     ctx->untrusted = untrusted;
84     return 1;
85  err:
86     OSSL_STACK_OF_X509_free(untrusted);
87     return 0;
88 }
89
90 static int cmp_ctx_set_md(OSSL_CMP_CTX *ctx, EVP_MD **pmd, int nid)
91 {
92     EVP_MD *md = EVP_MD_fetch(ctx->libctx, OBJ_nid2sn(nid), ctx->propq);
93     /* fetching in advance to be able to throw error early if unsupported */
94
95     if (md == NULL) {
96         ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_ALGORITHM);
97         return 0;
98     }
99     EVP_MD_free(*pmd);
100     *pmd = md;
101     return 1;
102 }
103
104 /*
105  * Allocates and initializes OSSL_CMP_CTX context structure with default values.
106  * Returns new context on success, NULL on error
107  */
108 OSSL_CMP_CTX *OSSL_CMP_CTX_new(OSSL_LIB_CTX *libctx, const char *propq)
109 {
110     OSSL_CMP_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
111
112     if (ctx == NULL)
113         goto err;
114
115     ctx->libctx = libctx;
116     if (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL)
117         goto err;
118
119     ctx->log_verbosity = OSSL_CMP_LOG_INFO;
120
121     ctx->status = OSSL_CMP_PKISTATUS_unspecified;
122     ctx->failInfoCode = -1;
123
124     ctx->keep_alive = 1;
125     ctx->msg_timeout = -1;
126
127     if ((ctx->untrusted = sk_X509_new_null()) == NULL) {
128         ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
129         goto err;
130     }
131
132     ctx->pbm_slen = 16;
133     if (!cmp_ctx_set_md(ctx, &ctx->pbm_owf, NID_sha256))
134         goto err;
135     ctx->pbm_itercnt = 500;
136     ctx->pbm_mac = NID_hmac_sha1;
137
138     if (!cmp_ctx_set_md(ctx, &ctx->digest, NID_sha256))
139         goto err;
140     ctx->popoMethod = OSSL_CRMF_POPO_SIGNATURE;
141     ctx->revocationReason = CRL_REASON_NONE;
142
143     /* all other elements are initialized to 0 or NULL, respectively */
144     return ctx;
145
146  err:
147     OSSL_CMP_CTX_free(ctx);
148     return NULL;
149 }
150
151 #define OSSL_CMP_ITAVs_free(itavs) \
152     sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free);
153 #define X509_EXTENSIONS_free(exts) \
154     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free)
155 #define OSSL_CMP_PKIFREETEXT_free(text) \
156     sk_ASN1_UTF8STRING_pop_free(text, ASN1_UTF8STRING_free)
157
158 /* Prepare the OSSL_CMP_CTX for next use, partly re-initializing OSSL_CMP_CTX */
159 int OSSL_CMP_CTX_reinit(OSSL_CMP_CTX *ctx)
160 {
161     if (ctx == NULL) {
162         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
163         return 0;
164     }
165
166     if (ctx->http_ctx != NULL) {
167         (void)OSSL_HTTP_close(ctx->http_ctx, 1);
168         ossl_cmp_debug(ctx, "disconnected from CMP server");
169         ctx->http_ctx = NULL;
170     }
171     ctx->status = OSSL_CMP_PKISTATUS_unspecified;
172     ctx->failInfoCode = -1;
173
174     OSSL_CMP_ITAVs_free(ctx->genm_ITAVs);
175     ctx->genm_ITAVs = NULL;
176
177     return ossl_cmp_ctx_set0_statusString(ctx, NULL)
178         && ossl_cmp_ctx_set0_newCert(ctx, NULL)
179         && ossl_cmp_ctx_set1_newChain(ctx, NULL)
180         && ossl_cmp_ctx_set1_caPubs(ctx, NULL)
181         && ossl_cmp_ctx_set1_extraCertsIn(ctx, NULL)
182         && ossl_cmp_ctx_set1_validatedSrvCert(ctx, NULL)
183         && OSSL_CMP_CTX_set1_transactionID(ctx, NULL)
184         && OSSL_CMP_CTX_set1_senderNonce(ctx, NULL)
185         && ossl_cmp_ctx_set1_recipNonce(ctx, NULL);
186 }
187
188 /* Frees OSSL_CMP_CTX variables allocated in OSSL_CMP_CTX_new() */
189 void OSSL_CMP_CTX_free(OSSL_CMP_CTX *ctx)
190 {
191     if (ctx == NULL)
192         return;
193
194     if (ctx->http_ctx != NULL) {
195         (void)OSSL_HTTP_close(ctx->http_ctx, 1);
196         ossl_cmp_debug(ctx, "disconnected from CMP server");
197     }
198     OPENSSL_free(ctx->propq);
199     OPENSSL_free(ctx->serverPath);
200     OPENSSL_free(ctx->server);
201     OPENSSL_free(ctx->proxy);
202     OPENSSL_free(ctx->no_proxy);
203
204     X509_free(ctx->srvCert);
205     X509_free(ctx->validatedSrvCert);
206     X509_NAME_free(ctx->expected_sender);
207     X509_STORE_free(ctx->trusted);
208     OSSL_STACK_OF_X509_free(ctx->untrusted);
209
210     X509_free(ctx->cert);
211     OSSL_STACK_OF_X509_free(ctx->chain);
212     EVP_PKEY_free(ctx->pkey);
213     ASN1_OCTET_STRING_free(ctx->referenceValue);
214     if (ctx->secretValue != NULL)
215         OPENSSL_cleanse(ctx->secretValue->data, ctx->secretValue->length);
216     ASN1_OCTET_STRING_free(ctx->secretValue);
217     EVP_MD_free(ctx->pbm_owf);
218
219     X509_NAME_free(ctx->recipient);
220     EVP_MD_free(ctx->digest);
221     ASN1_OCTET_STRING_free(ctx->transactionID);
222     ASN1_OCTET_STRING_free(ctx->senderNonce);
223     ASN1_OCTET_STRING_free(ctx->recipNonce);
224     OSSL_CMP_ITAVs_free(ctx->geninfo_ITAVs);
225     OSSL_STACK_OF_X509_free(ctx->extraCertsOut);
226
227     EVP_PKEY_free(ctx->newPkey);
228     X509_NAME_free(ctx->issuer);
229     X509_NAME_free(ctx->subjectName);
230     sk_GENERAL_NAME_pop_free(ctx->subjectAltNames, GENERAL_NAME_free);
231     X509_EXTENSIONS_free(ctx->reqExtensions);
232     sk_POLICYINFO_pop_free(ctx->policies, POLICYINFO_free);
233     X509_free(ctx->oldCert);
234     X509_REQ_free(ctx->p10CSR);
235
236     OSSL_CMP_ITAVs_free(ctx->genm_ITAVs);
237
238     OSSL_CMP_PKIFREETEXT_free(ctx->statusString);
239     X509_free(ctx->newCert);
240     OSSL_STACK_OF_X509_free(ctx->newChain);
241     OSSL_STACK_OF_X509_free(ctx->caPubs);
242     OSSL_STACK_OF_X509_free(ctx->extraCertsIn);
243
244     OPENSSL_free(ctx);
245 }
246
247 #define DEFINE_OSSL_set(PREFIX, FIELD, TYPE) \
248 int PREFIX##_set_##FIELD(OSSL_CMP_CTX *ctx, TYPE val) \
249 { \
250     if (ctx == NULL) { \
251         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \
252         return 0; \
253     } \
254     ctx->FIELD = val; \
255     return 1; \
256 }
257
258 DEFINE_OSSL_set(ossl_cmp_ctx, status, int)
259
260 #define DEFINE_OSSL_get(PREFIX, FIELD, TYPE, ERR_RET) \
261 TYPE PREFIX##_get_##FIELD(const OSSL_CMP_CTX *ctx) \
262 { \
263     if (ctx == NULL) { \
264         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \
265         return ERR_RET; \
266     } \
267     return ctx->FIELD; \
268 }
269
270 /*
271  * Returns the PKIStatus from the last CertRepMessage
272  * or Revocation Response or error message, -1 on error
273  */
274 DEFINE_OSSL_get(OSSL_CMP_CTX, status, int, -1)
275
276 /*
277  * Returns the statusString from the last CertRepMessage
278  * or Revocation Response or error message, NULL on error
279  */
280 DEFINE_OSSL_CMP_CTX_get0(statusString, OSSL_CMP_PKIFREETEXT)
281
282 DEFINE_OSSL_set0(ossl_cmp_ctx, statusString, OSSL_CMP_PKIFREETEXT)
283
284 /* Set callback function for checking if the cert is ok or should be rejected */
285 DEFINE_OSSL_set(OSSL_CMP_CTX, certConf_cb, OSSL_CMP_certConf_cb_t)
286
287 /*
288  * Set argument, respectively a pointer to a structure containing arguments,
289  * optionally to be used by the certConf callback.
290  */
291 DEFINE_OSSL_set(OSSL_CMP_CTX, certConf_cb_arg, void *)
292
293 /*
294  * Get argument, respectively the pointer to a structure containing arguments,
295  * optionally to be used by certConf callback.
296  * Returns callback argument set previously (NULL if not set or on error)
297  */
298 DEFINE_OSSL_get(OSSL_CMP_CTX, certConf_cb_arg, void *, NULL)
299
300 #ifndef OPENSSL_NO_TRACE
301 static size_t ossl_cmp_log_trace_cb(const char *buf, size_t cnt,
302                                     int category, int cmd, void *vdata)
303 {
304     OSSL_CMP_CTX *ctx = vdata;
305     const char *msg;
306     OSSL_CMP_severity level = -1;
307     char *func = NULL;
308     char *file = NULL;
309     int line = 0;
310
311     if (buf == NULL || cnt == 0 || cmd != OSSL_TRACE_CTRL_WRITE || ctx == NULL)
312         return 0;
313     if (ctx->log_cb == NULL)
314         return 1; /* silently drop message */
315
316     msg = ossl_cmp_log_parse_metadata(buf, &level, &func, &file, &line);
317
318     if (level > ctx->log_verbosity) /* excludes the case level is unknown */
319         goto end; /* suppress output since severity is not sufficient */
320
321     if (!ctx->log_cb(func != NULL ? func : "(no func)",
322                      file != NULL ? file : "(no file)",
323                      line, level, msg))
324         cnt = 0;
325
326  end:
327     OPENSSL_free(func);
328     OPENSSL_free(file);
329     return cnt;
330 }
331 #endif
332
333 /* Print CMP log messages (i.e., diagnostic info) via the log cb of the ctx */
334 int ossl_cmp_print_log(OSSL_CMP_severity level, const OSSL_CMP_CTX *ctx,
335                        const char *func, const char *file, int line,
336                        const char *level_str, const char *format, ...)
337 {
338     va_list args;
339     char hugebuf[1024 * 2];
340     int res = 0;
341
342     if (ctx == NULL || ctx->log_cb == NULL)
343         return 1; /* silently drop message */
344
345     if (level > ctx->log_verbosity) /* excludes the case level is unknown */
346         return 1; /* suppress output since severity is not sufficient */
347
348     if (format == NULL)
349         return 0;
350
351     va_start(args, format);
352
353     if (func == NULL)
354         func = "(unset function name)";
355     if (file == NULL)
356         file = "(unset file name)";
357     if (level_str == NULL)
358         level_str = "(unset level string)";
359
360 #ifndef OPENSSL_NO_TRACE
361     if (OSSL_TRACE_ENABLED(CMP)) {
362         OSSL_TRACE_BEGIN(CMP) {
363             int printed =
364                 BIO_snprintf(hugebuf, sizeof(hugebuf),
365                              "%s:%s:%d:" OSSL_CMP_LOG_PREFIX "%s: ",
366                              func, file, line, level_str);
367             if (printed > 0 && (size_t)printed < sizeof(hugebuf)) {
368                 if (BIO_vsnprintf(hugebuf + printed,
369                                   sizeof(hugebuf) - printed, format, args) > 0)
370                     res = BIO_puts(trc_out, hugebuf) > 0;
371             }
372         } OSSL_TRACE_END(CMP);
373     }
374 #else /* compensate for disabled trace API */
375     {
376         if (BIO_vsnprintf(hugebuf, sizeof(hugebuf), format, args) > 0)
377             res = ctx->log_cb(func, file, line, level, hugebuf);
378     }
379 #endif
380     va_end(args);
381     return res;
382 }
383
384 /* Set a callback function for error reporting and logging messages */
385 int OSSL_CMP_CTX_set_log_cb(OSSL_CMP_CTX *ctx, OSSL_CMP_log_cb_t cb)
386 {
387     if (ctx == NULL) {
388         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
389         return 0;
390     }
391     ctx->log_cb = cb;
392
393 #ifndef OPENSSL_NO_TRACE
394     /* do also in case cb == NULL, to switch off logging output: */
395     if (!OSSL_trace_set_callback(OSSL_TRACE_CATEGORY_CMP,
396                                  ossl_cmp_log_trace_cb, ctx))
397         return 0;
398 #endif
399
400     return 1;
401 }
402
403 /* Print OpenSSL and CMP errors via the log cb of the ctx or ERR_print_errors */
404 void OSSL_CMP_CTX_print_errors(const OSSL_CMP_CTX *ctx)
405 {
406     if (ctx != NULL && OSSL_CMP_LOG_ERR > ctx->log_verbosity)
407         return; /* suppress output since severity is not sufficient */
408     OSSL_CMP_print_errors_cb(ctx == NULL ? NULL : ctx->log_cb);
409 }
410
411 /*
412  * Set or clear the reference value to be used for identification
413  * (i.e., the user name) when using PBMAC.
414  */
415 int OSSL_CMP_CTX_set1_referenceValue(OSSL_CMP_CTX *ctx,
416                                      const unsigned char *ref, int len)
417 {
418     if (ctx == NULL) {
419         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
420         return 0;
421     }
422     return
423         ossl_cmp_asn1_octet_string_set1_bytes(&ctx->referenceValue, ref, len);
424 }
425
426 /* Set or clear the password to be used for protecting messages with PBMAC */
427 int OSSL_CMP_CTX_set1_secretValue(OSSL_CMP_CTX *ctx, const unsigned char *sec,
428                                   int len)
429 {
430     ASN1_OCTET_STRING *secretValue = NULL;
431
432     if (ctx == NULL) {
433         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
434         return 0;
435     }
436     if (ossl_cmp_asn1_octet_string_set1_bytes(&secretValue, sec, len) != 1)
437         return 0;
438     if (ctx->secretValue != NULL) {
439         OPENSSL_cleanse(ctx->secretValue->data, ctx->secretValue->length);
440         ASN1_OCTET_STRING_free(ctx->secretValue);
441     }
442     ctx->secretValue = secretValue;
443     return 1;
444 }
445
446 #define DEFINE_OSSL_CMP_CTX_get1_certs(FIELD) \
447 STACK_OF(X509) *OSSL_CMP_CTX_get1_##FIELD(const OSSL_CMP_CTX *ctx) \
448 { \
449     if (ctx == NULL) { \
450         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \
451         return NULL; \
452     } \
453     return X509_chain_up_ref(ctx->FIELD); \
454 }
455
456 /* Returns the cert chain computed by OSSL_CMP_certConf_cb(), NULL on error */
457 DEFINE_OSSL_CMP_CTX_get1_certs(newChain)
458
459 #define DEFINE_OSSL_set1_certs(PREFIX, FIELD) \
460 int PREFIX##_set1_##FIELD(OSSL_CMP_CTX *ctx, STACK_OF(X509) *certs) \
461 { \
462     if (ctx == NULL) { \
463         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \
464         return 0; \
465     } \
466     OSSL_STACK_OF_X509_free(ctx->FIELD); \
467     ctx->FIELD = NULL; \
468     return certs == NULL || (ctx->FIELD = X509_chain_up_ref(certs)) != NULL; \
469 }
470
471 /*
472  * Copies any given stack of inbound X509 certificates to newChain
473  * of the OSSL_CMP_CTX structure so that they may be retrieved later.
474  */
475 DEFINE_OSSL_set1_certs(ossl_cmp_ctx, newChain)
476
477 /* Returns the stack of extraCerts received in CertRepMessage, NULL on error */
478 DEFINE_OSSL_CMP_CTX_get1_certs(extraCertsIn)
479
480 /*
481  * Copies any given stack of inbound X509 certificates to extraCertsIn
482  * of the OSSL_CMP_CTX structure so that they may be retrieved later.
483  */
484 DEFINE_OSSL_set1_certs(ossl_cmp_ctx, extraCertsIn)
485
486 /*
487  * Copies any given stack as the new stack of X509
488  * certificates to send out in the extraCerts field.
489  */
490 DEFINE_OSSL_set1_certs(OSSL_CMP_CTX, extraCertsOut)
491
492 /*
493  * Add the given policy info object
494  * to the X509_EXTENSIONS of the requested certificate template.
495  */
496 int OSSL_CMP_CTX_push0_policy(OSSL_CMP_CTX *ctx, POLICYINFO *pinfo)
497 {
498     if (ctx == NULL || pinfo == NULL) {
499         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
500         return 0;
501     }
502
503     if (ctx->policies == NULL
504             && (ctx->policies = CERTIFICATEPOLICIES_new()) == NULL)
505         return 0;
506
507     return sk_POLICYINFO_push(ctx->policies, pinfo);
508 }
509
510 /* Add an ITAV for geninfo of the PKI message header */
511 int OSSL_CMP_CTX_push0_geninfo_ITAV(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *itav)
512 {
513     if (ctx == NULL) {
514         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
515         return 0;
516     }
517     return OSSL_CMP_ITAV_push0_stack_item(&ctx->geninfo_ITAVs, itav);
518 }
519
520 int OSSL_CMP_CTX_reset_geninfo_ITAVs(OSSL_CMP_CTX *ctx)
521 {
522     if (ctx == NULL) {
523         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
524         return 0;
525     }
526     OSSL_CMP_ITAVs_free(ctx->geninfo_ITAVs);
527     ctx->geninfo_ITAVs = NULL;
528     return 1;
529 }
530
531 /* Add an itav for the body of outgoing general messages */
532 int OSSL_CMP_CTX_push0_genm_ITAV(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *itav)
533 {
534     if (ctx == NULL) {
535         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
536         return 0;
537     }
538     return OSSL_CMP_ITAV_push0_stack_item(&ctx->genm_ITAVs, itav);
539 }
540
541 /*
542  * Returns a duplicate of the stack of X509 certificates that
543  * were received in the caPubs field of the last CertRepMessage.
544  * Returns NULL on error
545  */
546 DEFINE_OSSL_CMP_CTX_get1_certs(caPubs)
547
548 /*
549  * Copies any given stack of certificates to the given
550  * OSSL_CMP_CTX structure so that they may be retrieved later.
551  */
552 DEFINE_OSSL_set1_certs(ossl_cmp_ctx, caPubs)
553
554 #define char_dup OPENSSL_strdup
555 #define char_free OPENSSL_free
556 #define DEFINE_OSSL_CMP_CTX_set1(FIELD, TYPE) /* this uses _dup */ \
557 int OSSL_CMP_CTX_set1_##FIELD(OSSL_CMP_CTX *ctx, const TYPE *val) \
558 { \
559     TYPE *val_dup = NULL; \
560     \
561     if (ctx == NULL) { \
562         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \
563         return 0; \
564     } \
565     \
566     if (val != NULL && (val_dup = TYPE##_dup(val)) == NULL) \
567         return 0; \
568     TYPE##_free(ctx->FIELD); \
569     ctx->FIELD = val_dup; \
570     return 1; \
571 }
572
573 #define X509_invalid(cert) (!ossl_x509v3_cache_extensions(cert))
574 #define EVP_PKEY_invalid(key) 0
575
576 #define DEFINE_OSSL_set1_up_ref(PREFIX, FIELD, TYPE) \
577 int PREFIX##_set1_##FIELD(OSSL_CMP_CTX *ctx, TYPE *val) \
578 { \
579     if (ctx == NULL) { \
580         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \
581         return 0; \
582     } \
583     \
584     /* prevent misleading error later on malformed cert or provider issue */ \
585     if (val != NULL && TYPE##_invalid(val)) { \
586         ERR_raise(ERR_LIB_CMP, CMP_R_POTENTIALLY_INVALID_CERTIFICATE); \
587         return 0; \
588     } \
589     if (val != NULL && !TYPE##_up_ref(val)) \
590         return 0; \
591     TYPE##_free(ctx->FIELD); \
592     ctx->FIELD = val; \
593     return 1; \
594 }
595
596 DEFINE_OSSL_set1_up_ref(ossl_cmp_ctx, validatedSrvCert, X509)
597
598 /*
599  * Pins the server certificate to be directly trusted (even if it is expired)
600  * for verifying response messages.
601  * Cert pointer is not consumed. It may be NULL to clear the entry.
602  */
603 DEFINE_OSSL_set1_up_ref(OSSL_CMP_CTX, srvCert, X509)
604
605 /* Set the X509 name of the recipient. Set in the PKIHeader */
606 DEFINE_OSSL_CMP_CTX_set1(recipient, X509_NAME)
607
608 /* Store the X509 name of the expected sender in the PKIHeader of responses */
609 DEFINE_OSSL_CMP_CTX_set1(expected_sender, X509_NAME)
610
611 /* Set the X509 name of the issuer. Set in the PKIHeader */
612 DEFINE_OSSL_CMP_CTX_set1(issuer, X509_NAME)
613
614 /*
615  * Set the subject name that will be placed in the certificate
616  * request. This will be the subject name on the received certificate.
617  */
618 DEFINE_OSSL_CMP_CTX_set1(subjectName, X509_NAME)
619
620 /* Set the X.509v3 certificate request extensions to be used in IR/CR/KUR */
621 int OSSL_CMP_CTX_set0_reqExtensions(OSSL_CMP_CTX *ctx, X509_EXTENSIONS *exts)
622 {
623     if (ctx == NULL) {
624         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
625         return 0;
626     }
627
628     if (sk_GENERAL_NAME_num(ctx->subjectAltNames) > 0 && exts != NULL
629             && X509v3_get_ext_by_NID(exts, NID_subject_alt_name, -1) >= 0) {
630         ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_SAN_SOURCES);
631         return 0;
632     }
633     X509_EXTENSIONS_free(ctx->reqExtensions);
634     ctx->reqExtensions = exts;
635     return 1;
636 }
637
638 /* returns 1 if ctx contains a Subject Alternative Name extension, else 0 */
639 int OSSL_CMP_CTX_reqExtensions_have_SAN(OSSL_CMP_CTX *ctx)
640 {
641     if (ctx == NULL) {
642         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
643         return -1;
644     }
645     /* if one of the following conditions 'fail' this is not an error */
646     return ctx->reqExtensions != NULL
647         && X509v3_get_ext_by_NID(ctx->reqExtensions,
648                                  NID_subject_alt_name, -1) >= 0;
649 }
650
651 /*
652  * Add a GENERAL_NAME structure that will be added to the CRMF
653  * request's extensions field to request subject alternative names.
654  */
655 int OSSL_CMP_CTX_push1_subjectAltName(OSSL_CMP_CTX *ctx,
656                                       const GENERAL_NAME *name)
657 {
658     GENERAL_NAME *name_dup;
659
660     if (ctx == NULL || name == NULL) {
661         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
662         return 0;
663     }
664
665     if (OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) == 1) {
666         ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_SAN_SOURCES);
667         return 0;
668     }
669
670     if (ctx->subjectAltNames == NULL
671             && (ctx->subjectAltNames = sk_GENERAL_NAME_new_null()) == NULL)
672         return 0;
673     if ((name_dup = GENERAL_NAME_dup(name)) == NULL)
674         return 0;
675     if (!sk_GENERAL_NAME_push(ctx->subjectAltNames, name_dup)) {
676         GENERAL_NAME_free(name_dup);
677         return 0;
678     }
679     return 1;
680 }
681
682 /*
683  * Set our own client certificate, used for example in KUR and when
684  * doing the IR with existing certificate.
685  */
686 DEFINE_OSSL_set1_up_ref(OSSL_CMP_CTX, cert, X509)
687
688 int OSSL_CMP_CTX_build_cert_chain(OSSL_CMP_CTX *ctx, X509_STORE *own_trusted,
689                                   STACK_OF(X509) *candidates)
690 {
691     STACK_OF(X509) *chain;
692
693     if (ctx == NULL) {
694         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
695         return 0;
696     }
697
698     if (!ossl_x509_add_certs_new(&ctx->untrusted, candidates,
699                                  X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
700         return 0;
701
702     ossl_cmp_debug(ctx, "trying to build chain for own CMP signer cert");
703     chain = X509_build_chain(ctx->cert, ctx->untrusted, own_trusted, 0,
704                              ctx->libctx, ctx->propq);
705     if (chain == NULL) {
706         ERR_raise(ERR_LIB_CMP, CMP_R_FAILED_BUILDING_OWN_CHAIN);
707         return 0;
708     }
709     ossl_cmp_debug(ctx, "success building chain for own CMP signer cert");
710     ctx->chain = chain;
711     return 1;
712 }
713
714 /*
715  * Set the old certificate that we are updating in KUR
716  * or the certificate to be revoked in RR, respectively.
717  * Also used as reference cert (defaulting to cert) for deriving subject DN
718  * and SANs. Its issuer is used as default recipient in the CMP message header.
719  */
720 DEFINE_OSSL_set1_up_ref(OSSL_CMP_CTX, oldCert, X509)
721
722 /* Set the PKCS#10 CSR to be sent in P10CR */
723 DEFINE_OSSL_CMP_CTX_set1(p10CSR, X509_REQ)
724
725 /*
726  * Set the (newly received in IP/KUP/CP) certificate in the context.
727  * This only permits for one cert to be enrolled at a time.
728  */
729 DEFINE_OSSL_set0(ossl_cmp_ctx, newCert, X509)
730
731 /* Get successfully validated server cert, if any, of current transaction */
732 DEFINE_OSSL_CMP_CTX_get0(validatedSrvCert, X509)
733
734 /*
735  * Get the (newly received in IP/KUP/CP) client certificate from the context
736  * This only permits for one client cert to be received...
737  */
738 DEFINE_OSSL_CMP_CTX_get0(newCert, X509)
739
740 /* Set the client's current private key */
741 DEFINE_OSSL_set1_up_ref(OSSL_CMP_CTX, pkey, EVP_PKEY)
742
743 /* Set new key pair. Used e.g. when doing Key Update */
744 int OSSL_CMP_CTX_set0_newPkey(OSSL_CMP_CTX *ctx, int priv, EVP_PKEY *pkey)
745 {
746     if (ctx == NULL) {
747         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
748         return 0;
749     }
750
751     EVP_PKEY_free(ctx->newPkey);
752     ctx->newPkey = pkey;
753     ctx->newPkey_priv = priv;
754     return 1;
755 }
756
757 /* Get the private/public key to use for cert enrollment, or NULL on error */
758 EVP_PKEY *OSSL_CMP_CTX_get0_newPkey(const OSSL_CMP_CTX *ctx, int priv)
759 {
760     if (ctx == NULL) {
761         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
762         return NULL;
763     }
764
765     if (ctx->newPkey != NULL)
766         return priv && !ctx->newPkey_priv ? NULL : ctx->newPkey;
767     if (ctx->p10CSR != NULL)
768         return priv ? NULL : X509_REQ_get0_pubkey(ctx->p10CSR);
769     return ctx->pkey; /* may be NULL */
770 }
771
772 #define DEFINE_set1_ASN1_OCTET_STRING(PREFIX, FIELD) \
773 int PREFIX##_set1_##FIELD(OSSL_CMP_CTX *ctx, const ASN1_OCTET_STRING *id) \
774 { \
775     if (ctx == NULL) { \
776         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \
777         return 0; \
778     } \
779     return ossl_cmp_asn1_octet_string_set1(&ctx->FIELD, id); \
780 }
781
782 /* Set the given transactionID to the context */
783 DEFINE_set1_ASN1_OCTET_STRING(OSSL_CMP_CTX, transactionID)
784
785 /* Set the nonce to be used for the recipNonce in the message created next */
786 DEFINE_set1_ASN1_OCTET_STRING(ossl_cmp_ctx, recipNonce)
787
788 /* Stores the given nonce as the last senderNonce sent out */
789 DEFINE_set1_ASN1_OCTET_STRING(OSSL_CMP_CTX, senderNonce)
790
791 /* Set the proxy server to use for HTTP(S) connections */
792 DEFINE_OSSL_CMP_CTX_set1(proxy, char)
793
794 /* Set the (HTTP) hostname of the CMP server */
795 DEFINE_OSSL_CMP_CTX_set1(server, char)
796
797 /* Set the server exclusion list of the HTTP proxy server */
798 DEFINE_OSSL_CMP_CTX_set1(no_proxy, char)
799
800 /* Set the http connect/disconnect callback function to be used for HTTP(S) */
801 DEFINE_OSSL_set(OSSL_CMP_CTX, http_cb, OSSL_HTTP_bio_cb_t)
802
803 /* Set argument optionally to be used by the http connect/disconnect callback */
804 DEFINE_OSSL_set(OSSL_CMP_CTX, http_cb_arg, void *)
805
806 /*
807  * Get argument optionally to be used by the http connect/disconnect callback
808  * Returns callback argument set previously (NULL if not set or on error)
809  */
810 DEFINE_OSSL_get(OSSL_CMP_CTX, http_cb_arg, void *, NULL)
811
812 /* Set callback function for sending CMP request and receiving response */
813 DEFINE_OSSL_set(OSSL_CMP_CTX, transfer_cb, OSSL_CMP_transfer_cb_t)
814
815 /* Set argument optionally to be used by the transfer callback */
816 DEFINE_OSSL_set(OSSL_CMP_CTX, transfer_cb_arg, void *)
817
818 /*
819  * Get argument optionally to be used by the transfer callback.
820  * Returns callback argument set previously (NULL if not set or on error)
821  */
822 DEFINE_OSSL_get(OSSL_CMP_CTX, transfer_cb_arg, void *, NULL)
823
824 /** Set the HTTP server port to be used */
825 DEFINE_OSSL_set(OSSL_CMP_CTX, serverPort, int)
826
827 /* Set the HTTP path to be used on the server (e.g "pkix/") */
828 DEFINE_OSSL_CMP_CTX_set1(serverPath, char)
829
830 /* Set the failInfo error code as bit encoding in OSSL_CMP_CTX */
831 DEFINE_OSSL_set(ossl_cmp_ctx, failInfoCode, int)
832
833 /*
834  * Get the failInfo error code in OSSL_CMP_CTX as bit encoding.
835  * Returns bit string as integer on success, -1 on error
836  */
837 DEFINE_OSSL_get(OSSL_CMP_CTX, failInfoCode, int, -1)
838
839 /* Set a Boolean or integer option of the context to the "val" arg */
840 int OSSL_CMP_CTX_set_option(OSSL_CMP_CTX *ctx, int opt, int val)
841 {
842     int min_val;
843
844     if (ctx == NULL) {
845         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
846         return 0;
847     }
848
849     switch (opt) {
850     case OSSL_CMP_OPT_REVOCATION_REASON:
851         min_val = OCSP_REVOKED_STATUS_NOSTATUS;
852         break;
853     case OSSL_CMP_OPT_POPO_METHOD:
854         min_val = OSSL_CRMF_POPO_NONE;
855         break;
856     default:
857         min_val = 0;
858         break;
859     }
860     if (val < min_val) {
861         ERR_raise(ERR_LIB_CMP, CMP_R_VALUE_TOO_SMALL);
862         return 0;
863     }
864
865     switch (opt) {
866     case OSSL_CMP_OPT_LOG_VERBOSITY:
867         if (val > OSSL_CMP_LOG_MAX) {
868             ERR_raise(ERR_LIB_CMP, CMP_R_VALUE_TOO_LARGE);
869             return 0;
870         }
871         ctx->log_verbosity = val;
872         break;
873     case OSSL_CMP_OPT_IMPLICIT_CONFIRM:
874         ctx->implicitConfirm = val;
875         break;
876     case OSSL_CMP_OPT_DISABLE_CONFIRM:
877         ctx->disableConfirm = val;
878         break;
879     case OSSL_CMP_OPT_UNPROTECTED_SEND:
880         ctx->unprotectedSend = val;
881         break;
882     case OSSL_CMP_OPT_UNPROTECTED_ERRORS:
883         ctx->unprotectedErrors = val;
884         break;
885     case OSSL_CMP_OPT_VALIDITY_DAYS:
886         ctx->days = val;
887         break;
888     case OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT:
889         ctx->SubjectAltName_nodefault = val;
890         break;
891     case OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL:
892         ctx->setSubjectAltNameCritical = val;
893         break;
894     case OSSL_CMP_OPT_POLICIES_CRITICAL:
895         ctx->setPoliciesCritical = val;
896         break;
897     case OSSL_CMP_OPT_IGNORE_KEYUSAGE:
898         ctx->ignore_keyusage = val;
899         break;
900     case OSSL_CMP_OPT_POPO_METHOD:
901         if (val > OSSL_CRMF_POPO_KEYAGREE) {
902             ERR_raise(ERR_LIB_CMP, CMP_R_VALUE_TOO_LARGE);
903             return 0;
904         }
905         ctx->popoMethod = val;
906         break;
907     case OSSL_CMP_OPT_DIGEST_ALGNID:
908         if (!cmp_ctx_set_md(ctx, &ctx->digest, val))
909             return 0;
910         break;
911     case OSSL_CMP_OPT_OWF_ALGNID:
912         if (!cmp_ctx_set_md(ctx, &ctx->pbm_owf, val))
913             return 0;
914         break;
915     case OSSL_CMP_OPT_MAC_ALGNID:
916         ctx->pbm_mac = val;
917         break;
918     case OSSL_CMP_OPT_KEEP_ALIVE:
919         ctx->keep_alive = val;
920         break;
921     case OSSL_CMP_OPT_MSG_TIMEOUT:
922         ctx->msg_timeout = val;
923         break;
924     case OSSL_CMP_OPT_TOTAL_TIMEOUT:
925         ctx->total_timeout = val;
926         break;
927     case OSSL_CMP_OPT_PERMIT_TA_IN_EXTRACERTS_FOR_IR:
928         ctx->permitTAInExtraCertsForIR = val;
929         break;
930     case OSSL_CMP_OPT_REVOCATION_REASON:
931         if (val > OCSP_REVOKED_STATUS_AACOMPROMISE) {
932             ERR_raise(ERR_LIB_CMP, CMP_R_VALUE_TOO_LARGE);
933             return 0;
934         }
935         ctx->revocationReason = val;
936         break;
937     default:
938         ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_OPTION);
939         return 0;
940     }
941
942     return 1;
943 }
944
945 /*
946  * Reads a Boolean or integer option value from the context.
947  * Returns -1 on error (which is the default OSSL_CMP_OPT_REVOCATION_REASON)
948  */
949 int OSSL_CMP_CTX_get_option(const OSSL_CMP_CTX *ctx, int opt)
950 {
951     if (ctx == NULL) {
952         ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
953         return -1;
954     }
955
956     switch (opt) {
957     case OSSL_CMP_OPT_LOG_VERBOSITY:
958         return ctx->log_verbosity;
959     case OSSL_CMP_OPT_IMPLICIT_CONFIRM:
960         return ctx->implicitConfirm;
961     case OSSL_CMP_OPT_DISABLE_CONFIRM:
962         return ctx->disableConfirm;
963     case OSSL_CMP_OPT_UNPROTECTED_SEND:
964         return ctx->unprotectedSend;
965     case OSSL_CMP_OPT_UNPROTECTED_ERRORS:
966         return ctx->unprotectedErrors;
967     case OSSL_CMP_OPT_VALIDITY_DAYS:
968         return ctx->days;
969     case OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT:
970         return ctx->SubjectAltName_nodefault;
971     case OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL:
972         return ctx->setSubjectAltNameCritical;
973     case OSSL_CMP_OPT_POLICIES_CRITICAL:
974         return ctx->setPoliciesCritical;
975     case OSSL_CMP_OPT_IGNORE_KEYUSAGE:
976         return ctx->ignore_keyusage;
977     case OSSL_CMP_OPT_POPO_METHOD:
978         return ctx->popoMethod;
979     case OSSL_CMP_OPT_DIGEST_ALGNID:
980         return EVP_MD_get_type(ctx->digest);
981     case OSSL_CMP_OPT_OWF_ALGNID:
982         return EVP_MD_get_type(ctx->pbm_owf);
983     case OSSL_CMP_OPT_MAC_ALGNID:
984         return ctx->pbm_mac;
985     case OSSL_CMP_OPT_KEEP_ALIVE:
986         return ctx->keep_alive;
987     case OSSL_CMP_OPT_MSG_TIMEOUT:
988         return ctx->msg_timeout;
989     case OSSL_CMP_OPT_TOTAL_TIMEOUT:
990         return ctx->total_timeout;
991     case OSSL_CMP_OPT_PERMIT_TA_IN_EXTRACERTS_FOR_IR:
992         return ctx->permitTAInExtraCertsForIR;
993     case OSSL_CMP_OPT_REVOCATION_REASON:
994         return ctx->revocationReason;
995     default:
996         ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_OPTION);
997         return -1;
998     }
999 }