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