2 * Copyright 2007-2019 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright Nokia 2007-2019
4 * Copyright Siemens AG 2015-2019
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
16 #include "http_server.h"
20 #include "cmp_mock_srv.h"
22 /* tweaks needed due to missing unistd.h on Windows */
24 # define access _access
30 #include <openssl/ui.h>
31 #include <openssl/pkcs12.h>
32 #include <openssl/ssl.h>
34 /* explicit #includes not strictly needed since implied by the above: */
36 #include <openssl/cmp.h>
37 #include <openssl/cmp_util.h>
38 #include <openssl/crmf.h>
39 #include <openssl/crypto.h>
40 #include <openssl/err.h>
41 #include <openssl/store.h>
42 #include <openssl/objects.h>
43 #include <openssl/x509.h>
46 DEFINE_STACK_OF(X509_EXTENSION)
47 DEFINE_STACK_OF(OSSL_CMP_ITAV)
49 /* start TODO remove when PR #11755 is merged */
50 static char *get_passwd(const char *pass, const char *desc)
54 app_passwd(pass, NULL, &result, NULL);
58 static void cleanse(char *str)
61 OPENSSL_cleanse(str, strlen(str));
64 static void clear_free(char *str)
67 OPENSSL_clear_free(str, strlen(str));
70 static int load_key_cert_crl(const char *uri, int maybe_stdin,
71 const char *pass, const char *desc,
72 EVP_PKEY **ppkey, X509 **pcert, X509_CRL **pcrl)
75 OSSL_STORE_CTX *ctx = NULL;
85 uidata.password = pass;
86 uidata.prompt_info = uri;
88 ctx = OSSL_STORE_open(uri, get_ui_method(), &uidata, NULL, NULL);
90 BIO_printf(bio_err, "Could not open file or uri %s for loading %s\n",
96 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
97 int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info);
99 info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
103 if (OSSL_STORE_eof(ctx))
109 case OSSL_STORE_INFO_PKEY:
110 if (ppkey != NULL && *ppkey == NULL)
111 err = ((*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) == NULL);
113 case OSSL_STORE_INFO_CERT:
114 if (pcert != NULL && *pcert == NULL)
115 err = ((*pcert = OSSL_STORE_INFO_get1_CERT(info)) == NULL);
117 case OSSL_STORE_INFO_CRL:
118 if (pcrl != NULL && *pcrl == NULL)
119 err = ((*pcrl = OSSL_STORE_INFO_get1_CRL(info)) == NULL);
122 /* skip any other type */
125 OSSL_STORE_INFO_free(info);
127 BIO_printf(bio_err, "Could not read %s of %s from %s\n",
135 OSSL_STORE_close(ctx);
137 ERR_print_errors(bio_err);
142 EVP_PKEY *load_key_preliminary(const char *uri, int format, int may_stdin,
143 const char *pass, ENGINE *e, const char *desc)
145 EVP_PKEY *pkey = NULL;
148 desc = "private key";
150 if (format == FORMAT_ENGINE) {
152 BIO_printf(bio_err, "No engine specified for loading %s\n", desc);
154 #ifndef OPENSSL_NO_ENGINE
157 cb_data.password = pass;
158 cb_data.prompt_info = uri;
159 if (ENGINE_init(e)) {
160 pkey = ENGINE_load_private_key(e, uri,
161 (UI_METHOD *)get_ui_method(),
166 BIO_printf(bio_err, "Cannot load %s from engine\n", desc);
167 ERR_print_errors(bio_err);
170 BIO_printf(bio_err, "Engines not supported for loading %s\n", desc);
174 (void)load_key_cert_crl(uri, may_stdin, pass, desc, &pkey, NULL, NULL);
178 BIO_printf(bio_err, "Unable to load %s\n", desc);
179 ERR_print_errors(bio_err);
184 static X509 *load_cert_pass(const char *uri, int maybe_stdin,
185 const char *pass, const char *desc)
190 desc = "certificate";
191 (void)load_key_cert_crl(uri, maybe_stdin, pass, desc, NULL, &cert, NULL);
193 BIO_printf(bio_err, "Unable to load %s\n", desc);
194 ERR_print_errors(bio_err);
198 /* end TODO remove when PR #11755 is merged */
200 static char *opt_config = NULL;
201 #define CMP_SECTION "cmp"
202 #define SECTION_NAME_MAX 40 /* max length of section name */
203 #define DEFAULT_SECTION "default"
204 static char *opt_section = CMP_SECTION;
207 #define PROG cmp_main
208 static char *prog = "cmp";
210 static int read_config(void);
212 static CONF *conf = NULL; /* OpenSSL config file context structure */
213 static OSSL_CMP_CTX *cmp_ctx = NULL; /* the client-side CMP context */
215 /* TODO remove when new setup_engine_flags() is in apps/lib/apps.c (PR #4277) */
217 ENGINE *setup_engine_flags(const char *engine, unsigned int flags, int debug)
219 return setup_engine(engine, debug);
222 /* the type of cmp command we want to send */
232 /* message transfer */
233 static char *opt_server = NULL;
234 static char server_port_s[32] = { '\0' };
235 static int server_port = 0;
236 static char *opt_proxy = NULL;
237 static char *opt_no_proxy = NULL;
238 static char *opt_path = "/";
239 static int opt_msg_timeout = -1;
240 static int opt_total_timeout = -1;
242 /* server authentication */
243 static char *opt_trusted = NULL;
244 static char *opt_untrusted = NULL;
245 static char *opt_srvcert = NULL;
246 static char *opt_recipient = NULL;
247 static char *opt_expect_sender = NULL;
248 static int opt_ignore_keyusage = 0;
249 static int opt_unprotected_errors = 0;
250 static char *opt_extracertsout = NULL;
251 static char *opt_cacertsout = NULL;
253 /* client authentication */
254 static char *opt_ref = NULL;
255 static char *opt_secret = NULL;
256 static char *opt_cert = NULL;
257 static char *opt_key = NULL;
258 static char *opt_keypass = NULL;
259 static char *opt_digest = NULL;
260 static char *opt_mac = NULL;
261 static char *opt_extracerts = NULL;
262 static int opt_unprotected_requests = 0;
264 /* generic message */
265 static char *opt_cmd_s = NULL;
266 static int opt_cmd = -1;
267 static char *opt_geninfo = NULL;
268 static char *opt_infotype_s = NULL;
269 static int opt_infotype = NID_undef;
271 /* certificate enrollment */
272 static char *opt_newkey = NULL;
273 static char *opt_newkeypass = NULL;
274 static char *opt_subject = NULL;
275 static char *opt_issuer = NULL;
276 static int opt_days = 0;
277 static char *opt_reqexts = NULL;
278 static char *opt_sans = NULL;
279 static int opt_san_nodefault = 0;
280 static char *opt_policies = NULL;
281 static char *opt_policy_oids = NULL;
282 static int opt_policy_oids_critical = 0;
283 static int opt_popo = OSSL_CRMF_POPO_NONE - 1;
284 static char *opt_csr = NULL;
285 static char *opt_out_trusted = NULL;
286 static int opt_implicit_confirm = 0;
287 static int opt_disable_confirm = 0;
288 static char *opt_certout = NULL;
290 /* certificate enrollment and revocation */
291 static char *opt_oldcert = NULL;
292 static int opt_revreason = CRL_REASON_NONE;
294 /* credentials format */
295 static char *opt_certform_s = "PEM";
296 static int opt_certform = FORMAT_PEM;
297 static char *opt_keyform_s = "PEM";
298 static int opt_keyform = FORMAT_PEM;
299 static char *opt_certsform_s = "PEM";
300 static int opt_certsform = FORMAT_PEM;
301 static char *opt_otherpass = NULL;
302 static char *opt_engine = NULL;
305 static int opt_tls_used = 0;
306 static char *opt_tls_cert = NULL;
307 static char *opt_tls_key = NULL;
308 static char *opt_tls_keypass = NULL;
309 static char *opt_tls_extra = NULL;
310 static char *opt_tls_trusted = NULL;
311 static char *opt_tls_host = NULL;
313 /* client-side debugging */
314 static int opt_batch = 0;
315 static int opt_repeat = 1;
316 static char *opt_reqin = NULL;
317 static int opt_reqin_new_tid = 0;
318 static char *opt_reqout = NULL;
319 static char *opt_rspin = NULL;
320 static char *opt_rspout = NULL;
321 static int opt_use_mock_srv = 0;
323 /* server-side debugging */
324 static char *opt_port = NULL;
325 static int opt_max_msgs = 0;
327 static char *opt_srv_ref = NULL;
328 static char *opt_srv_secret = NULL;
329 static char *opt_srv_cert = NULL;
330 static char *opt_srv_key = NULL;
331 static char *opt_srv_keypass = NULL;
333 static char *opt_srv_trusted = NULL;
334 static char *opt_srv_untrusted = NULL;
335 static char *opt_rsp_cert = NULL;
336 static char *opt_rsp_extracerts = NULL;
337 static char *opt_rsp_capubs = NULL;
338 static int opt_poll_count = 0;
339 static int opt_check_after = 1;
340 static int opt_grant_implicitconf = 0;
342 static int opt_pkistatus = OSSL_CMP_PKISTATUS_accepted;
343 static int opt_failure = INT_MIN;
344 static int opt_failurebits = 0;
345 static char *opt_statusstring = NULL;
346 static int opt_send_error = 0;
347 static int opt_send_unprotected = 0;
348 static int opt_send_unprot_err = 0;
349 static int opt_accept_unprotected = 0;
350 static int opt_accept_unprot_err = 0;
351 static int opt_accept_raverified = 0;
353 static X509_VERIFY_PARAM *vpm = NULL;
355 typedef enum OPTION_choice {
356 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
357 OPT_CONFIG, OPT_SECTION,
359 OPT_CMD, OPT_INFOTYPE, OPT_GENINFO,
361 OPT_NEWKEY, OPT_NEWKEYPASS, OPT_SUBJECT, OPT_ISSUER,
362 OPT_DAYS, OPT_REQEXTS,
363 OPT_SANS, OPT_SAN_NODEFAULT,
364 OPT_POLICIES, OPT_POLICY_OIDS, OPT_POLICY_OIDS_CRITICAL,
366 OPT_OUT_TRUSTED, OPT_IMPLICIT_CONFIRM, OPT_DISABLE_CONFIRM,
369 OPT_OLDCERT, OPT_REVREASON,
371 OPT_SERVER, OPT_PROXY, OPT_NO_PROXY, OPT_PATH,
372 OPT_MSG_TIMEOUT, OPT_TOTAL_TIMEOUT,
374 OPT_TRUSTED, OPT_UNTRUSTED, OPT_SRVCERT,
375 OPT_RECIPIENT, OPT_EXPECT_SENDER,
376 OPT_IGNORE_KEYUSAGE, OPT_UNPROTECTED_ERRORS,
377 OPT_EXTRACERTSOUT, OPT_CACERTSOUT,
379 OPT_REF, OPT_SECRET, OPT_CERT, OPT_KEY, OPT_KEYPASS,
380 OPT_DIGEST, OPT_MAC, OPT_EXTRACERTS,
381 OPT_UNPROTECTED_REQUESTS,
383 OPT_CERTFORM, OPT_KEYFORM, OPT_CERTSFORM,
385 #ifndef OPENSSL_NO_ENGINE
390 OPT_TLS_USED, OPT_TLS_CERT, OPT_TLS_KEY,
392 OPT_TLS_EXTRA, OPT_TLS_TRUSTED, OPT_TLS_HOST,
394 OPT_BATCH, OPT_REPEAT,
395 OPT_REQIN, OPT_REQIN_NEW_TID, OPT_REQOUT, OPT_RSPIN, OPT_RSPOUT,
397 OPT_USE_MOCK_SRV, OPT_PORT, OPT_MAX_MSGS,
398 OPT_SRV_REF, OPT_SRV_SECRET,
399 OPT_SRV_CERT, OPT_SRV_KEY, OPT_SRV_KEYPASS,
400 OPT_SRV_TRUSTED, OPT_SRV_UNTRUSTED,
401 OPT_RSP_CERT, OPT_RSP_EXTRACERTS, OPT_RSP_CAPUBS,
402 OPT_POLL_COUNT, OPT_CHECK_AFTER,
403 OPT_GRANT_IMPLICITCONF,
404 OPT_PKISTATUS, OPT_FAILURE,
405 OPT_FAILUREBITS, OPT_STATUSSTRING,
406 OPT_SEND_ERROR, OPT_SEND_UNPROTECTED,
407 OPT_SEND_UNPROT_ERR, OPT_ACCEPT_UNPROTECTED,
408 OPT_ACCEPT_UNPROT_ERR, OPT_ACCEPT_RAVERIFIED,
413 const OPTIONS cmp_options[] = {
414 /* entries must be in the same order as enumerated above!! */
415 {"help", OPT_HELP, '-', "Display this summary"},
416 {"config", OPT_CONFIG, 's',
417 "Configuration file to use. \"\" = none. Default from env variable OPENSSL_CONF"},
418 {"section", OPT_SECTION, 's',
419 "Section(s) in config file to get options from. \"\" = 'default'. Default 'cmp'"},
421 OPT_SECTION("Generic message"),
422 {"cmd", OPT_CMD, 's', "CMP request to send: ir/cr/kur/p10cr/rr/genm"},
423 {"infotype", OPT_INFOTYPE, 's',
424 "InfoType name for requesting specific info in genm, e.g. 'signKeyPairTypes'"},
425 {"geninfo", OPT_GENINFO, 's',
426 "generalInfo integer values to place in request PKIHeader with given OID"},
428 "specified in the form <OID>:int:<n>, e.g. \"1.2.3:int:987\""},
430 OPT_SECTION("Certificate enrollment"),
431 {"newkey", OPT_NEWKEY, 's',
432 "Private or public key for the requested cert. Default: CSR key or client key"},
433 {"newkeypass", OPT_NEWKEYPASS, 's', "New private key pass phrase source"},
434 {"subject", OPT_SUBJECT, 's',
435 "Distinguished Name (DN) of subject to use in the requested cert template"},
437 "For kur, default is the subject DN of the reference cert (see -oldcert);"},
439 "this default is used for ir and cr only if no Subject Alt Names are set"},
440 {"issuer", OPT_ISSUER, 's',
441 "DN of the issuer to place in the requested certificate template"},
443 "also used as recipient if neither -recipient nor -srvcert are given"},
444 {"days", OPT_DAYS, 'n',
445 "Requested validity time of the new certificate in number of days"},
446 {"reqexts", OPT_REQEXTS, 's',
447 "Name of config file section defining certificate request extensions"},
448 {"sans", OPT_SANS, 's',
449 "Subject Alt Names (IPADDR/DNS/URI) to add as (critical) cert req extension"},
450 {"san_nodefault", OPT_SAN_NODEFAULT, '-',
451 "Do not take default SANs from reference certificate (see -oldcert)"},
452 {"policies", OPT_POLICIES, 's',
453 "Name of config file section defining policies certificate request extension"},
454 {"policy_oids", OPT_POLICY_OIDS, 's',
455 "Policy OID(s) to add as policies certificate request extension"},
456 {"policy_oids_critical", OPT_POLICY_OIDS_CRITICAL, '-',
457 "Flag the policy OID(s) given with -policy_oids as critical"},
458 {"popo", OPT_POPO, 'n',
459 "Proof-of-Possession (POPO) method to use for ir/cr/kur where"},
461 "-1 = NONE, 0 = RAVERIFIED, 1 = SIGNATURE (default), 2 = KEYENC"},
462 {"csr", OPT_CSR, 's',
463 "CSR file in PKCS#10 format to use in p10cr for legacy support"},
464 {"out_trusted", OPT_OUT_TRUSTED, 's',
465 "Certificates to trust when verifying newly enrolled certificates"},
466 {"implicit_confirm", OPT_IMPLICIT_CONFIRM, '-',
467 "Request implicit confirmation of newly enrolled certificates"},
468 {"disable_confirm", OPT_DISABLE_CONFIRM, '-',
469 "Do not confirm newly enrolled certificate w/o requesting implicit"},
471 "confirmation. WARNING: This leads to behavior violating RFC 4210"},
472 {"certout", OPT_CERTOUT, 's',
473 "File to save newly enrolled certificate"},
475 OPT_SECTION("Certificate enrollment and revocation"),
477 {"oldcert", OPT_OLDCERT, 's',
478 "Certificate to be updated (defaulting to -cert) or to be revoked in rr;"},
480 "also used as reference (defaulting to -cert) for subject DN and SANs."},
482 "Its issuer is used as recipient unless -srvcert, -recipient or -issuer given"},
483 {"revreason", OPT_REVREASON, 'n',
484 "Reason code to include in revocation request (rr); possible values:"},
486 "0..6, 8..10 (see RFC5280, 5.3.1) or -1. Default -1 = none included"},
488 OPT_SECTION("Message transfer"),
489 {"server", OPT_SERVER, 's',
490 "[http[s]://]address[:port] of CMP server. Default port 80 or 443."},
492 "The address may be a DNS name or an IP address"},
493 {"proxy", OPT_PROXY, 's',
494 "[http[s]://]address[:port][/path] of HTTP(S) proxy to use; path is ignored"},
495 {"no_proxy", OPT_NO_PROXY, 's',
496 "List of addresses of servers not to use HTTP(S) proxy for"},
498 "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"},
499 {"path", OPT_PATH, 's',
500 "HTTP path (aka CMP alias) at the CMP server. Default \"/\""},
501 {"msg_timeout", OPT_MSG_TIMEOUT, 'n',
502 "Timeout per CMP message round trip (or 0 for none). Default 120 seconds"},
503 {"total_timeout", OPT_TOTAL_TIMEOUT, 'n',
504 "Overall time an enrollment incl. polling may take. Default 0 = infinite"},
506 OPT_SECTION("Server authentication"),
507 {"trusted", OPT_TRUSTED, 's',
508 "Trusted certs used for CMP server authentication when verifying responses"},
509 {OPT_MORE_STR, 0, 0, "unless -srvcert is given"},
510 {"untrusted", OPT_UNTRUSTED, 's',
511 "Intermediate certs for chain construction verifying CMP/TLS/enrolled certs"},
512 {"srvcert", OPT_SRVCERT, 's',
513 "Specific CMP server cert to use and trust directly when verifying responses"},
514 {"recipient", OPT_RECIPIENT, 's',
515 "Distinguished Name (DN) of the recipient to use unless -srvcert is given"},
516 {"expect_sender", OPT_EXPECT_SENDER, 's',
517 "DN of expected response sender. Defaults to DN of -srvcert, if provided"},
518 {"ignore_keyusage", OPT_IGNORE_KEYUSAGE, '-',
519 "Ignore CMP signer cert key usage, else 'digitalSignature' must be allowed"},
520 {"unprotected_errors", OPT_UNPROTECTED_ERRORS, '-',
521 "Accept missing or invalid protection of regular error messages and negative"},
523 "certificate responses (ip/cp/kup), revocation responses (rp), and PKIConf"},
525 "WARNING: This setting leads to behavior allowing violation of RFC 4210"},
526 {"extracertsout", OPT_EXTRACERTSOUT, 's',
527 "File to save extra certificates received in the extraCerts field"},
528 {"cacertsout", OPT_CACERTSOUT, 's',
529 "File to save CA certificates received in the caPubs field of 'ip' messages"},
531 OPT_SECTION("Client authentication"),
532 {"ref", OPT_REF, 's',
533 "Reference value to use as senderKID in case no -cert is given"},
534 {"secret", OPT_SECRET, 's',
535 "Password source for client authentication with a pre-shared key (secret)"},
536 {"cert", OPT_CERT, 's',
537 "Client's current certificate (needed unless using -secret for PBM);"},
539 "any further certs included are appended in extraCerts field"},
540 {"key", OPT_KEY, 's', "Private key for the client's current certificate"},
541 {"keypass", OPT_KEYPASS, 's',
542 "Client private key (and cert and old cert file) pass phrase source"},
543 {"digest", OPT_DIGEST, 's',
544 "Digest to use in message protection and POPO signatures. Default \"sha256\""},
545 {"mac", OPT_MAC, 's',
546 "MAC algorithm to use in PBM-based message protection. Default \"hmac-sha1\""},
547 {"extracerts", OPT_EXTRACERTS, 's',
548 "Certificates to append in extraCerts field of outgoing messages"},
549 {"unprotected_requests", OPT_UNPROTECTED_REQUESTS, '-',
550 "Send messages without CMP-level protection"},
552 OPT_SECTION("Credentials format"),
553 {"certform", OPT_CERTFORM, 's',
554 "Format (PEM or DER) to use when saving a certificate to a file. Default PEM"},
556 "This also determines format to use for writing (not supported for P12)"},
557 {"keyform", OPT_KEYFORM, 's',
558 "Format to assume when reading key files. Default PEM"},
559 {"certsform", OPT_CERTSFORM, 's',
560 "Format (PEM/DER/P12) to try first reading multiple certs. Default PEM"},
561 {"otherpass", OPT_OTHERPASS, 's',
562 "Pass phrase source potentially needed for loading certificates of others"},
563 #ifndef OPENSSL_NO_ENGINE
564 {"engine", OPT_ENGINE, 's',
565 "Use crypto engine with given identifier, possibly a hardware device."},
567 "Engines may be defined in OpenSSL config file engine section."},
569 "Options like -key specifying keys held in the engine can give key IDs"},
571 "prefixed by 'engine:', e.g. '-key engine:pkcs11:object=mykey;pin-value=1234'"},
575 OPT_SECTION("TLS connection"),
576 {"tls_used", OPT_TLS_USED, '-',
577 "Enable using TLS (also when other TLS options are not set)"},
578 {"tls_cert", OPT_TLS_CERT, 's',
579 "Client's TLS certificate. May include chain to be provided to TLS server"},
580 {"tls_key", OPT_TLS_KEY, 's',
581 "Private key for the client's TLS certificate"},
582 {"tls_keypass", OPT_TLS_KEYPASS, 's',
583 "Pass phrase source for the client's private TLS key (and TLS cert file)"},
584 {"tls_extra", OPT_TLS_EXTRA, 's',
585 "Extra certificates to provide to TLS server during TLS handshake"},
586 {"tls_trusted", OPT_TLS_TRUSTED, 's',
587 "Trusted certificates to use for verifying the TLS server certificate;"},
588 {OPT_MORE_STR, 0, 0, "this implies host name validation"},
589 {"tls_host", OPT_TLS_HOST, 's',
590 "Address to be checked (rather than -server) during TLS host name validation"},
592 OPT_SECTION("Client-side debugging"),
593 {"batch", OPT_BATCH, '-',
594 "Do not interactively prompt for input when a password is required etc."},
595 {"repeat", OPT_REPEAT, 'n',
596 "Invoke the transaction the given number of times. Default 1"},
597 {"reqin", OPT_REQIN, 's', "Take sequence of CMP requests from file(s)"},
598 {"reqin_new_tid", OPT_REQIN_NEW_TID, '-',
599 "Use fresh transactionID for CMP requests read from -reqin"},
600 {"reqout", OPT_REQOUT, 's', "Save sequence of CMP requests to file(s)"},
601 {"rspin", OPT_RSPIN, 's',
602 "Process sequence of CMP responses provided in file(s), skipping server"},
603 {"rspout", OPT_RSPOUT, 's', "Save sequence of CMP responses to file(s)"},
605 {"use_mock_srv", OPT_USE_MOCK_SRV, '-', "Use mock server at API level, bypassing HTTP"},
607 OPT_SECTION("Mock server"),
608 {"port", OPT_PORT, 's', "Act as HTTP mock server listening on given port"},
609 {"max_msgs", OPT_MAX_MSGS, 'n',
610 "max number of messages handled by HTTP mock server. Default: 0 = unlimited"},
612 {"srv_ref", OPT_SRV_REF, 's',
613 "Reference value to use as senderKID of server in case no -srv_cert is given"},
614 {"srv_secret", OPT_SRV_SECRET, 's',
615 "Password source for server authentication with a pre-shared key (secret)"},
616 {"srv_cert", OPT_SRV_CERT, 's', "Certificate of the server"},
617 {"srv_key", OPT_SRV_KEY, 's',
618 "Private key used by the server for signing messages"},
619 {"srv_keypass", OPT_SRV_KEYPASS, 's',
620 "Server private key (and cert) file pass phrase source"},
622 {"srv_trusted", OPT_SRV_TRUSTED, 's',
623 "Trusted certificates for client authentication"},
624 {"srv_untrusted", OPT_SRV_UNTRUSTED, 's',
625 "Intermediate certs that may be useful for verifying CMP protection"},
626 {"rsp_cert", OPT_RSP_CERT, 's',
627 "Certificate to be returned as mock enrollment result"},
628 {"rsp_extracerts", OPT_RSP_EXTRACERTS, 's',
629 "Extra certificates to be included in mock certification responses"},
630 {"rsp_capubs", OPT_RSP_CAPUBS, 's',
631 "CA certificates to be included in mock ip response"},
632 {"poll_count", OPT_POLL_COUNT, 'n',
633 "Number of times the client must poll before receiving a certificate"},
634 {"check_after", OPT_CHECK_AFTER, 'n',
635 "The check_after value (time to wait) to include in poll response"},
636 {"grant_implicitconf", OPT_GRANT_IMPLICITCONF, '-',
637 "Grant implicit confirmation of newly enrolled certificate"},
639 {"pkistatus", OPT_PKISTATUS, 'n',
640 "PKIStatus to be included in server response. Possible values: 0..6"},
641 {"failure", OPT_FAILURE, 'n',
642 "A single failure info bit number to include in server response, 0..26"},
643 {"failurebits", OPT_FAILUREBITS, 'n',
644 "Number representing failure bits to include in server response, 0..2^27 - 1"},
645 {"statusstring", OPT_STATUSSTRING, 's',
646 "Status string to be included in server response"},
647 {"send_error", OPT_SEND_ERROR, '-',
648 "Force server to reply with error message"},
649 {"send_unprotected", OPT_SEND_UNPROTECTED, '-',
650 "Send response messages without CMP-level protection"},
651 {"send_unprot_err", OPT_SEND_UNPROT_ERR, '-',
652 "In case of negative responses, server shall send unprotected error messages,"},
654 "certificate responses (ip/cp/kup), and revocation responses (rp)."},
656 "WARNING: This setting leads to behavior violating RFC 4210"},
657 {"accept_unprotected", OPT_ACCEPT_UNPROTECTED, '-',
658 "Accept missing or invalid protection of requests"},
659 {"accept_unprot_err", OPT_ACCEPT_UNPROT_ERR, '-',
660 "Accept unprotected error messages from client"},
661 {"accept_raverified", OPT_ACCEPT_RAVERIFIED, '-',
662 "Accept RAVERIFIED as proof-of-possession (POPO)"},
673 static varref cmp_vars[] = { /* must be in same order as enumerated above! */
674 {&opt_config}, {&opt_section},
676 {&opt_cmd_s}, {&opt_infotype_s}, {&opt_geninfo},
678 {&opt_newkey}, {&opt_newkeypass}, {&opt_subject}, {&opt_issuer},
679 {(char **)&opt_days}, {&opt_reqexts},
680 {&opt_sans}, {(char **)&opt_san_nodefault},
681 {&opt_policies}, {&opt_policy_oids}, {(char **)&opt_policy_oids_critical},
682 {(char **)&opt_popo}, {&opt_csr},
684 {(char **)&opt_implicit_confirm}, {(char **)&opt_disable_confirm},
687 {&opt_oldcert}, {(char **)&opt_revreason},
689 {&opt_server}, {&opt_proxy}, {&opt_no_proxy}, {&opt_path},
690 {(char **)&opt_msg_timeout}, {(char **)&opt_total_timeout},
692 {&opt_trusted}, {&opt_untrusted}, {&opt_srvcert},
693 {&opt_recipient}, {&opt_expect_sender},
694 {(char **)&opt_ignore_keyusage}, {(char **)&opt_unprotected_errors},
695 {&opt_extracertsout}, {&opt_cacertsout},
697 {&opt_ref}, {&opt_secret}, {&opt_cert}, {&opt_key}, {&opt_keypass},
698 {&opt_digest}, {&opt_mac}, {&opt_extracerts},
699 {(char **)&opt_unprotected_requests},
701 {&opt_certform_s}, {&opt_keyform_s}, {&opt_certsform_s},
703 #ifndef OPENSSL_NO_ENGINE
707 {(char **)&opt_tls_used}, {&opt_tls_cert}, {&opt_tls_key},
709 {&opt_tls_extra}, {&opt_tls_trusted}, {&opt_tls_host},
711 {(char **)&opt_batch}, {(char **)&opt_repeat},
712 {&opt_reqin}, {(char **)&opt_reqin_new_tid},
713 {&opt_reqout}, {&opt_rspin}, {&opt_rspout},
715 {(char **)&opt_use_mock_srv}, {&opt_port}, {(char **)&opt_max_msgs},
716 {&opt_srv_ref}, {&opt_srv_secret},
717 {&opt_srv_cert}, {&opt_srv_key}, {&opt_srv_keypass},
718 {&opt_srv_trusted}, {&opt_srv_untrusted},
719 {&opt_rsp_cert}, {&opt_rsp_extracerts}, {&opt_rsp_capubs},
720 {(char **)&opt_poll_count}, {(char **)&opt_check_after},
721 {(char **)&opt_grant_implicitconf},
722 {(char **)&opt_pkistatus}, {(char **)&opt_failure},
723 {(char **)&opt_failurebits}, {&opt_statusstring},
724 {(char **)&opt_send_error}, {(char **)&opt_send_unprotected},
725 {(char **)&opt_send_unprot_err}, {(char **)&opt_accept_unprotected},
726 {(char **)&opt_accept_unprot_err}, {(char **)&opt_accept_raverified},
732 # define FUNC (strcmp(OPENSSL_FUNC, "(unknown function)") == 0 \
733 ? "CMP" : "OPENSSL_FUNC")
734 # define PRINT_LOCATION(bio) BIO_printf(bio, "%s:%s:%d:", \
735 FUNC, OPENSSL_FILE, OPENSSL_LINE)
737 # define PRINT_LOCATION(bio) ((void)0)
739 #define CMP_print(bio, prefix, msg, a1, a2, a3) \
740 (PRINT_LOCATION(bio), \
741 BIO_printf(bio, "CMP %s: " msg "\n", prefix, a1, a2, a3))
742 #define CMP_INFO(msg, a1, a2, a3) CMP_print(bio_out, "info", msg, a1, a2, a3)
743 #define CMP_info(msg) CMP_INFO(msg"%s%s%s", "", "", "")
744 #define CMP_info1(msg, a1) CMP_INFO(msg"%s%s", a1, "", "")
745 #define CMP_info2(msg, a1, a2) CMP_INFO(msg"%s", a1, a2, "")
746 #define CMP_info3(msg, a1, a2, a3) CMP_INFO(msg, a1, a2, a3)
747 #define CMP_WARN(m, a1, a2, a3) CMP_print(bio_out, "warning", m, a1, a2, a3)
748 #define CMP_warn(msg) CMP_WARN(msg"%s%s%s", "", "", "")
749 #define CMP_warn1(msg, a1) CMP_WARN(msg"%s%s", a1, "", "")
750 #define CMP_warn2(msg, a1, a2) CMP_WARN(msg"%s", a1, a2, "")
751 #define CMP_warn3(msg, a1, a2, a3) CMP_WARN(msg, a1, a2, a3)
752 #define CMP_ERR(msg, a1, a2, a3) CMP_print(bio_err, "error", msg, a1, a2, a3)
753 #define CMP_err(msg) CMP_ERR(msg"%s%s%s", "", "", "")
754 #define CMP_err1(msg, a1) CMP_ERR(msg"%s%s", a1, "", "")
755 #define CMP_err2(msg, a1, a2) CMP_ERR(msg"%s", a1, a2, "")
756 #define CMP_err3(msg, a1, a2, a3) CMP_ERR(msg, a1, a2, a3)
758 static int print_to_bio_out(const char *func, const char *file, int line,
759 OSSL_CMP_severity level, const char *msg)
761 return OSSL_CMP_print_to_bio(bio_out, func, file, line, level, msg);
764 /* code duplicated from crypto/cmp/cmp_util.c */
765 static int sk_X509_add1_cert(STACK_OF(X509) *sk, X509 *cert,
766 int no_dup, int prepend)
770 * not using sk_X509_set_cmp_func() and sk_X509_find()
771 * because this re-orders the certs on the stack
775 for (i = 0; i < sk_X509_num(sk); i++) {
776 if (X509_cmp(sk_X509_value(sk, i), cert) == 0)
780 if (!X509_up_ref(cert))
782 if (!sk_X509_insert(sk, cert, prepend ? 0 : -1)) {
789 /* code duplicated from crypto/cmp/cmp_util.c */
790 static int sk_X509_add1_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs,
791 int no_self_signed, int no_dups, int prepend)
792 /* compiler would allow 'const' for the list of certs, yet they are up-ref'ed */
800 for (i = 0; i < sk_X509_num(certs); i++) {
801 X509 *cert = sk_X509_value(certs, i);
803 if (!no_self_signed || X509_check_issued(cert, cert) != X509_V_OK) {
804 if (!sk_X509_add1_cert(sk, cert, no_dups, prepend))
811 /* TODO potentially move to apps/lib/apps.c */
812 static char *next_item(char *opt) /* in list separated by comma and/or space */
814 /* advance to separator (comma or whitespace), if any */
815 while (*opt != ',' && !isspace(*opt) && *opt != '\0') {
816 if (*opt == '\\' && opt[1] != '\0')
817 /* skip and unescape '\' escaped char */
818 memmove(opt, opt + 1, strlen(opt));
822 /* terminate current item */
824 /* skip over any whitespace after separator */
825 while (isspace(*opt))
828 return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
831 static EVP_PKEY *load_key_pwd(const char *uri, int format,
832 const char *pass, ENGINE *e, const char *desc)
834 char *pass_string = get_passwd(pass, desc);
835 EVP_PKEY *pkey = load_key_preliminary(uri, format, 0, pass_string, e, desc);
837 clear_free(pass_string);
841 static X509 *load_cert_pwd(const char *uri, const char *pass, const char *desc)
844 char *pass_string = get_passwd(pass, desc);
846 cert = load_cert_pass(uri, 0, pass_string, desc);
847 clear_free(pass_string);
851 /* TODO remove when PR #4930 is merged */
852 static int load_pkcs12(BIO *in, const char *desc,
853 pem_password_cb *pem_cb, void *cb_data,
854 EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
857 char tpass[PEM_BUFSIZE];
860 PKCS12 *p12 = d2i_PKCS12_bio(in, NULL);
863 desc = "PKCS12 input";
865 BIO_printf(bio_err, "error loading PKCS12 file for %s\n", desc);
869 /* See if an empty password will do */
870 if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) {
874 pem_cb = wrap_password_callback;
875 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
877 BIO_printf(bio_err, "passphrase callback error for %s\n", desc);
880 if (len < PEM_BUFSIZE)
882 if (!PKCS12_verify_mac(p12, tpass, len)) {
884 "mac verify error (wrong password?) in PKCS12 file for %s\n",
890 ret = PKCS12_parse(p12, pass, pkey, cert, ca);
896 /* TODO potentially move this and related functions to apps/lib/apps.c */
897 static int adjust_format(const char **infile, int format, int engine_ok)
899 if (!strncasecmp(*infile, "http://", 7)
900 || !strncasecmp(*infile, "https://", 8)) {
901 format = FORMAT_HTTP;
902 } else if (engine_ok && strncasecmp(*infile, "engine:", 7) == 0) {
904 format = FORMAT_ENGINE;
906 if (strncasecmp(*infile, "file:", 5) == 0)
909 * the following is a heuristic whether first to try PEM or DER
910 * or PKCS12 as the input format for files
912 if (strlen(*infile) >= 4) {
913 const char *extension = *infile + strlen(*infile) - 4;
915 if (strncasecmp(extension, ".crt", 4) == 0
916 || strncasecmp(extension, ".pem", 4) == 0)
917 /* weak recognition of PEM format */
919 else if (strncasecmp(extension, ".cer", 4) == 0
920 || strncasecmp(extension, ".der", 4) == 0)
921 /* weak recognition of DER format */
922 format = FORMAT_ASN1;
923 else if (strncasecmp(extension, ".p12", 4) == 0)
924 /* weak recognition of PKCS#12 format */
925 format = FORMAT_PKCS12;
926 /* else retain given format */
933 * TODO potentially move this and related functions to apps/lib/
934 * or even better extend OSSL_STORE with type OSSL_STORE_INFO_CRL
936 static X509_REQ *load_csr_autofmt(const char *infile, const char *desc)
939 BIO *bio_bak = bio_err;
941 int format = adjust_format(&infile, FORMAT_PEM, 0);
943 can_retry = format == FORMAT_PEM || format == FORMAT_ASN1;
945 bio_err = NULL; /* do not show errors on more than one try */
946 csr = load_csr(infile, format, desc);
948 if (csr == NULL && can_retry) {
950 format = (format == FORMAT_PEM ? FORMAT_ASN1 : FORMAT_PEM);
951 csr = load_csr(infile, format, desc);
954 ERR_print_errors(bio_err);
955 BIO_printf(bio_err, "error: unable to load %s from file '%s'\n", desc,
961 /* TODO replace by calling generalized load_certs() when PR #4930 is merged */
962 static int load_certs_preliminary(const char *file, STACK_OF(X509) **certs,
963 int format, const char *pass,
969 if (format == FORMAT_PKCS12) {
970 BIO *bio = bio_open_default(file, 'r', format);
973 EVP_PKEY *pkey = NULL; /* pkey is needed until PR #4930 is merged */
976 cb_data.password = pass;
977 cb_data.prompt_info = file;
978 ret = load_pkcs12(bio, desc, wrap_password_callback,
979 &cb_data, &pkey, &cert, certs);
983 } else if (format == FORMAT_ASN1) { /* load only one cert in this case */
984 CMP_warn1("can load only one certificate in DER format from %s", file);
985 cert = load_cert_pass(file, 0, pass, desc);
987 if (format == FORMAT_PKCS12 || format == FORMAT_ASN1) {
990 *certs = sk_X509_new_null();
992 ret = sk_X509_insert(*certs, cert, 0);
997 ret = load_certs(file, certs, format, pass, desc);
1002 static void warn_certs_expired(const char *file, STACK_OF(X509) **certs)
1008 for (i = 0; i < sk_X509_num(*certs); i++) {
1009 cert = sk_X509_value(*certs, i);
1010 res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
1011 X509_get0_notAfter(cert));
1013 subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1014 CMP_warn3("certificate from '%s' with subject '%s' %s", file, subj,
1015 res > 0 ? "has expired" : "not yet valid");
1022 * TODO potentially move this and related functions to apps/lib/
1023 * or even better extend OSSL_STORE with type OSSL_STORE_INFO_CERTS
1025 static int load_certs_autofmt(const char *infile, STACK_OF(X509) **certs,
1026 int exclude_http, const char *pass,
1031 BIO *bio_bak = bio_err;
1032 int format = adjust_format(&infile, opt_certsform, 0);
1034 if (exclude_http && format == FORMAT_HTTP) {
1035 BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
1038 pass_string = get_passwd(pass, desc);
1039 if (format != FORMAT_HTTP)
1040 bio_err = NULL; /* do not show errors on more than one try */
1041 ret = load_certs_preliminary(infile, certs, format, pass_string, desc);
1043 if (!ret && format != FORMAT_HTTP) {
1044 int format2 = format == FORMAT_PEM ? FORMAT_ASN1 : FORMAT_PEM;
1047 ret = load_certs_preliminary(infile, certs, format2, pass_string, desc);
1049 clear_free(pass_string);
1052 warn_certs_expired(infile, certs);
1056 /* set expected host name/IP addr and clears the email addr in the given ts */
1057 static int truststore_set_host_etc(X509_STORE *ts, char *host)
1059 X509_VERIFY_PARAM *ts_vpm = X509_STORE_get0_param(ts);
1061 /* first clear any host names, IP, and email addresses */
1062 if (!X509_VERIFY_PARAM_set1_host(ts_vpm, NULL, 0)
1063 || !X509_VERIFY_PARAM_set1_ip(ts_vpm, NULL, 0)
1064 || !X509_VERIFY_PARAM_set1_email(ts_vpm, NULL, 0))
1066 X509_VERIFY_PARAM_set_hostflags(ts_vpm,
1067 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT |
1068 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
1069 return (host != NULL && X509_VERIFY_PARAM_set1_ip_asc(ts_vpm, host))
1070 || X509_VERIFY_PARAM_set1_host(ts_vpm, host, 0);
1073 static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
1074 const STACK_OF(X509) *certs /* may NULL */)
1079 store = X509_STORE_new();
1082 for (i = 0; i < sk_X509_num(certs); i++) {
1083 if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
1084 X509_STORE_free(store);
1091 /* write OSSL_CMP_MSG DER-encoded to the specified file name item */
1092 static int write_PKIMESSAGE(const OSSL_CMP_MSG *msg, char **filenames)
1097 if (msg == NULL || filenames == NULL) {
1098 CMP_err("NULL arg to write_PKIMESSAGE");
1101 if (*filenames == NULL) {
1102 CMP_err("Not enough file names provided for writing PKIMessage");
1107 *filenames = next_item(file);
1108 bio = BIO_new_file(file, "wb");
1110 CMP_err1("Cannot open file '%s' for writing", file);
1113 if (i2d_OSSL_CMP_MSG_bio(bio, msg) < 0) {
1114 CMP_err1("Cannot write PKIMessage to file '%s'", file);
1122 /* read DER-encoded OSSL_CMP_MSG from the specified file name item */
1123 static OSSL_CMP_MSG *read_PKIMESSAGE(char **filenames)
1129 if (filenames == NULL) {
1130 CMP_err("NULL arg to read_PKIMESSAGE");
1133 if (*filenames == NULL) {
1134 CMP_err("Not enough file names provided for reading PKIMessage");
1139 *filenames = next_item(file);
1140 bio = BIO_new_file(file, "rb");
1142 CMP_err1("Cannot open file '%s' for reading", file);
1145 ret = d2i_OSSL_CMP_MSG_bio(bio, NULL);
1147 CMP_err1("Cannot read PKIMessage from file '%s'", file);
1153 * Sends the PKIMessage req and on success place the response in *res
1154 * basically like OSSL_CMP_MSG_http_perform(), but in addition allows
1155 * to dump the sequence of requests and responses to files and/or
1156 * to take the sequence of requests and responses from files.
1158 static OSSL_CMP_MSG *read_write_req_resp(OSSL_CMP_CTX *ctx,
1159 const OSSL_CMP_MSG *req)
1161 OSSL_CMP_MSG *req_new = NULL;
1162 OSSL_CMP_MSG *res = NULL;
1163 OSSL_CMP_PKIHEADER *hdr;
1165 if (req != NULL && opt_reqout != NULL
1166 && !write_PKIMESSAGE(req, &opt_reqout))
1168 if (opt_reqin != NULL && opt_rspin == NULL) {
1169 if ((req_new = read_PKIMESSAGE(&opt_reqin)) == NULL)
1172 * The transaction ID in req_new read from opt_reqin may not be fresh.
1173 * In this case the server may complain "Transaction id already in use."
1174 * The following workaround unfortunately requires re-protection.
1176 if (opt_reqin_new_tid
1177 && !OSSL_CMP_MSG_update_transactionID(ctx, req_new))
1181 if (opt_rspin != NULL) {
1182 res = read_PKIMESSAGE(&opt_rspin);
1184 const OSSL_CMP_MSG *actual_req = opt_reqin != NULL ? req_new : req;
1186 res = opt_use_mock_srv
1187 ? OSSL_CMP_CTX_server_perform(ctx, actual_req)
1188 : OSSL_CMP_MSG_http_perform(ctx, actual_req);
1193 if (opt_reqin != NULL || opt_rspin != NULL) {
1194 /* need to satisfy nonce and transactionID checks */
1195 ASN1_OCTET_STRING *nonce;
1196 ASN1_OCTET_STRING *tid;
1198 hdr = OSSL_CMP_MSG_get0_header(res);
1199 nonce = OSSL_CMP_HDR_get0_recipNonce(hdr);
1200 tid = OSSL_CMP_HDR_get0_transactionID(hdr);
1201 if (!OSSL_CMP_CTX_set1_senderNonce(ctx, nonce)
1202 || !OSSL_CMP_CTX_set1_transactionID(ctx, tid)) {
1203 OSSL_CMP_MSG_free(res);
1209 if (opt_rspout != NULL && !write_PKIMESSAGE(res, &opt_rspout)) {
1210 OSSL_CMP_MSG_free(res);
1215 OSSL_CMP_MSG_free(req_new);
1220 * parse string as integer value, not allowing trailing garbage, see also
1221 * https://www.gnu.org/software/libc/manual/html_node/Parsing-of-Integers.html
1223 * returns integer value, or INT_MIN on error
1225 static int atoint(const char *str)
1228 long res = strtol(str, &tailptr, 10);
1230 if ((*tailptr != '\0') || (res < INT_MIN) || (res > INT_MAX))
1236 static int parse_addr(char **opt_string, int port, const char *name)
1240 if (strncasecmp(*opt_string, OSSL_HTTP_PREFIX,
1241 strlen(OSSL_HTTP_PREFIX)) == 0) {
1242 *opt_string += strlen(OSSL_HTTP_PREFIX);
1243 } else if (strncasecmp(*opt_string, OSSL_HTTPS_PREFIX,
1244 strlen(OSSL_HTTPS_PREFIX)) == 0) {
1245 *opt_string += strlen(OSSL_HTTPS_PREFIX);
1247 port = 443; /* == integer value of OSSL_HTTPS_PORT */
1250 if ((port_string = strrchr(*opt_string, ':')) == NULL)
1251 return port; /* using default */
1252 *(port_string++) = '\0';
1253 port = atoint(port_string);
1254 if ((port <= 0) || (port > 65535)) {
1255 CMP_err2("invalid %s port '%s' given, sane range 1-65535",
1262 static int set1_store_parameters(X509_STORE *ts)
1267 /* copy vpm to store */
1268 if (!X509_STORE_set1_param(ts, vpm /* may be NULL */)) {
1269 BIO_printf(bio_err, "error setting verification parameters\n");
1270 OSSL_CMP_CTX_print_errors(cmp_ctx);
1274 X509_STORE_set_verify_cb(ts, X509_STORE_CTX_print_verify_cb);
1279 static int set_name(const char *str,
1280 int (*set_fn) (OSSL_CMP_CTX *ctx, const X509_NAME *name),
1281 OSSL_CMP_CTX *ctx, const char *desc)
1284 X509_NAME *n = parse_name(str, MBSTRING_ASC, 0);
1287 CMP_err2("cannot parse %s DN '%s'", desc, str);
1290 if (!(*set_fn) (ctx, n)) {
1292 CMP_err("out of memory");
1300 static int set_gennames(OSSL_CMP_CTX *ctx, char *names, const char *desc)
1304 for (; names != NULL; names = next) {
1307 next = next_item(names);
1308 if (strcmp(names, "critical") == 0) {
1309 (void)OSSL_CMP_CTX_set_option(ctx,
1310 OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL,
1315 /* try IP address first, then URI or domain name */
1316 (void)ERR_set_mark();
1317 n = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_IPADD, names, 0);
1319 n = a2i_GENERAL_NAME(NULL, NULL, NULL,
1320 strchr(names, ':') != NULL ? GEN_URI : GEN_DNS,
1322 (void)ERR_pop_to_mark();
1325 CMP_err2("bad syntax of %s '%s'", desc, names);
1328 if (!OSSL_CMP_CTX_push1_subjectAltName(ctx, n)) {
1329 GENERAL_NAME_free(n);
1330 CMP_err("out of memory");
1333 GENERAL_NAME_free(n);
1338 /* TODO potentially move to apps/lib/apps.c */
1340 * create cert store structure with certificates read from given file(s)
1341 * returns pointer to created X509_STORE on success, NULL on error
1343 static X509_STORE *load_certstore(char *input, const char *desc)
1345 X509_STORE *store = NULL;
1346 STACK_OF(X509) *certs = NULL;
1351 while (input != NULL) {
1352 char *next = next_item(input); \
1354 if (!load_certs_autofmt(input, &certs, 1, opt_otherpass, desc)
1355 || !(store = sk_X509_to_store(store, certs))) {
1356 /* CMP_err("out of memory"); */
1357 X509_STORE_free(store);
1361 sk_X509_pop_free(certs, X509_free);
1366 sk_X509_pop_free(certs, X509_free);
1370 /* TODO potentially move to apps/lib/apps.c */
1371 static STACK_OF(X509) *load_certs_multifile(char *files,
1372 const char *pass, const char *desc)
1374 STACK_OF(X509) *certs = NULL;
1375 STACK_OF(X509) *result = sk_X509_new_null();
1382 while (files != NULL) {
1383 char *next = next_item(files);
1385 if (!load_certs_autofmt(files, &certs, 0, pass, desc))
1387 if (!sk_X509_add1_certs(result, certs, 0, 1 /* no dups */, 0))
1389 sk_X509_pop_free(certs, X509_free);
1396 BIO_printf(bio_err, "out of memory\n");
1398 sk_X509_pop_free(certs, X509_free);
1399 sk_X509_pop_free(result, X509_free);
1403 typedef int (*add_X509_stack_fn_t)(void *ctx, const STACK_OF(X509) *certs);
1404 typedef int (*add_X509_fn_t)(void *ctx, const X509 *cert);
1406 static int setup_certs(char *files, const char *desc, void *ctx,
1407 add_X509_stack_fn_t addn_fn, add_X509_fn_t add1_fn)
1411 if (files != NULL) {
1412 STACK_OF(X509) *certs = load_certs_multifile(files, opt_otherpass,
1414 if (certs == NULL) {
1417 if (addn_fn != NULL) {
1418 ret = (*addn_fn)(ctx, certs);
1422 for (i = 0; i < sk_X509_num(certs /* may be NULL */); i++)
1423 ret &= (*add1_fn)(ctx, sk_X509_value(certs, i));
1425 sk_X509_pop_free(certs, X509_free);
1433 * parse and transform some options, checking their syntax.
1434 * Returns 1 on success, 0 on error
1436 static int transform_opts(void)
1438 if (opt_cmd_s != NULL) {
1439 if (!strcmp(opt_cmd_s, "ir")) {
1441 } else if (!strcmp(opt_cmd_s, "kur")) {
1443 } else if (!strcmp(opt_cmd_s, "cr")) {
1445 } else if (!strcmp(opt_cmd_s, "p10cr")) {
1446 opt_cmd = CMP_P10CR;
1447 } else if (!strcmp(opt_cmd_s, "rr")) {
1449 } else if (!strcmp(opt_cmd_s, "genm")) {
1452 CMP_err1("unknown cmp command '%s'", opt_cmd_s);
1456 CMP_err("no cmp command to execute");
1460 #ifdef OPENSSL_NO_ENGINE
1461 # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12 | OPT_FMT_ENGINE)
1463 # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12)
1466 if (opt_keyform_s != NULL
1467 && !opt_format(opt_keyform_s, FORMAT_OPTIONS, &opt_keyform)) {
1468 CMP_err("unknown option given for key loading format");
1472 #undef FORMAT_OPTIONS
1474 if (opt_certform_s != NULL
1475 && !opt_format(opt_certform_s, OPT_FMT_PEMDER, &opt_certform)) {
1476 CMP_err("unknown option given for certificate storing format");
1480 if (opt_certsform_s != NULL
1481 && !opt_format(opt_certsform_s, OPT_FMT_PEMDER | OPT_FMT_PKCS12,
1483 CMP_err("unknown option given for certificate list loading format");
1490 static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *e)
1492 OSSL_CMP_CTX *ctx; /* extra CMP (client) ctx partly used by server */
1493 OSSL_CMP_SRV_CTX *srv_ctx = ossl_cmp_mock_srv_new();
1495 if (srv_ctx == NULL)
1497 ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx);
1499 if (opt_srv_ref == NULL) {
1500 if (opt_srv_cert == NULL) {
1501 /* opt_srv_cert should determine the sender */
1502 CMP_err("must give -srv_ref for server if no -srv_cert given");
1506 if (!OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_srv_ref,
1507 strlen(opt_srv_ref)))
1511 if (opt_srv_secret != NULL) {
1513 char *pass_str = get_passwd(opt_srv_secret, "PBMAC secret of server");
1515 if (pass_str != NULL) {
1516 cleanse(opt_srv_secret);
1517 res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_str,
1519 clear_free(pass_str);
1523 } else if (opt_srv_cert == NULL) {
1524 CMP_err("server credentials must be given if -use_mock_srv or -port is used");
1527 CMP_warn("server will not be able to handle PBM-protected requests since -srv_secret is not given");
1530 if (opt_srv_secret == NULL
1531 && ((opt_srv_cert == NULL) != (opt_srv_key == NULL))) {
1532 CMP_err("must give both -srv_cert and -srv_key options or neither");
1535 if (opt_srv_cert != NULL) {
1536 X509 *srv_cert = load_cert_pwd(opt_srv_cert, opt_srv_keypass,
1537 "certificate of the server");
1538 if (srv_cert == NULL || !OSSL_CMP_CTX_set1_clCert(ctx, srv_cert)) {
1539 X509_free(srv_cert);
1542 X509_free(srv_cert);
1544 if (opt_srv_key != NULL) {
1545 EVP_PKEY *pkey = load_key_pwd(opt_srv_key, opt_keyform,
1547 e, "private key for server cert");
1549 if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) {
1550 EVP_PKEY_free(pkey);
1553 EVP_PKEY_free(pkey);
1555 cleanse(opt_srv_keypass);
1557 if (opt_srv_trusted != NULL) {
1559 load_certstore(opt_srv_trusted, "certificates trusted by server");
1563 if (!set1_store_parameters(ts)
1564 || !truststore_set_host_etc(ts, NULL)
1565 || !OSSL_CMP_CTX_set0_trustedStore(ctx, ts)) {
1566 X509_STORE_free(ts);
1570 CMP_warn("server will not be able to handle signature-protected requests since -srv_trusted is not given");
1572 if (!setup_certs(opt_srv_untrusted, "untrusted certificates", ctx,
1573 (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted_certs,
1577 if (opt_rsp_cert == NULL) {
1578 CMP_err("must give -rsp_cert for mock server");
1581 X509 *cert = load_cert_pwd(opt_rsp_cert, opt_keypass,
1582 "cert to be returned by the mock server");
1586 /* from server perspective the server is the client */
1587 if (!ossl_cmp_mock_srv_set1_certOut(srv_ctx, cert)) {
1593 /* TODO find a cleaner solution not requiring type casts */
1594 if (!setup_certs(opt_rsp_extracerts,
1595 "CMP extra certificates for mock server", srv_ctx,
1596 (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_chainOut,
1599 if (!setup_certs(opt_rsp_capubs, "caPubs for mock server", srv_ctx,
1600 (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_caPubsOut,
1603 (void)ossl_cmp_mock_srv_set_pollCount(srv_ctx, opt_poll_count);
1604 (void)ossl_cmp_mock_srv_set_checkAfterTime(srv_ctx, opt_check_after);
1605 if (opt_grant_implicitconf)
1606 (void)OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(srv_ctx, 1);
1608 if (opt_failure != INT_MIN) { /* option has been set explicity */
1609 if (opt_failure < 0 || OSSL_CMP_PKIFAILUREINFO_MAX < opt_failure) {
1610 CMP_err1("-failure out of range, should be >= 0 and <= %d",
1611 OSSL_CMP_PKIFAILUREINFO_MAX);
1614 if (opt_failurebits != 0)
1615 CMP_warn("-failurebits overrides -failure");
1617 opt_failurebits = 1 << opt_failure;
1619 if ((unsigned)opt_failurebits > OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN) {
1620 CMP_err("-failurebits out of range");
1623 if (!ossl_cmp_mock_srv_set_statusInfo(srv_ctx, opt_pkistatus,
1624 opt_failurebits, opt_statusstring))
1628 (void)ossl_cmp_mock_srv_set_send_error(srv_ctx, 1);
1630 if (opt_send_unprotected)
1631 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1);
1632 if (opt_send_unprot_err)
1633 (void)OSSL_CMP_SRV_CTX_set_send_unprotected_errors(srv_ctx, 1);
1634 if (opt_accept_unprotected)
1635 (void)OSSL_CMP_SRV_CTX_set_accept_unprotected(srv_ctx, 1);
1636 if (opt_accept_unprot_err)
1637 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1);
1638 if (opt_accept_raverified)
1639 (void)OSSL_CMP_SRV_CTX_set_accept_raverified(srv_ctx, 1);
1644 ossl_cmp_mock_srv_free(srv_ctx);
1649 * set up verification aspects of OSSL_CMP_CTX w.r.t. opts from config file/CLI.
1650 * Returns pointer on success, NULL on error
1652 static int setup_verification_ctx(OSSL_CMP_CTX *ctx)
1654 if (!setup_certs(opt_untrusted, "untrusted certificates", ctx,
1655 (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted_certs,
1659 if (opt_srvcert != NULL || opt_trusted != NULL) {
1660 X509_STORE *ts = NULL;
1662 if (opt_srvcert != NULL) {
1665 if (opt_trusted != NULL) {
1666 CMP_warn("-trusted option is ignored since -srvcert option is present");
1669 if (opt_recipient != NULL) {
1670 CMP_warn("-recipient option is ignored since -srvcert option is present");
1671 opt_recipient = NULL;
1673 srvcert = load_cert_pwd(opt_srvcert, opt_otherpass,
1674 "directly trusted CMP server certificate");
1675 if (srvcert == NULL)
1677 * opt_otherpass is needed in case
1678 * opt_srvcert is an encrypted PKCS#12 file
1681 if (!OSSL_CMP_CTX_set1_srvCert(ctx, srvcert)) {
1686 if ((ts = X509_STORE_new()) == NULL)
1689 if (opt_trusted != NULL
1690 && (ts = load_certstore(opt_trusted, "trusted certificates"))
1693 if (!set1_store_parameters(ts) /* also copies vpm */
1695 * clear any expected host/ip/email address;
1696 * opt_expect_sender is used instead
1698 || !truststore_set_host_etc(ts, NULL)
1699 || !OSSL_CMP_CTX_set0_trustedStore(ctx, ts)) {
1700 X509_STORE_free(ts);
1705 if (opt_ignore_keyusage)
1706 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IGNORE_KEYUSAGE, 1);
1708 if (opt_unprotected_errors)
1709 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1);
1711 if (opt_out_trusted != NULL) { /* for use in OSSL_CMP_certConf_cb() */
1712 X509_VERIFY_PARAM *out_vpm = NULL;
1713 X509_STORE *out_trusted =
1714 load_certstore(opt_out_trusted,
1715 "trusted certs for verifying newly enrolled cert");
1717 if (out_trusted == NULL)
1719 /* any -verify_hostname, -verify_ip, and -verify_email apply here */
1720 if (!set1_store_parameters(out_trusted))
1722 /* ignore any -attime here, new certs are current anyway */
1723 out_vpm = X509_STORE_get0_param(out_trusted);
1724 X509_VERIFY_PARAM_clear_flags(out_vpm, X509_V_FLAG_USE_CHECK_TIME);
1726 (void)OSSL_CMP_CTX_set_certConf_cb_arg(ctx, out_trusted);
1729 if (opt_disable_confirm)
1730 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DISABLE_CONFIRM, 1);
1732 if (opt_implicit_confirm)
1733 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM, 1);
1735 (void)OSSL_CMP_CTX_set_certConf_cb(ctx, OSSL_CMP_certConf_cb);
1740 CMP_err("out of memory");
1745 #ifndef OPENSSL_NO_SOCK
1747 * set up ssl_ctx for the OSSL_CMP_CTX based on options from config file/CLI.
1748 * Returns pointer on success, NULL on error
1750 static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, ENGINE *e)
1752 STACK_OF(X509) *untrusted_certs = OSSL_CMP_CTX_get0_untrusted_certs(ctx);
1753 EVP_PKEY *pkey = NULL;
1754 X509_STORE *trust_store = NULL;
1758 ssl_ctx = SSL_CTX_new(TLS_client_method());
1759 if (ssl_ctx == NULL)
1762 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
1764 if (opt_tls_trusted != NULL) {
1765 if ((trust_store = load_certstore(opt_tls_trusted,
1766 "trusted TLS certificates")) == NULL)
1768 SSL_CTX_set_cert_store(ssl_ctx, trust_store);
1769 /* for improved diagnostics on SSL_CTX_build_cert_chain() errors: */
1770 X509_STORE_set_verify_cb(trust_store, X509_STORE_CTX_print_verify_cb);
1773 if (opt_tls_cert != NULL && opt_tls_key != NULL) {
1775 STACK_OF(X509) *certs = NULL;
1777 if (!load_certs_autofmt(opt_tls_cert, &certs, 0, opt_tls_keypass,
1778 "TLS client certificate (optionally with chain)"))
1780 * opt_tls_keypass is needed in case opt_tls_cert is an encrypted
1785 cert = sk_X509_delete(certs, 0);
1786 if (cert == NULL || SSL_CTX_use_certificate(ssl_ctx, cert) <= 0) {
1787 CMP_err1("unable to use client TLS certificate file '%s'",
1790 sk_X509_pop_free(certs, X509_free);
1793 X509_free(cert); /* we do not need the handle any more */
1796 * Any further certs and any untrusted certs are used for constructing
1797 * the client cert chain to be provided along with the TLS client cert
1798 * to the TLS server.
1800 if (!SSL_CTX_set0_chain(ssl_ctx, certs)) {
1801 CMP_err("could not set TLS client cert chain");
1802 sk_X509_pop_free(certs, X509_free);
1805 for (i = 0; i < sk_X509_num(untrusted_certs); i++) {
1806 cert = sk_X509_value(untrusted_certs, i);
1807 if (!SSL_CTX_add1_chain_cert(ssl_ctx, cert)) {
1808 CMP_err("could not add untrusted cert to TLS client cert chain");
1812 if (!SSL_CTX_build_cert_chain(ssl_ctx,
1813 SSL_BUILD_CHAIN_FLAG_UNTRUSTED |
1814 SSL_BUILD_CHAIN_FLAG_NO_ROOT)) {
1815 CMP_warn("could not build cert chain for own TLS cert");
1816 OSSL_CMP_CTX_print_errors(ctx);
1819 /* If present we append to the list also the certs from opt_tls_extra */
1820 if (opt_tls_extra != NULL) {
1821 STACK_OF(X509) *tls_extra = load_certs_multifile(opt_tls_extra,
1823 "extra certificates for TLS");
1826 if (tls_extra == NULL)
1828 for (i = 0; i < sk_X509_num(tls_extra); i++) {
1829 cert = sk_X509_value(tls_extra, i);
1831 res = SSL_CTX_add_extra_chain_cert(ssl_ctx, cert);
1835 sk_X509_free(tls_extra);
1837 BIO_printf(bio_err, "error: unable to add TLS extra certs\n");
1842 pkey = load_key_pwd(opt_tls_key, opt_keyform, opt_tls_keypass,
1843 e, "TLS client private key");
1844 cleanse(opt_tls_keypass);
1848 * verify the key matches the cert,
1849 * not using SSL_CTX_check_private_key(ssl_ctx)
1850 * because it gives poor and sometimes misleading diagnostics
1852 if (!X509_check_private_key(SSL_CTX_get0_certificate(ssl_ctx),
1854 CMP_err2("TLS private key '%s' does not match the TLS certificate '%s'\n",
1855 opt_tls_key, opt_tls_cert);
1856 EVP_PKEY_free(pkey);
1857 pkey = NULL; /* otherwise, for some reason double free! */
1860 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) <= 0) {
1861 CMP_err1("unable to use TLS client private key '%s'", opt_tls_key);
1862 EVP_PKEY_free(pkey);
1863 pkey = NULL; /* otherwise, for some reason double free! */
1866 EVP_PKEY_free(pkey); /* we do not need the handle any more */
1868 if (opt_tls_trusted != NULL) {
1869 /* enable and parameterize server hostname/IP address check */
1870 if (!truststore_set_host_etc(trust_store,
1871 opt_tls_host != NULL ?
1872 opt_tls_host : opt_server))
1873 /* TODO: is the server host name correct for TLS via proxy? */
1875 SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
1879 SSL_CTX_free(ssl_ctx);
1885 * set up protection aspects of OSSL_CMP_CTX based on options from config
1886 * file/CLI while parsing options and checking their consistency.
1887 * Returns 1 on success, 0 on error
1889 static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *e)
1891 if (!opt_unprotected_requests && opt_secret == NULL && opt_cert == NULL) {
1892 CMP_err("must give client credentials unless -unprotected_requests is set");
1896 if (opt_ref == NULL && opt_cert == NULL && opt_subject == NULL) {
1897 /* cert or subject should determine the sender */
1898 CMP_err("must give -ref if no -cert and no -subject given");
1901 if (!opt_secret && ((opt_cert == NULL) != (opt_key == NULL))) {
1902 CMP_err("must give both -cert and -key options or neither");
1905 if (opt_secret != NULL) {
1906 char *pass_string = get_passwd(opt_secret, "PBMAC");
1909 if (pass_string != NULL) {
1910 cleanse(opt_secret);
1911 res = OSSL_CMP_CTX_set1_secretValue(ctx,
1912 (unsigned char *)pass_string,
1913 strlen(pass_string));
1914 clear_free(pass_string);
1918 if (opt_cert != NULL || opt_key != NULL)
1919 CMP_warn("no signature-based protection used since -secret is given");
1922 && !OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_ref,
1926 if (opt_key != NULL) {
1927 EVP_PKEY *pkey = load_key_pwd(opt_key, opt_keyform, opt_keypass, e,
1928 "private key for CMP client certificate");
1930 if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) {
1931 EVP_PKEY_free(pkey);
1934 EVP_PKEY_free(pkey);
1936 if (opt_secret == NULL && opt_srvcert == NULL && opt_trusted == NULL) {
1937 CMP_err("missing -secret or -srvcert or -trusted");
1941 if (opt_cert != NULL) {
1943 STACK_OF(X509) *certs = NULL;
1946 if (!load_certs_autofmt(opt_cert, &certs, 0, opt_keypass,
1947 "CMP client certificate (and optionally extra certs)"))
1948 /* opt_keypass is needed if opt_cert is an encrypted PKCS#12 file */
1951 clcert = sk_X509_delete(certs, 0);
1952 if (clcert == NULL) {
1953 CMP_err("no client certificate found");
1954 sk_X509_pop_free(certs, X509_free);
1957 ok = OSSL_CMP_CTX_set1_clCert(ctx, clcert);
1961 /* add any remaining certs to the list of untrusted certs */
1962 STACK_OF(X509) *untrusted = OSSL_CMP_CTX_get0_untrusted_certs(ctx);
1963 ok = untrusted != NULL ?
1964 sk_X509_add1_certs(untrusted, certs, 0, 1 /* no dups */, 0) :
1965 OSSL_CMP_CTX_set1_untrusted_certs(ctx, certs);
1967 sk_X509_pop_free(certs, X509_free);
1972 if (!setup_certs(opt_extracerts, "extra certificates for CMP", ctx,
1973 (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_extraCertsOut,
1976 cleanse(opt_otherpass);
1978 if (opt_unprotected_requests)
1979 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1);
1981 if (opt_digest != NULL) {
1982 int digest = OBJ_ln2nid(opt_digest);
1984 if (digest == NID_undef) {
1985 CMP_err1("digest algorithm name not recognized: '%s'", opt_digest);
1988 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DIGEST_ALGNID, digest);
1989 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_OWF_ALGNID, digest);
1992 if (opt_mac != NULL) {
1993 int mac = OBJ_ln2nid(opt_mac);
1994 if (mac == NID_undef) {
1995 CMP_err1("MAC algorithm name not recognized: '%s'", opt_mac);
1998 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MAC_ALGNID, mac);
2003 CMP_err("out of memory");
2009 * set up IR/CR/KUR/CertConf/RR specific parts of the OSSL_CMP_CTX
2010 * based on options from config file/CLI.
2011 * Returns pointer on success, NULL on error
2013 static int setup_request_ctx(OSSL_CMP_CTX *ctx, ENGINE *e)
2015 if (opt_subject == NULL && opt_oldcert == NULL && opt_cert == NULL)
2016 CMP_warn("no -subject given, neither -oldcert nor -cert available as default");
2017 if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject")
2018 || !set_name(opt_issuer, OSSL_CMP_CTX_set1_issuer, ctx, "issuer"))
2021 if (opt_newkey != NULL) {
2022 const char *file = opt_newkey;
2023 const int format = opt_keyform;
2024 const char *pass = opt_newkeypass;
2025 const char *desc = "new private or public key for cert to be enrolled";
2026 EVP_PKEY *pkey = load_key_pwd(file, format, pass, e, NULL);
2031 pkey = load_pubkey(file, format, 0, pass, e, desc);
2034 cleanse(opt_newkeypass);
2035 if (pkey == NULL || !OSSL_CMP_CTX_set0_newPkey(ctx, priv, pkey)) {
2036 EVP_PKEY_free(pkey);
2042 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_VALIDITY_DAYS,
2045 if (opt_policies != NULL && opt_policy_oids != NULL) {
2046 CMP_err("cannot have policies both via -policies and via -policy_oids");
2050 if (opt_reqexts != NULL || opt_policies != NULL) {
2052 X509_EXTENSIONS *exts = sk_X509_EXTENSION_new_null();
2056 X509V3_set_ctx(&ext_ctx, NULL, NULL, NULL, NULL, 0);
2057 X509V3_set_nconf(&ext_ctx, conf);
2058 if (opt_reqexts != NULL
2059 && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_reqexts, &exts)) {
2060 CMP_err1("cannot load certificate request extension section '%s'",
2062 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
2065 if (opt_policies != NULL
2066 && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_policies, &exts)) {
2067 CMP_err1("cannot load policy cert request extension section '%s'",
2069 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
2072 OSSL_CMP_CTX_set0_reqExtensions(ctx, exts);
2074 if (OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) && opt_sans != NULL) {
2075 CMP_err("cannot have Subject Alternative Names both via -reqexts and via -sans");
2079 if (!set_gennames(ctx, opt_sans, "Subject Alternative Name"))
2082 if (opt_san_nodefault) {
2083 if (opt_sans != NULL)
2084 CMP_warn("-opt_san_nodefault has no effect when -sans is used");
2085 (void)OSSL_CMP_CTX_set_option(ctx,
2086 OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT, 1);
2089 if (opt_policy_oids_critical) {
2090 if (opt_policy_oids == NULL)
2091 CMP_warn("-opt_policy_oids_critical has no effect unless -policy_oids is given");
2092 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POLICIES_CRITICAL, 1);
2095 while (opt_policy_oids != NULL) {
2096 ASN1_OBJECT *policy;
2098 char *next = next_item(opt_policy_oids);
2100 if ((policy = OBJ_txt2obj(opt_policy_oids, 1)) == 0) {
2101 CMP_err1("unknown policy OID '%s'", opt_policy_oids);
2105 if ((pinfo = POLICYINFO_new()) == NULL) {
2106 ASN1_OBJECT_free(policy);
2109 pinfo->policyid = policy;
2111 if (!OSSL_CMP_CTX_push0_policy(ctx, pinfo)) {
2112 CMP_err1("cannot add policy with OID '%s'", opt_policy_oids);
2113 POLICYINFO_free(pinfo);
2116 opt_policy_oids = next;
2119 if (opt_popo >= OSSL_CRMF_POPO_NONE)
2120 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POPO_METHOD, opt_popo);
2122 if (opt_csr != NULL) {
2123 if (opt_cmd != CMP_P10CR) {
2124 CMP_warn("-csr option is ignored for command other than p10cr");
2127 load_csr_autofmt(opt_csr, "PKCS#10 CSR for p10cr");
2131 if (!OSSL_CMP_CTX_set1_p10CSR(ctx, csr)) {
2139 if (opt_oldcert != NULL) {
2140 X509 *oldcert = load_cert_pwd(opt_oldcert, opt_keypass,
2141 "certificate to be updated/revoked");
2142 /* opt_keypass is needed if opt_oldcert is an encrypted PKCS#12 file */
2144 if (oldcert == NULL)
2146 if (!OSSL_CMP_CTX_set1_oldCert(ctx, oldcert)) {
2152 cleanse(opt_keypass);
2153 if (opt_revreason > CRL_REASON_NONE)
2154 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_REVOCATION_REASON,
2160 CMP_err("out of memory");
2165 static int handle_opt_geninfo(OSSL_CMP_CTX *ctx)
2171 OSSL_CMP_ITAV *itav;
2173 char *valptr = strchr(opt_geninfo, ':');
2175 if (valptr == NULL) {
2176 CMP_err("missing ':' in -geninfo option");
2182 if (strncasecmp(valptr, "int:", 4) != 0) {
2183 CMP_err("missing 'int:' in -geninfo option");
2188 value = strtol(valptr, &endstr, 10);
2189 if (endstr == valptr || *endstr != '\0') {
2190 CMP_err("cannot parse int in -geninfo option");
2194 type = OBJ_txt2obj(opt_geninfo, 1);
2196 CMP_err("cannot parse OID in -geninfo option");
2200 aint = ASN1_INTEGER_new();
2201 if (aint == NULL || !ASN1_INTEGER_set(aint, value))
2204 val = ASN1_TYPE_new();
2206 ASN1_INTEGER_free(aint);
2209 ASN1_TYPE_set(val, V_ASN1_INTEGER, aint);
2210 itav = OSSL_CMP_ITAV_create(type, val);
2212 ASN1_TYPE_free(val);
2216 if (!OSSL_CMP_CTX_push0_geninfo_ITAV(ctx, itav)) {
2217 OSSL_CMP_ITAV_free(itav);
2223 CMP_err("out of memory");
2229 * set up the client-side OSSL_CMP_CTX based on options from config file/CLI
2230 * while parsing options and checking their consistency.
2231 * Prints reason for error to bio_err.
2232 * Returns 1 on success, 0 on error
2234 static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *e)
2237 char server_buf[200] = { '\0' };
2238 char proxy_buf[200] = { '\0' };
2239 char *proxy_host = NULL;
2240 char *proxy_port_str = NULL;
2242 if (opt_server == NULL) {
2243 CMP_err("missing server address[:port]");
2245 } else if ((server_port =
2246 parse_addr(&opt_server, server_port, "server")) < 0) {
2249 if (server_port != 0)
2250 BIO_snprintf(server_port_s, sizeof(server_port_s), "%d", server_port);
2251 if (!OSSL_CMP_CTX_set1_server(ctx, opt_server)
2252 || !OSSL_CMP_CTX_set_serverPort(ctx, server_port)
2253 || !OSSL_CMP_CTX_set1_serverPath(ctx, opt_path))
2255 if (opt_proxy != NULL && !OSSL_CMP_CTX_set1_proxy(ctx, opt_proxy))
2257 (void)BIO_snprintf(server_buf, sizeof(server_buf), "http%s://%s%s%s/%s",
2258 opt_tls_used ? "s" : "", opt_server,
2259 server_port == 0 ? "" : ":", server_port_s,
2260 opt_path[0] == '/' ? opt_path + 1 : opt_path);
2262 if (opt_proxy != NULL)
2263 (void)BIO_snprintf(proxy_buf, sizeof(proxy_buf), " via %s", opt_proxy);
2264 CMP_info2("will contact %s%s", server_buf, proxy_buf);
2266 if (!transform_opts())
2269 if (opt_cmd == CMP_IR || opt_cmd == CMP_CR || opt_cmd == CMP_KUR) {
2270 if (opt_newkey == NULL && opt_key == NULL && opt_csr == NULL) {
2271 CMP_err("missing -newkey (or -key) to be certified");
2274 if (opt_certout == NULL) {
2275 CMP_err("-certout not given, nowhere to save certificate");
2279 if (opt_cmd == CMP_KUR) {
2280 char *ref_cert = opt_oldcert != NULL ? opt_oldcert : opt_cert;
2282 if (ref_cert == NULL) {
2283 CMP_err("missing -oldcert option for certificate to be updated");
2286 if (opt_subject != NULL)
2287 CMP_warn2("-subject '%s' given, which overrides the subject of '%s' in KUR",
2288 opt_subject, ref_cert);
2290 if (opt_cmd == CMP_RR && opt_oldcert == NULL) {
2291 CMP_err("missing certificate to be revoked");
2294 if (opt_cmd == CMP_P10CR && opt_csr == NULL) {
2295 CMP_err("missing PKCS#10 CSR for p10cr");
2299 if (opt_recipient == NULL && opt_srvcert == NULL && opt_issuer == NULL
2300 && opt_oldcert == NULL && opt_cert == NULL)
2301 CMP_warn("missing -recipient, -srvcert, -issuer, -oldcert or -cert; recipient will be set to \"NULL-DN\"");
2303 if (opt_infotype_s != NULL) {
2304 char id_buf[100] = "id-it-";
2306 strncat(id_buf, opt_infotype_s, sizeof(id_buf) - strlen(id_buf) - 1);
2307 if ((opt_infotype = OBJ_sn2nid(id_buf)) == NID_undef) {
2308 CMP_err("unknown OID name in -infotype option");
2313 if (!setup_verification_ctx(ctx))
2316 if (opt_msg_timeout >= 0) /* must do this before setup_ssl_ctx() */
2317 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT,
2319 if (opt_total_timeout >= 0)
2320 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_TOTAL_TIMEOUT,
2323 if (opt_reqin != NULL && opt_rspin != NULL)
2324 CMP_warn("-reqin is ignored since -rspin is present");
2325 if (opt_reqin_new_tid && opt_reqin == NULL)
2326 CMP_warn("-reqin_new_tid is ignored since -reqin is not present");
2327 if (opt_reqin != NULL || opt_reqout != NULL
2328 || opt_rspin != NULL || opt_rspout != NULL || opt_use_mock_srv)
2329 (void)OSSL_CMP_CTX_set_transfer_cb(ctx, read_write_req_resp);
2331 if ((opt_tls_cert != NULL || opt_tls_key != NULL
2332 || opt_tls_keypass != NULL || opt_tls_extra != NULL
2333 || opt_tls_trusted != NULL || opt_tls_host != NULL)
2335 CMP_warn("TLS options(s) given but not -tls_used");
2337 #ifdef OPENSSL_NO_SOCK
2338 BIO_printf(bio_err, "Cannot use TLS - sockets not supported\n");
2341 APP_HTTP_TLS_INFO *info;
2343 if (opt_tls_cert != NULL
2344 || opt_tls_key != NULL || opt_tls_keypass != NULL) {
2345 if (opt_tls_key == NULL) {
2346 CMP_err("missing -tls_key option");
2348 } else if (opt_tls_cert == NULL) {
2349 CMP_err("missing -tls_cert option");
2353 if (opt_use_mock_srv) {
2354 CMP_err("cannot use TLS options together with -use_mock_srv");
2357 if ((info = OPENSSL_zalloc(sizeof(*info))) == NULL)
2359 (void)OSSL_CMP_CTX_set_http_cb_arg(ctx, info);
2360 /* info will be freed along with CMP ctx */
2361 info->server = opt_server;
2362 info->port = server_port_s;
2363 info->use_proxy = opt_proxy != NULL;
2364 info->timeout = OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT);
2365 info->ssl_ctx = setup_ssl_ctx(ctx, e);
2366 if (info->ssl_ctx == NULL)
2368 (void)OSSL_CMP_CTX_set_http_cb(ctx, app_http_tls_cb);
2372 if (!setup_protection_ctx(ctx, e))
2375 if (!setup_request_ctx(ctx, e))
2378 if (!set_name(opt_recipient, OSSL_CMP_CTX_set1_recipient, ctx, "recipient")
2379 || !set_name(opt_expect_sender, OSSL_CMP_CTX_set1_expected_sender,
2380 ctx, "expected sender"))
2383 if (opt_geninfo != NULL && !handle_opt_geninfo(ctx))
2389 OPENSSL_free(proxy_host);
2390 OPENSSL_free(proxy_port_str);
2393 CMP_err("out of memory");
2398 * write out the given certificate to the output specified by bio.
2399 * Depending on options use either PEM or DER format.
2400 * Returns 1 on success, 0 on error
2402 static int write_cert(BIO *bio, X509 *cert)
2404 if ((opt_certform == FORMAT_PEM && PEM_write_bio_X509(bio, cert))
2405 || (opt_certform == FORMAT_ASN1 && i2d_X509_bio(bio, cert)))
2407 if (opt_certform != FORMAT_PEM && opt_certform != FORMAT_ASN1)
2409 "error: unsupported type '%s' for writing certificates\n",
2415 * writes out a stack of certs to the given file.
2416 * Depending on options use either PEM or DER format,
2417 * where DER does not make much sense for writing more than one cert!
2418 * Returns number of written certificates on success, 0 on error.
2420 static int save_certs(OSSL_CMP_CTX *ctx,
2421 STACK_OF(X509) *certs, char *destFile, char *desc)
2425 int n = sk_X509_num(certs);
2427 CMP_info3("received %d %s certificate(s), saving to file '%s'",
2429 if (n > 1 && opt_certform != FORMAT_PEM)
2430 CMP_warn("saving more than one certificate in non-PEM format");
2432 if (destFile == NULL || (bio = BIO_new(BIO_s_file())) == NULL
2433 || !BIO_write_filename(bio, (char *)destFile)) {
2434 CMP_err1("could not open file '%s' for writing", destFile);
2439 for (i = 0; i < n; i++) {
2440 if (!write_cert(bio, sk_X509_value(certs, i))) {
2441 CMP_err1("cannot write certificate to file '%s'", destFile);
2452 static void print_itavs(STACK_OF(OSSL_CMP_ITAV) *itavs)
2454 OSSL_CMP_ITAV *itav = NULL;
2457 int n = sk_OSSL_CMP_ITAV_num(itavs); /* itavs == NULL leads to 0 */
2460 CMP_info("genp contains no ITAV");
2464 for (i = 0; i < n; i++) {
2465 itav = sk_OSSL_CMP_ITAV_value(itavs, i);
2466 OBJ_obj2txt(buf, 128, OSSL_CMP_ITAV_get0_type(itav), 0);
2467 CMP_info1("genp contains ITAV of type: %s", buf);
2471 static char opt_item[SECTION_NAME_MAX + 1];
2472 /* get previous name from a comma-separated list of names */
2473 static const char *prev_item(const char *opt, const char *end)
2481 while (beg != opt && beg[-1] != ',' && !isspace(beg[-1]))
2484 if (len > SECTION_NAME_MAX)
2485 len = SECTION_NAME_MAX;
2486 strncpy(opt_item, beg, len);
2487 opt_item[SECTION_NAME_MAX] = '\0'; /* avoid gcc v8 O3 stringop-truncation */
2488 opt_item[len] = '\0';
2489 if (len > SECTION_NAME_MAX)
2490 CMP_warn2("using only first %d characters of section name starting with \"%s\"",
2491 SECTION_NAME_MAX, opt_item);
2492 while (beg != opt && (beg[-1] == ',' || isspace(beg[-1])))
2497 /* get str value for name from a comma-separated hierarchy of config sections */
2498 static char *conf_get_string(const CONF *src_conf, const char *groups,
2502 const char *end = groups + strlen(groups);
2504 while ((end = prev_item(groups, end)) != NULL) {
2505 if ((res = NCONF_get_string(src_conf, opt_item, name)) != NULL)
2511 /* get long val for name from a comma-separated hierarchy of config sections */
2512 static int conf_get_number_e(const CONF *conf_, const char *groups,
2513 const char *name, long *result)
2515 char *str = conf_get_string(conf_, groups, name);
2519 if (str == NULL || *str == '\0')
2522 res = strtol(str, &tailptr, 10);
2523 if (res == LONG_MIN || res == LONG_MAX || *tailptr != '\0')
2531 * use the command line option table to read values from the CMP section
2532 * of openssl.cnf. Defaults are taken from the config file, they can be
2533 * overwritten on the command line.
2535 static int read_config(void)
2541 int provider_option;
2542 int verification_option;
2545 * starting with offset OPT_SECTION because OPT_CONFIG and OPT_SECTION would
2546 * not make sense within the config file. They have already been handled.
2548 for (i = OPT_SECTION - OPT_HELP, opt = &cmp_options[OPT_SECTION];
2549 opt->name; i++, opt++) {
2550 if (!strcmp(opt->name, OPT_SECTION_STR)
2551 || !strcmp(opt->name, OPT_MORE_STR)) {
2555 provider_option = (OPT_PROV__FIRST <= opt->retval
2556 && opt->retval < OPT_PROV__LAST);
2557 verification_option = (OPT_V__FIRST <= opt->retval
2558 && opt->retval < OPT_V__LAST);
2559 if (provider_option || verification_option)
2561 if (cmp_vars[i].txt == NULL) {
2562 CMP_err1("internal: cmp_vars array too short, i=%d", i);
2565 switch (opt->valtype) {
2569 if (!conf_get_number_e(conf, opt_section, opt->name, &num)) {
2571 continue; /* option not provided */
2575 * do not use '<' in cmp_options. Incorrect treatment
2576 * somewhere in args_verify() can wrongly set badarg = 1
2581 txt = conf_get_string(conf, opt_section, opt->name);
2584 continue; /* option not provided */
2588 CMP_err2("internal: unsupported type '%c' for option '%s'",
2589 opt->valtype, opt->name);
2593 if (provider_option || verification_option) {
2598 BIO_snprintf(arg1, 81, "-%s", (char *)opt->name);
2599 conf_argv[0] = prog;
2600 conf_argv[1] = arg1;
2601 if (opt->valtype == '-') {
2606 conf_argv[2] = conf_get_string(conf, opt_section, opt->name);
2609 if (conf_argc > 1) {
2610 (void)opt_init(conf_argc, conf_argv, cmp_options);
2613 ? !opt_provider(opt_next())
2614 : !opt_verify(opt_next(), vpm)) {
2615 CMP_err2("for option '%s' in config file section '%s'",
2616 opt->name, opt_section);
2621 switch (opt->valtype) {
2624 if (num < INT_MIN || INT_MAX < num) {
2626 "integer value out of range for option '%s'\n",
2630 *cmp_vars[i].num = (int)num;
2633 *cmp_vars[i].num_long = num;
2636 if (txt != NULL && txt[0] == '\0')
2637 txt = NULL; /* reset option on empty string input */
2638 *cmp_vars[i].txt = txt;
2647 static char *opt_str(char *opt)
2649 char *arg = opt_arg();
2651 if (arg[0] == '\0') {
2652 CMP_warn1("argument of -%s option is empty string, resetting option",
2655 } else if (arg[0] == '-') {
2656 CMP_warn1("argument of -%s option starts with hyphen", opt);
2661 static int opt_nat(void)
2665 if (opt_int(opt_arg(), &result) && result < 0)
2666 BIO_printf(bio_err, "error: argument '%s' must not be negative\n",
2671 /* returns 1 on success, 0 on error, -1 on -help (i.e., stop with success) */
2672 static int get_opts(int argc, char **argv)
2676 prog = opt_init(argc, argv, cmp_options);
2678 while ((o = opt_next()) != OPT_EOF) {
2684 opt_help(cmp_options);
2686 case OPT_CONFIG: /* has already been handled */
2688 case OPT_SECTION: /* has already been handled */
2691 opt_server = opt_str("server");
2694 opt_proxy = opt_str("proxy");
2697 opt_no_proxy = opt_str("no_proxy");
2700 opt_path = opt_str("path");
2702 case OPT_MSG_TIMEOUT:
2703 if ((opt_msg_timeout = opt_nat()) < 0)
2706 case OPT_TOTAL_TIMEOUT:
2707 if ((opt_total_timeout = opt_nat()) < 0)
2714 opt_tls_cert = opt_str("tls_cert");
2717 opt_tls_key = opt_str("tls_key");
2719 case OPT_TLS_KEYPASS:
2720 opt_tls_keypass = opt_str("tls_keypass");
2723 opt_tls_extra = opt_str("tls_extra");
2725 case OPT_TLS_TRUSTED:
2726 opt_tls_trusted = opt_str("tls_trusted");
2729 opt_tls_host = opt_str("tls_host");
2732 opt_ref = opt_str("ref");
2735 opt_secret = opt_str("secret");
2738 opt_cert = opt_str("cert");
2741 opt_key = opt_str("key");
2744 opt_keypass = opt_str("keypass");
2747 opt_digest = opt_str("digest");
2750 opt_mac = opt_str("mac");
2752 case OPT_EXTRACERTS:
2753 opt_extracerts = opt_str("extracerts");
2755 case OPT_UNPROTECTED_REQUESTS:
2756 opt_unprotected_requests = 1;
2760 opt_trusted = opt_str("trusted");
2763 opt_untrusted = opt_str("untrusted");
2766 opt_srvcert = opt_str("srvcert");
2769 opt_recipient = opt_str("recipient");
2771 case OPT_EXPECT_SENDER:
2772 opt_expect_sender = opt_str("expect_sender");
2774 case OPT_IGNORE_KEYUSAGE:
2775 opt_ignore_keyusage = 1;
2777 case OPT_UNPROTECTED_ERRORS:
2778 opt_unprotected_errors = 1;
2780 case OPT_EXTRACERTSOUT:
2781 opt_extracertsout = opt_str("extracertsout");
2783 case OPT_CACERTSOUT:
2784 opt_cacertsout = opt_str("cacertsout");
2788 if (!opt_verify(o, vpm))
2792 opt_cmd_s = opt_str("cmd");
2795 opt_infotype_s = opt_str("infotype");
2798 opt_geninfo = opt_str("geninfo");
2802 opt_newkey = opt_str("newkey");
2804 case OPT_NEWKEYPASS:
2805 opt_newkeypass = opt_str("newkeypass");
2808 opt_subject = opt_str("subject");
2811 opt_issuer = opt_str("issuer");
2814 if ((opt_days = opt_nat()) < 0)
2818 opt_reqexts = opt_str("reqexts");
2821 opt_sans = opt_str("sans");
2823 case OPT_SAN_NODEFAULT:
2824 opt_san_nodefault = 1;
2827 opt_policies = opt_str("policies");
2829 case OPT_POLICY_OIDS:
2830 opt_policy_oids = opt_str("policy_oids");
2832 case OPT_POLICY_OIDS_CRITICAL:
2833 opt_policy_oids_critical = 1;
2836 if (!opt_int(opt_arg(), &opt_popo)
2837 || opt_popo < OSSL_CRMF_POPO_NONE
2838 || opt_popo > OSSL_CRMF_POPO_KEYENC) {
2839 CMP_err("invalid popo spec. Valid values are -1 .. 2");
2844 opt_csr = opt_arg();
2846 case OPT_OUT_TRUSTED:
2847 opt_out_trusted = opt_str("out_trusted");
2849 case OPT_IMPLICIT_CONFIRM:
2850 opt_implicit_confirm = 1;
2852 case OPT_DISABLE_CONFIRM:
2853 opt_disable_confirm = 1;
2856 opt_certout = opt_str("certout");
2859 opt_oldcert = opt_str("oldcert");
2862 if (!opt_int(opt_arg(), &opt_revreason)
2863 || opt_revreason < CRL_REASON_NONE
2864 || opt_revreason > CRL_REASON_AA_COMPROMISE
2865 || opt_revreason == 7) {
2866 CMP_err("invalid revreason. Valid values are -1 .. 6, 8 .. 10");
2871 opt_certform_s = opt_str("certform");
2874 opt_keyform_s = opt_str("keyform");
2877 opt_certsform_s = opt_str("certsform");
2880 opt_otherpass = opt_str("otherpass");
2882 #ifndef OPENSSL_NO_ENGINE
2884 opt_engine = opt_str("engine");
2887 case OPT_PROV_CASES:
2888 if (!opt_provider(o))
2896 opt_repeat = opt_nat();
2899 opt_reqin = opt_str("reqin");
2901 case OPT_REQIN_NEW_TID:
2902 opt_reqin_new_tid = 1;
2905 opt_reqout = opt_str("reqout");
2908 opt_rspin = opt_str("rspin");
2911 opt_rspout = opt_str("rspout");
2913 case OPT_USE_MOCK_SRV:
2914 opt_use_mock_srv = 1;
2917 opt_port = opt_str("port");
2920 if ((opt_max_msgs = opt_nat()) < 0)
2924 opt_srv_ref = opt_str("srv_ref");
2926 case OPT_SRV_SECRET:
2927 opt_srv_secret = opt_str("srv_secret");
2930 opt_srv_cert = opt_str("srv_cert");
2933 opt_srv_key = opt_str("srv_key");
2935 case OPT_SRV_KEYPASS:
2936 opt_srv_keypass = opt_str("srv_keypass");
2938 case OPT_SRV_TRUSTED:
2939 opt_srv_trusted = opt_str("srv_trusted");
2941 case OPT_SRV_UNTRUSTED:
2942 opt_srv_untrusted = opt_str("srv_untrusted");
2945 opt_rsp_cert = opt_str("rsp_cert");
2947 case OPT_RSP_EXTRACERTS:
2948 opt_rsp_extracerts = opt_str("rsp_extracerts");
2950 case OPT_RSP_CAPUBS:
2951 opt_rsp_capubs = opt_str("rsp_capubs");
2953 case OPT_POLL_COUNT:
2954 opt_poll_count = opt_nat();
2956 case OPT_CHECK_AFTER:
2957 opt_check_after = opt_nat();
2959 case OPT_GRANT_IMPLICITCONF:
2960 opt_grant_implicitconf = 1;
2963 opt_pkistatus = opt_nat();
2966 opt_failure = opt_nat();
2968 case OPT_FAILUREBITS:
2969 opt_failurebits = opt_nat();
2971 case OPT_STATUSSTRING:
2972 opt_statusstring = opt_str("statusstring");
2974 case OPT_SEND_ERROR:
2977 case OPT_SEND_UNPROTECTED:
2978 opt_send_unprotected = 1;
2980 case OPT_SEND_UNPROT_ERR:
2981 opt_send_unprot_err = 1;
2983 case OPT_ACCEPT_UNPROTECTED:
2984 opt_accept_unprotected = 1;
2986 case OPT_ACCEPT_UNPROT_ERR:
2987 opt_accept_unprot_err = 1;
2989 case OPT_ACCEPT_RAVERIFIED:
2990 opt_accept_raverified = 1;
2994 argc = opt_num_rest();
2997 CMP_err1("unknown parameter %s", argv[0]);
3003 CMP_err1("use -help for summary of '%s' options", prog);
3007 int cmp_main(int argc, char **argv)
3009 char *configfile = NULL;
3011 X509 *newcert = NULL;
3013 char mock_server[] = "mock server:1";
3014 int ret = 0; /* default: failure */
3017 opt_help(cmp_options);
3022 * handle OPT_CONFIG and OPT_SECTION upfront to take effect for other opts
3024 for (i = 1; i < argc - 1; i++) {
3025 if (*argv[i] == '-') {
3026 if (!strcmp(argv[i] + 1, cmp_options[OPT_CONFIG - OPT_HELP].name))
3027 opt_config = argv[i + 1];
3028 else if (!strcmp(argv[i] + 1,
3029 cmp_options[OPT_SECTION - OPT_HELP].name))
3030 opt_section = argv[i + 1];
3033 if (opt_section[0] == '\0') /* empty string */
3034 opt_section = DEFAULT_SECTION;
3036 vpm = X509_VERIFY_PARAM_new();
3038 CMP_err("out of memory");
3042 /* read default values for options from config file */
3043 configfile = opt_config != NULL ? opt_config : default_config_file;
3044 if (configfile && configfile[0] != '\0' /* non-empty string */
3045 && (configfile != default_config_file
3046 || access(configfile, F_OK) != -1)) {
3047 CMP_info1("using OpenSSL configuration file '%s'", configfile);
3048 conf = app_load_config(configfile);
3052 if (strcmp(opt_section, CMP_SECTION) == 0) { /* default */
3053 if (!NCONF_get_section(conf, opt_section))
3054 CMP_info2("no [%s] section found in config file '%s';"
3055 " will thus use just [default] and unnamed section if present",
3056 opt_section, configfile);
3058 const char *end = opt_section + strlen(opt_section);
3059 while ((end = prev_item(opt_section, end)) != NULL) {
3060 if (!NCONF_get_section(conf, opt_item)) {
3061 CMP_err2("no [%s] section found in config file '%s'",
3062 opt_item, configfile);
3071 (void)BIO_flush(bio_err); /* prevent interference with opt_help() */
3073 ret = get_opts(argc, argv);
3079 #ifndef OPENSSL_NO_ENGINE
3080 UI_METHOD *ui_fallback_method;
3081 # ifndef OPENSSL_NO_UI_CONSOLE
3082 ui_fallback_method = UI_OpenSSL();
3084 ui_fallback_method = (UI_METHOD *)UI_null();
3086 UI_method_set_reader(ui_fallback_method, NULL);
3090 if (opt_engine != NULL)
3091 e = setup_engine_flags(opt_engine, 0 /* not: ENGINE_METHOD_ALL */, 0);
3093 if (opt_port != NULL) {
3094 if (opt_use_mock_srv) {
3095 CMP_err("cannot use both -port and -use_mock_srv options");
3098 if (opt_server != NULL) {
3099 CMP_err("cannot use both -port and -server options");
3104 if ((cmp_ctx = OSSL_CMP_CTX_new()) == NULL) {
3105 CMP_err("out of memory");
3108 if (!OSSL_CMP_CTX_set_log_cb(cmp_ctx, print_to_bio_out)) {
3109 CMP_err1("cannot set up error reporting and logging for %s", prog);
3112 if ((opt_use_mock_srv || opt_port != NULL)) {
3113 OSSL_CMP_SRV_CTX *srv_ctx;
3115 if ((srv_ctx = setup_srv_ctx(e)) == NULL)
3117 OSSL_CMP_CTX_set_transfer_cb_arg(cmp_ctx, srv_ctx);
3118 if (!OSSL_CMP_CTX_set_log_cb(OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx),
3119 print_to_bio_out)) {
3120 CMP_err1("cannot set up error reporting and logging for %s", prog);
3126 if (opt_port != NULL) { /* act as very basic CMP HTTP server */
3127 #ifdef OPENSSL_NO_SOCK
3128 BIO_printf(bio_err, "Cannot act as server - sockets not supported\n");
3134 if ((acbio = http_server_init_bio(prog, opt_port)) == NULL)
3136 while (opt_max_msgs <= 0 || msgs < opt_max_msgs) {
3137 OSSL_CMP_MSG *req = NULL;
3138 OSSL_CMP_MSG *resp = NULL;
3140 ret = http_server_get_asn1_req(ASN1_ITEM_rptr(OSSL_CMP_MSG),
3141 (ASN1_VALUE **)&req, &cbio, acbio,
3146 break; /* fatal error */
3151 resp = OSSL_CMP_CTX_server_perform(cmp_ctx, req);
3152 OSSL_CMP_MSG_free(req);
3154 break; /* treated as fatal error */
3155 ret = http_server_send_asn1_resp(cbio, "application/pkixcmp",
3156 ASN1_ITEM_rptr(OSSL_CMP_MSG),
3157 (const ASN1_VALUE *)resp);
3158 OSSL_CMP_MSG_free(resp);
3160 break; /* treated as fatal error */
3166 BIO_free_all(acbio);
3170 /* else act as CMP client */
3172 if (opt_use_mock_srv) {
3173 if (opt_server != NULL) {
3174 CMP_err("cannot use both -use_mock_srv and -server options");
3177 if (opt_proxy != NULL) {
3178 CMP_err("cannot use both -use_mock_srv and -proxy options");
3181 opt_server = mock_server;
3184 if (opt_server == NULL) {
3185 CMP_err("missing -server option");
3190 if (!setup_client_ctx(cmp_ctx, e)) {
3191 CMP_err("cannot set up CMP context");
3194 for (i = 0; i < opt_repeat; i++) {
3195 /* everything is ready, now connect and perform the command! */
3198 newcert = OSSL_CMP_exec_IR_ses(cmp_ctx);
3199 if (newcert == NULL)
3203 newcert = OSSL_CMP_exec_KUR_ses(cmp_ctx);
3204 if (newcert == NULL)
3208 newcert = OSSL_CMP_exec_CR_ses(cmp_ctx);
3209 if (newcert == NULL)
3213 newcert = OSSL_CMP_exec_P10CR_ses(cmp_ctx);
3214 if (newcert == NULL)
3218 if (OSSL_CMP_exec_RR_ses(cmp_ctx) == NULL)
3223 STACK_OF(OSSL_CMP_ITAV) *itavs;
3225 if (opt_infotype != NID_undef) {
3226 OSSL_CMP_ITAV *itav =
3227 OSSL_CMP_ITAV_create(OBJ_nid2obj(opt_infotype), NULL);
3230 OSSL_CMP_CTX_push0_genm_ITAV(cmp_ctx, itav);
3233 if ((itavs = OSSL_CMP_exec_GENM_ses(cmp_ctx)) == NULL)
3236 sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free);
3244 /* print PKIStatusInfo (this is in case there has been no error) */
3245 int status = OSSL_CMP_CTX_get_status(cmp_ctx);
3246 char *buf = app_malloc(OSSL_CMP_PKISI_BUFLEN, "PKIStatusInfo buf");
3247 const char *string =
3248 OSSL_CMP_CTX_snprint_PKIStatus(cmp_ctx, buf,
3249 OSSL_CMP_PKISI_BUFLEN);
3252 status == OSSL_CMP_PKISTATUS_accepted ? "info" :
3253 status == OSSL_CMP_PKISTATUS_rejection ? "server error" :
3254 status == OSSL_CMP_PKISTATUS_waiting ? "internal error"
3256 "received from %s %s %s", opt_server,
3257 string != NULL ? string : "<unknown PKIStatus>", "");
3261 if (opt_cacertsout != NULL) {
3262 STACK_OF(X509) *certs = OSSL_CMP_CTX_get1_caPubs(cmp_ctx);
3264 if (sk_X509_num(certs) > 0
3265 && save_certs(cmp_ctx, certs, opt_cacertsout, "CA") < 0) {
3266 sk_X509_pop_free(certs, X509_free);
3269 sk_X509_pop_free(certs, X509_free);
3272 if (opt_extracertsout != NULL) {
3273 STACK_OF(X509) *certs = OSSL_CMP_CTX_get1_extraCertsIn(cmp_ctx);
3274 if (sk_X509_num(certs) > 0
3275 && save_certs(cmp_ctx, certs, opt_extracertsout,
3277 sk_X509_pop_free(certs, X509_free);
3280 sk_X509_pop_free(certs, X509_free);
3283 if (opt_certout != NULL && newcert != NULL) {
3284 STACK_OF(X509) *certs = sk_X509_new_null();
3286 if (certs == NULL || !sk_X509_push(certs, newcert)
3287 || save_certs(cmp_ctx, certs, opt_certout,
3289 sk_X509_free(certs);
3292 sk_X509_free(certs);
3294 if (!OSSL_CMP_CTX_reinit(cmp_ctx))
3300 /* in case we ended up here on error without proper cleaning */
3301 cleanse(opt_keypass);
3302 cleanse(opt_newkeypass);
3303 cleanse(opt_otherpass);
3304 cleanse(opt_tls_keypass);
3305 cleanse(opt_secret);
3306 cleanse(opt_srv_keypass);
3307 cleanse(opt_srv_secret);
3310 OSSL_CMP_CTX_print_errors(cmp_ctx);
3312 ossl_cmp_mock_srv_free(OSSL_CMP_CTX_get_transfer_cb_arg(cmp_ctx));
3314 APP_HTTP_TLS_INFO *http_tls_info =
3315 OSSL_CMP_CTX_get_http_cb_arg(cmp_ctx);
3317 if (http_tls_info != NULL) {
3318 SSL_CTX_free(http_tls_info->ssl_ctx);
3319 OPENSSL_free(http_tls_info);
3322 X509_STORE_free(OSSL_CMP_CTX_get_certConf_cb_arg(cmp_ctx));
3323 OSSL_CMP_CTX_free(cmp_ctx);
3324 X509_VERIFY_PARAM_free(vpm);
3327 NCONF_free(conf); /* must not do as long as opt_... variables are used */
3328 OSSL_CMP_log_close();
3330 return ret == 0 ? EXIT_FAILURE : EXIT_SUCCESS;