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