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 char *opt_reqout = NULL;
318 static char *opt_rspin = NULL;
319 static char *opt_rspout = NULL;
320 static int opt_use_mock_srv = 0;
322 /* server-side debugging */
323 static char *opt_port = NULL;
324 static int opt_max_msgs = 0;
326 static char *opt_srv_ref = NULL;
327 static char *opt_srv_secret = NULL;
328 static char *opt_srv_cert = NULL;
329 static char *opt_srv_key = NULL;
330 static char *opt_srv_keypass = NULL;
332 static char *opt_srv_trusted = NULL;
333 static char *opt_srv_untrusted = NULL;
334 static char *opt_rsp_cert = NULL;
335 static char *opt_rsp_extracerts = NULL;
336 static char *opt_rsp_capubs = NULL;
337 static int opt_poll_count = 0;
338 static int opt_check_after = 1;
339 static int opt_grant_implicitconf = 0;
341 static int opt_pkistatus = OSSL_CMP_PKISTATUS_accepted;
342 static int opt_failure = INT_MIN;
343 static int opt_failurebits = 0;
344 static char *opt_statusstring = NULL;
345 static int opt_send_error = 0;
346 static int opt_send_unprotected = 0;
347 static int opt_send_unprot_err = 0;
348 static int opt_accept_unprotected = 0;
349 static int opt_accept_unprot_err = 0;
350 static int opt_accept_raverified = 0;
352 static X509_VERIFY_PARAM *vpm = NULL;
354 typedef enum OPTION_choice {
355 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
356 OPT_CONFIG, OPT_SECTION,
358 OPT_CMD, OPT_INFOTYPE, OPT_GENINFO,
360 OPT_NEWKEY, OPT_NEWKEYPASS, OPT_SUBJECT, OPT_ISSUER,
361 OPT_DAYS, OPT_REQEXTS,
362 OPT_SANS, OPT_SAN_NODEFAULT,
363 OPT_POLICIES, OPT_POLICY_OIDS, OPT_POLICY_OIDS_CRITICAL,
365 OPT_OUT_TRUSTED, OPT_IMPLICIT_CONFIRM, OPT_DISABLE_CONFIRM,
368 OPT_OLDCERT, OPT_REVREASON,
370 OPT_SERVER, OPT_PROXY, OPT_NO_PROXY, OPT_PATH,
371 OPT_MSG_TIMEOUT, OPT_TOTAL_TIMEOUT,
373 OPT_TRUSTED, OPT_UNTRUSTED, OPT_SRVCERT,
374 OPT_RECIPIENT, OPT_EXPECT_SENDER,
375 OPT_IGNORE_KEYUSAGE, OPT_UNPROTECTED_ERRORS,
376 OPT_EXTRACERTSOUT, OPT_CACERTSOUT,
378 OPT_REF, OPT_SECRET, OPT_CERT, OPT_KEY, OPT_KEYPASS,
379 OPT_DIGEST, OPT_MAC, OPT_EXTRACERTS,
380 OPT_UNPROTECTED_REQUESTS,
382 OPT_CERTFORM, OPT_KEYFORM, OPT_CERTSFORM,
384 #ifndef OPENSSL_NO_ENGINE
389 OPT_TLS_USED, OPT_TLS_CERT, OPT_TLS_KEY,
391 OPT_TLS_EXTRA, OPT_TLS_TRUSTED, OPT_TLS_HOST,
393 OPT_BATCH, OPT_REPEAT,
394 OPT_REQIN, OPT_REQOUT, OPT_RSPIN, OPT_RSPOUT,
396 OPT_USE_MOCK_SRV, OPT_PORT, OPT_MAX_MSGS,
397 OPT_SRV_REF, OPT_SRV_SECRET,
398 OPT_SRV_CERT, OPT_SRV_KEY, OPT_SRV_KEYPASS,
399 OPT_SRV_TRUSTED, OPT_SRV_UNTRUSTED,
400 OPT_RSP_CERT, OPT_RSP_EXTRACERTS, OPT_RSP_CAPUBS,
401 OPT_POLL_COUNT, OPT_CHECK_AFTER,
402 OPT_GRANT_IMPLICITCONF,
403 OPT_PKISTATUS, OPT_FAILURE,
404 OPT_FAILUREBITS, OPT_STATUSSTRING,
405 OPT_SEND_ERROR, OPT_SEND_UNPROTECTED,
406 OPT_SEND_UNPROT_ERR, OPT_ACCEPT_UNPROTECTED,
407 OPT_ACCEPT_UNPROT_ERR, OPT_ACCEPT_RAVERIFIED,
412 const OPTIONS cmp_options[] = {
413 /* entries must be in the same order as enumerated above!! */
414 {"help", OPT_HELP, '-', "Display this summary"},
415 {"config", OPT_CONFIG, 's',
416 "Configuration file to use. \"\" = none. Default from env variable OPENSSL_CONF"},
417 {"section", OPT_SECTION, 's',
418 "Section(s) in config file to get options from. \"\" = 'default'. Default 'cmp'"},
420 OPT_SECTION("Generic message"),
421 {"cmd", OPT_CMD, 's', "CMP request to send: ir/cr/kur/p10cr/rr/genm"},
422 {"infotype", OPT_INFOTYPE, 's',
423 "InfoType name for requesting specific info in genm, e.g. 'signKeyPairTypes'"},
424 {"geninfo", OPT_GENINFO, 's',
425 "generalInfo integer values to place in request PKIHeader with given OID"},
427 "specified in the form <OID>:int:<n>, e.g. \"1.2.3:int:987\""},
429 OPT_SECTION("Certificate enrollment"),
430 {"newkey", OPT_NEWKEY, 's',
431 "Private or public key for the requested cert. Default: CSR key or client key"},
432 {"newkeypass", OPT_NEWKEYPASS, 's', "New private key pass phrase source"},
433 {"subject", OPT_SUBJECT, 's',
434 "Distinguished Name (DN) of subject to use in the requested cert template"},
436 "For kur, default is the subject DN of the reference cert (see -oldcert);"},
438 "this default is used for ir and cr only if no Subject Alt Names are set"},
439 {"issuer", OPT_ISSUER, 's',
440 "DN of the issuer to place in the requested certificate template"},
442 "also used as recipient if neither -recipient nor -srvcert are given"},
443 {"days", OPT_DAYS, 'n',
444 "Requested validity time of the new certificate in number of days"},
445 {"reqexts", OPT_REQEXTS, 's',
446 "Name of config file section defining certificate request extensions"},
447 {"sans", OPT_SANS, 's',
448 "Subject Alt Names (IPADDR/DNS/URI) to add as (critical) cert req extension"},
449 {"san_nodefault", OPT_SAN_NODEFAULT, '-',
450 "Do not take default SANs from reference certificate (see -oldcert)"},
451 {"policies", OPT_POLICIES, 's',
452 "Name of config file section defining policies certificate request extension"},
453 {"policy_oids", OPT_POLICY_OIDS, 's',
454 "Policy OID(s) to add as policies certificate request extension"},
455 {"policy_oids_critical", OPT_POLICY_OIDS_CRITICAL, '-',
456 "Flag the policy OID(s) given with -policy_oids as critical"},
457 {"popo", OPT_POPO, 'n',
458 "Proof-of-Possession (POPO) method to use for ir/cr/kur where"},
460 "-1 = NONE, 0 = RAVERIFIED, 1 = SIGNATURE (default), 2 = KEYENC"},
461 {"csr", OPT_CSR, 's',
462 "CSR file in PKCS#10 format to use in p10cr for legacy support"},
463 {"out_trusted", OPT_OUT_TRUSTED, 's',
464 "Certificates to trust when verifying newly enrolled certificates"},
465 {"implicit_confirm", OPT_IMPLICIT_CONFIRM, '-',
466 "Request implicit confirmation of newly enrolled certificates"},
467 {"disable_confirm", OPT_DISABLE_CONFIRM, '-',
468 "Do not confirm newly enrolled certificate w/o requesting implicit"},
470 "confirmation. WARNING: This leads to behavior violating RFC 4210"},
471 {"certout", OPT_CERTOUT, 's',
472 "File to save newly enrolled certificate"},
474 OPT_SECTION("Certificate enrollment and revocation"),
476 {"oldcert", OPT_OLDCERT, 's',
477 "Certificate to be updated (defaulting to -cert) or to be revoked in rr;"},
479 "also used as reference (defaulting to -cert) for subject DN and SANs."},
481 "Its issuer is used as recipient unless -srvcert, -recipient or -issuer given"},
482 {"revreason", OPT_REVREASON, 'n',
483 "Reason code to include in revocation request (rr); possible values:"},
485 "0..6, 8..10 (see RFC5280, 5.3.1) or -1. Default -1 = none included"},
487 OPT_SECTION("Message transfer"),
488 {"server", OPT_SERVER, 's',
489 "[http[s]://]address[:port] of CMP server. Default port 80 or 443."},
491 "The address may be a DNS name or an IP address"},
492 {"proxy", OPT_PROXY, 's',
493 "[http[s]://]address[:port][/path] of HTTP(S) proxy to use; path is ignored"},
494 {"no_proxy", OPT_NO_PROXY, 's',
495 "List of addresses of servers not to use HTTP(S) proxy for"},
497 "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"},
498 {"path", OPT_PATH, 's',
499 "HTTP path (aka CMP alias) at the CMP server. Default \"/\""},
500 {"msg_timeout", OPT_MSG_TIMEOUT, 'n',
501 "Timeout per CMP message round trip (or 0 for none). Default 120 seconds"},
502 {"total_timeout", OPT_TOTAL_TIMEOUT, 'n',
503 "Overall time an enrollment incl. polling may take. Default 0 = infinite"},
505 OPT_SECTION("Server authentication"),
506 {"trusted", OPT_TRUSTED, 's',
507 "Trusted certs used for CMP server authentication when verifying responses"},
508 {OPT_MORE_STR, 0, 0, "unless -srvcert is given"},
509 {"untrusted", OPT_UNTRUSTED, 's',
510 "Intermediate certs for chain construction verifying CMP/TLS/enrolled certs"},
511 {"srvcert", OPT_SRVCERT, 's',
512 "Specific CMP server cert to use and trust directly when verifying responses"},
513 {"recipient", OPT_RECIPIENT, 's',
514 "Distinguished Name (DN) of the recipient to use unless -srvcert is given"},
515 {"expect_sender", OPT_EXPECT_SENDER, 's',
516 "DN of expected response sender. Defaults to DN of -srvcert, if provided"},
517 {"ignore_keyusage", OPT_IGNORE_KEYUSAGE, '-',
518 "Ignore CMP signer cert key usage, else 'digitalSignature' must be allowed"},
519 {"unprotected_errors", OPT_UNPROTECTED_ERRORS, '-',
520 "Accept missing or invalid protection of regular error messages and negative"},
522 "certificate responses (ip/cp/kup), revocation responses (rp), and PKIConf"},
524 "WARNING: This setting leads to behavior allowing violation of RFC 4210"},
525 {"extracertsout", OPT_EXTRACERTSOUT, 's',
526 "File to save extra certificates received in the extraCerts field"},
527 {"cacertsout", OPT_CACERTSOUT, 's',
528 "File to save CA certificates received in the caPubs field of 'ip' messages"},
530 OPT_SECTION("Client authentication"),
531 {"ref", OPT_REF, 's',
532 "Reference value to use as senderKID in case no -cert is given"},
533 {"secret", OPT_SECRET, 's',
534 "Password source for client authentication with a pre-shared key (secret)"},
535 {"cert", OPT_CERT, 's',
536 "Client's current certificate (needed unless using -secret for PBM);"},
538 "any further certs included are appended in extraCerts field"},
539 {"key", OPT_KEY, 's', "Private key for the client's current certificate"},
540 {"keypass", OPT_KEYPASS, 's',
541 "Client private key (and cert and old cert file) pass phrase source"},
542 {"digest", OPT_DIGEST, 's',
543 "Digest to use in message protection and POPO signatures. Default \"sha256\""},
544 {"mac", OPT_MAC, 's',
545 "MAC algorithm to use in PBM-based message protection. Default \"hmac-sha1\""},
546 {"extracerts", OPT_EXTRACERTS, 's',
547 "Certificates to append in extraCerts field of outgoing messages"},
548 {"unprotected_requests", OPT_UNPROTECTED_REQUESTS, '-',
549 "Send messages without CMP-level protection"},
551 OPT_SECTION("Credentials format"),
552 {"certform", OPT_CERTFORM, 's',
553 "Format (PEM or DER) to use when saving a certificate to a file. Default PEM"},
555 "This also determines format to use for writing (not supported for P12)"},
556 {"keyform", OPT_KEYFORM, 's',
557 "Format to assume when reading key files. Default PEM"},
558 {"certsform", OPT_CERTSFORM, 's',
559 "Format (PEM/DER/P12) to try first reading multiple certs. Default PEM"},
560 {"otherpass", OPT_OTHERPASS, 's',
561 "Pass phrase source potentially needed for loading certificates of others"},
562 #ifndef OPENSSL_NO_ENGINE
563 {"engine", OPT_ENGINE, 's',
564 "Use crypto engine with given identifier, possibly a hardware device."},
566 "Engines may be defined in OpenSSL config file engine section."},
568 "Options like -key specifying keys held in the engine can give key IDs"},
570 "prefixed by 'engine:', e.g. '-key engine:pkcs11:object=mykey;pin-value=1234'"},
574 OPT_SECTION("TLS connection"),
575 {"tls_used", OPT_TLS_USED, '-',
576 "Enable using TLS (also when other TLS options are not set)"},
577 {"tls_cert", OPT_TLS_CERT, 's',
578 "Client's TLS certificate. May include chain to be provided to TLS server"},
579 {"tls_key", OPT_TLS_KEY, 's',
580 "Private key for the client's TLS certificate"},
581 {"tls_keypass", OPT_TLS_KEYPASS, 's',
582 "Pass phrase source for the client's private TLS key (and TLS cert file)"},
583 {"tls_extra", OPT_TLS_EXTRA, 's',
584 "Extra certificates to provide to TLS server during TLS handshake"},
585 {"tls_trusted", OPT_TLS_TRUSTED, 's',
586 "Trusted certificates to use for verifying the TLS server certificate;"},
587 {OPT_MORE_STR, 0, 0, "this implies host name validation"},
588 {"tls_host", OPT_TLS_HOST, 's',
589 "Address to be checked (rather than -server) during TLS host name validation"},
591 OPT_SECTION("Client-side debugging"),
592 {"batch", OPT_BATCH, '-',
593 "Do not interactively prompt for input when a password is required etc."},
594 {"repeat", OPT_REPEAT, 'n',
595 "Invoke the transaction the given number of times. Default 1"},
596 {"reqin", OPT_REQIN, 's', "Take sequence of CMP requests from file(s)"},
597 {"reqout", OPT_REQOUT, 's', "Save sequence of CMP requests to file(s)"},
598 {"rspin", OPT_RSPIN, 's',
599 "Process sequence of CMP responses provided in file(s), skipping server"},
600 {"rspout", OPT_RSPOUT, 's', "Save sequence of CMP responses to file(s)"},
602 {"use_mock_srv", OPT_USE_MOCK_SRV, '-', "Use mock server at API level, bypassing HTTP"},
604 OPT_SECTION("Mock server"),
605 {"port", OPT_PORT, 's', "Act as HTTP mock server listening on given port"},
606 {"max_msgs", OPT_MAX_MSGS, 'n',
607 "max number of messages handled by HTTP mock server. Default: 0 = unlimited"},
609 {"srv_ref", OPT_SRV_REF, 's',
610 "Reference value to use as senderKID of server in case no -srv_cert is given"},
611 {"srv_secret", OPT_SRV_SECRET, 's',
612 "Password source for server authentication with a pre-shared key (secret)"},
613 {"srv_cert", OPT_SRV_CERT, 's', "Certificate of the server"},
614 {"srv_key", OPT_SRV_KEY, 's',
615 "Private key used by the server for signing messages"},
616 {"srv_keypass", OPT_SRV_KEYPASS, 's',
617 "Server private key (and cert) file pass phrase source"},
619 {"srv_trusted", OPT_SRV_TRUSTED, 's',
620 "Trusted certificates for client authentication"},
621 {"srv_untrusted", OPT_SRV_UNTRUSTED, 's',
622 "Intermediate certs that may be useful for verifying CMP protection"},
623 {"rsp_cert", OPT_RSP_CERT, 's',
624 "Certificate to be returned as mock enrollment result"},
625 {"rsp_extracerts", OPT_RSP_EXTRACERTS, 's',
626 "Extra certificates to be included in mock certification responses"},
627 {"rsp_capubs", OPT_RSP_CAPUBS, 's',
628 "CA certificates to be included in mock ip response"},
629 {"poll_count", OPT_POLL_COUNT, 'n',
630 "Number of times the client must poll before receiving a certificate"},
631 {"check_after", OPT_CHECK_AFTER, 'n',
632 "The check_after value (time to wait) to include in poll response"},
633 {"grant_implicitconf", OPT_GRANT_IMPLICITCONF, '-',
634 "Grant implicit confirmation of newly enrolled certificate"},
636 {"pkistatus", OPT_PKISTATUS, 'n',
637 "PKIStatus to be included in server response. Possible values: 0..6"},
638 {"failure", OPT_FAILURE, 'n',
639 "A single failure info bit number to include in server response, 0..26"},
640 {"failurebits", OPT_FAILUREBITS, 'n',
641 "Number representing failure bits to include in server response, 0..2^27 - 1"},
642 {"statusstring", OPT_STATUSSTRING, 's',
643 "Status string to be included in server response"},
644 {"send_error", OPT_SEND_ERROR, '-',
645 "Force server to reply with error message"},
646 {"send_unprotected", OPT_SEND_UNPROTECTED, '-',
647 "Send response messages without CMP-level protection"},
648 {"send_unprot_err", OPT_SEND_UNPROT_ERR, '-',
649 "In case of negative responses, server shall send unprotected error messages,"},
651 "certificate responses (ip/cp/kup), and revocation responses (rp)."},
653 "WARNING: This setting leads to behavior violating RFC 4210"},
654 {"accept_unprotected", OPT_ACCEPT_UNPROTECTED, '-',
655 "Accept missing or invalid protection of requests"},
656 {"accept_unprot_err", OPT_ACCEPT_UNPROT_ERR, '-',
657 "Accept unprotected error messages from client"},
658 {"accept_raverified", OPT_ACCEPT_RAVERIFIED, '-',
659 "Accept RAVERIFIED as proof-of-possession (POPO)"},
670 static varref cmp_vars[] = { /* must be in same order as enumerated above! */
671 {&opt_config}, {&opt_section},
673 {&opt_cmd_s}, {&opt_infotype_s}, {&opt_geninfo},
675 {&opt_newkey}, {&opt_newkeypass}, {&opt_subject}, {&opt_issuer},
676 {(char **)&opt_days}, {&opt_reqexts},
677 {&opt_sans}, {(char **)&opt_san_nodefault},
678 {&opt_policies}, {&opt_policy_oids}, {(char **)&opt_policy_oids_critical},
679 {(char **)&opt_popo}, {&opt_csr},
681 {(char **)&opt_implicit_confirm}, {(char **)&opt_disable_confirm},
684 {&opt_oldcert}, {(char **)&opt_revreason},
686 {&opt_server}, {&opt_proxy}, {&opt_no_proxy}, {&opt_path},
687 {(char **)&opt_msg_timeout}, {(char **)&opt_total_timeout},
689 {&opt_trusted}, {&opt_untrusted}, {&opt_srvcert},
690 {&opt_recipient}, {&opt_expect_sender},
691 {(char **)&opt_ignore_keyusage}, {(char **)&opt_unprotected_errors},
692 {&opt_extracertsout}, {&opt_cacertsout},
694 {&opt_ref}, {&opt_secret}, {&opt_cert}, {&opt_key}, {&opt_keypass},
695 {&opt_digest}, {&opt_mac}, {&opt_extracerts},
696 {(char **)&opt_unprotected_requests},
698 {&opt_certform_s}, {&opt_keyform_s}, {&opt_certsform_s},
700 #ifndef OPENSSL_NO_ENGINE
704 {(char **)&opt_tls_used}, {&opt_tls_cert}, {&opt_tls_key},
706 {&opt_tls_extra}, {&opt_tls_trusted}, {&opt_tls_host},
708 {(char **)&opt_batch}, {(char **)&opt_repeat},
709 {&opt_reqin}, {&opt_reqout}, {&opt_rspin}, {&opt_rspout},
711 {(char **)&opt_use_mock_srv}, {&opt_port}, {(char **)&opt_max_msgs},
712 {&opt_srv_ref}, {&opt_srv_secret},
713 {&opt_srv_cert}, {&opt_srv_key}, {&opt_srv_keypass},
714 {&opt_srv_trusted}, {&opt_srv_untrusted},
715 {&opt_rsp_cert}, {&opt_rsp_extracerts}, {&opt_rsp_capubs},
716 {(char **)&opt_poll_count}, {(char **)&opt_check_after},
717 {(char **)&opt_grant_implicitconf},
718 {(char **)&opt_pkistatus}, {(char **)&opt_failure},
719 {(char **)&opt_failurebits}, {&opt_statusstring},
720 {(char **)&opt_send_error}, {(char **)&opt_send_unprotected},
721 {(char **)&opt_send_unprot_err}, {(char **)&opt_accept_unprotected},
722 {(char **)&opt_accept_unprot_err}, {(char **)&opt_accept_raverified},
728 # define FUNC (strcmp(OPENSSL_FUNC, "(unknown function)") == 0 \
729 ? "CMP" : "OPENSSL_FUNC")
730 # define PRINT_LOCATION(bio) BIO_printf(bio, "%s:%s:%d:", \
731 FUNC, OPENSSL_FILE, OPENSSL_LINE)
733 # define PRINT_LOCATION(bio) ((void)0)
735 #define CMP_print(bio, prefix, msg, a1, a2, a3) \
736 (PRINT_LOCATION(bio), \
737 BIO_printf(bio, "CMP %s: " msg "\n", prefix, a1, a2, a3))
738 #define CMP_INFO(msg, a1, a2, a3) CMP_print(bio_out, "info", msg, a1, a2, a3)
739 #define CMP_info(msg) CMP_INFO(msg"%s%s%s", "", "", "")
740 #define CMP_info1(msg, a1) CMP_INFO(msg"%s%s", a1, "", "")
741 #define CMP_info2(msg, a1, a2) CMP_INFO(msg"%s", a1, a2, "")
742 #define CMP_info3(msg, a1, a2, a3) CMP_INFO(msg, a1, a2, a3)
743 #define CMP_WARN(m, a1, a2, a3) CMP_print(bio_out, "warning", m, a1, a2, a3)
744 #define CMP_warn(msg) CMP_WARN(msg"%s%s%s", "", "", "")
745 #define CMP_warn1(msg, a1) CMP_WARN(msg"%s%s", a1, "", "")
746 #define CMP_warn2(msg, a1, a2) CMP_WARN(msg"%s", a1, a2, "")
747 #define CMP_warn3(msg, a1, a2, a3) CMP_WARN(msg, a1, a2, a3)
748 #define CMP_ERR(msg, a1, a2, a3) CMP_print(bio_err, "error", msg, a1, a2, a3)
749 #define CMP_err(msg) CMP_ERR(msg"%s%s%s", "", "", "")
750 #define CMP_err1(msg, a1) CMP_ERR(msg"%s%s", a1, "", "")
751 #define CMP_err2(msg, a1, a2) CMP_ERR(msg"%s", a1, a2, "")
752 #define CMP_err3(msg, a1, a2, a3) CMP_ERR(msg, a1, a2, a3)
754 static int print_to_bio_out(const char *func, const char *file, int line,
755 OSSL_CMP_severity level, const char *msg)
757 return OSSL_CMP_print_to_bio(bio_out, func, file, line, level, msg);
760 /* code duplicated from crypto/cmp/cmp_util.c */
761 static int sk_X509_add1_cert(STACK_OF(X509) *sk, X509 *cert,
762 int no_dup, int prepend)
766 * not using sk_X509_set_cmp_func() and sk_X509_find()
767 * because this re-orders the certs on the stack
771 for (i = 0; i < sk_X509_num(sk); i++) {
772 if (X509_cmp(sk_X509_value(sk, i), cert) == 0)
776 if (!X509_up_ref(cert))
778 if (!sk_X509_insert(sk, cert, prepend ? 0 : -1)) {
785 /* code duplicated from crypto/cmp/cmp_util.c */
786 static int sk_X509_add1_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs,
787 int no_self_signed, int no_dups, int prepend)
788 /* compiler would allow 'const' for the list of certs, yet they are up-ref'ed */
796 for (i = 0; i < sk_X509_num(certs); i++) {
797 X509 *cert = sk_X509_value(certs, i);
799 if (!no_self_signed || X509_check_issued(cert, cert) != X509_V_OK) {
800 if (!sk_X509_add1_cert(sk, cert, no_dups, prepend))
807 /* TODO potentially move to apps/lib/apps.c */
808 static char *next_item(char *opt) /* in list separated by comma and/or space */
810 /* advance to separator (comma or whitespace), if any */
811 while (*opt != ',' && !isspace(*opt) && *opt != '\0') {
812 if (*opt == '\\' && opt[1] != '\0')
813 /* skip and unescape '\' escaped char */
814 memmove(opt, opt + 1, strlen(opt));
818 /* terminate current item */
820 /* skip over any whitespace after separator */
821 while (isspace(*opt))
824 return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
827 static EVP_PKEY *load_key_pwd(const char *uri, int format,
828 const char *pass, ENGINE *e, const char *desc)
830 char *pass_string = get_passwd(pass, desc);
831 EVP_PKEY *pkey = load_key_preliminary(uri, format, 0, pass_string, e, desc);
833 clear_free(pass_string);
837 static X509 *load_cert_pwd(const char *uri, const char *pass, const char *desc)
840 char *pass_string = get_passwd(pass, desc);
842 cert = load_cert_pass(uri, 0, pass_string, desc);
843 clear_free(pass_string);
847 /* TODO remove when PR #4930 is merged */
848 static int load_pkcs12(BIO *in, const char *desc,
849 pem_password_cb *pem_cb, void *cb_data,
850 EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
853 char tpass[PEM_BUFSIZE];
856 PKCS12 *p12 = d2i_PKCS12_bio(in, NULL);
859 desc = "PKCS12 input";
861 BIO_printf(bio_err, "error loading PKCS12 file for %s\n", desc);
865 /* See if an empty password will do */
866 if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) {
870 pem_cb = wrap_password_callback;
871 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
873 BIO_printf(bio_err, "passphrase callback error for %s\n", desc);
876 if (len < PEM_BUFSIZE)
878 if (!PKCS12_verify_mac(p12, tpass, len)) {
880 "mac verify error (wrong password?) in PKCS12 file for %s\n",
886 ret = PKCS12_parse(p12, pass, pkey, cert, ca);
892 /* TODO potentially move this and related functions to apps/lib/apps.c */
893 static int adjust_format(const char **infile, int format, int engine_ok)
895 if (!strncasecmp(*infile, "http://", 7)
896 || !strncasecmp(*infile, "https://", 8)) {
897 format = FORMAT_HTTP;
898 } else if (engine_ok && strncasecmp(*infile, "engine:", 7) == 0) {
900 format = FORMAT_ENGINE;
902 if (strncasecmp(*infile, "file:", 5) == 0)
905 * the following is a heuristic whether first to try PEM or DER
906 * or PKCS12 as the input format for files
908 if (strlen(*infile) >= 4) {
909 const char *extension = *infile + strlen(*infile) - 4;
911 if (strncasecmp(extension, ".crt", 4) == 0
912 || strncasecmp(extension, ".pem", 4) == 0)
913 /* weak recognition of PEM format */
915 else if (strncasecmp(extension, ".cer", 4) == 0
916 || strncasecmp(extension, ".der", 4) == 0)
917 /* weak recognition of DER format */
918 format = FORMAT_ASN1;
919 else if (strncasecmp(extension, ".p12", 4) == 0)
920 /* weak recognition of PKCS#12 format */
921 format = FORMAT_PKCS12;
922 /* else retain given format */
929 * TODO potentially move this and related functions to apps/lib/
930 * or even better extend OSSL_STORE with type OSSL_STORE_INFO_CRL
932 static X509_REQ *load_csr_autofmt(const char *infile, const char *desc)
935 BIO *bio_bak = bio_err;
937 int format = adjust_format(&infile, FORMAT_PEM, 0);
939 can_retry = format == FORMAT_PEM || format == FORMAT_ASN1;
941 bio_err = NULL; /* do not show errors on more than one try */
942 csr = load_csr(infile, format, desc);
944 if (csr == NULL && can_retry) {
946 format = (format == FORMAT_PEM ? FORMAT_ASN1 : FORMAT_PEM);
947 csr = load_csr(infile, format, desc);
950 ERR_print_errors(bio_err);
951 BIO_printf(bio_err, "error: unable to load %s from file '%s'\n", desc,
957 /* TODO replace by calling generalized load_certs() when PR #4930 is merged */
958 static int load_certs_preliminary(const char *file, STACK_OF(X509) **certs,
959 int format, const char *pass,
965 if (format == FORMAT_PKCS12) {
966 BIO *bio = bio_open_default(file, 'r', format);
969 EVP_PKEY *pkey = NULL; /* pkey is needed until PR #4930 is merged */
972 cb_data.password = pass;
973 cb_data.prompt_info = file;
974 ret = load_pkcs12(bio, desc, wrap_password_callback,
975 &cb_data, &pkey, &cert, certs);
979 } else if (format == FORMAT_ASN1) { /* load only one cert in this case */
980 CMP_warn1("can load only one certificate in DER format from %s", file);
981 cert = load_cert_pass(file, 0, pass, desc);
983 if (format == FORMAT_PKCS12 || format == FORMAT_ASN1) {
986 *certs = sk_X509_new_null();
988 ret = sk_X509_insert(*certs, cert, 0);
993 ret = load_certs(file, certs, format, pass, desc);
998 static void warn_certs_expired(const char *file, STACK_OF(X509) **certs)
1004 for (i = 0; i < sk_X509_num(*certs); i++) {
1005 cert = sk_X509_value(*certs, i);
1006 res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
1007 X509_get0_notAfter(cert));
1009 subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1010 CMP_warn3("certificate from '%s' with subject '%s' %s", file, subj,
1011 res > 0 ? "has expired" : "not yet valid");
1018 * TODO potentially move this and related functions to apps/lib/
1019 * or even better extend OSSL_STORE with type OSSL_STORE_INFO_CERTS
1021 static int load_certs_autofmt(const char *infile, STACK_OF(X509) **certs,
1022 int exclude_http, const char *pass,
1027 BIO *bio_bak = bio_err;
1028 int format = adjust_format(&infile, opt_certsform, 0);
1030 if (exclude_http && format == FORMAT_HTTP) {
1031 BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
1034 pass_string = get_passwd(pass, desc);
1035 if (format != FORMAT_HTTP)
1036 bio_err = NULL; /* do not show errors on more than one try */
1037 ret = load_certs_preliminary(infile, certs, format, pass_string, desc);
1039 if (!ret && format != FORMAT_HTTP) {
1040 int format2 = format == FORMAT_PEM ? FORMAT_ASN1 : FORMAT_PEM;
1043 ret = load_certs_preliminary(infile, certs, format2, pass_string, desc);
1045 clear_free(pass_string);
1048 warn_certs_expired(infile, certs);
1052 /* set expected host name/IP addr and clears the email addr in the given ts */
1053 static int truststore_set_host_etc(X509_STORE *ts, char *host)
1055 X509_VERIFY_PARAM *ts_vpm = X509_STORE_get0_param(ts);
1057 /* first clear any host names, IP, and email addresses */
1058 if (!X509_VERIFY_PARAM_set1_host(ts_vpm, NULL, 0)
1059 || !X509_VERIFY_PARAM_set1_ip(ts_vpm, NULL, 0)
1060 || !X509_VERIFY_PARAM_set1_email(ts_vpm, NULL, 0))
1062 X509_VERIFY_PARAM_set_hostflags(ts_vpm,
1063 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT |
1064 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
1065 return (host != NULL && X509_VERIFY_PARAM_set1_ip_asc(ts_vpm, host))
1066 || X509_VERIFY_PARAM_set1_host(ts_vpm, host, 0);
1069 static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
1070 const STACK_OF(X509) *certs /* may NULL */)
1075 store = X509_STORE_new();
1078 for (i = 0; i < sk_X509_num(certs); i++) {
1079 if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
1080 X509_STORE_free(store);
1087 /* write OSSL_CMP_MSG DER-encoded to the specified file name item */
1088 static int write_PKIMESSAGE(const OSSL_CMP_MSG *msg, char **filenames)
1093 if (msg == NULL || filenames == NULL) {
1094 CMP_err("NULL arg to write_PKIMESSAGE");
1097 if (*filenames == NULL) {
1098 CMP_err("Not enough file names provided for writing PKIMessage");
1103 *filenames = next_item(file);
1104 bio = BIO_new_file(file, "wb");
1106 CMP_err1("Cannot open file '%s' for writing", file);
1109 if (i2d_OSSL_CMP_MSG_bio(bio, msg) < 0) {
1110 CMP_err1("Cannot write PKIMessage to file '%s'", file);
1118 /* read DER-encoded OSSL_CMP_MSG from the specified file name item */
1119 static OSSL_CMP_MSG *read_PKIMESSAGE(char **filenames)
1125 if (filenames == NULL) {
1126 CMP_err("NULL arg to read_PKIMESSAGE");
1129 if (*filenames == NULL) {
1130 CMP_err("Not enough file names provided for reading PKIMessage");
1135 *filenames = next_item(file);
1136 bio = BIO_new_file(file, "rb");
1138 CMP_err1("Cannot open file '%s' for reading", file);
1141 ret = d2i_OSSL_CMP_MSG_bio(bio, NULL);
1143 CMP_err1("Cannot read PKIMessage from file '%s'", file);
1149 * Sends the PKIMessage req and on success place the response in *res
1150 * basically like OSSL_CMP_MSG_http_perform(), but in addition allows
1151 * to dump the sequence of requests and responses to files and/or
1152 * to take the sequence of requests and responses from files.
1154 static OSSL_CMP_MSG *read_write_req_resp(OSSL_CMP_CTX *ctx,
1155 const OSSL_CMP_MSG *req)
1157 OSSL_CMP_MSG *req_new = NULL;
1158 OSSL_CMP_MSG *res = NULL;
1159 OSSL_CMP_PKIHEADER *hdr;
1161 if (req != NULL && opt_reqout != NULL
1162 && !write_PKIMESSAGE(req, &opt_reqout))
1164 if (opt_reqin != NULL) {
1165 if (opt_rspin != NULL) {
1166 CMP_warn("-reqin is ignored since -rspin is present");
1168 if ((req_new = read_PKIMESSAGE(&opt_reqin)) == NULL)
1171 * The transaction ID in req_new may not be fresh.
1172 * In this case the Insta Demo CA correctly complains:
1173 * "Transaction id already in use."
1174 * The following workaround unfortunately requires re-protection.
1175 * See also https://github.com/mpeylo/cmpossl/issues/8
1177 #if defined(USE_TRANSACTIONID_WORKAROUND)
1178 hdr = OSSL_CMP_MSG_get0_header(req_new);
1179 if (!OSSL_CMP_CTX_set1_transactionID(hdr, NULL)
1180 || !ossl_cmp_msg_protect(ctx, req_new))
1186 if (opt_rspin != NULL) {
1187 res = read_PKIMESSAGE(&opt_rspin);
1189 const OSSL_CMP_MSG *actual_req = opt_reqin != NULL ? req_new : req;
1191 res = opt_use_mock_srv
1192 ? OSSL_CMP_CTX_server_perform(ctx, actual_req)
1193 : OSSL_CMP_MSG_http_perform(ctx, actual_req);
1198 if (opt_reqin != NULL || opt_rspin != NULL) {
1199 /* need to satisfy nonce and transactionID checks */
1200 ASN1_OCTET_STRING *nonce;
1201 ASN1_OCTET_STRING *tid;
1203 hdr = OSSL_CMP_MSG_get0_header(res);
1204 nonce = OSSL_CMP_HDR_get0_recipNonce(hdr);
1205 tid = OSSL_CMP_HDR_get0_transactionID(hdr);
1206 if (!OSSL_CMP_CTX_set1_senderNonce(ctx, nonce)
1207 || !OSSL_CMP_CTX_set1_transactionID(ctx, tid)) {
1208 OSSL_CMP_MSG_free(res);
1214 if (opt_rspout != NULL && !write_PKIMESSAGE(res, &opt_rspout)) {
1215 OSSL_CMP_MSG_free(res);
1220 OSSL_CMP_MSG_free(req_new);
1225 * parse string as integer value, not allowing trailing garbage, see also
1226 * https://www.gnu.org/software/libc/manual/html_node/Parsing-of-Integers.html
1228 * returns integer value, or INT_MIN on error
1230 static int atoint(const char *str)
1233 long res = strtol(str, &tailptr, 10);
1235 if ((*tailptr != '\0') || (res < INT_MIN) || (res > INT_MAX))
1241 static int parse_addr(char **opt_string, int port, const char *name)
1245 if (strncasecmp(*opt_string, OSSL_HTTP_PREFIX,
1246 strlen(OSSL_HTTP_PREFIX)) == 0) {
1247 *opt_string += strlen(OSSL_HTTP_PREFIX);
1248 } else if (strncasecmp(*opt_string, OSSL_HTTPS_PREFIX,
1249 strlen(OSSL_HTTPS_PREFIX)) == 0) {
1250 *opt_string += strlen(OSSL_HTTPS_PREFIX);
1252 port = 443; /* == integer value of OSSL_HTTPS_PORT */
1255 if ((port_string = strrchr(*opt_string, ':')) == NULL)
1256 return port; /* using default */
1257 *(port_string++) = '\0';
1258 port = atoint(port_string);
1259 if ((port <= 0) || (port > 65535)) {
1260 CMP_err2("invalid %s port '%s' given, sane range 1-65535",
1267 static int set1_store_parameters(X509_STORE *ts)
1272 /* copy vpm to store */
1273 if (!X509_STORE_set1_param(ts, vpm /* may be NULL */)) {
1274 BIO_printf(bio_err, "error setting verification parameters\n");
1275 OSSL_CMP_CTX_print_errors(cmp_ctx);
1279 X509_STORE_set_verify_cb(ts, X509_STORE_CTX_print_verify_cb);
1284 static int set_name(const char *str,
1285 int (*set_fn) (OSSL_CMP_CTX *ctx, const X509_NAME *name),
1286 OSSL_CMP_CTX *ctx, const char *desc)
1289 X509_NAME *n = parse_name(str, MBSTRING_ASC, 0);
1292 CMP_err2("cannot parse %s DN '%s'", desc, str);
1295 if (!(*set_fn) (ctx, n)) {
1297 CMP_err("out of memory");
1305 static int set_gennames(OSSL_CMP_CTX *ctx, char *names, const char *desc)
1309 for (; names != NULL; names = next) {
1312 next = next_item(names);
1313 if (strcmp(names, "critical") == 0) {
1314 (void)OSSL_CMP_CTX_set_option(ctx,
1315 OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL,
1320 /* try IP address first, then URI or domain name */
1321 (void)ERR_set_mark();
1322 n = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_IPADD, names, 0);
1324 n = a2i_GENERAL_NAME(NULL, NULL, NULL,
1325 strchr(names, ':') != NULL ? GEN_URI : GEN_DNS,
1327 (void)ERR_pop_to_mark();
1330 CMP_err2("bad syntax of %s '%s'", desc, names);
1333 if (!OSSL_CMP_CTX_push1_subjectAltName(ctx, n)) {
1334 GENERAL_NAME_free(n);
1335 CMP_err("out of memory");
1338 GENERAL_NAME_free(n);
1343 /* TODO potentially move to apps/lib/apps.c */
1345 * create cert store structure with certificates read from given file(s)
1346 * returns pointer to created X509_STORE on success, NULL on error
1348 static X509_STORE *load_certstore(char *input, const char *desc)
1350 X509_STORE *store = NULL;
1351 STACK_OF(X509) *certs = NULL;
1356 while (input != NULL) {
1357 char *next = next_item(input); \
1359 if (!load_certs_autofmt(input, &certs, 1, opt_otherpass, desc)
1360 || !(store = sk_X509_to_store(store, certs))) {
1361 /* CMP_err("out of memory"); */
1362 X509_STORE_free(store);
1366 sk_X509_pop_free(certs, X509_free);
1371 sk_X509_pop_free(certs, X509_free);
1375 /* TODO potentially move to apps/lib/apps.c */
1376 static STACK_OF(X509) *load_certs_multifile(char *files,
1377 const char *pass, const char *desc)
1379 STACK_OF(X509) *certs = NULL;
1380 STACK_OF(X509) *result = sk_X509_new_null();
1387 while (files != NULL) {
1388 char *next = next_item(files);
1390 if (!load_certs_autofmt(files, &certs, 0, pass, desc))
1392 if (!sk_X509_add1_certs(result, certs, 0, 1 /* no dups */, 0))
1394 sk_X509_pop_free(certs, X509_free);
1401 BIO_printf(bio_err, "out of memory\n");
1403 sk_X509_pop_free(certs, X509_free);
1404 sk_X509_pop_free(result, X509_free);
1408 typedef int (*add_X509_stack_fn_t)(void *ctx, const STACK_OF(X509) *certs);
1409 typedef int (*add_X509_fn_t)(void *ctx, const X509 *cert);
1411 static int setup_certs(char *files, const char *desc, void *ctx,
1412 add_X509_stack_fn_t addn_fn, add_X509_fn_t add1_fn)
1416 if (files != NULL) {
1417 STACK_OF(X509) *certs = load_certs_multifile(files, opt_otherpass,
1419 if (certs == NULL) {
1422 if (addn_fn != NULL) {
1423 ret = (*addn_fn)(ctx, certs);
1427 for (i = 0; i < sk_X509_num(certs /* may be NULL */); i++)
1428 ret &= (*add1_fn)(ctx, sk_X509_value(certs, i));
1430 sk_X509_pop_free(certs, X509_free);
1438 * parse and transform some options, checking their syntax.
1439 * Returns 1 on success, 0 on error
1441 static int transform_opts(void)
1443 if (opt_cmd_s != NULL) {
1444 if (!strcmp(opt_cmd_s, "ir")) {
1446 } else if (!strcmp(opt_cmd_s, "kur")) {
1448 } else if (!strcmp(opt_cmd_s, "cr")) {
1450 } else if (!strcmp(opt_cmd_s, "p10cr")) {
1451 opt_cmd = CMP_P10CR;
1452 } else if (!strcmp(opt_cmd_s, "rr")) {
1454 } else if (!strcmp(opt_cmd_s, "genm")) {
1457 CMP_err1("unknown cmp command '%s'", opt_cmd_s);
1461 CMP_err("no cmp command to execute");
1465 #ifdef OPENSSL_NO_ENGINE
1466 # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12 | OPT_FMT_ENGINE)
1468 # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12)
1471 if (opt_keyform_s != NULL
1472 && !opt_format(opt_keyform_s, FORMAT_OPTIONS, &opt_keyform)) {
1473 CMP_err("unknown option given for key loading format");
1477 #undef FORMAT_OPTIONS
1479 if (opt_certform_s != NULL
1480 && !opt_format(opt_certform_s, OPT_FMT_PEMDER, &opt_certform)) {
1481 CMP_err("unknown option given for certificate storing format");
1485 if (opt_certsform_s != NULL
1486 && !opt_format(opt_certsform_s, OPT_FMT_PEMDER | OPT_FMT_PKCS12,
1488 CMP_err("unknown option given for certificate list loading format");
1495 static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *e)
1497 OSSL_CMP_CTX *ctx; /* extra CMP (client) ctx partly used by server */
1498 OSSL_CMP_SRV_CTX *srv_ctx = ossl_cmp_mock_srv_new();
1500 if (srv_ctx == NULL)
1502 ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx);
1504 if (opt_srv_ref == NULL) {
1505 if (opt_srv_cert == NULL) {
1506 /* opt_srv_cert should determine the sender */
1507 CMP_err("must give -srv_ref for server if no -srv_cert given");
1511 if (!OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_srv_ref,
1512 strlen(opt_srv_ref)))
1516 if (opt_srv_secret != NULL) {
1518 char *pass_str = get_passwd(opt_srv_secret, "PBMAC secret of server");
1520 if (pass_str != NULL) {
1521 cleanse(opt_srv_secret);
1522 res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_str,
1524 clear_free(pass_str);
1528 } else if (opt_srv_cert == NULL) {
1529 CMP_err("server credentials must be given if -use_mock_srv or -port is used");
1532 CMP_warn("server will not be able to handle PBM-protected requests since -srv_secret is not given");
1535 if (opt_srv_secret == NULL
1536 && ((opt_srv_cert == NULL) != (opt_srv_key == NULL))) {
1537 CMP_err("must give both -srv_cert and -srv_key options or neither");
1540 if (opt_srv_cert != NULL) {
1541 X509 *srv_cert = load_cert_pwd(opt_srv_cert, opt_srv_keypass,
1542 "certificate of the server");
1543 if (srv_cert == NULL || !OSSL_CMP_CTX_set1_clCert(ctx, srv_cert)) {
1544 X509_free(srv_cert);
1547 X509_free(srv_cert);
1549 if (opt_srv_key != NULL) {
1550 EVP_PKEY *pkey = load_key_pwd(opt_srv_key, opt_keyform,
1552 e, "private key for server cert");
1554 if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) {
1555 EVP_PKEY_free(pkey);
1558 EVP_PKEY_free(pkey);
1560 cleanse(opt_srv_keypass);
1562 if (opt_srv_trusted != NULL) {
1564 load_certstore(opt_srv_trusted, "certificates trusted by server");
1568 if (!set1_store_parameters(ts)
1569 || !truststore_set_host_etc(ts, NULL)
1570 || !OSSL_CMP_CTX_set0_trustedStore(ctx, ts)) {
1571 X509_STORE_free(ts);
1575 CMP_warn("server will not be able to handle signature-protected requests since -srv_trusted is not given");
1577 if (!setup_certs(opt_srv_untrusted, "untrusted certificates", ctx,
1578 (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted_certs,
1582 if (opt_rsp_cert == NULL) {
1583 CMP_err("must give -rsp_cert for mock server");
1586 X509 *cert = load_cert_pwd(opt_rsp_cert, opt_keypass,
1587 "cert to be returned by the mock server");
1591 /* from server perspective the server is the client */
1592 if (!ossl_cmp_mock_srv_set1_certOut(srv_ctx, cert)) {
1598 /* TODO find a cleaner solution not requiring type casts */
1599 if (!setup_certs(opt_rsp_extracerts,
1600 "CMP extra certificates for mock server", srv_ctx,
1601 (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_chainOut,
1604 if (!setup_certs(opt_rsp_capubs, "caPubs for mock server", srv_ctx,
1605 (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_caPubsOut,
1608 (void)ossl_cmp_mock_srv_set_pollCount(srv_ctx, opt_poll_count);
1609 (void)ossl_cmp_mock_srv_set_checkAfterTime(srv_ctx, opt_check_after);
1610 if (opt_grant_implicitconf)
1611 (void)OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(srv_ctx, 1);
1613 if (opt_failure != INT_MIN) { /* option has been set explicity */
1614 if (opt_failure < 0 || OSSL_CMP_PKIFAILUREINFO_MAX < opt_failure) {
1615 CMP_err1("-failure out of range, should be >= 0 and <= %d",
1616 OSSL_CMP_PKIFAILUREINFO_MAX);
1619 if (opt_failurebits != 0)
1620 CMP_warn("-failurebits overrides -failure");
1622 opt_failurebits = 1 << opt_failure;
1624 if ((unsigned)opt_failurebits > OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN) {
1625 CMP_err("-failurebits out of range");
1628 if (!ossl_cmp_mock_srv_set_statusInfo(srv_ctx, opt_pkistatus,
1629 opt_failurebits, opt_statusstring))
1633 (void)ossl_cmp_mock_srv_set_send_error(srv_ctx, 1);
1635 if (opt_send_unprotected)
1636 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1);
1637 if (opt_send_unprot_err)
1638 (void)OSSL_CMP_SRV_CTX_set_send_unprotected_errors(srv_ctx, 1);
1639 if (opt_accept_unprotected)
1640 (void)OSSL_CMP_SRV_CTX_set_accept_unprotected(srv_ctx, 1);
1641 if (opt_accept_unprot_err)
1642 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1);
1643 if (opt_accept_raverified)
1644 (void)OSSL_CMP_SRV_CTX_set_accept_raverified(srv_ctx, 1);
1649 ossl_cmp_mock_srv_free(srv_ctx);
1654 * set up verification aspects of OSSL_CMP_CTX w.r.t. opts from config file/CLI.
1655 * Returns pointer on success, NULL on error
1657 static int setup_verification_ctx(OSSL_CMP_CTX *ctx)
1659 if (!setup_certs(opt_untrusted, "untrusted certificates", ctx,
1660 (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted_certs,
1664 if (opt_srvcert != NULL || opt_trusted != NULL) {
1665 X509_STORE *ts = NULL;
1667 if (opt_srvcert != NULL) {
1670 if (opt_trusted != NULL) {
1671 CMP_warn("-trusted option is ignored since -srvcert option is present");
1674 if (opt_recipient != NULL) {
1675 CMP_warn("-recipient option is ignored since -srvcert option is present");
1676 opt_recipient = NULL;
1678 srvcert = load_cert_pwd(opt_srvcert, opt_otherpass,
1679 "directly trusted CMP server certificate");
1680 if (srvcert == NULL)
1682 * opt_otherpass is needed in case
1683 * opt_srvcert is an encrypted PKCS#12 file
1686 if (!OSSL_CMP_CTX_set1_srvCert(ctx, srvcert)) {
1691 if ((ts = X509_STORE_new()) == NULL)
1694 if (opt_trusted != NULL
1695 && (ts = load_certstore(opt_trusted, "trusted certificates"))
1698 if (!set1_store_parameters(ts) /* also copies vpm */
1700 * clear any expected host/ip/email address;
1701 * opt_expect_sender is used instead
1703 || !truststore_set_host_etc(ts, NULL)
1704 || !OSSL_CMP_CTX_set0_trustedStore(ctx, ts)) {
1705 X509_STORE_free(ts);
1710 if (opt_ignore_keyusage)
1711 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IGNORE_KEYUSAGE, 1);
1713 if (opt_unprotected_errors)
1714 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1);
1716 if (opt_out_trusted != NULL) { /* for use in OSSL_CMP_certConf_cb() */
1717 X509_VERIFY_PARAM *out_vpm = NULL;
1718 X509_STORE *out_trusted =
1719 load_certstore(opt_out_trusted,
1720 "trusted certs for verifying newly enrolled cert");
1722 if (out_trusted == NULL)
1724 /* any -verify_hostname, -verify_ip, and -verify_email apply here */
1725 if (!set1_store_parameters(out_trusted))
1727 /* ignore any -attime here, new certs are current anyway */
1728 out_vpm = X509_STORE_get0_param(out_trusted);
1729 X509_VERIFY_PARAM_clear_flags(out_vpm, X509_V_FLAG_USE_CHECK_TIME);
1731 (void)OSSL_CMP_CTX_set_certConf_cb_arg(ctx, out_trusted);
1734 if (opt_disable_confirm)
1735 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DISABLE_CONFIRM, 1);
1737 if (opt_implicit_confirm)
1738 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM, 1);
1740 (void)OSSL_CMP_CTX_set_certConf_cb(ctx, OSSL_CMP_certConf_cb);
1745 CMP_err("out of memory");
1750 #ifndef OPENSSL_NO_SOCK
1752 * set up ssl_ctx for the OSSL_CMP_CTX based on options from config file/CLI.
1753 * Returns pointer on success, NULL on error
1755 static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, ENGINE *e)
1757 STACK_OF(X509) *untrusted_certs = OSSL_CMP_CTX_get0_untrusted_certs(ctx);
1758 EVP_PKEY *pkey = NULL;
1759 X509_STORE *trust_store = NULL;
1763 ssl_ctx = SSL_CTX_new(TLS_client_method());
1764 if (ssl_ctx == NULL)
1767 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
1769 if (opt_tls_trusted != NULL) {
1770 if ((trust_store = load_certstore(opt_tls_trusted,
1771 "trusted TLS certificates")) == NULL)
1773 SSL_CTX_set_cert_store(ssl_ctx, trust_store);
1774 /* for improved diagnostics on SSL_CTX_build_cert_chain() errors: */
1775 X509_STORE_set_verify_cb(trust_store, X509_STORE_CTX_print_verify_cb);
1778 if (opt_tls_cert != NULL && opt_tls_key != NULL) {
1780 STACK_OF(X509) *certs = NULL;
1782 if (!load_certs_autofmt(opt_tls_cert, &certs, 0, opt_tls_keypass,
1783 "TLS client certificate (optionally with chain)"))
1785 * opt_tls_keypass is needed in case opt_tls_cert is an encrypted
1790 cert = sk_X509_delete(certs, 0);
1791 if (cert == NULL || SSL_CTX_use_certificate(ssl_ctx, cert) <= 0) {
1792 CMP_err1("unable to use client TLS certificate file '%s'",
1795 sk_X509_pop_free(certs, X509_free);
1798 X509_free(cert); /* we do not need the handle any more */
1801 * Any further certs and any untrusted certs are used for constructing
1802 * the client cert chain to be provided along with the TLS client cert
1803 * to the TLS server.
1805 if (!SSL_CTX_set0_chain(ssl_ctx, certs)) {
1806 CMP_err("could not set TLS client cert chain");
1807 sk_X509_pop_free(certs, X509_free);
1810 for (i = 0; i < sk_X509_num(untrusted_certs); i++) {
1811 cert = sk_X509_value(untrusted_certs, i);
1812 if (!SSL_CTX_add1_chain_cert(ssl_ctx, cert)) {
1813 CMP_err("could not add untrusted cert to TLS client cert chain");
1817 if (!SSL_CTX_build_cert_chain(ssl_ctx,
1818 SSL_BUILD_CHAIN_FLAG_UNTRUSTED |
1819 SSL_BUILD_CHAIN_FLAG_NO_ROOT)) {
1820 CMP_warn("could not build cert chain for own TLS cert");
1821 OSSL_CMP_CTX_print_errors(ctx);
1824 /* If present we append to the list also the certs from opt_tls_extra */
1825 if (opt_tls_extra != NULL) {
1826 STACK_OF(X509) *tls_extra = load_certs_multifile(opt_tls_extra,
1828 "extra certificates for TLS");
1831 if (tls_extra == NULL)
1833 for (i = 0; i < sk_X509_num(tls_extra); i++) {
1834 cert = sk_X509_value(tls_extra, i);
1836 res = SSL_CTX_add_extra_chain_cert(ssl_ctx, cert);
1840 sk_X509_free(tls_extra);
1842 BIO_printf(bio_err, "error: unable to add TLS extra certs\n");
1847 pkey = load_key_pwd(opt_tls_key, opt_keyform, opt_tls_keypass,
1848 e, "TLS client private key");
1849 cleanse(opt_tls_keypass);
1853 * verify the key matches the cert,
1854 * not using SSL_CTX_check_private_key(ssl_ctx)
1855 * because it gives poor and sometimes misleading diagnostics
1857 if (!X509_check_private_key(SSL_CTX_get0_certificate(ssl_ctx),
1859 CMP_err2("TLS private key '%s' does not match the TLS certificate '%s'\n",
1860 opt_tls_key, opt_tls_cert);
1861 EVP_PKEY_free(pkey);
1862 pkey = NULL; /* otherwise, for some reason double free! */
1865 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) <= 0) {
1866 CMP_err1("unable to use TLS client private key '%s'", opt_tls_key);
1867 EVP_PKEY_free(pkey);
1868 pkey = NULL; /* otherwise, for some reason double free! */
1871 EVP_PKEY_free(pkey); /* we do not need the handle any more */
1873 if (opt_tls_trusted != NULL) {
1874 /* enable and parameterize server hostname/IP address check */
1875 if (!truststore_set_host_etc(trust_store,
1876 opt_tls_host != NULL ?
1877 opt_tls_host : opt_server))
1878 /* TODO: is the server host name correct for TLS via proxy? */
1880 SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
1884 SSL_CTX_free(ssl_ctx);
1890 * set up protection aspects of OSSL_CMP_CTX based on options from config
1891 * file/CLI while parsing options and checking their consistency.
1892 * Returns 1 on success, 0 on error
1894 static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *e)
1896 if (!opt_unprotected_requests && opt_secret == NULL && opt_cert == NULL) {
1897 CMP_err("must give client credentials unless -unprotected_requests is set");
1901 if (opt_ref == NULL && opt_cert == NULL && opt_subject == NULL) {
1902 /* cert or subject should determine the sender */
1903 CMP_err("must give -ref if no -cert and no -subject given");
1906 if (!opt_secret && ((opt_cert == NULL) != (opt_key == NULL))) {
1907 CMP_err("must give both -cert and -key options or neither");
1910 if (opt_secret != NULL) {
1911 char *pass_string = get_passwd(opt_secret, "PBMAC");
1914 if (pass_string != NULL) {
1915 cleanse(opt_secret);
1916 res = OSSL_CMP_CTX_set1_secretValue(ctx,
1917 (unsigned char *)pass_string,
1918 strlen(pass_string));
1919 clear_free(pass_string);
1923 if (opt_cert != NULL || opt_key != NULL)
1924 CMP_warn("no signature-based protection used since -secret is given");
1927 && !OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_ref,
1931 if (opt_key != NULL) {
1932 EVP_PKEY *pkey = load_key_pwd(opt_key, opt_keyform, opt_keypass, e,
1933 "private key for CMP client certificate");
1935 if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) {
1936 EVP_PKEY_free(pkey);
1939 EVP_PKEY_free(pkey);
1941 if (opt_secret == NULL && opt_srvcert == NULL && opt_trusted == NULL) {
1942 CMP_err("missing -secret or -srvcert or -trusted");
1946 if (opt_cert != NULL) {
1948 STACK_OF(X509) *certs = NULL;
1951 if (!load_certs_autofmt(opt_cert, &certs, 0, opt_keypass,
1952 "CMP client certificate (and optionally extra certs)"))
1953 /* opt_keypass is needed if opt_cert is an encrypted PKCS#12 file */
1956 clcert = sk_X509_delete(certs, 0);
1957 if (clcert == NULL) {
1958 CMP_err("no client certificate found");
1959 sk_X509_pop_free(certs, X509_free);
1962 ok = OSSL_CMP_CTX_set1_clCert(ctx, clcert);
1966 /* add any remaining certs to the list of untrusted certs */
1967 STACK_OF(X509) *untrusted = OSSL_CMP_CTX_get0_untrusted_certs(ctx);
1968 ok = untrusted != NULL ?
1969 sk_X509_add1_certs(untrusted, certs, 0, 1 /* no dups */, 0) :
1970 OSSL_CMP_CTX_set1_untrusted_certs(ctx, certs);
1972 sk_X509_pop_free(certs, X509_free);
1977 if (!setup_certs(opt_extracerts, "extra certificates for CMP", ctx,
1978 (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_extraCertsOut,
1981 cleanse(opt_otherpass);
1983 if (opt_unprotected_requests)
1984 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1);
1986 if (opt_digest != NULL) {
1987 int digest = OBJ_ln2nid(opt_digest);
1989 if (digest == NID_undef) {
1990 CMP_err1("digest algorithm name not recognized: '%s'", opt_digest);
1993 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DIGEST_ALGNID, digest);
1994 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_OWF_ALGNID, digest);
1997 if (opt_mac != NULL) {
1998 int mac = OBJ_ln2nid(opt_mac);
1999 if (mac == NID_undef) {
2000 CMP_err1("MAC algorithm name not recognized: '%s'", opt_mac);
2003 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MAC_ALGNID, mac);
2008 CMP_err("out of memory");
2014 * set up IR/CR/KUR/CertConf/RR specific parts of the OSSL_CMP_CTX
2015 * based on options from config file/CLI.
2016 * Returns pointer on success, NULL on error
2018 static int setup_request_ctx(OSSL_CMP_CTX *ctx, ENGINE *e)
2020 if (opt_subject == NULL && opt_oldcert == NULL && opt_cert == NULL)
2021 CMP_warn("no -subject given, neither -oldcert nor -cert available as default");
2022 if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject")
2023 || !set_name(opt_issuer, OSSL_CMP_CTX_set1_issuer, ctx, "issuer"))
2026 if (opt_newkey != NULL) {
2027 const char *file = opt_newkey;
2028 const int format = opt_keyform;
2029 const char *pass = opt_newkeypass;
2030 const char *desc = "new private or public key for cert to be enrolled";
2031 EVP_PKEY *pkey = load_key_pwd(file, format, pass, e, NULL);
2036 pkey = load_pubkey(file, format, 0, pass, e, desc);
2039 cleanse(opt_newkeypass);
2040 if (pkey == NULL || !OSSL_CMP_CTX_set0_newPkey(ctx, priv, pkey)) {
2041 EVP_PKEY_free(pkey);
2047 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_VALIDITY_DAYS,
2050 if (opt_policies != NULL && opt_policy_oids != NULL) {
2051 CMP_err("cannot have policies both via -policies and via -policy_oids");
2055 if (opt_reqexts != NULL || opt_policies != NULL) {
2057 X509_EXTENSIONS *exts = sk_X509_EXTENSION_new_null();
2061 X509V3_set_ctx(&ext_ctx, NULL, NULL, NULL, NULL, 0);
2062 X509V3_set_nconf(&ext_ctx, conf);
2063 if (opt_reqexts != NULL
2064 && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_reqexts, &exts)) {
2065 CMP_err1("cannot load certificate request extension section '%s'",
2067 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
2070 if (opt_policies != NULL
2071 && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_policies, &exts)) {
2072 CMP_err1("cannot load policy cert request extension section '%s'",
2074 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
2077 OSSL_CMP_CTX_set0_reqExtensions(ctx, exts);
2079 if (OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) && opt_sans != NULL) {
2080 CMP_err("cannot have Subject Alternative Names both via -reqexts and via -sans");
2084 if (!set_gennames(ctx, opt_sans, "Subject Alternative Name"))
2087 if (opt_san_nodefault) {
2088 if (opt_sans != NULL)
2089 CMP_warn("-opt_san_nodefault has no effect when -sans is used");
2090 (void)OSSL_CMP_CTX_set_option(ctx,
2091 OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT, 1);
2094 if (opt_policy_oids_critical) {
2095 if (opt_policy_oids == NULL)
2096 CMP_warn("-opt_policy_oids_critical has no effect unless -policy_oids is given");
2097 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POLICIES_CRITICAL, 1);
2100 while (opt_policy_oids != NULL) {
2101 ASN1_OBJECT *policy;
2103 char *next = next_item(opt_policy_oids);
2105 if ((policy = OBJ_txt2obj(opt_policy_oids, 1)) == 0) {
2106 CMP_err1("unknown policy OID '%s'", opt_policy_oids);
2110 if ((pinfo = POLICYINFO_new()) == NULL) {
2111 ASN1_OBJECT_free(policy);
2114 pinfo->policyid = policy;
2116 if (!OSSL_CMP_CTX_push0_policy(ctx, pinfo)) {
2117 CMP_err1("cannot add policy with OID '%s'", opt_policy_oids);
2118 POLICYINFO_free(pinfo);
2121 opt_policy_oids = next;
2124 if (opt_popo >= OSSL_CRMF_POPO_NONE)
2125 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POPO_METHOD, opt_popo);
2127 if (opt_csr != NULL) {
2128 if (opt_cmd != CMP_P10CR) {
2129 CMP_warn("-csr option is ignored for command other than p10cr");
2132 load_csr_autofmt(opt_csr, "PKCS#10 CSR for p10cr");
2136 if (!OSSL_CMP_CTX_set1_p10CSR(ctx, csr)) {
2144 if (opt_oldcert != NULL) {
2145 X509 *oldcert = load_cert_pwd(opt_oldcert, opt_keypass,
2146 "certificate to be updated/revoked");
2147 /* opt_keypass is needed if opt_oldcert is an encrypted PKCS#12 file */
2149 if (oldcert == NULL)
2151 if (!OSSL_CMP_CTX_set1_oldCert(ctx, oldcert)) {
2157 cleanse(opt_keypass);
2158 if (opt_revreason > CRL_REASON_NONE)
2159 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_REVOCATION_REASON,
2165 CMP_err("out of memory");
2170 static int handle_opt_geninfo(OSSL_CMP_CTX *ctx)
2176 OSSL_CMP_ITAV *itav;
2178 char *valptr = strchr(opt_geninfo, ':');
2180 if (valptr == NULL) {
2181 CMP_err("missing ':' in -geninfo option");
2187 if (strncasecmp(valptr, "int:", 4) != 0) {
2188 CMP_err("missing 'int:' in -geninfo option");
2193 value = strtol(valptr, &endstr, 10);
2194 if (endstr == valptr || *endstr != '\0') {
2195 CMP_err("cannot parse int in -geninfo option");
2199 type = OBJ_txt2obj(opt_geninfo, 1);
2201 CMP_err("cannot parse OID in -geninfo option");
2205 aint = ASN1_INTEGER_new();
2206 if (aint == NULL || !ASN1_INTEGER_set(aint, value))
2209 val = ASN1_TYPE_new();
2211 ASN1_INTEGER_free(aint);
2214 ASN1_TYPE_set(val, V_ASN1_INTEGER, aint);
2215 itav = OSSL_CMP_ITAV_create(type, val);
2217 ASN1_TYPE_free(val);
2221 if (!OSSL_CMP_CTX_push0_geninfo_ITAV(ctx, itav)) {
2222 OSSL_CMP_ITAV_free(itav);
2228 CMP_err("out of memory");
2234 * set up the client-side OSSL_CMP_CTX based on options from config file/CLI
2235 * while parsing options and checking their consistency.
2236 * Prints reason for error to bio_err.
2237 * Returns 1 on success, 0 on error
2239 static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *e)
2242 char server_buf[200] = { '\0' };
2243 char proxy_buf[200] = { '\0' };
2244 char *proxy_host = NULL;
2245 char *proxy_port_str = NULL;
2247 if (opt_server == NULL) {
2248 CMP_err("missing server address[:port]");
2250 } else if ((server_port =
2251 parse_addr(&opt_server, server_port, "server")) < 0) {
2254 if (server_port != 0)
2255 BIO_snprintf(server_port_s, sizeof(server_port_s), "%d", server_port);
2256 if (!OSSL_CMP_CTX_set1_server(ctx, opt_server)
2257 || !OSSL_CMP_CTX_set_serverPort(ctx, server_port)
2258 || !OSSL_CMP_CTX_set1_serverPath(ctx, opt_path))
2260 if (opt_proxy != NULL && !OSSL_CMP_CTX_set1_proxy(ctx, opt_proxy))
2262 (void)BIO_snprintf(server_buf, sizeof(server_buf), "http%s://%s%s%s/%s",
2263 opt_tls_used ? "s" : "", opt_server,
2264 server_port == 0 ? "" : ":", server_port_s,
2265 opt_path[0] == '/' ? opt_path + 1 : opt_path);
2267 if (opt_proxy != NULL)
2268 (void)BIO_snprintf(proxy_buf, sizeof(proxy_buf), " via %s", opt_proxy);
2269 CMP_info2("will contact %s%s", server_buf, proxy_buf);
2271 if (!transform_opts())
2274 if (opt_cmd == CMP_IR || opt_cmd == CMP_CR || opt_cmd == CMP_KUR) {
2275 if (opt_newkey == NULL && opt_key == NULL && opt_csr == NULL) {
2276 CMP_err("missing -newkey (or -key) to be certified");
2279 if (opt_certout == NULL) {
2280 CMP_err("-certout not given, nowhere to save certificate");
2284 if (opt_cmd == CMP_KUR) {
2285 char *ref_cert = opt_oldcert != NULL ? opt_oldcert : opt_cert;
2287 if (ref_cert == NULL) {
2288 CMP_err("missing -oldcert option for certificate to be updated");
2291 if (opt_subject != NULL)
2292 CMP_warn2("-subject '%s' given, which overrides the subject of '%s' in KUR",
2293 opt_subject, ref_cert);
2295 if (opt_cmd == CMP_RR && opt_oldcert == NULL) {
2296 CMP_err("missing certificate to be revoked");
2299 if (opt_cmd == CMP_P10CR && opt_csr == NULL) {
2300 CMP_err("missing PKCS#10 CSR for p10cr");
2304 if (opt_recipient == NULL && opt_srvcert == NULL && opt_issuer == NULL
2305 && opt_oldcert == NULL && opt_cert == NULL)
2306 CMP_warn("missing -recipient, -srvcert, -issuer, -oldcert or -cert; recipient will be set to \"NULL-DN\"");
2308 if (opt_infotype_s != NULL) {
2309 char id_buf[100] = "id-it-";
2311 strncat(id_buf, opt_infotype_s, sizeof(id_buf) - strlen(id_buf) - 1);
2312 if ((opt_infotype = OBJ_sn2nid(id_buf)) == NID_undef) {
2313 CMP_err("unknown OID name in -infotype option");
2318 if (!setup_verification_ctx(ctx))
2321 if (opt_msg_timeout >= 0) /* must do this before setup_ssl_ctx() */
2322 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT,
2324 if (opt_total_timeout >= 0)
2325 (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_TOTAL_TIMEOUT,
2328 if (opt_reqin != NULL || opt_reqout != NULL
2329 || opt_rspin != NULL || opt_rspout != NULL || opt_use_mock_srv)
2330 (void)OSSL_CMP_CTX_set_transfer_cb(ctx, read_write_req_resp);
2332 if ((opt_tls_cert != NULL || opt_tls_key != NULL
2333 || opt_tls_keypass != NULL || opt_tls_extra != NULL
2334 || opt_tls_trusted != NULL || opt_tls_host != NULL)
2336 CMP_warn("TLS options(s) given but not -tls_used");
2338 #ifdef OPENSSL_NO_SOCK
2339 BIO_printf(bio_err, "Cannot use TLS - sockets not supported\n");
2342 APP_HTTP_TLS_INFO *info;
2344 if (opt_tls_cert != NULL
2345 || opt_tls_key != NULL || opt_tls_keypass != NULL) {
2346 if (opt_tls_key == NULL) {
2347 CMP_err("missing -tls_key option");
2349 } else if (opt_tls_cert == NULL) {
2350 CMP_err("missing -tls_cert option");
2354 if (opt_use_mock_srv) {
2355 CMP_err("cannot use TLS options together with -use_mock_srv");
2358 if ((info = OPENSSL_zalloc(sizeof(*info))) == NULL)
2360 (void)OSSL_CMP_CTX_set_http_cb_arg(ctx, info);
2361 /* info will be freed along with CMP ctx */
2362 info->server = opt_server;
2363 info->port = server_port_s;
2364 info->use_proxy = opt_proxy != NULL;
2365 info->timeout = OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT);
2366 info->ssl_ctx = setup_ssl_ctx(ctx, e);
2367 if (info->ssl_ctx == NULL)
2369 (void)OSSL_CMP_CTX_set_http_cb(ctx, app_http_tls_cb);
2373 if (!setup_protection_ctx(ctx, e))
2376 if (!setup_request_ctx(ctx, e))
2379 if (!set_name(opt_recipient, OSSL_CMP_CTX_set1_recipient, ctx, "recipient")
2380 || !set_name(opt_expect_sender, OSSL_CMP_CTX_set1_expected_sender,
2381 ctx, "expected sender"))
2384 if (opt_geninfo != NULL && !handle_opt_geninfo(ctx))
2390 OPENSSL_free(proxy_host);
2391 OPENSSL_free(proxy_port_str);
2394 CMP_err("out of memory");
2399 * write out the given certificate to the output specified by bio.
2400 * Depending on options use either PEM or DER format.
2401 * Returns 1 on success, 0 on error
2403 static int write_cert(BIO *bio, X509 *cert)
2405 if ((opt_certform == FORMAT_PEM && PEM_write_bio_X509(bio, cert))
2406 || (opt_certform == FORMAT_ASN1 && i2d_X509_bio(bio, cert)))
2408 if (opt_certform != FORMAT_PEM && opt_certform != FORMAT_ASN1)
2410 "error: unsupported type '%s' for writing certificates\n",
2416 * writes out a stack of certs to the given file.
2417 * Depending on options use either PEM or DER format,
2418 * where DER does not make much sense for writing more than one cert!
2419 * Returns number of written certificates on success, 0 on error.
2421 static int save_certs(OSSL_CMP_CTX *ctx,
2422 STACK_OF(X509) *certs, char *destFile, char *desc)
2426 int n = sk_X509_num(certs);
2428 CMP_info3("received %d %s certificate(s), saving to file '%s'",
2430 if (n > 1 && opt_certform != FORMAT_PEM)
2431 CMP_warn("saving more than one certificate in non-PEM format");
2433 if (destFile == NULL || (bio = BIO_new(BIO_s_file())) == NULL
2434 || !BIO_write_filename(bio, (char *)destFile)) {
2435 CMP_err1("could not open file '%s' for writing", destFile);
2440 for (i = 0; i < n; i++) {
2441 if (!write_cert(bio, sk_X509_value(certs, i))) {
2442 CMP_err1("cannot write certificate to file '%s'", destFile);
2453 static void print_itavs(STACK_OF(OSSL_CMP_ITAV) *itavs)
2455 OSSL_CMP_ITAV *itav = NULL;
2458 int n = sk_OSSL_CMP_ITAV_num(itavs); /* itavs == NULL leads to 0 */
2461 CMP_info("genp contains no ITAV");
2465 for (i = 0; i < n; i++) {
2466 itav = sk_OSSL_CMP_ITAV_value(itavs, i);
2467 OBJ_obj2txt(buf, 128, OSSL_CMP_ITAV_get0_type(itav), 0);
2468 CMP_info1("genp contains ITAV of type: %s", buf);
2472 static char opt_item[SECTION_NAME_MAX + 1];
2473 /* get previous name from a comma-separated list of names */
2474 static const char *prev_item(const char *opt, const char *end)
2482 while (beg != opt && beg[-1] != ',' && !isspace(beg[-1]))
2485 if (len > SECTION_NAME_MAX)
2486 len = SECTION_NAME_MAX;
2487 strncpy(opt_item, beg, len);
2488 opt_item[SECTION_NAME_MAX] = '\0'; /* avoid gcc v8 O3 stringop-truncation */
2489 opt_item[len] = '\0';
2490 if (len > SECTION_NAME_MAX)
2491 CMP_warn2("using only first %d characters of section name starting with \"%s\"",
2492 SECTION_NAME_MAX, opt_item);
2493 while (beg != opt && (beg[-1] == ',' || isspace(beg[-1])))
2498 /* get str value for name from a comma-separated hierarchy of config sections */
2499 static char *conf_get_string(const CONF *src_conf, const char *groups,
2503 const char *end = groups + strlen(groups);
2505 while ((end = prev_item(groups, end)) != NULL) {
2506 if ((res = NCONF_get_string(src_conf, opt_item, name)) != NULL)
2512 /* get long val for name from a comma-separated hierarchy of config sections */
2513 static int conf_get_number_e(const CONF *conf_, const char *groups,
2514 const char *name, long *result)
2516 char *str = conf_get_string(conf_, groups, name);
2520 if (str == NULL || *str == '\0')
2523 res = strtol(str, &tailptr, 10);
2524 if (res == LONG_MIN || res == LONG_MAX || *tailptr != '\0')
2532 * use the command line option table to read values from the CMP section
2533 * of openssl.cnf. Defaults are taken from the config file, they can be
2534 * overwritten on the command line.
2536 static int read_config(void)
2542 int provider_option;
2543 int verification_option;
2546 * starting with offset OPT_SECTION because OPT_CONFIG and OPT_SECTION would
2547 * not make sense within the config file. They have already been handled.
2549 for (i = OPT_SECTION - OPT_HELP, opt = &cmp_options[OPT_SECTION];
2550 opt->name; i++, opt++) {
2551 if (!strcmp(opt->name, OPT_SECTION_STR)
2552 || !strcmp(opt->name, OPT_MORE_STR)) {
2556 provider_option = (OPT_PROV__FIRST <= opt->retval
2557 && opt->retval < OPT_PROV__LAST);
2558 verification_option = (OPT_V__FIRST <= opt->retval
2559 && opt->retval < OPT_V__LAST);
2560 if (provider_option || verification_option)
2562 if (cmp_vars[i].txt == NULL) {
2563 CMP_err1("internal: cmp_vars array too short, i=%d", i);
2566 switch (opt->valtype) {
2570 if (!conf_get_number_e(conf, opt_section, opt->name, &num)) {
2572 continue; /* option not provided */
2576 * do not use '<' in cmp_options. Incorrect treatment
2577 * somewhere in args_verify() can wrongly set badarg = 1
2582 txt = conf_get_string(conf, opt_section, opt->name);
2585 continue; /* option not provided */
2589 CMP_err2("internal: unsupported type '%c' for option '%s'",
2590 opt->valtype, opt->name);
2594 if (provider_option || verification_option) {
2599 BIO_snprintf(arg1, 81, "-%s", (char *)opt->name);
2600 conf_argv[0] = prog;
2601 conf_argv[1] = arg1;
2602 if (opt->valtype == '-') {
2607 conf_argv[2] = conf_get_string(conf, opt_section, opt->name);
2610 if (conf_argc > 1) {
2611 (void)opt_init(conf_argc, conf_argv, cmp_options);
2614 ? !opt_provider(opt_next())
2615 : !opt_verify(opt_next(), vpm)) {
2616 CMP_err2("for option '%s' in config file section '%s'",
2617 opt->name, opt_section);
2622 switch (opt->valtype) {
2625 if (num < INT_MIN || INT_MAX < num) {
2627 "integer value out of range for option '%s'\n",
2631 *cmp_vars[i].num = (int)num;
2634 *cmp_vars[i].num_long = num;
2637 if (txt != NULL && txt[0] == '\0')
2638 txt = NULL; /* reset option on empty string input */
2639 *cmp_vars[i].txt = txt;
2648 static char *opt_str(char *opt)
2650 char *arg = opt_arg();
2652 if (arg[0] == '\0') {
2653 CMP_warn1("argument of -%s option is empty string, resetting option",
2656 } else if (arg[0] == '-') {
2657 CMP_warn1("argument of -%s option starts with hyphen", opt);
2662 static int opt_nat(void)
2666 if (opt_int(opt_arg(), &result) && result < 0)
2667 BIO_printf(bio_err, "error: argument '%s' must not be negative\n",
2672 /* returns 1 on success, 0 on error, -1 on -help (i.e., stop with success) */
2673 static int get_opts(int argc, char **argv)
2677 prog = opt_init(argc, argv, cmp_options);
2679 while ((o = opt_next()) != OPT_EOF) {
2685 opt_help(cmp_options);
2687 case OPT_CONFIG: /* has already been handled */
2689 case OPT_SECTION: /* has already been handled */
2692 opt_server = opt_str("server");
2695 opt_proxy = opt_str("proxy");
2698 opt_no_proxy = opt_str("no_proxy");
2701 opt_path = opt_str("path");
2703 case OPT_MSG_TIMEOUT:
2704 if ((opt_msg_timeout = opt_nat()) < 0)
2707 case OPT_TOTAL_TIMEOUT:
2708 if ((opt_total_timeout = opt_nat()) < 0)
2715 opt_tls_cert = opt_str("tls_cert");
2718 opt_tls_key = opt_str("tls_key");
2720 case OPT_TLS_KEYPASS:
2721 opt_tls_keypass = opt_str("tls_keypass");
2724 opt_tls_extra = opt_str("tls_extra");
2726 case OPT_TLS_TRUSTED:
2727 opt_tls_trusted = opt_str("tls_trusted");
2730 opt_tls_host = opt_str("tls_host");
2733 opt_ref = opt_str("ref");
2736 opt_secret = opt_str("secret");
2739 opt_cert = opt_str("cert");
2742 opt_key = opt_str("key");
2745 opt_keypass = opt_str("keypass");
2748 opt_digest = opt_str("digest");
2751 opt_mac = opt_str("mac");
2753 case OPT_EXTRACERTS:
2754 opt_extracerts = opt_str("extracerts");
2756 case OPT_UNPROTECTED_REQUESTS:
2757 opt_unprotected_requests = 1;
2761 opt_trusted = opt_str("trusted");
2764 opt_untrusted = opt_str("untrusted");
2767 opt_srvcert = opt_str("srvcert");
2770 opt_recipient = opt_str("recipient");
2772 case OPT_EXPECT_SENDER:
2773 opt_expect_sender = opt_str("expect_sender");
2775 case OPT_IGNORE_KEYUSAGE:
2776 opt_ignore_keyusage = 1;
2778 case OPT_UNPROTECTED_ERRORS:
2779 opt_unprotected_errors = 1;
2781 case OPT_EXTRACERTSOUT:
2782 opt_extracertsout = opt_str("extracertsout");
2784 case OPT_CACERTSOUT:
2785 opt_cacertsout = opt_str("cacertsout");
2789 if (!opt_verify(o, vpm))
2793 opt_cmd_s = opt_str("cmd");
2796 opt_infotype_s = opt_str("infotype");
2799 opt_geninfo = opt_str("geninfo");
2803 opt_newkey = opt_str("newkey");
2805 case OPT_NEWKEYPASS:
2806 opt_newkeypass = opt_str("newkeypass");
2809 opt_subject = opt_str("subject");
2812 opt_issuer = opt_str("issuer");
2815 if ((opt_days = opt_nat()) < 0)
2819 opt_reqexts = opt_str("reqexts");
2822 opt_sans = opt_str("sans");
2824 case OPT_SAN_NODEFAULT:
2825 opt_san_nodefault = 1;
2828 opt_policies = opt_str("policies");
2830 case OPT_POLICY_OIDS:
2831 opt_policy_oids = opt_str("policy_oids");
2833 case OPT_POLICY_OIDS_CRITICAL:
2834 opt_policy_oids_critical = 1;
2837 if (!opt_int(opt_arg(), &opt_popo)
2838 || opt_popo < OSSL_CRMF_POPO_NONE
2839 || opt_popo > OSSL_CRMF_POPO_KEYENC) {
2840 CMP_err("invalid popo spec. Valid values are -1 .. 2");
2845 opt_csr = opt_arg();
2847 case OPT_OUT_TRUSTED:
2848 opt_out_trusted = opt_str("out_trusted");
2850 case OPT_IMPLICIT_CONFIRM:
2851 opt_implicit_confirm = 1;
2853 case OPT_DISABLE_CONFIRM:
2854 opt_disable_confirm = 1;
2857 opt_certout = opt_str("certout");
2860 opt_oldcert = opt_str("oldcert");
2863 if (!opt_int(opt_arg(), &opt_revreason)
2864 || opt_revreason < CRL_REASON_NONE
2865 || opt_revreason > CRL_REASON_AA_COMPROMISE
2866 || opt_revreason == 7) {
2867 CMP_err("invalid revreason. Valid values are -1 .. 6, 8 .. 10");
2872 opt_certform_s = opt_str("certform");
2875 opt_keyform_s = opt_str("keyform");
2878 opt_certsform_s = opt_str("certsform");
2881 opt_otherpass = opt_str("otherpass");
2883 #ifndef OPENSSL_NO_ENGINE
2885 opt_engine = opt_str("engine");
2888 case OPT_PROV_CASES:
2889 if (!opt_provider(o))
2897 opt_repeat = opt_nat();
2900 opt_reqin = opt_str("reqin");
2903 opt_reqout = opt_str("reqout");
2906 opt_rspin = opt_str("rspin");
2909 opt_rspout = opt_str("rspout");
2911 case OPT_USE_MOCK_SRV:
2912 opt_use_mock_srv = 1;
2915 opt_port = opt_str("port");
2918 if ((opt_max_msgs = opt_nat()) < 0)
2922 opt_srv_ref = opt_str("srv_ref");
2924 case OPT_SRV_SECRET:
2925 opt_srv_secret = opt_str("srv_secret");
2928 opt_srv_cert = opt_str("srv_cert");
2931 opt_srv_key = opt_str("srv_key");
2933 case OPT_SRV_KEYPASS:
2934 opt_srv_keypass = opt_str("srv_keypass");
2936 case OPT_SRV_TRUSTED:
2937 opt_srv_trusted = opt_str("srv_trusted");
2939 case OPT_SRV_UNTRUSTED:
2940 opt_srv_untrusted = opt_str("srv_untrusted");
2943 opt_rsp_cert = opt_str("rsp_cert");
2945 case OPT_RSP_EXTRACERTS:
2946 opt_rsp_extracerts = opt_str("rsp_extracerts");
2948 case OPT_RSP_CAPUBS:
2949 opt_rsp_capubs = opt_str("rsp_capubs");
2951 case OPT_POLL_COUNT:
2952 opt_poll_count = opt_nat();
2954 case OPT_CHECK_AFTER:
2955 opt_check_after = opt_nat();
2957 case OPT_GRANT_IMPLICITCONF:
2958 opt_grant_implicitconf = 1;
2961 opt_pkistatus = opt_nat();
2964 opt_failure = opt_nat();
2966 case OPT_FAILUREBITS:
2967 opt_failurebits = opt_nat();
2969 case OPT_STATUSSTRING:
2970 opt_statusstring = opt_str("statusstring");
2972 case OPT_SEND_ERROR:
2975 case OPT_SEND_UNPROTECTED:
2976 opt_send_unprotected = 1;
2978 case OPT_SEND_UNPROT_ERR:
2979 opt_send_unprot_err = 1;
2981 case OPT_ACCEPT_UNPROTECTED:
2982 opt_accept_unprotected = 1;
2984 case OPT_ACCEPT_UNPROT_ERR:
2985 opt_accept_unprot_err = 1;
2987 case OPT_ACCEPT_RAVERIFIED:
2988 opt_accept_raverified = 1;
2992 argc = opt_num_rest();
2995 CMP_err1("unknown parameter %s", argv[0]);
3001 CMP_err1("use -help for summary of '%s' options", prog);
3005 int cmp_main(int argc, char **argv)
3007 char *configfile = NULL;
3009 X509 *newcert = NULL;
3011 char mock_server[] = "mock server:1";
3012 int ret = 0; /* default: failure */
3015 opt_help(cmp_options);
3020 * handle OPT_CONFIG and OPT_SECTION upfront to take effect for other opts
3022 for (i = 1; i < argc - 1; i++) {
3023 if (*argv[i] == '-') {
3024 if (!strcmp(argv[i] + 1, cmp_options[OPT_CONFIG - OPT_HELP].name))
3025 opt_config = argv[i + 1];
3026 else if (!strcmp(argv[i] + 1,
3027 cmp_options[OPT_SECTION - OPT_HELP].name))
3028 opt_section = argv[i + 1];
3031 if (opt_section[0] == '\0') /* empty string */
3032 opt_section = DEFAULT_SECTION;
3034 vpm = X509_VERIFY_PARAM_new();
3036 CMP_err("out of memory");
3040 /* read default values for options from config file */
3041 configfile = opt_config != NULL ? opt_config : default_config_file;
3042 if (configfile && configfile[0] != '\0' /* non-empty string */
3043 && (configfile != default_config_file
3044 || access(configfile, F_OK) != -1)) {
3045 CMP_info1("using OpenSSL configuration file '%s'", configfile);
3046 conf = app_load_config(configfile);
3050 if (strcmp(opt_section, CMP_SECTION) == 0) { /* default */
3051 if (!NCONF_get_section(conf, opt_section))
3052 CMP_info2("no [%s] section found in config file '%s';"
3053 " will thus use just [default] and unnamed section if present",
3054 opt_section, configfile);
3056 const char *end = opt_section + strlen(opt_section);
3057 while ((end = prev_item(opt_section, end)) != NULL) {
3058 if (!NCONF_get_section(conf, opt_item)) {
3059 CMP_err2("no [%s] section found in config file '%s'",
3060 opt_item, configfile);
3069 (void)BIO_flush(bio_err); /* prevent interference with opt_help() */
3071 ret = get_opts(argc, argv);
3077 #ifndef OPENSSL_NO_ENGINE
3078 UI_METHOD *ui_fallback_method;
3079 # ifndef OPENSSL_NO_UI_CONSOLE
3080 ui_fallback_method = UI_OpenSSL();
3082 ui_fallback_method = (UI_METHOD *)UI_null();
3084 UI_method_set_reader(ui_fallback_method, NULL);
3088 if (opt_engine != NULL)
3089 e = setup_engine_flags(opt_engine, 0 /* not: ENGINE_METHOD_ALL */, 0);
3091 if (opt_port != NULL) {
3092 if (opt_use_mock_srv) {
3093 CMP_err("cannot use both -port and -use_mock_srv options");
3096 if (opt_server != NULL) {
3097 CMP_err("cannot use both -port and -server options");
3102 if ((cmp_ctx = OSSL_CMP_CTX_new()) == NULL) {
3103 CMP_err("out of memory");
3106 if (!OSSL_CMP_CTX_set_log_cb(cmp_ctx, print_to_bio_out)) {
3107 CMP_err1("cannot set up error reporting and logging for %s", prog);
3110 if ((opt_use_mock_srv || opt_port != NULL)) {
3111 OSSL_CMP_SRV_CTX *srv_ctx;
3113 if ((srv_ctx = setup_srv_ctx(e)) == NULL)
3115 OSSL_CMP_CTX_set_transfer_cb_arg(cmp_ctx, srv_ctx);
3116 if (!OSSL_CMP_CTX_set_log_cb(OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx),
3117 print_to_bio_out)) {
3118 CMP_err1("cannot set up error reporting and logging for %s", prog);
3124 if (opt_port != NULL) { /* act as very basic CMP HTTP server */
3125 #ifdef OPENSSL_NO_SOCK
3126 BIO_printf(bio_err, "Cannot act as server - sockets not supported\n");
3132 if ((acbio = http_server_init_bio(prog, opt_port)) == NULL)
3134 while (opt_max_msgs <= 0 || msgs < opt_max_msgs) {
3135 OSSL_CMP_MSG *req = NULL;
3136 OSSL_CMP_MSG *resp = NULL;
3138 ret = http_server_get_asn1_req(ASN1_ITEM_rptr(OSSL_CMP_MSG),
3139 (ASN1_VALUE **)&req, &cbio, acbio,
3144 break; /* fatal error */
3149 resp = OSSL_CMP_CTX_server_perform(cmp_ctx, req);
3150 OSSL_CMP_MSG_free(req);
3152 break; /* treated as fatal error */
3153 ret = http_server_send_asn1_resp(cbio, "application/pkixcmp",
3154 ASN1_ITEM_rptr(OSSL_CMP_MSG),
3155 (const ASN1_VALUE *)resp);
3156 OSSL_CMP_MSG_free(resp);
3158 break; /* treated as fatal error */
3164 BIO_free_all(acbio);
3168 /* else act as CMP client */
3170 if (opt_use_mock_srv) {
3171 if (opt_server != NULL) {
3172 CMP_err("cannot use both -use_mock_srv and -server options");
3175 if (opt_proxy != NULL) {
3176 CMP_err("cannot use both -use_mock_srv and -proxy options");
3179 opt_server = mock_server;
3182 if (opt_server == NULL) {
3183 CMP_err("missing -server option");
3188 if (!setup_client_ctx(cmp_ctx, e)) {
3189 CMP_err("cannot set up CMP context");
3192 for (i = 0; i < opt_repeat; i++) {
3193 /* everything is ready, now connect and perform the command! */
3196 newcert = OSSL_CMP_exec_IR_ses(cmp_ctx);
3197 if (newcert == NULL)
3201 newcert = OSSL_CMP_exec_KUR_ses(cmp_ctx);
3202 if (newcert == NULL)
3206 newcert = OSSL_CMP_exec_CR_ses(cmp_ctx);
3207 if (newcert == NULL)
3211 newcert = OSSL_CMP_exec_P10CR_ses(cmp_ctx);
3212 if (newcert == NULL)
3216 if (OSSL_CMP_exec_RR_ses(cmp_ctx) == NULL)
3221 STACK_OF(OSSL_CMP_ITAV) *itavs;
3223 if (opt_infotype != NID_undef) {
3224 OSSL_CMP_ITAV *itav =
3225 OSSL_CMP_ITAV_create(OBJ_nid2obj(opt_infotype), NULL);
3228 OSSL_CMP_CTX_push0_genm_ITAV(cmp_ctx, itav);
3231 if ((itavs = OSSL_CMP_exec_GENM_ses(cmp_ctx)) == NULL)
3234 sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free);
3242 /* print PKIStatusInfo (this is in case there has been no error) */
3243 int status = OSSL_CMP_CTX_get_status(cmp_ctx);
3244 char *buf = app_malloc(OSSL_CMP_PKISI_BUFLEN, "PKIStatusInfo buf");
3245 const char *string =
3246 OSSL_CMP_CTX_snprint_PKIStatus(cmp_ctx, buf,
3247 OSSL_CMP_PKISI_BUFLEN);
3250 status == OSSL_CMP_PKISTATUS_accepted ? "info" :
3251 status == OSSL_CMP_PKISTATUS_rejection ? "server error" :
3252 status == OSSL_CMP_PKISTATUS_waiting ? "internal error"
3254 "received from %s %s %s", opt_server,
3255 string != NULL ? string : "<unknown PKIStatus>", "");
3259 if (opt_cacertsout != NULL) {
3260 STACK_OF(X509) *certs = OSSL_CMP_CTX_get1_caPubs(cmp_ctx);
3262 if (sk_X509_num(certs) > 0
3263 && save_certs(cmp_ctx, certs, opt_cacertsout, "CA") < 0) {
3264 sk_X509_pop_free(certs, X509_free);
3267 sk_X509_pop_free(certs, X509_free);
3270 if (opt_extracertsout != NULL) {
3271 STACK_OF(X509) *certs = OSSL_CMP_CTX_get1_extraCertsIn(cmp_ctx);
3272 if (sk_X509_num(certs) > 0
3273 && save_certs(cmp_ctx, certs, opt_extracertsout,
3275 sk_X509_pop_free(certs, X509_free);
3278 sk_X509_pop_free(certs, X509_free);
3281 if (opt_certout != NULL && newcert != NULL) {
3282 STACK_OF(X509) *certs = sk_X509_new_null();
3284 if (certs == NULL || !sk_X509_push(certs, newcert)
3285 || save_certs(cmp_ctx, certs, opt_certout,
3287 sk_X509_free(certs);
3290 sk_X509_free(certs);
3292 if (!OSSL_CMP_CTX_reinit(cmp_ctx))
3298 /* in case we ended up here on error without proper cleaning */
3299 cleanse(opt_keypass);
3300 cleanse(opt_newkeypass);
3301 cleanse(opt_otherpass);
3302 cleanse(opt_tls_keypass);
3303 cleanse(opt_secret);
3304 cleanse(opt_srv_keypass);
3305 cleanse(opt_srv_secret);
3308 OSSL_CMP_CTX_print_errors(cmp_ctx);
3310 ossl_cmp_mock_srv_free(OSSL_CMP_CTX_get_transfer_cb_arg(cmp_ctx));
3312 APP_HTTP_TLS_INFO *http_tls_info =
3313 OSSL_CMP_CTX_get_http_cb_arg(cmp_ctx);
3315 if (http_tls_info != NULL) {
3316 SSL_CTX_free(http_tls_info->ssl_ctx);
3317 OPENSSL_free(http_tls_info);
3320 X509_STORE_free(OSSL_CMP_CTX_get_certConf_cb_arg(cmp_ctx));
3321 OSSL_CMP_CTX_free(cmp_ctx);
3322 X509_VERIFY_PARAM_free(vpm);
3325 NCONF_free(conf); /* must not do as long as opt_... variables are used */
3326 OSSL_CMP_log_close();
3328 return ret == 0 ? EXIT_FAILURE : EXIT_SUCCESS;