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