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