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