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