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