CMP app and app_http_tls_cb(): pick the right TLS hostname (also without port)
[openssl.git] / apps / cmp.c
1 /*
2  * Copyright 2007-2022 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright Nokia 2007-2019
4  * Copyright Siemens AG 2015-2019
5  *
6  * Licensed under the Apache License 2.0 (the "License").  You may not use
7  * this file except in compliance with the License.  You can obtain a copy
8  * in the file LICENSE in the source distribution or at
9  * https://www.openssl.org/source/license.html
10  */
11
12 /* This app is disabled when OPENSSL_NO_CMP is defined. */
13
14 #include <string.h>
15 #include <ctype.h>
16
17 #include "apps.h"
18 #include "http_server.h"
19 #include "s_apps.h"
20 #include "progs.h"
21
22 #include "cmp_mock_srv.h"
23
24 /* tweaks needed due to missing unistd.h on Windows */
25 #if defined(_WIN32) && !defined(__BORLANDC__)
26 # define access _access
27 #endif
28 #ifndef F_OK
29 # define F_OK 0
30 #endif
31
32 #include <openssl/ui.h>
33 #include <openssl/pkcs12.h>
34 #include <openssl/ssl.h>
35
36 /* explicit #includes not strictly needed since implied by the above: */
37 #include <stdlib.h>
38 #include <openssl/cmp.h>
39 #include <openssl/cmp_util.h>
40 #include <openssl/crmf.h>
41 #include <openssl/crypto.h>
42 #include <openssl/err.h>
43 #include <openssl/store.h>
44 #include <openssl/objects.h>
45 #include <openssl/x509.h>
46
47 static char *prog;
48 static char *opt_config = NULL;
49 #define CMP_SECTION "cmp"
50 #define SECTION_NAME_MAX 40 /* max length of section name */
51 #define DEFAULT_SECTION "default"
52 static char *opt_section = CMP_SECTION;
53 static int opt_verbosity = OSSL_CMP_LOG_INFO;
54
55 static int read_config(void);
56
57 static CONF *conf = NULL; /* OpenSSL config file context structure */
58 static OSSL_CMP_CTX *cmp_ctx = NULL; /* the client-side CMP context */
59
60 /* the type of cmp command we want to send */
61 typedef enum {
62     CMP_IR,
63     CMP_KUR,
64     CMP_CR,
65     CMP_P10CR,
66     CMP_RR,
67     CMP_GENM
68 } cmp_cmd_t;
69
70 /* message transfer */
71 #ifndef OPENSSL_NO_SOCK
72 static char *opt_server = NULL;
73 static char *opt_proxy = NULL;
74 static char *opt_no_proxy = NULL;
75 #endif
76 static char *opt_recipient = NULL;
77 static char *opt_path = NULL;
78 static int opt_keep_alive = 1;
79 static int opt_msg_timeout = -1;
80 static int opt_total_timeout = -1;
81
82 /* server authentication */
83 static char *opt_trusted = NULL;
84 static char *opt_untrusted = NULL;
85 static char *opt_srvcert = NULL;
86 static char *opt_expect_sender = NULL;
87 static int opt_ignore_keyusage = 0;
88 static int opt_unprotected_errors = 0;
89 static char *opt_srvcertout = NULL;
90 static char *opt_extracertsout = NULL;
91 static char *opt_cacertsout = NULL;
92
93 /* client authentication */
94 static char *opt_ref = NULL;
95 static char *opt_secret = NULL;
96 static char *opt_cert = NULL;
97 static char *opt_own_trusted = NULL;
98 static char *opt_key = NULL;
99 static char *opt_keypass = NULL;
100 static char *opt_digest = NULL;
101 static char *opt_mac = NULL;
102 static char *opt_extracerts = NULL;
103 static int opt_unprotected_requests = 0;
104
105 /* generic message */
106 static char *opt_cmd_s = NULL;
107 static int opt_cmd = -1;
108 static char *opt_geninfo = NULL;
109 static char *opt_infotype_s = NULL;
110 static int opt_infotype = NID_undef;
111
112 /* certificate enrollment */
113 static char *opt_newkey = NULL;
114 static char *opt_newkeypass = NULL;
115 static char *opt_subject = NULL;
116 static char *opt_issuer = NULL;
117 static int opt_days = 0;
118 static char *opt_reqexts = NULL;
119 static char *opt_sans = NULL;
120 static int opt_san_nodefault = 0;
121 static char *opt_policies = NULL;
122 static char *opt_policy_oids = NULL;
123 static int opt_policy_oids_critical = 0;
124 static int opt_popo = OSSL_CRMF_POPO_NONE - 1;
125 static char *opt_csr = NULL;
126 static char *opt_out_trusted = NULL;
127 static int opt_implicit_confirm = 0;
128 static int opt_disable_confirm = 0;
129 static char *opt_certout = NULL;
130 static char *opt_chainout = NULL;
131
132 /* certificate enrollment and revocation */
133 static char *opt_oldcert = NULL;
134 static int opt_revreason = CRL_REASON_NONE;
135
136 /* credentials format */
137 static char *opt_certform_s = "PEM";
138 static int opt_certform = FORMAT_PEM;
139 static char *opt_keyform_s = NULL;
140 static int opt_keyform = FORMAT_UNDEF;
141 static char *opt_otherpass = NULL;
142 static char *opt_engine = NULL;
143
144 #ifndef OPENSSL_NO_SOCK
145 /* TLS connection */
146 static int opt_tls_used = 0;
147 static char *opt_tls_cert = NULL;
148 static char *opt_tls_key = NULL;
149 static char *opt_tls_keypass = NULL;
150 static char *opt_tls_extra = NULL;
151 static char *opt_tls_trusted = NULL;
152 static char *opt_tls_host = NULL;
153 #endif
154
155 /* client-side debugging */
156 static int opt_batch = 0;
157 static int opt_repeat = 1;
158 static char *opt_reqin = NULL;
159 static int opt_reqin_new_tid = 0;
160 static char *opt_reqout = NULL;
161 static char *opt_rspin = NULL;
162 static int rspin_in_use = 0;
163 static char *opt_rspout = NULL;
164 static int opt_use_mock_srv = 0;
165
166 /* mock server */
167 #ifndef OPENSSL_NO_SOCK
168 static char *opt_port = NULL;
169 static int opt_max_msgs = 0;
170 #endif
171 static char *opt_srv_ref = NULL;
172 static char *opt_srv_secret = NULL;
173 static char *opt_srv_cert = NULL;
174 static char *opt_srv_key = NULL;
175 static char *opt_srv_keypass = NULL;
176
177 static char *opt_srv_trusted = NULL;
178 static char *opt_srv_untrusted = NULL;
179 static char *opt_ref_cert = NULL;
180 static char *opt_rsp_cert = NULL;
181 static char *opt_rsp_extracerts = NULL;
182 static char *opt_rsp_capubs = NULL;
183 static int opt_poll_count = 0;
184 static int opt_check_after = 1;
185 static int opt_grant_implicitconf = 0;
186
187 static int opt_pkistatus = OSSL_CMP_PKISTATUS_accepted;
188 static int opt_failure = INT_MIN;
189 static int opt_failurebits = 0;
190 static char *opt_statusstring = NULL;
191 static int opt_send_error = 0;
192 static int opt_send_unprotected = 0;
193 static int opt_send_unprot_err = 0;
194 static int opt_accept_unprotected = 0;
195 static int opt_accept_unprot_err = 0;
196 static int opt_accept_raverified = 0;
197
198 static X509_VERIFY_PARAM *vpm = NULL;
199
200 typedef enum OPTION_choice {
201     OPT_COMMON,
202     OPT_CONFIG, OPT_SECTION, OPT_VERBOSITY,
203
204     OPT_CMD, OPT_INFOTYPE, OPT_GENINFO,
205
206     OPT_NEWKEY, OPT_NEWKEYPASS, OPT_SUBJECT, OPT_ISSUER,
207     OPT_DAYS, OPT_REQEXTS,
208     OPT_SANS, OPT_SAN_NODEFAULT,
209     OPT_POLICIES, OPT_POLICY_OIDS, OPT_POLICY_OIDS_CRITICAL,
210     OPT_POPO, OPT_CSR,
211     OPT_OUT_TRUSTED, OPT_IMPLICIT_CONFIRM, OPT_DISABLE_CONFIRM,
212     OPT_CERTOUT, OPT_CHAINOUT,
213
214     OPT_OLDCERT, OPT_REVREASON,
215
216 #ifndef OPENSSL_NO_SOCK
217     OPT_SERVER, OPT_PROXY, OPT_NO_PROXY,
218 #endif
219     OPT_RECIPIENT, OPT_PATH,
220     OPT_KEEP_ALIVE, OPT_MSG_TIMEOUT, OPT_TOTAL_TIMEOUT,
221
222     OPT_TRUSTED, OPT_UNTRUSTED, OPT_SRVCERT,
223     OPT_EXPECT_SENDER,
224     OPT_IGNORE_KEYUSAGE, OPT_UNPROTECTED_ERRORS,
225     OPT_SRVCERTOUT, OPT_EXTRACERTSOUT, OPT_CACERTSOUT,
226
227     OPT_REF, OPT_SECRET, OPT_CERT, OPT_OWN_TRUSTED, OPT_KEY, OPT_KEYPASS,
228     OPT_DIGEST, OPT_MAC, OPT_EXTRACERTS,
229     OPT_UNPROTECTED_REQUESTS,
230
231     OPT_CERTFORM, OPT_KEYFORM,
232     OPT_OTHERPASS,
233 #ifndef OPENSSL_NO_ENGINE
234     OPT_ENGINE,
235 #endif
236     OPT_PROV_ENUM,
237     OPT_R_ENUM,
238
239 #ifndef OPENSSL_NO_SOCK
240     OPT_TLS_USED, OPT_TLS_CERT, OPT_TLS_KEY,
241     OPT_TLS_KEYPASS,
242     OPT_TLS_EXTRA, OPT_TLS_TRUSTED, OPT_TLS_HOST,
243 #endif
244
245     OPT_BATCH, OPT_REPEAT,
246     OPT_REQIN, OPT_REQIN_NEW_TID, OPT_REQOUT, OPT_RSPIN, OPT_RSPOUT,
247     OPT_USE_MOCK_SRV,
248
249 #ifndef OPENSSL_NO_SOCK
250     OPT_PORT, OPT_MAX_MSGS,
251 #endif
252     OPT_SRV_REF, OPT_SRV_SECRET,
253     OPT_SRV_CERT, OPT_SRV_KEY, OPT_SRV_KEYPASS,
254     OPT_SRV_TRUSTED, OPT_SRV_UNTRUSTED,
255     OPT_REF_CERT, OPT_RSP_CERT, OPT_RSP_EXTRACERTS, OPT_RSP_CAPUBS,
256     OPT_POLL_COUNT, OPT_CHECK_AFTER,
257     OPT_GRANT_IMPLICITCONF,
258     OPT_PKISTATUS, OPT_FAILURE,
259     OPT_FAILUREBITS, OPT_STATUSSTRING,
260     OPT_SEND_ERROR, OPT_SEND_UNPROTECTED,
261     OPT_SEND_UNPROT_ERR, OPT_ACCEPT_UNPROTECTED,
262     OPT_ACCEPT_UNPROT_ERR, OPT_ACCEPT_RAVERIFIED,
263
264     OPT_V_ENUM
265 } OPTION_CHOICE;
266
267 const OPTIONS cmp_options[] = {
268     /* entries must be in the same order as enumerated above!! */
269     {"help", OPT_HELP, '-', "Display this summary"},
270     {"config", OPT_CONFIG, 's',
271      "Configuration file to use. \"\" = none. Default from env variable OPENSSL_CONF"},
272     {"section", OPT_SECTION, 's',
273      "Section(s) in config file to get options from. \"\" = 'default'. Default 'cmp'"},
274     {"verbosity", OPT_VERBOSITY, 'N',
275      "Log level; 3=ERR, 4=WARN, 6=INFO, 7=DEBUG, 8=TRACE. Default 6 = INFO"},
276
277     OPT_SECTION("Generic message"),
278     {"cmd", OPT_CMD, 's', "CMP request to send: ir/cr/kur/p10cr/rr/genm"},
279     {"infotype", OPT_INFOTYPE, 's',
280      "InfoType name for requesting specific info in genm, e.g. 'signKeyPairTypes'"},
281     {"geninfo", OPT_GENINFO, 's',
282      "generalInfo integer values to place in request PKIHeader with given OID"},
283     {OPT_MORE_STR, 0, 0,
284      "specified in the form <OID>:int:<n>, e.g. \"1.2.3.4:int:56789\""},
285
286     OPT_SECTION("Certificate enrollment"),
287     {"newkey", OPT_NEWKEY, 's',
288      "Private or public key for the requested cert. Default: CSR key or client key"},
289     {"newkeypass", OPT_NEWKEYPASS, 's', "New private key pass phrase source"},
290     {"subject", OPT_SUBJECT, 's',
291      "Distinguished Name (DN) of subject to use in the requested cert template"},
292     {OPT_MORE_STR, 0, 0,
293      "For kur, default is subject of -csr arg or reference cert (see -oldcert)"},
294     {OPT_MORE_STR, 0, 0,
295      "this default is used for ir and cr only if no Subject Alt Names are set"},
296     {"issuer", OPT_ISSUER, 's',
297      "DN of the issuer to place in the requested certificate template"},
298     {OPT_MORE_STR, 0, 0,
299      "also used as recipient if neither -recipient nor -srvcert are given"},
300     {"days", OPT_DAYS, 'N',
301      "Requested validity time of the new certificate in number of days"},
302     {"reqexts", OPT_REQEXTS, 's',
303      "Name of config file section defining certificate request extensions."},
304     {OPT_MORE_STR, 0, 0,
305      "Augments or replaces any extensions contained CSR given with -csr"},
306     {"sans", OPT_SANS, 's',
307      "Subject Alt Names (IPADDR/DNS/URI) to add as (critical) cert req extension"},
308     {"san_nodefault", OPT_SAN_NODEFAULT, '-',
309      "Do not take default SANs from reference certificate (see -oldcert)"},
310     {"policies", OPT_POLICIES, 's',
311      "Name of config file section defining policies certificate request extension"},
312     {"policy_oids", OPT_POLICY_OIDS, 's',
313      "Policy OID(s) to add as policies certificate request extension"},
314     {"policy_oids_critical", OPT_POLICY_OIDS_CRITICAL, '-',
315      "Flag the policy OID(s) given with -policy_oids as critical"},
316     {"popo", OPT_POPO, 'n',
317      "Proof-of-Possession (POPO) method to use for ir/cr/kur where"},
318     {OPT_MORE_STR, 0, 0,
319      "-1 = NONE, 0 = RAVERIFIED, 1 = SIGNATURE (default), 2 = KEYENC"},
320     {"csr", OPT_CSR, 's',
321      "PKCS#10 CSR file in PEM or DER format to convert or to use in p10cr"},
322     {"out_trusted", OPT_OUT_TRUSTED, 's',
323      "Certificates to trust when verifying newly enrolled certificates"},
324     {"implicit_confirm", OPT_IMPLICIT_CONFIRM, '-',
325      "Request implicit confirmation of newly enrolled certificates"},
326     {"disable_confirm", OPT_DISABLE_CONFIRM, '-',
327      "Do not confirm newly enrolled certificate w/o requesting implicit"},
328     {OPT_MORE_STR, 0, 0,
329      "confirmation. WARNING: This leads to behavior violating RFC 4210"},
330     {"certout", OPT_CERTOUT, 's',
331      "File to save newly enrolled certificate"},
332     {"chainout", OPT_CHAINOUT, 's',
333      "File to save the chain of newly enrolled certificate"},
334
335     OPT_SECTION("Certificate enrollment and revocation"),
336
337     {"oldcert", OPT_OLDCERT, 's',
338      "Certificate to be updated (defaulting to -cert) or to be revoked in rr;"},
339     {OPT_MORE_STR, 0, 0,
340      "also used as reference (defaulting to -cert) for subject DN and SANs."},
341     {OPT_MORE_STR, 0, 0,
342      "Issuer is used as recipient unless -recipient, -srvcert, or -issuer given"},
343     {"revreason", OPT_REVREASON, 'n',
344      "Reason code to include in revocation request (rr); possible values:"},
345     {OPT_MORE_STR, 0, 0,
346      "0..6, 8..10 (see RFC5280, 5.3.1) or -1. Default -1 = none included"},
347
348     OPT_SECTION("Message transfer"),
349 #ifdef OPENSSL_NO_SOCK
350     {OPT_MORE_STR, 0, 0,
351      "NOTE: -server, -proxy, and -no_proxy not supported due to no-sock build"},
352 #else
353     {"server", OPT_SERVER, 's',
354      "[http[s]://]address[:port][/path] of CMP server. Default port 80 or 443."},
355     {OPT_MORE_STR, 0, 0,
356      "address may be a DNS name or an IP address; path can be overridden by -path"},
357     {"proxy", OPT_PROXY, 's',
358      "[http[s]://]address[:port][/path] of HTTP(S) proxy to use; path is ignored"},
359     {"no_proxy", OPT_NO_PROXY, 's',
360      "List of addresses of servers not to use HTTP(S) proxy for"},
361     {OPT_MORE_STR, 0, 0,
362      "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"},
363 #endif
364     {"recipient", OPT_RECIPIENT, 's',
365      "DN of CA. Default: subject of -srvcert, -issuer, issuer of -oldcert or -cert"},
366     {"path", OPT_PATH, 's',
367      "HTTP path (aka CMP alias) at the CMP server. Default from -server, else \"/\""},
368     {"keep_alive", OPT_KEEP_ALIVE, 'N',
369      "Persistent HTTP connections. 0: no, 1 (the default): request, 2: require"},
370     {"msg_timeout", OPT_MSG_TIMEOUT, 'N',
371      "Number of seconds allowed per CMP message round trip, or 0 for infinite"},
372     {"total_timeout", OPT_TOTAL_TIMEOUT, 'N',
373      "Overall time an enrollment incl. polling may take. Default 0 = infinite"},
374
375     OPT_SECTION("Server authentication"),
376     {"trusted", OPT_TRUSTED, 's',
377      "Certificates to use as trust anchors when verifying signed CMP responses"},
378     {OPT_MORE_STR, 0, 0, "unless -srvcert is given"},
379     {"untrusted", OPT_UNTRUSTED, 's',
380      "Intermediate CA certs for chain construction for CMP/TLS/enrolled certs"},
381     {"srvcert", OPT_SRVCERT, 's',
382      "Server cert to pin and trust directly when verifying signed CMP responses"},
383     {"expect_sender", OPT_EXPECT_SENDER, 's',
384      "DN of expected sender of responses. Defaults to subject of -srvcert, if any"},
385     {"ignore_keyusage", OPT_IGNORE_KEYUSAGE, '-',
386      "Ignore CMP signer cert key usage, else 'digitalSignature' must be allowed"},
387     {"unprotected_errors", OPT_UNPROTECTED_ERRORS, '-',
388      "Accept missing or invalid protection of regular error messages and negative"},
389     {OPT_MORE_STR, 0, 0,
390      "certificate responses (ip/cp/kup), revocation responses (rp), and PKIConf"},
391     {OPT_MORE_STR, 0, 0,
392      "WARNING: This setting leads to behavior allowing violation of RFC 4210"},
393     { "srvcertout", OPT_SRVCERTOUT, 's',
394       "File to save the server cert used and validated for CMP response protection"},
395     {"extracertsout", OPT_EXTRACERTSOUT, 's',
396      "File to save extra certificates received in the extraCerts field"},
397     {"cacertsout", OPT_CACERTSOUT, 's',
398      "File to save CA certificates received in the caPubs field of 'ip' messages"},
399
400     OPT_SECTION("Client authentication"),
401     {"ref", OPT_REF, 's',
402      "Reference value to use as senderKID in case no -cert is given"},
403     {"secret", OPT_SECRET, 's',
404      "Prefer PBM (over signatures) for protecting msgs with given password source"},
405     {"cert", OPT_CERT, 's',
406      "Client's CMP signer certificate; its public key must match the -key argument"},
407     {OPT_MORE_STR, 0, 0,
408      "This also used as default reference for subject DN and SANs."},
409     {OPT_MORE_STR, 0, 0,
410      "Any further certs included are appended to the untrusted certs"},
411     {"own_trusted", OPT_OWN_TRUSTED, 's',
412      "Optional certs to verify chain building for own CMP signer cert"},
413     {"key", OPT_KEY, 's', "CMP signer private key, not used when -secret given"},
414     {"keypass", OPT_KEYPASS, 's',
415      "Client private key (and cert and old cert) pass phrase source"},
416     {"digest", OPT_DIGEST, 's',
417      "Digest to use in message protection and POPO signatures. Default \"sha256\""},
418     {"mac", OPT_MAC, 's',
419      "MAC algorithm to use in PBM-based message protection. Default \"hmac-sha1\""},
420     {"extracerts", OPT_EXTRACERTS, 's',
421      "Certificates to append in extraCerts field of outgoing messages."},
422     {OPT_MORE_STR, 0, 0,
423      "This can be used as the default CMP signer cert chain to include"},
424     {"unprotected_requests", OPT_UNPROTECTED_REQUESTS, '-',
425      "Send request messages without CMP-level protection"},
426
427     OPT_SECTION("Credentials format"),
428     {"certform", OPT_CERTFORM, 's',
429      "Format (PEM or DER) to use when saving a certificate to a file. Default PEM"},
430     {"keyform", OPT_KEYFORM, 's',
431      "Format of the key input (ENGINE, other values ignored)"},
432     {"otherpass", OPT_OTHERPASS, 's',
433      "Pass phrase source potentially needed for loading certificates of others"},
434 #ifndef OPENSSL_NO_ENGINE
435     {"engine", OPT_ENGINE, 's',
436      "Use crypto engine with given identifier, possibly a hardware device."},
437     {OPT_MORE_STR, 0, 0,
438      "Engines may also be defined in OpenSSL config file engine section."},
439 #endif
440     OPT_PROV_OPTIONS,
441     OPT_R_OPTIONS,
442
443     OPT_SECTION("TLS connection"),
444 #ifdef OPENSSL_NO_SOCK
445     {OPT_MORE_STR, 0, 0,
446      "NOTE: -tls_used and all other TLS options not supported due to no-sock build"},
447 #else
448     {"tls_used", OPT_TLS_USED, '-',
449      "Enable using TLS (also when other TLS options are not set)"},
450     {"tls_cert", OPT_TLS_CERT, 's',
451      "Client's TLS certificate. May include chain to be provided to TLS server"},
452     {"tls_key", OPT_TLS_KEY, 's',
453      "Private key for the client's TLS certificate"},
454     {"tls_keypass", OPT_TLS_KEYPASS, 's',
455      "Pass phrase source for the client's private TLS key (and TLS cert)"},
456     {"tls_extra", OPT_TLS_EXTRA, 's',
457      "Extra certificates to provide to TLS server during TLS handshake"},
458     {"tls_trusted", OPT_TLS_TRUSTED, 's',
459      "Trusted certificates to use for verifying the TLS server certificate;"},
460     {OPT_MORE_STR, 0, 0, "this implies hostname validation"},
461     {"tls_host", OPT_TLS_HOST, 's',
462      "Address to be checked (rather than -server) during TLS hostname validation"},
463 #endif
464
465     OPT_SECTION("Client-side debugging"),
466     {"batch", OPT_BATCH, '-',
467      "Do not interactively prompt for input when a password is required etc."},
468     {"repeat", OPT_REPEAT, 'p',
469      "Invoke the transaction the given positive number of times. Default 1"},
470     {"reqin", OPT_REQIN, 's',
471      "Take sequence of CMP requests to send to server from file(s)"},
472     {"reqin_new_tid", OPT_REQIN_NEW_TID, '-',
473      "Use fresh transactionID for CMP requests read from -reqin"},
474     {"reqout", OPT_REQOUT, 's',
475      "Save sequence of CMP requests created by the client to file(s)"},
476     {"rspin", OPT_RSPIN, 's',
477      "Process sequence of CMP responses provided in file(s), skipping server"},
478     {"rspout", OPT_RSPOUT, 's',
479      "Save sequence of actually used CMP responses to file(s)"},
480
481     {"use_mock_srv", OPT_USE_MOCK_SRV, '-',
482      "Use internal mock server at API level, bypassing socket-based HTTP"},
483
484     OPT_SECTION("Mock server"),
485 #ifdef OPENSSL_NO_SOCK
486     {OPT_MORE_STR, 0, 0,
487      "NOTE: -port and -max_msgs not supported due to no-sock build"},
488 #else
489     {"port", OPT_PORT, 's',
490      "Act as HTTP-based mock server listening on given port"},
491     {"max_msgs", OPT_MAX_MSGS, 'N',
492      "max number of messages handled by HTTP mock server. Default: 0 = unlimited"},
493 #endif
494
495     {"srv_ref", OPT_SRV_REF, 's',
496      "Reference value to use as senderKID of server in case no -srv_cert is given"},
497     {"srv_secret", OPT_SRV_SECRET, 's',
498      "Password source for server authentication with a pre-shared key (secret)"},
499     {"srv_cert", OPT_SRV_CERT, 's', "Certificate of the server"},
500     {"srv_key", OPT_SRV_KEY, 's',
501      "Private key used by the server for signing messages"},
502     {"srv_keypass", OPT_SRV_KEYPASS, 's',
503      "Server private key (and cert) pass phrase source"},
504
505     {"srv_trusted", OPT_SRV_TRUSTED, 's',
506      "Trusted certificates for client authentication"},
507     {"srv_untrusted", OPT_SRV_UNTRUSTED, 's',
508      "Intermediate certs that may be useful for verifying CMP protection"},
509     {"ref_cert", OPT_RSP_CERT, 's',
510      "Certificate to be expected for rr and any oldCertID in kur messages"},
511     {"rsp_cert", OPT_RSP_CERT, 's',
512      "Certificate to be returned as mock enrollment result"},
513     {"rsp_extracerts", OPT_RSP_EXTRACERTS, 's',
514      "Extra certificates to be included in mock certification responses"},
515     {"rsp_capubs", OPT_RSP_CAPUBS, 's',
516      "CA certificates to be included in mock ip response"},
517     {"poll_count", OPT_POLL_COUNT, 'N',
518      "Number of times the client must poll before receiving a certificate"},
519     {"check_after", OPT_CHECK_AFTER, 'N',
520      "The check_after value (time to wait) to include in poll response"},
521     {"grant_implicitconf", OPT_GRANT_IMPLICITCONF, '-',
522      "Grant implicit confirmation of newly enrolled certificate"},
523
524     {"pkistatus", OPT_PKISTATUS, 'N',
525      "PKIStatus to be included in server response. Possible values: 0..6"},
526     {"failure", OPT_FAILURE, 'N',
527      "A single failure info bit number to include in server response, 0..26"},
528     {"failurebits", OPT_FAILUREBITS, 'N',
529      "Number representing failure bits to include in server response, 0..2^27 - 1"},
530     {"statusstring", OPT_STATUSSTRING, 's',
531      "Status string to be included in server response"},
532     {"send_error", OPT_SEND_ERROR, '-',
533      "Force server to reply with error message"},
534     {"send_unprotected", OPT_SEND_UNPROTECTED, '-',
535      "Send response messages without CMP-level protection"},
536     {"send_unprot_err", OPT_SEND_UNPROT_ERR, '-',
537      "In case of negative responses, server shall send unprotected error messages,"},
538     {OPT_MORE_STR, 0, 0,
539      "certificate responses (ip/cp/kup), and revocation responses (rp)."},
540     {OPT_MORE_STR, 0, 0,
541      "WARNING: This setting leads to behavior violating RFC 4210"},
542     {"accept_unprotected", OPT_ACCEPT_UNPROTECTED, '-',
543      "Accept missing or invalid protection of requests"},
544     {"accept_unprot_err", OPT_ACCEPT_UNPROT_ERR, '-',
545      "Accept unprotected error messages from client"},
546     {"accept_raverified", OPT_ACCEPT_RAVERIFIED, '-',
547      "Accept RAVERIFIED as proof-of-possession (POPO)"},
548
549     OPT_V_OPTIONS,
550     {NULL}
551 };
552
553 typedef union {
554     char **txt;
555     int *num;
556     long *num_long;
557 } varref;
558 static varref cmp_vars[] = { /* must be in same order as enumerated above! */
559     {&opt_config}, {&opt_section}, {(char **)&opt_verbosity},
560
561     {&opt_cmd_s}, {&opt_infotype_s}, {&opt_geninfo},
562
563     {&opt_newkey}, {&opt_newkeypass}, {&opt_subject}, {&opt_issuer},
564     {(char **)&opt_days}, {&opt_reqexts},
565     {&opt_sans}, {(char **)&opt_san_nodefault},
566     {&opt_policies}, {&opt_policy_oids}, {(char **)&opt_policy_oids_critical},
567     {(char **)&opt_popo}, {&opt_csr},
568     {&opt_out_trusted},
569     {(char **)&opt_implicit_confirm}, {(char **)&opt_disable_confirm},
570     {&opt_certout}, {&opt_chainout},
571
572     {&opt_oldcert}, {(char **)&opt_revreason},
573
574 #ifndef OPENSSL_NO_SOCK
575     {&opt_server}, {&opt_proxy}, {&opt_no_proxy},
576 #endif
577     {&opt_recipient}, {&opt_path}, {(char **)&opt_keep_alive},
578     {(char **)&opt_msg_timeout}, {(char **)&opt_total_timeout},
579
580     {&opt_trusted}, {&opt_untrusted}, {&opt_srvcert},
581     {&opt_expect_sender},
582     {(char **)&opt_ignore_keyusage}, {(char **)&opt_unprotected_errors},
583     {&opt_srvcertout}, {&opt_extracertsout}, {&opt_cacertsout},
584
585     {&opt_ref}, {&opt_secret},
586     {&opt_cert}, {&opt_own_trusted}, {&opt_key}, {&opt_keypass},
587     {&opt_digest}, {&opt_mac}, {&opt_extracerts},
588     {(char **)&opt_unprotected_requests},
589
590     {&opt_certform_s}, {&opt_keyform_s},
591     {&opt_otherpass},
592 #ifndef OPENSSL_NO_ENGINE
593     {&opt_engine},
594 #endif
595
596 #ifndef OPENSSL_NO_SOCK
597     {(char **)&opt_tls_used}, {&opt_tls_cert}, {&opt_tls_key},
598     {&opt_tls_keypass},
599     {&opt_tls_extra}, {&opt_tls_trusted}, {&opt_tls_host},
600 #endif
601
602     {(char **)&opt_batch}, {(char **)&opt_repeat},
603     {&opt_reqin}, {(char **)&opt_reqin_new_tid},
604     {&opt_reqout}, {&opt_rspin}, {&opt_rspout},
605
606     {(char **)&opt_use_mock_srv},
607 #ifndef OPENSSL_NO_SOCK
608     {&opt_port}, {(char **)&opt_max_msgs},
609 #endif
610     {&opt_srv_ref}, {&opt_srv_secret},
611     {&opt_srv_cert}, {&opt_srv_key}, {&opt_srv_keypass},
612     {&opt_srv_trusted}, {&opt_srv_untrusted},
613     {&opt_ref_cert}, {&opt_rsp_cert}, {&opt_rsp_extracerts}, {&opt_rsp_capubs},
614     {(char **)&opt_poll_count}, {(char **)&opt_check_after},
615     {(char **)&opt_grant_implicitconf},
616     {(char **)&opt_pkistatus}, {(char **)&opt_failure},
617     {(char **)&opt_failurebits}, {&opt_statusstring},
618     {(char **)&opt_send_error}, {(char **)&opt_send_unprotected},
619     {(char **)&opt_send_unprot_err}, {(char **)&opt_accept_unprotected},
620     {(char **)&opt_accept_unprot_err}, {(char **)&opt_accept_raverified},
621
622     {NULL}
623 };
624
625 #define FUNC (strcmp(OPENSSL_FUNC, "(unknown function)") == 0   \
626               ? "CMP" : OPENSSL_FUNC)
627 #define CMP_print(bio, level, prefix, msg, a1, a2, a3) \
628     ((void)(level > opt_verbosity ? 0 : \
629             (BIO_printf(bio, "%s:%s:%d:CMP %s: " msg "\n", \
630                         FUNC, OPENSSL_FILE, OPENSSL_LINE, prefix, a1, a2, a3))))
631 #define CMP_DEBUG(m, a1, a2, a3) \
632     CMP_print(bio_out, OSSL_CMP_LOG_DEBUG, "debug", m, a1, a2, a3)
633 #define CMP_debug(msg)             CMP_DEBUG(msg"%s%s%s", "", "", "")
634 #define CMP_debug1(msg, a1)        CMP_DEBUG(msg"%s%s",   a1, "", "")
635 #define CMP_debug2(msg, a1, a2)    CMP_DEBUG(msg"%s",     a1, a2, "")
636 #define CMP_debug3(msg, a1, a2, a3) CMP_DEBUG(msg,        a1, a2, a3)
637 #define CMP_INFO(msg, a1, a2, a3) \
638     CMP_print(bio_out, OSSL_CMP_LOG_INFO, "info", msg, a1, a2, a3)
639 #define CMP_info(msg)              CMP_INFO(msg"%s%s%s", "", "", "")
640 #define CMP_info1(msg, a1)         CMP_INFO(msg"%s%s",   a1, "", "")
641 #define CMP_info2(msg, a1, a2)     CMP_INFO(msg"%s",     a1, a2, "")
642 #define CMP_info3(msg, a1, a2, a3) CMP_INFO(msg,         a1, a2, a3)
643 #define CMP_WARN(m, a1, a2, a3) \
644     CMP_print(bio_out, OSSL_CMP_LOG_WARNING, "warning", m, a1, a2, a3)
645 #define CMP_warn(msg)              CMP_WARN(msg"%s%s%s", "", "", "")
646 #define CMP_warn1(msg, a1)         CMP_WARN(msg"%s%s",   a1, "", "")
647 #define CMP_warn2(msg, a1, a2)     CMP_WARN(msg"%s",     a1, a2, "")
648 #define CMP_warn3(msg, a1, a2, a3) CMP_WARN(msg,         a1, a2, a3)
649 #define CMP_ERR(msg, a1, a2, a3) \
650     CMP_print(bio_err, OSSL_CMP_LOG_ERR, "error", msg, a1, a2, a3)
651 #define CMP_err(msg)               CMP_ERR(msg"%s%s%s", "", "", "")
652 #define CMP_err1(msg, a1)          CMP_ERR(msg"%s%s",   a1, "", "")
653 #define CMP_err2(msg, a1, a2)      CMP_ERR(msg"%s",     a1, a2, "")
654 #define CMP_err3(msg, a1, a2, a3)  CMP_ERR(msg,         a1, a2, a3)
655
656 static int print_to_bio_out(const char *func, const char *file, int line,
657                             OSSL_CMP_severity level, const char *msg)
658 {
659     return OSSL_CMP_print_to_bio(bio_out, func, file, line, level, msg);
660 }
661
662 static int print_to_bio_err(const char *func, const char *file, int line,
663                             OSSL_CMP_severity level, const char *msg)
664 {
665     return OSSL_CMP_print_to_bio(bio_err, func, file, line, level, msg);
666 }
667
668 static int set_verbosity(int level)
669 {
670     if (level < OSSL_CMP_LOG_EMERG || level > OSSL_CMP_LOG_MAX) {
671         CMP_err1("Logging verbosity level %d out of range (0 .. 8)", level);
672         return 0;
673     }
674     opt_verbosity = level;
675     return 1;
676 }
677
678 static EVP_PKEY *load_key_pwd(const char *uri, int format,
679                               const char *pass, ENGINE *eng, const char *desc)
680 {
681     char *pass_string = get_passwd(pass, desc);
682     EVP_PKEY *pkey = load_key(uri, format, 0, pass_string, eng, desc);
683
684     clear_free(pass_string);
685     return pkey;
686 }
687
688 static X509 *load_cert_pwd(const char *uri, const char *pass, const char *desc)
689 {
690     X509 *cert;
691     char *pass_string = get_passwd(pass, desc);
692
693     cert = load_cert_pass(uri, FORMAT_UNDEF, 0, pass_string, desc);
694     clear_free(pass_string);
695     return cert;
696 }
697
698 /* set expected hostname/IP addr and clears the email addr in the given ts */
699 static int truststore_set_host_etc(X509_STORE *ts, const char *host)
700 {
701     X509_VERIFY_PARAM *ts_vpm = X509_STORE_get0_param(ts);
702
703     /* first clear any hostnames, IP, and email addresses */
704     if (!X509_VERIFY_PARAM_set1_host(ts_vpm, NULL, 0)
705             || !X509_VERIFY_PARAM_set1_ip(ts_vpm, NULL, 0)
706             || !X509_VERIFY_PARAM_set1_email(ts_vpm, NULL, 0))
707         return 0;
708     X509_VERIFY_PARAM_set_hostflags(ts_vpm,
709                                     X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT |
710                                     X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
711     return (host != NULL && X509_VERIFY_PARAM_set1_ip_asc(ts_vpm, host))
712         || X509_VERIFY_PARAM_set1_host(ts_vpm, host, 0);
713 }
714
715 /* write OSSL_CMP_MSG DER-encoded to the specified file name item */
716 static int write_PKIMESSAGE(const OSSL_CMP_MSG *msg, char **filenames)
717 {
718     char *file;
719
720     if (msg == NULL || filenames == NULL) {
721         CMP_err("NULL arg to write_PKIMESSAGE");
722         return 0;
723     }
724     if (*filenames == NULL) {
725         CMP_err("not enough file names provided for writing PKIMessage");
726         return 0;
727     }
728
729     file = *filenames;
730     *filenames = next_item(file);
731     if (OSSL_CMP_MSG_write(file, msg) < 0) {
732         CMP_err1("cannot write PKIMessage to file '%s'", file);
733         return 0;
734     }
735     return 1;
736 }
737
738 /* read DER-encoded OSSL_CMP_MSG from the specified file name item */
739 static OSSL_CMP_MSG *read_PKIMESSAGE(const char *desc, char **filenames)
740 {
741     char *file;
742     OSSL_CMP_MSG *ret;
743
744     if (filenames == NULL || desc == NULL) {
745         CMP_err("NULL arg to read_PKIMESSAGE");
746         return NULL;
747     }
748     if (*filenames == NULL) {
749         CMP_err("not enough file names provided for reading PKIMessage");
750         return NULL;
751     }
752
753     file = *filenames;
754     *filenames = next_item(file);
755
756     ret = OSSL_CMP_MSG_read(file, app_get0_libctx(), app_get0_propq());
757     if (ret == NULL)
758         CMP_err1("cannot read PKIMessage from file '%s'", file);
759     else
760         CMP_info2("%s %s", desc, file);
761     return ret;
762 }
763
764 /*-
765  * Sends the PKIMessage req and on success place the response in *res
766  * basically like OSSL_CMP_MSG_http_perform(), but in addition allows
767  * to dump the sequence of requests and responses to files and/or
768  * to take the sequence of requests and responses from files.
769  */
770 static OSSL_CMP_MSG *read_write_req_resp(OSSL_CMP_CTX *ctx,
771                                          const OSSL_CMP_MSG *req)
772 {
773     OSSL_CMP_MSG *req_new = NULL;
774     OSSL_CMP_MSG *res = NULL;
775     OSSL_CMP_PKIHEADER *hdr;
776     const char *prev_opt_rspin = opt_rspin;
777
778     if (opt_reqout != NULL && !write_PKIMESSAGE(req, &opt_reqout))
779         goto err;
780     if (opt_reqin != NULL && opt_rspin == NULL) {
781         if ((req_new = read_PKIMESSAGE("actually sending", &opt_reqin)) == NULL)
782             goto err;
783         /*-
784          * The transaction ID in req_new read from opt_reqin may not be fresh.
785          * In this case the server may complain "Transaction id already in use."
786          * The following workaround unfortunately requires re-protection.
787          */
788         if (opt_reqin_new_tid
789                 && !OSSL_CMP_MSG_update_transactionID(ctx, req_new))
790             goto err;
791
792         /*
793          * Except for first request, need to satisfy recipNonce check by server.
794          * Unfortunately requires re-protection if protection is required.
795          */
796         if (!OSSL_CMP_MSG_update_recipNonce(ctx, req_new))
797             goto err;
798     }
799
800     if (opt_rspin != NULL) {
801         res = read_PKIMESSAGE("actually using", &opt_rspin);
802     } else {
803         const OSSL_CMP_MSG *actual_req = req_new != NULL ? req_new : req;
804
805         if (opt_use_mock_srv) {
806             if (rspin_in_use)
807                 CMP_warn("too few -rspin filename arguments; resorting to using mock server");
808             res = OSSL_CMP_CTX_server_perform(ctx, actual_req);
809         } else {
810 #ifndef OPENSSL_NO_SOCK
811             if (opt_server == NULL) {
812                 CMP_err("missing -server or -use_mock_srv option, or too few -rspin filename arguments");
813                 goto err;
814             }
815             if (rspin_in_use)
816                 CMP_warn("too few -rspin filename arguments; resorting to contacting server");
817             res = OSSL_CMP_MSG_http_perform(ctx, actual_req);
818 #else
819             CMP_err("-server not supported on no-sock build; missing -use_mock_srv option or too few -rspin filename arguments");
820 #endif
821         }
822         rspin_in_use = 0;
823     }
824     if (res == NULL)
825         goto err;
826
827     if (req_new != NULL || prev_opt_rspin != NULL) {
828         /* need to satisfy nonce and transactionID checks by client */
829         ASN1_OCTET_STRING *nonce;
830         ASN1_OCTET_STRING *tid;
831
832         hdr = OSSL_CMP_MSG_get0_header(res);
833         nonce = OSSL_CMP_HDR_get0_recipNonce(hdr);
834         tid = OSSL_CMP_HDR_get0_transactionID(hdr);
835         if (!OSSL_CMP_CTX_set1_senderNonce(ctx, nonce)
836                 || !OSSL_CMP_CTX_set1_transactionID(ctx, tid)) {
837             OSSL_CMP_MSG_free(res);
838             res = NULL;
839             goto err;
840         }
841     }
842
843     if (opt_rspout != NULL && !write_PKIMESSAGE(res, &opt_rspout)) {
844         OSSL_CMP_MSG_free(res);
845         res = NULL;
846     }
847
848  err:
849     OSSL_CMP_MSG_free(req_new);
850     return res;
851 }
852
853 static int set_name(const char *str,
854                     int (*set_fn) (OSSL_CMP_CTX *ctx, const X509_NAME *name),
855                     OSSL_CMP_CTX *ctx, const char *desc)
856 {
857     if (str != NULL) {
858         X509_NAME *n = parse_name(str, MBSTRING_ASC, 1, desc);
859
860         if (n == NULL)
861             return 0;
862         if (!(*set_fn) (ctx, n)) {
863             X509_NAME_free(n);
864             CMP_err("out of memory");
865             return 0;
866         }
867         X509_NAME_free(n);
868     }
869     return 1;
870 }
871
872 static int set_gennames(OSSL_CMP_CTX *ctx, char *names, const char *desc)
873 {
874     char *next;
875
876     for (; names != NULL; names = next) {
877         GENERAL_NAME *n;
878
879         next = next_item(names);
880         if (strcmp(names, "critical") == 0) {
881             (void)OSSL_CMP_CTX_set_option(ctx,
882                                           OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL,
883                                           1);
884             continue;
885         }
886
887         /* try IP address first, then email/URI/domain name */
888         (void)ERR_set_mark();
889         n = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_IPADD, names, 0);
890         if (n == NULL)
891             n = a2i_GENERAL_NAME(NULL, NULL, NULL,
892                                  strchr(names, '@') != NULL ? GEN_EMAIL :
893                                  strchr(names, ':') != NULL ? GEN_URI : GEN_DNS,
894                                  names, 0);
895         (void)ERR_pop_to_mark();
896
897         if (n == NULL) {
898             CMP_err2("bad syntax of %s '%s'", desc, names);
899             return 0;
900         }
901         if (!OSSL_CMP_CTX_push1_subjectAltName(ctx, n)) {
902             GENERAL_NAME_free(n);
903             CMP_err("out of memory");
904             return 0;
905         }
906         GENERAL_NAME_free(n);
907     }
908     return 1;
909 }
910
911 static X509_STORE *load_trusted(char *input, int for_new_cert, const char *desc)
912 {
913     X509_STORE *ts = load_certstore(input, opt_otherpass, desc, vpm);
914
915     if (ts == NULL)
916         return NULL;
917     X509_STORE_set_verify_cb(ts, X509_STORE_CTX_print_verify_cb);
918
919     /* copy vpm to store */
920     if (X509_STORE_set1_param(ts, vpm /* may be NULL */)
921             && (for_new_cert || truststore_set_host_etc(ts, NULL)))
922         return ts;
923     BIO_printf(bio_err, "error setting verification parameters for %s\n", desc);
924     OSSL_CMP_CTX_print_errors(cmp_ctx);
925     X509_STORE_free(ts);
926     return NULL;
927 }
928
929 typedef int (*add_X509_stack_fn_t)(void *ctx, const STACK_OF(X509) *certs);
930
931 static int setup_certs(char *files, const char *desc, void *ctx,
932                        add_X509_stack_fn_t set1_fn)
933 {
934     STACK_OF(X509) *certs;
935     int ok;
936
937     if (files == NULL)
938         return 1;
939     if ((certs = load_certs_multifile(files, opt_otherpass, desc, vpm)) == NULL)
940         return 0;
941     ok = (*set1_fn)(ctx, certs);
942     OSSL_STACK_OF_X509_free(certs);
943     return ok;
944 }
945
946 /*
947  * parse and transform some options, checking their syntax.
948  * Returns 1 on success, 0 on error
949  */
950 static int transform_opts(void)
951 {
952     if (opt_cmd_s != NULL) {
953         if (!strcmp(opt_cmd_s, "ir")) {
954             opt_cmd = CMP_IR;
955         } else if (!strcmp(opt_cmd_s, "kur")) {
956             opt_cmd = CMP_KUR;
957         } else if (!strcmp(opt_cmd_s, "cr")) {
958             opt_cmd = CMP_CR;
959         } else if (!strcmp(opt_cmd_s, "p10cr")) {
960             opt_cmd = CMP_P10CR;
961         } else if (!strcmp(opt_cmd_s, "rr")) {
962             opt_cmd = CMP_RR;
963         } else if (!strcmp(opt_cmd_s, "genm")) {
964             opt_cmd = CMP_GENM;
965         } else {
966             CMP_err1("unknown cmp command '%s'", opt_cmd_s);
967             return 0;
968         }
969     } else {
970         CMP_err("no cmp command to execute");
971         return 0;
972     }
973
974 #ifndef OPENSSL_NO_ENGINE
975 # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12 | OPT_FMT_ENGINE)
976 #else
977 # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12)
978 #endif
979
980     if (opt_keyform_s != NULL
981             && !opt_format(opt_keyform_s, FORMAT_OPTIONS, &opt_keyform)) {
982         CMP_err("unknown option given for key loading format");
983         return 0;
984     }
985
986 #undef FORMAT_OPTIONS
987
988     if (opt_certform_s != NULL
989             && !opt_format(opt_certform_s, OPT_FMT_PEMDER, &opt_certform)) {
990         CMP_err("unknown option given for certificate storing format");
991         return 0;
992     }
993
994     return 1;
995 }
996
997 static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine)
998 {
999     OSSL_CMP_CTX *ctx; /* extra CMP (client) ctx partly used by server */
1000     OSSL_CMP_SRV_CTX *srv_ctx = ossl_cmp_mock_srv_new(app_get0_libctx(),
1001                                                       app_get0_propq());
1002
1003     if (srv_ctx == NULL)
1004         return NULL;
1005     ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx);
1006
1007     if (opt_srv_ref == NULL) {
1008         if (opt_srv_cert == NULL) {
1009             /* opt_srv_cert should determine the sender */
1010             CMP_err("must give -srv_ref for mock server if no -srv_cert given");
1011             goto err;
1012         }
1013     } else {
1014         if (!OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_srv_ref,
1015                                               strlen(opt_srv_ref)))
1016             goto err;
1017     }
1018
1019     if (opt_srv_secret != NULL) {
1020         int res;
1021         char *pass_str = get_passwd(opt_srv_secret, "PBMAC secret of mock server");
1022
1023         if (pass_str != NULL) {
1024             cleanse(opt_srv_secret);
1025             res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_str,
1026                                                 strlen(pass_str));
1027             clear_free(pass_str);
1028             if (res == 0)
1029                 goto err;
1030         }
1031     } else if (opt_srv_cert == NULL) {
1032         CMP_err("server credentials (-srv_secret or -srv_cert) must be given if -use_mock_srv or -port is used");
1033         goto err;
1034     } else {
1035         CMP_warn("server will not be able to handle PBM-protected requests since -srv_secret is not given");
1036     }
1037
1038     if (opt_srv_secret == NULL
1039             && ((opt_srv_cert == NULL) != (opt_srv_key == NULL))) {
1040         CMP_err("must give both -srv_cert and -srv_key options or neither");
1041         goto err;
1042     }
1043     if (opt_srv_cert != NULL) {
1044         X509 *srv_cert = load_cert_pwd(opt_srv_cert, opt_srv_keypass,
1045                                        "certificate of the mock server");
1046
1047         if (srv_cert == NULL || !OSSL_CMP_CTX_set1_cert(ctx, srv_cert)) {
1048             X509_free(srv_cert);
1049             goto err;
1050         }
1051         X509_free(srv_cert);
1052     }
1053     if (opt_srv_key != NULL) {
1054         EVP_PKEY *pkey = load_key_pwd(opt_srv_key, opt_keyform,
1055                                       opt_srv_keypass,
1056                                       engine, "private key for mock server cert");
1057
1058         if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) {
1059             EVP_PKEY_free(pkey);
1060             goto err;
1061         }
1062         EVP_PKEY_free(pkey);
1063     }
1064     cleanse(opt_srv_keypass);
1065
1066     if (opt_srv_trusted != NULL) {
1067         X509_STORE *ts =
1068             load_trusted(opt_srv_trusted, 0, "certs trusted by mock server");
1069
1070         if (ts == NULL || !OSSL_CMP_CTX_set0_trusted(ctx, ts)) {
1071             X509_STORE_free(ts);
1072             goto err;
1073         }
1074     } else {
1075         CMP_warn("mock server will not be able to handle signature-protected requests since -srv_trusted is not given");
1076     }
1077     if (!setup_certs(opt_srv_untrusted,
1078                      "untrusted certificates for mock server", ctx,
1079                      (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted))
1080         goto err;
1081
1082     if (opt_ref_cert != NULL) {
1083         X509 *cert = load_cert_pwd(opt_ref_cert, opt_keypass,
1084                                    "reference cert to be expected by the mock server");
1085
1086         if (cert == NULL)
1087             goto err;
1088         if (!ossl_cmp_mock_srv_set1_refCert(srv_ctx, cert)) {
1089             X509_free(cert);
1090             goto err;
1091         }
1092         X509_free(cert);
1093     }
1094     if (opt_rsp_cert == NULL) {
1095         CMP_warn("no -rsp_cert given for mock server");
1096     } else {
1097         X509 *cert = load_cert_pwd(opt_rsp_cert, opt_keypass,
1098                                    "cert to be returned by the mock server");
1099
1100         if (cert == NULL)
1101             goto err;
1102         if (!ossl_cmp_mock_srv_set1_certOut(srv_ctx, cert)) {
1103             X509_free(cert);
1104             goto err;
1105         }
1106         X509_free(cert);
1107     }
1108     if (!setup_certs(opt_rsp_extracerts,
1109                      "CMP extra certificates for mock server", srv_ctx,
1110                      (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_chainOut))
1111         goto err;
1112     if (!setup_certs(opt_rsp_capubs, "caPubs for mock server", srv_ctx,
1113                      (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_caPubsOut))
1114         goto err;
1115     (void)ossl_cmp_mock_srv_set_pollCount(srv_ctx, opt_poll_count);
1116     (void)ossl_cmp_mock_srv_set_checkAfterTime(srv_ctx, opt_check_after);
1117     if (opt_grant_implicitconf)
1118         (void)OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(srv_ctx, 1);
1119
1120     if (opt_failure != INT_MIN) { /* option has been set explicitly */
1121         if (opt_failure < 0 || OSSL_CMP_PKIFAILUREINFO_MAX < opt_failure) {
1122             CMP_err1("-failure out of range, should be >= 0 and <= %d",
1123                      OSSL_CMP_PKIFAILUREINFO_MAX);
1124             goto err;
1125         }
1126         if (opt_failurebits != 0)
1127             CMP_warn("-failurebits overrides -failure");
1128         else
1129             opt_failurebits = 1 << opt_failure;
1130     }
1131     if ((unsigned)opt_failurebits > OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN) {
1132         CMP_err("-failurebits out of range");
1133         goto err;
1134     }
1135     if (!ossl_cmp_mock_srv_set_statusInfo(srv_ctx, opt_pkistatus,
1136                                           opt_failurebits, opt_statusstring))
1137         goto err;
1138
1139     if (opt_send_error)
1140         (void)ossl_cmp_mock_srv_set_sendError(srv_ctx, 1);
1141
1142     if (opt_send_unprotected)
1143         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1);
1144     if (opt_send_unprot_err)
1145         (void)OSSL_CMP_SRV_CTX_set_send_unprotected_errors(srv_ctx, 1);
1146     if (opt_accept_unprotected)
1147         (void)OSSL_CMP_SRV_CTX_set_accept_unprotected(srv_ctx, 1);
1148     if (opt_accept_unprot_err)
1149         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1);
1150     if (opt_accept_raverified)
1151         (void)OSSL_CMP_SRV_CTX_set_accept_raverified(srv_ctx, 1);
1152
1153     return srv_ctx;
1154
1155  err:
1156     ossl_cmp_mock_srv_free(srv_ctx);
1157     return NULL;
1158 }
1159
1160 /*
1161  * set up verification aspects of OSSL_CMP_CTX w.r.t. opts from config file/CLI.
1162  * Returns pointer on success, NULL on error
1163  */
1164 static int setup_verification_ctx(OSSL_CMP_CTX *ctx)
1165 {
1166     if (!setup_certs(opt_untrusted, "untrusted certificates", ctx,
1167                      (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted))
1168         return 0;
1169
1170     if (opt_srvcert != NULL || opt_trusted != NULL) {
1171         X509 *srvcert;
1172         X509_STORE *ts;
1173         int ok;
1174
1175         if (opt_srvcert != NULL) {
1176             if (opt_trusted != NULL) {
1177                 CMP_warn("-trusted option is ignored since -srvcert option is present");
1178                 opt_trusted = NULL;
1179             }
1180             if (opt_recipient != NULL) {
1181                 CMP_warn("-recipient option is ignored since -srvcert option is present");
1182                 opt_recipient = NULL;
1183             }
1184             srvcert = load_cert_pwd(opt_srvcert, opt_otherpass,
1185                                     "directly trusted CMP server certificate");
1186             ok = srvcert != NULL && OSSL_CMP_CTX_set1_srvCert(ctx, srvcert);
1187             X509_free(srvcert);
1188             if (!ok)
1189                 return 0;
1190         }
1191         if (opt_trusted != NULL) {
1192             /*
1193              * the 0 arg below clears any expected host/ip/email address;
1194              * opt_expect_sender is used instead
1195              */
1196             ts = load_trusted(opt_trusted, 0, "certs trusted by client");
1197
1198             if (ts == NULL || !OSSL_CMP_CTX_set0_trusted(ctx, ts)) {
1199                 X509_STORE_free(ts);
1200                 return 0;
1201             }
1202         }
1203     }
1204
1205     if (opt_ignore_keyusage)
1206         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IGNORE_KEYUSAGE, 1);
1207
1208     if (opt_unprotected_errors)
1209         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1);
1210
1211     if (opt_out_trusted != NULL) { /* for use in OSSL_CMP_certConf_cb() */
1212         X509_VERIFY_PARAM *out_vpm = NULL;
1213         X509_STORE *out_trusted =
1214             load_trusted(opt_out_trusted, 1,
1215                          "trusted certs for verifying newly enrolled cert");
1216
1217         if (out_trusted == NULL)
1218             return 0;
1219         /* ignore any -attime here, new certs are current anyway */
1220         out_vpm = X509_STORE_get0_param(out_trusted);
1221         X509_VERIFY_PARAM_clear_flags(out_vpm, X509_V_FLAG_USE_CHECK_TIME);
1222
1223         (void)OSSL_CMP_CTX_set_certConf_cb_arg(ctx, out_trusted);
1224     }
1225
1226     if (opt_disable_confirm)
1227         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DISABLE_CONFIRM, 1);
1228
1229     if (opt_implicit_confirm)
1230         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM, 1);
1231
1232     return 1;
1233 }
1234
1235 #ifndef OPENSSL_NO_SOCK
1236 /*
1237  * set up ssl_ctx for the OSSL_CMP_CTX based on options from config file/CLI.
1238  * Returns pointer on success, NULL on error
1239  */
1240 static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, const char *host,
1241                               ENGINE *engine)
1242 {
1243     STACK_OF(X509) *untrusted = OSSL_CMP_CTX_get0_untrusted(ctx);
1244     EVP_PKEY *pkey = NULL;
1245     X509_STORE *trust_store = NULL;
1246     SSL_CTX *ssl_ctx;
1247     int i;
1248
1249     ssl_ctx = SSL_CTX_new(TLS_client_method());
1250     if (ssl_ctx == NULL)
1251         return NULL;
1252
1253     if (opt_tls_trusted != NULL) {
1254         trust_store = load_trusted(opt_tls_trusted, 0, "trusted TLS certs");
1255         if (trust_store == NULL)
1256             goto err;
1257         SSL_CTX_set_cert_store(ssl_ctx, trust_store);
1258         SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
1259     } else {
1260         CMP_warn("-tls_used given without -tls_trusted; will not authenticate the TLS server");
1261     }
1262
1263     if (opt_tls_cert != NULL && opt_tls_key != NULL) {
1264         X509 *cert;
1265         STACK_OF(X509) *certs = NULL;
1266         int ok;
1267
1268         if (!load_cert_certs(opt_tls_cert, &cert, &certs, 0, opt_tls_keypass,
1269                              "TLS client certificate (optionally with chain)",
1270                              vpm))
1271             /* need opt_tls_keypass if opt_tls_cert is encrypted PKCS#12 file */
1272             goto err;
1273
1274         ok = SSL_CTX_use_certificate(ssl_ctx, cert) > 0;
1275         X509_free(cert);
1276
1277         /*
1278          * Any further certs and any untrusted certs are used for constructing
1279          * the chain to be provided with the TLS client cert to the TLS server.
1280          */
1281         if (!ok || !SSL_CTX_set0_chain(ssl_ctx, certs)) {
1282             CMP_err1("unable to use client TLS certificate file '%s'",
1283                      opt_tls_cert);
1284             OSSL_STACK_OF_X509_free(certs);
1285             goto err;
1286         }
1287         for (i = 0; i < sk_X509_num(untrusted); i++) {
1288             cert = sk_X509_value(untrusted, i);
1289             if (!SSL_CTX_add1_chain_cert(ssl_ctx, cert)) {
1290                 CMP_err("could not add untrusted cert to TLS client cert chain");
1291                 goto err;
1292             }
1293         }
1294
1295         {
1296             X509_VERIFY_PARAM *tls_vpm = NULL;
1297             unsigned long bak_flags = 0; /* compiler warns without init */
1298
1299             if (trust_store != NULL) {
1300                 tls_vpm = X509_STORE_get0_param(trust_store);
1301                 bak_flags = X509_VERIFY_PARAM_get_flags(tls_vpm);
1302                 /* disable any cert status/revocation checking etc. */
1303                 X509_VERIFY_PARAM_clear_flags(tls_vpm,
1304                                               ~(X509_V_FLAG_USE_CHECK_TIME
1305                                                 | X509_V_FLAG_NO_CHECK_TIME
1306                                                 | X509_V_FLAG_PARTIAL_CHAIN
1307                                                 | X509_V_FLAG_POLICY_CHECK));
1308             }
1309             CMP_debug("trying to build cert chain for own TLS cert");
1310             if (SSL_CTX_build_cert_chain(ssl_ctx,
1311                                          SSL_BUILD_CHAIN_FLAG_UNTRUSTED |
1312                                          SSL_BUILD_CHAIN_FLAG_NO_ROOT)) {
1313                 CMP_debug("success building cert chain for own TLS cert");
1314             } else {
1315                 OSSL_CMP_CTX_print_errors(ctx);
1316                 CMP_warn("could not build cert chain for own TLS cert");
1317             }
1318             if (trust_store != NULL)
1319                 X509_VERIFY_PARAM_set_flags(tls_vpm, bak_flags);
1320         }
1321
1322         /* If present we append to the list also the certs from opt_tls_extra */
1323         if (opt_tls_extra != NULL) {
1324             STACK_OF(X509) *tls_extra = load_certs_multifile(opt_tls_extra,
1325                                                              opt_otherpass,
1326                                                              "extra certificates for TLS",
1327                                                              vpm);
1328             int res = 1;
1329
1330             if (tls_extra == NULL)
1331                 goto err;
1332             for (i = 0; i < sk_X509_num(tls_extra); i++) {
1333                 cert = sk_X509_value(tls_extra, i);
1334                 if (res != 0)
1335                     res = SSL_CTX_add_extra_chain_cert(ssl_ctx, cert);
1336                 if (res == 0)
1337                     X509_free(cert);
1338             }
1339             sk_X509_free(tls_extra);
1340             if (res == 0) {
1341                 BIO_printf(bio_err, "error: unable to add TLS extra certs\n");
1342                 goto err;
1343             }
1344         }
1345
1346         pkey = load_key_pwd(opt_tls_key, opt_keyform, opt_tls_keypass,
1347                             engine, "TLS client private key");
1348         cleanse(opt_tls_keypass);
1349         if (pkey == NULL)
1350             goto err;
1351         /*
1352          * verify the key matches the cert,
1353          * not using SSL_CTX_check_private_key(ssl_ctx)
1354          * because it gives poor and sometimes misleading diagnostics
1355          */
1356         if (!X509_check_private_key(SSL_CTX_get0_certificate(ssl_ctx),
1357                                     pkey)) {
1358             CMP_err2("TLS private key '%s' does not match the TLS certificate '%s'\n",
1359                      opt_tls_key, opt_tls_cert);
1360             EVP_PKEY_free(pkey);
1361             pkey = NULL; /* otherwise, for some reason double free! */
1362             goto err;
1363         }
1364         if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) <= 0) {
1365             CMP_err1("unable to use TLS client private key '%s'", opt_tls_key);
1366             EVP_PKEY_free(pkey);
1367             pkey = NULL; /* otherwise, for some reason double free! */
1368             goto err;
1369         }
1370         EVP_PKEY_free(pkey); /* we do not need the handle any more */
1371     } else {
1372         CMP_warn("-tls_used given without -tls_key; cannot authenticate to the TLS server");
1373     }
1374     if (trust_store != NULL) {
1375         /*
1376          * Enable and parameterize server hostname/IP address check.
1377          * If we did this before checking our own TLS cert
1378          * the expected hostname would mislead the check.
1379          */
1380         if (!truststore_set_host_etc(trust_store,
1381                                      opt_tls_host != NULL ? opt_tls_host : host))
1382             goto err;
1383     }
1384     return ssl_ctx;
1385  err:
1386     SSL_CTX_free(ssl_ctx);
1387     return NULL;
1388 }
1389 #endif /* OPENSSL_NO_SOCK */
1390
1391 /*
1392  * set up protection aspects of OSSL_CMP_CTX based on options from config
1393  * file/CLI while parsing options and checking their consistency.
1394  * Returns 1 on success, 0 on error
1395  */
1396 static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
1397 {
1398     if (!opt_unprotected_requests && opt_secret == NULL && opt_key == NULL) {
1399         CMP_err("must give -key or -secret unless -unprotected_requests is used");
1400         return 0;
1401     }
1402
1403     if (opt_ref == NULL && opt_cert == NULL && opt_subject == NULL) {
1404         /* cert or subject should determine the sender */
1405         CMP_err("must give -ref if no -cert and no -subject given");
1406         return 0;
1407     }
1408     if (!opt_secret && ((opt_cert == NULL) != (opt_key == NULL))) {
1409         CMP_err("must give both -cert and -key options or neither");
1410         return 0;
1411     }
1412     if (opt_secret != NULL) {
1413         char *pass_string = get_passwd(opt_secret, "PBMAC");
1414         int res;
1415
1416         if (pass_string != NULL) {
1417             cleanse(opt_secret);
1418             res = OSSL_CMP_CTX_set1_secretValue(ctx,
1419                                                 (unsigned char *)pass_string,
1420                                                 strlen(pass_string));
1421             clear_free(pass_string);
1422             if (res == 0)
1423                 return 0;
1424         }
1425         if (opt_cert != NULL || opt_key != NULL)
1426             CMP_warn("-cert and -key not used for protection since -secret is given");
1427     }
1428     if (opt_ref != NULL
1429             && !OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_ref,
1430                                                  strlen(opt_ref)))
1431         return 0;
1432
1433     if (opt_key != NULL) {
1434         EVP_PKEY *pkey = load_key_pwd(opt_key, opt_keyform, opt_keypass, engine,
1435                                       "private key for CMP client certificate");
1436
1437         if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) {
1438             EVP_PKEY_free(pkey);
1439             return 0;
1440         }
1441         EVP_PKEY_free(pkey);
1442     }
1443     if (opt_secret == NULL && opt_srvcert == NULL && opt_trusted == NULL)
1444         CMP_warn("will not authenticate server due to missing -secret, -trusted, or -srvcert");
1445
1446     if (opt_cert != NULL) {
1447         X509 *cert;
1448         STACK_OF(X509) *certs = NULL;
1449         X509_STORE *own_trusted = NULL;
1450         int ok;
1451
1452         if (!load_cert_certs(opt_cert, &cert, &certs, 0, opt_keypass,
1453                              "CMP client certificate (optionally with chain)",
1454                              vpm))
1455             /* opt_keypass is needed if opt_cert is an encrypted PKCS#12 file */
1456             return 0;
1457         ok = OSSL_CMP_CTX_set1_cert(ctx, cert);
1458         X509_free(cert);
1459         if (!ok) {
1460             CMP_err("out of memory");
1461         } else {
1462             if (opt_own_trusted != NULL) {
1463                 own_trusted = load_trusted(opt_own_trusted, 0,
1464                                            "trusted certs for verifying own CMP signer cert");
1465                 ok = own_trusted != NULL;
1466             }
1467             ok = ok && OSSL_CMP_CTX_build_cert_chain(ctx, own_trusted, certs);
1468         }
1469         X509_STORE_free(own_trusted);
1470         OSSL_STACK_OF_X509_free(certs);
1471         if (!ok)
1472             return 0;
1473     } else if (opt_own_trusted != NULL) {
1474         CMP_warn("-own_trusted option is ignored without -cert");
1475     }
1476
1477     if (!setup_certs(opt_extracerts, "extra certificates for CMP", ctx,
1478                      (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_extraCertsOut))
1479         return 0;
1480     cleanse(opt_otherpass);
1481
1482     if (opt_unprotected_requests)
1483         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1);
1484
1485     if (opt_digest != NULL) {
1486         int digest = OBJ_ln2nid(opt_digest);
1487
1488         if (digest == NID_undef) {
1489             CMP_err1("digest algorithm name not recognized: '%s'", opt_digest);
1490             return 0;
1491         }
1492         if (!OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DIGEST_ALGNID, digest)
1493             || !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_OWF_ALGNID, digest)) {
1494             CMP_err1("digest algorithm name not supported: '%s'", opt_digest);
1495             return 0;
1496         }
1497     }
1498
1499     if (opt_mac != NULL) {
1500         int mac = OBJ_ln2nid(opt_mac);
1501
1502         if (mac == NID_undef) {
1503             CMP_err1("MAC algorithm name not recognized: '%s'", opt_mac);
1504             return 0;
1505         }
1506         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MAC_ALGNID, mac);
1507     }
1508     return 1;
1509 }
1510
1511 /*
1512  * set up IR/CR/KUR/CertConf/RR specific parts of the OSSL_CMP_CTX
1513  * based on options from config file/CLI.
1514  * Returns pointer on success, NULL on error
1515  */
1516 static int setup_request_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
1517 {
1518     X509_REQ *csr = NULL;
1519     X509_EXTENSIONS *exts = NULL;
1520     X509V3_CTX ext_ctx;
1521
1522     if (opt_subject == NULL
1523             && opt_csr == NULL && opt_oldcert == NULL && opt_cert == NULL
1524             && opt_cmd != CMP_RR && opt_cmd != CMP_GENM)
1525         CMP_warn("no -subject given; no -csr or -oldcert or -cert available for fallback");
1526
1527     if (opt_cmd == CMP_IR || opt_cmd == CMP_CR || opt_cmd == CMP_KUR) {
1528         if (opt_newkey == NULL && opt_key == NULL && opt_csr == NULL) {
1529             CMP_err("missing -newkey (or -key) to be certified and no -csr given");
1530             return 0;
1531         }
1532         if (opt_certout == NULL) {
1533             CMP_err("-certout not given, nowhere to save newly enrolled certificate");
1534             return 0;
1535         }
1536         if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject")
1537                 || !set_name(opt_issuer, OSSL_CMP_CTX_set1_issuer, ctx, "issuer"))
1538             return 0;
1539     } else {
1540         const char *msg = "option is ignored for commands other than 'ir', 'cr', and 'kur'";
1541
1542         if (opt_subject != NULL) {
1543             if (opt_ref == NULL && opt_cert == NULL) {
1544                 /* will use subject as sender unless oldcert subject is used */
1545                 if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject"))
1546                     return 0;
1547             } else {
1548                 CMP_warn1("-subject %s since -ref or -cert is given", msg);
1549             }
1550         }
1551         if (opt_issuer != NULL)
1552             CMP_warn1("-issuer %s", msg);
1553         if (opt_reqexts != NULL)
1554             CMP_warn1("-reqexts %s", msg);
1555         if (opt_san_nodefault)
1556             CMP_warn1("-san_nodefault %s", msg);
1557         if (opt_sans != NULL)
1558             CMP_warn1("-sans %s", msg);
1559         if (opt_policies != NULL)
1560             CMP_warn1("-policies %s", msg);
1561         if (opt_policy_oids != NULL)
1562             CMP_warn1("-policy_oids %s", msg);
1563     }
1564     if (opt_cmd == CMP_KUR) {
1565         char *ref_cert = opt_oldcert != NULL ? opt_oldcert : opt_cert;
1566
1567         if (ref_cert == NULL && opt_csr == NULL) {
1568             CMP_err("missing -oldcert for certificate to be updated and no -csr given");
1569             return 0;
1570         }
1571         if (opt_subject != NULL)
1572             CMP_warn2("given -subject '%s' overrides the subject of '%s' for KUR",
1573                       opt_subject, ref_cert != NULL ? ref_cert : opt_csr);
1574     }
1575     if (opt_cmd == CMP_RR) {
1576         if (opt_oldcert == NULL && opt_csr == NULL) {
1577             CMP_err("missing -oldcert for certificate to be revoked and no -csr given");
1578             return 0;
1579         }
1580         if (opt_oldcert != NULL && opt_csr != NULL)
1581             CMP_warn("ignoring -csr since certificate to be revoked is given");
1582     }
1583     if (opt_cmd == CMP_P10CR && opt_csr == NULL) {
1584         CMP_err("missing PKCS#10 CSR for p10cr");
1585         return 0;
1586     }
1587
1588     if (opt_recipient == NULL && opt_srvcert == NULL && opt_issuer == NULL
1589             && opt_oldcert == NULL && opt_cert == NULL)
1590         CMP_warn("missing -recipient, -srvcert, -issuer, -oldcert or -cert; recipient will be set to \"NULL-DN\"");
1591
1592     if (opt_cmd == CMP_P10CR || opt_cmd == CMP_RR || opt_cmd == CMP_GENM) {
1593         const char *msg = "option is ignored for 'p10cr', 'rr', and 'genm' commands";
1594
1595         if (opt_newkeypass != NULL)
1596             CMP_warn1("-newkeypass %s", msg);
1597         if (opt_newkey != NULL)
1598             CMP_warn1("-newkey %s", msg);
1599         if (opt_days != 0)
1600             CMP_warn1("-days %s", msg);
1601         if (opt_popo != OSSL_CRMF_POPO_NONE - 1)
1602             CMP_warn1("-popo %s", msg);
1603     } else if (opt_newkey != NULL) {
1604         const char *file = opt_newkey;
1605         const int format = opt_keyform;
1606         const char *pass = opt_newkeypass;
1607         const char *desc = "new private key for cert to be enrolled";
1608         EVP_PKEY *pkey;
1609         int priv = 1;
1610         BIO *bio_bak = bio_err;
1611
1612         bio_err = NULL; /* suppress diagnostics on first try loading key */
1613         pkey = load_key_pwd(file, format, pass, engine, desc);
1614         bio_err = bio_bak;
1615         if (pkey == NULL) {
1616             ERR_clear_error();
1617             desc = opt_csr == NULL
1618                 ? "fallback public key for cert to be enrolled"
1619                 : "public key for checking cert resulting from p10cr";
1620             pkey = load_pubkey(file, format, 0, pass, engine, desc);
1621             priv = 0;
1622         }
1623         cleanse(opt_newkeypass);
1624         if (pkey == NULL || !OSSL_CMP_CTX_set0_newPkey(ctx, priv, pkey)) {
1625             EVP_PKEY_free(pkey);
1626             return 0;
1627         }
1628     }
1629
1630     if (opt_days > 0
1631             && !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_VALIDITY_DAYS,
1632                                         opt_days)) {
1633         CMP_err("could not set requested cert validity period");
1634         return 0;
1635     }
1636
1637     if (opt_policies != NULL && opt_policy_oids != NULL) {
1638         CMP_err("cannot have policies both via -policies and via -policy_oids");
1639         return 0;
1640     }
1641
1642     if (opt_csr != NULL) {
1643         if (opt_cmd == CMP_GENM) {
1644             CMP_warn("-csr option is ignored for command 'genm'");
1645         } else {
1646             csr = load_csr_autofmt(opt_csr, FORMAT_UNDEF, NULL, "PKCS#10 CSR");
1647             if (csr == NULL)
1648                 return 0;
1649             if (!OSSL_CMP_CTX_set1_p10CSR(ctx, csr))
1650                 goto oom;
1651         }
1652     }
1653     if (opt_reqexts != NULL || opt_policies != NULL) {
1654         if ((exts = sk_X509_EXTENSION_new_null()) == NULL)
1655             goto oom;
1656         X509V3_set_ctx(&ext_ctx, NULL, NULL, csr, NULL, X509V3_CTX_REPLACE);
1657         X509V3_set_nconf(&ext_ctx, conf);
1658         if (opt_reqexts != NULL
1659             && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_reqexts, &exts)) {
1660             CMP_err1("cannot load certificate request extension section '%s'",
1661                      opt_reqexts);
1662             goto exts_err;
1663         }
1664         if (opt_policies != NULL
1665             && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_policies, &exts)) {
1666             CMP_err1("cannot load policy cert request extension section '%s'",
1667                      opt_policies);
1668             goto exts_err;
1669         }
1670         OSSL_CMP_CTX_set0_reqExtensions(ctx, exts);
1671     }
1672     X509_REQ_free(csr);
1673     /* After here, must not goto oom/exts_err */
1674
1675     if (OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) && opt_sans != NULL) {
1676         CMP_err("cannot have Subject Alternative Names both via -reqexts and via -sans");
1677         return 0;
1678     }
1679     if (!set_gennames(ctx, opt_sans, "Subject Alternative Name"))
1680         return 0;
1681
1682     if (opt_san_nodefault) {
1683         if (opt_sans != NULL)
1684             CMP_warn("-opt_san_nodefault has no effect when -sans is used");
1685         (void)OSSL_CMP_CTX_set_option(ctx,
1686                                       OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT, 1);
1687     }
1688
1689     if (opt_policy_oids_critical) {
1690         if (opt_policy_oids == NULL)
1691             CMP_warn("-opt_policy_oids_critical has no effect unless -policy_oids is given");
1692         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POLICIES_CRITICAL, 1);
1693     }
1694
1695     while (opt_policy_oids != NULL) {
1696         ASN1_OBJECT *policy;
1697         POLICYINFO *pinfo;
1698         char *next = next_item(opt_policy_oids);
1699
1700         if ((policy = OBJ_txt2obj(opt_policy_oids, 1)) == 0) {
1701             CMP_err1("unknown policy OID '%s'", opt_policy_oids);
1702             return 0;
1703         }
1704
1705         if ((pinfo = POLICYINFO_new()) == NULL) {
1706             ASN1_OBJECT_free(policy);
1707             return 0;
1708         }
1709         pinfo->policyid = policy;
1710
1711         if (!OSSL_CMP_CTX_push0_policy(ctx, pinfo)) {
1712             CMP_err1("cannot add policy with OID '%s'", opt_policy_oids);
1713             POLICYINFO_free(pinfo);
1714             return 0;
1715         }
1716         opt_policy_oids = next;
1717     }
1718
1719     if (opt_popo >= OSSL_CRMF_POPO_NONE)
1720         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POPO_METHOD, opt_popo);
1721
1722     if (opt_oldcert != NULL) {
1723         if (opt_cmd == CMP_GENM) {
1724             CMP_warn("-oldcert option is ignored for command 'genm'");
1725         } else {
1726             X509 *oldcert = load_cert_pwd(opt_oldcert, opt_keypass,
1727                                           opt_cmd == CMP_KUR ?
1728                                           "certificate to be updated" :
1729                                           opt_cmd == CMP_RR ?
1730                                           "certificate to be revoked" :
1731                                           "reference certificate (oldcert)");
1732             /* opt_keypass needed if opt_oldcert is an encrypted PKCS#12 file */
1733
1734             if (oldcert == NULL)
1735                 return 0;
1736             if (!OSSL_CMP_CTX_set1_oldCert(ctx, oldcert)) {
1737                 X509_free(oldcert);
1738                 CMP_err("out of memory");
1739                 return 0;
1740             }
1741             X509_free(oldcert);
1742         }
1743     }
1744     cleanse(opt_keypass);
1745     if (opt_revreason > CRL_REASON_NONE)
1746         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_REVOCATION_REASON,
1747                                       opt_revreason);
1748
1749     return 1;
1750
1751  oom:
1752     CMP_err("out of memory");
1753  exts_err:
1754     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1755     X509_REQ_free(csr);
1756     return 0;
1757 }
1758
1759 static int handle_opt_geninfo(OSSL_CMP_CTX *ctx)
1760 {
1761     long value;
1762     ASN1_OBJECT *type;
1763     ASN1_INTEGER *aint;
1764     ASN1_TYPE *val;
1765     OSSL_CMP_ITAV *itav;
1766     char *endstr;
1767     char *valptr = strchr(opt_geninfo, ':');
1768
1769     if (valptr == NULL) {
1770         CMP_err("missing ':' in -geninfo option");
1771         return 0;
1772     }
1773     valptr[0] = '\0';
1774     valptr++;
1775
1776     if (!CHECK_AND_SKIP_CASE_PREFIX(valptr, "int:")) {
1777         CMP_err("missing 'int:' in -geninfo option");
1778         return 0;
1779     }
1780
1781     value = strtol(valptr, &endstr, 10);
1782     if (endstr == valptr || *endstr != '\0') {
1783         CMP_err("cannot parse int in -geninfo option");
1784         return 0;
1785     }
1786
1787     type = OBJ_txt2obj(opt_geninfo, 1);
1788     if (type == NULL) {
1789         CMP_err("cannot parse OID in -geninfo option");
1790         return 0;
1791     }
1792
1793     if ((aint = ASN1_INTEGER_new()) == NULL)
1794         goto oom;
1795
1796     val = ASN1_TYPE_new();
1797     if (!ASN1_INTEGER_set(aint, value) || val == NULL) {
1798         ASN1_INTEGER_free(aint);
1799         goto oom;
1800     }
1801     ASN1_TYPE_set(val, V_ASN1_INTEGER, aint);
1802     itav = OSSL_CMP_ITAV_create(type, val);
1803     if (itav == NULL) {
1804         ASN1_TYPE_free(val);
1805         goto oom;
1806     }
1807
1808     if (!OSSL_CMP_CTX_push0_geninfo_ITAV(ctx, itav)) {
1809         OSSL_CMP_ITAV_free(itav);
1810         return 0;
1811     }
1812     return 1;
1813
1814  oom:
1815     ASN1_OBJECT_free(type);
1816     CMP_err("out of memory");
1817     return 0;
1818 }
1819
1820 /*
1821  * set up the client-side OSSL_CMP_CTX based on options from config file/CLI
1822  * while parsing options and checking their consistency.
1823  * Prints reason for error to bio_err.
1824  * Returns 1 on success, 0 on error
1825  */
1826 static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine)
1827 {
1828     int ret = 0;
1829     char *host = NULL, *port = NULL, *path = NULL, *used_path = opt_path;
1830 #ifndef OPENSSL_NO_SOCK
1831     int portnum, use_ssl;
1832     static char server_port[32] = { '\0' };
1833     const char *proxy_host = NULL;
1834 #endif
1835     char server_buf[200] = "mock server";
1836     char proxy_buf[200] = "";
1837
1838     if (!opt_use_mock_srv && opt_rspin == NULL) { /* note: -port is not given */
1839 #ifndef OPENSSL_NO_SOCK
1840         if (opt_server == NULL) {
1841             CMP_err("missing -server or -use_mock_srv or -rspin option");
1842             goto err;
1843         }
1844 #else
1845         CMP_err("missing -use_mock_srv or -rspin option; -server option is not supported due to no-sock build");
1846         goto err;
1847 #endif
1848     }
1849 #ifndef OPENSSL_NO_SOCK
1850     if (opt_server == NULL) {
1851         if (opt_proxy != NULL)
1852             CMP_warn("ignoring -proxy option since -server is not given");
1853         if (opt_no_proxy != NULL)
1854             CMP_warn("ignoring -no_proxy option since -server is not given");
1855         if (opt_tls_used) {
1856             CMP_warn("ignoring -tls_used option since -server is not given");
1857             opt_tls_used = 0;
1858         }
1859         goto set_path;
1860     }
1861     if (!OSSL_HTTP_parse_url(opt_server, &use_ssl, NULL /* user */, &host, &port,
1862                              &portnum, &path, NULL /* q */, NULL /* frag */)) {
1863         CMP_err1("cannot parse -server URL: %s", opt_server);
1864         goto err;
1865     }
1866     if (use_ssl && !opt_tls_used) {
1867         CMP_err("missing -tls_used option since -server URL indicates HTTPS");
1868         goto err;
1869     }
1870
1871     BIO_snprintf(server_port, sizeof(server_port), "%s", port);
1872     if (opt_path == NULL)
1873         used_path = path;
1874     if (!OSSL_CMP_CTX_set1_server(ctx, host)
1875             || !OSSL_CMP_CTX_set_serverPort(ctx, portnum))
1876         goto oom;
1877     if (opt_proxy != NULL && !OSSL_CMP_CTX_set1_proxy(ctx, opt_proxy))
1878         goto oom;
1879     if (opt_no_proxy != NULL && !OSSL_CMP_CTX_set1_no_proxy(ctx, opt_no_proxy))
1880         goto oom;
1881     (void)BIO_snprintf(server_buf, sizeof(server_buf), "http%s://%s:%s/%s",
1882                        opt_tls_used ? "s" : "", host, port,
1883                        *used_path == '/' ? used_path + 1 : used_path);
1884
1885     proxy_host = OSSL_HTTP_adapt_proxy(opt_proxy, opt_no_proxy, host, use_ssl);
1886     if (proxy_host != NULL)
1887         (void)BIO_snprintf(proxy_buf, sizeof(proxy_buf), " via %s", proxy_host);
1888
1889  set_path:
1890 #endif
1891
1892     if (!OSSL_CMP_CTX_set1_serverPath(ctx, used_path))
1893         goto oom;
1894     if (!transform_opts())
1895         goto err;
1896
1897     if (opt_infotype_s != NULL) {
1898         char id_buf[100] = "id-it-";
1899
1900         strncat(id_buf, opt_infotype_s, sizeof(id_buf) - strlen(id_buf) - 1);
1901         if ((opt_infotype = OBJ_sn2nid(id_buf)) == NID_undef) {
1902             CMP_err("unknown OID name in -infotype option");
1903             goto err;
1904         }
1905     }
1906
1907     if (!setup_verification_ctx(ctx))
1908         goto err;
1909
1910     if (opt_keep_alive != 1)
1911         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_KEEP_ALIVE,
1912                                       opt_keep_alive);
1913     if (opt_total_timeout > 0 && opt_msg_timeout > 0
1914             && opt_total_timeout < opt_msg_timeout) {
1915         CMP_err2("-total_timeout argument = %d must not be < %d (-msg_timeout)",
1916                  opt_total_timeout, opt_msg_timeout);
1917         goto err;
1918     }
1919     if (opt_msg_timeout >= 0) /* must do this before setup_ssl_ctx() */
1920         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT,
1921                                       opt_msg_timeout);
1922     if (opt_total_timeout >= 0)
1923         (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_TOTAL_TIMEOUT,
1924                                       opt_total_timeout);
1925
1926     if (opt_rspin != NULL) {
1927         rspin_in_use = 1;
1928         if (opt_reqin != NULL)
1929             CMP_warn("-reqin is ignored since -rspin is present");
1930     }
1931     if (opt_reqin_new_tid && opt_reqin == NULL)
1932         CMP_warn("-reqin_new_tid is ignored since -reqin is not present");
1933     if (opt_reqin != NULL || opt_reqout != NULL
1934             || opt_rspin != NULL || opt_rspout != NULL || opt_use_mock_srv)
1935         (void)OSSL_CMP_CTX_set_transfer_cb(ctx, read_write_req_resp);
1936
1937 #ifndef OPENSSL_NO_SOCK
1938     if (opt_tls_used) {
1939         APP_HTTP_TLS_INFO *info;
1940
1941         if (opt_tls_cert != NULL
1942             || opt_tls_key != NULL || opt_tls_keypass != NULL) {
1943             if (opt_tls_key == NULL) {
1944                 CMP_err("missing -tls_key option");
1945                 goto err;
1946             } else if (opt_tls_cert == NULL) {
1947                 CMP_err("missing -tls_cert option");
1948                 goto err;
1949             }
1950         }
1951
1952         if ((info = OPENSSL_zalloc(sizeof(*info))) == NULL)
1953             goto err;
1954         (void)OSSL_CMP_CTX_set_http_cb_arg(ctx, info);
1955         info->server = host;
1956         info->port = server_port;
1957         /* workaround for callback design flaw, see #17088: */
1958         info->use_proxy = proxy_host != NULL;
1959         info->timeout = OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT);
1960         info->ssl_ctx = setup_ssl_ctx(ctx, host, engine);
1961
1962         if (info->ssl_ctx == NULL)
1963             goto err;
1964         (void)OSSL_CMP_CTX_set_http_cb(ctx, app_http_tls_cb);
1965     }
1966 #endif
1967
1968     if (!setup_protection_ctx(ctx, engine))
1969         goto err;
1970
1971     if (!setup_request_ctx(ctx, engine))
1972         goto err;
1973
1974     if (!set_name(opt_recipient, OSSL_CMP_CTX_set1_recipient, ctx, "recipient")
1975             || !set_name(opt_expect_sender, OSSL_CMP_CTX_set1_expected_sender,
1976                          ctx, "expected sender"))
1977         goto err;
1978
1979     if (opt_geninfo != NULL && !handle_opt_geninfo(ctx))
1980         goto err;
1981
1982     /* not printing earlier, to minimize confusion in case setup fails before */
1983     if (opt_rspin != NULL)
1984         CMP_info2("will contact %s%s "
1985                   "only if -rspin argument gives too few filenames",
1986                   server_buf, proxy_buf);
1987     else
1988         CMP_info2("will contact %s%s", server_buf, proxy_buf);
1989
1990     ret = 1;
1991
1992  err:
1993     OPENSSL_free(host);
1994     OPENSSL_free(port);
1995     OPENSSL_free(path);
1996     return ret;
1997  oom:
1998     CMP_err("out of memory");
1999     goto err;
2000 }
2001
2002 /*
2003  * write out the given certificate to the output specified by bio.
2004  * Depending on options use either PEM or DER format.
2005  * Returns 1 on success, 0 on error
2006  */
2007 static int write_cert(BIO *bio, X509 *cert)
2008 {
2009     if ((opt_certform == FORMAT_PEM && PEM_write_bio_X509(bio, cert))
2010             || (opt_certform == FORMAT_ASN1 && i2d_X509_bio(bio, cert)))
2011         return 1;
2012     if (opt_certform != FORMAT_PEM && opt_certform != FORMAT_ASN1)
2013         BIO_printf(bio_err,
2014                    "error: unsupported type '%s' for writing certificates\n",
2015                    opt_certform_s);
2016     return 0;
2017 }
2018
2019 /*
2020  * If file != NULL writes out a stack of certs to the given file.
2021  * If certs is NULL, the file is emptied.
2022  * Frees the certs if present.
2023  * Depending on options use either PEM or DER format,
2024  * where DER does not make much sense for writing more than one cert!
2025  * Returns number of written certificates on success, -1 on error.
2026  */
2027 static int save_free_certs(STACK_OF(X509) *certs,
2028                            const char *file, const char *desc)
2029 {
2030     BIO *bio = NULL;
2031     int i;
2032     int n = sk_X509_num(certs /* may be NULL */);
2033
2034     if (n < 0)
2035         n = 0;
2036     if (file == NULL)
2037         goto end;
2038     if (certs != NULL)
2039         CMP_info3("received %d %s certificate(s), saving to file '%s'",
2040                   n, desc, file);
2041     if (n > 1 && opt_certform != FORMAT_PEM)
2042         CMP_warn("saving more than one certificate in non-PEM format");
2043
2044     if ((bio = BIO_new(BIO_s_file())) == NULL
2045             || !BIO_write_filename(bio, (char *)file)) {
2046         CMP_err3("could not open file '%s' for %s %s certificate(s)",
2047                  file, certs == NULL ? "deleting" : "writing", desc);
2048         n = -1;
2049         goto end;
2050     }
2051
2052     for (i = 0; i < n; i++) {
2053         if (!write_cert(bio, sk_X509_value(certs, i))) {
2054             CMP_err2("cannot write %s certificate to file '%s'", desc, file);
2055             n = -1;
2056             goto end;
2057         }
2058     }
2059
2060  end:
2061     BIO_free(bio);
2062     OSSL_STACK_OF_X509_free(certs);
2063     return n;
2064 }
2065
2066 static int delete_file(const char *file, const char *desc)
2067 {
2068     if (file == NULL)
2069         return 1;
2070
2071     if (unlink(file) != 0 && errno != ENOENT) {
2072         CMP_err2("Failed to delete %s, which should be done to indicate there is no %s",
2073                  file, desc);
2074         return 0;
2075     }
2076     return 1;
2077 }
2078
2079 static int save_cert_or_delete(X509 *cert, const char *file, const char *desc)
2080 {
2081     if (file == NULL)
2082         return 1;
2083     if (cert == NULL) {
2084         char desc_cert[80];
2085
2086         BIO_snprintf(desc_cert, sizeof(desc_cert), "%s certificate", desc);
2087         return delete_file(file, desc_cert);
2088     } else {
2089         STACK_OF(X509) *certs = sk_X509_new_null();
2090
2091         if (!X509_add_cert(certs, cert, X509_ADD_FLAG_UP_REF)) {
2092             sk_X509_free(certs);
2093             return 0;
2094         }
2095         return save_free_certs(certs, file, desc) >= 0;
2096     }
2097 }
2098
2099 static int print_itavs(const STACK_OF(OSSL_CMP_ITAV) *itavs)
2100 {
2101     int i, ret = 1;
2102     int n = sk_OSSL_CMP_ITAV_num(itavs);
2103
2104     if (n <= 0) { /* also in case itavs == NULL */
2105         CMP_info("genp does not contain any ITAV");
2106         return ret;
2107     }
2108
2109     for (i = 1; i <= n; i++) {
2110         OSSL_CMP_ITAV *itav = sk_OSSL_CMP_ITAV_value(itavs, i - 1);
2111         ASN1_OBJECT *type = OSSL_CMP_ITAV_get0_type(itav);
2112         char name[80];
2113
2114         if (itav == NULL) {
2115             CMP_err1("could not get ITAV #%d from genp", i);
2116             ret = 0;
2117             continue;
2118         }
2119         if (i2t_ASN1_OBJECT(name, sizeof(name), type) <= 0) {
2120             CMP_err1("error parsing type of ITAV #%d from genp", i);
2121             ret = 0;
2122         }
2123         else {
2124             CMP_info2("ITAV #%d from genp type=%s", i, name);
2125         }
2126     }
2127     return ret;
2128 }
2129
2130 static char opt_item[SECTION_NAME_MAX + 1];
2131 /* get previous name from a comma or space-separated list of names */
2132 static const char *prev_item(const char *opt, const char *end)
2133 {
2134     const char *beg;
2135     size_t len;
2136
2137     if (end == opt)
2138         return NULL;
2139     beg = end;
2140     while (beg > opt) {
2141         --beg;
2142         if (beg[0] == ',' || isspace(beg[0])) {
2143             ++beg;
2144             break;
2145         }
2146     }
2147     len = end - beg;
2148     if (len > SECTION_NAME_MAX) {
2149         CMP_warn3("using only first %d characters of section name starting with \"%.*s\"",
2150                   SECTION_NAME_MAX, SECTION_NAME_MAX, beg);
2151         len = SECTION_NAME_MAX;
2152     }
2153     memcpy(opt_item, beg, len);
2154     opt_item[len] = '\0';
2155     while (beg > opt) {
2156         --beg;
2157         if (beg[0] != ',' && !isspace(beg[0])) {
2158             ++beg;
2159             break;
2160         }
2161     }
2162     return beg;
2163 }
2164
2165 /* get str value for name from a comma-separated hierarchy of config sections */
2166 static char *conf_get_string(const CONF *src_conf, const char *groups,
2167                              const char *name)
2168 {
2169     char *res = NULL;
2170     const char *end = groups + strlen(groups);
2171
2172     while ((end = prev_item(groups, end)) != NULL) {
2173         if ((res = NCONF_get_string(src_conf, opt_item, name)) != NULL)
2174             return res;
2175     }
2176     return res;
2177 }
2178
2179 /* get long val for name from a comma-separated hierarchy of config sections */
2180 static int conf_get_number_e(const CONF *conf_, const char *groups,
2181                              const char *name, long *result)
2182 {
2183     char *str = conf_get_string(conf_, groups, name);
2184     char *tailptr;
2185     long res;
2186
2187     if (str == NULL || *str == '\0')
2188         return 0;
2189
2190     res = strtol(str, &tailptr, 10);
2191     if (res == LONG_MIN || res == LONG_MAX || *tailptr != '\0')
2192         return 0;
2193
2194     *result = res;
2195     return 1;
2196 }
2197
2198 /*
2199  * use the command line option table to read values from the CMP section
2200  * of openssl.cnf.  Defaults are taken from the config file, they can be
2201  * overwritten on the command line.
2202  */
2203 static int read_config(void)
2204 {
2205     unsigned int i;
2206     long num = 0;
2207     char *txt = NULL;
2208     const OPTIONS *opt;
2209     int start_opt = OPT_VERBOSITY - OPT_HELP;
2210     int start_idx = OPT_VERBOSITY - 2;
2211     /*
2212      * starting with offset OPT_VERBOSITY because OPT_CONFIG and OPT_SECTION
2213      * would not make sense within the config file.
2214      */
2215     int n_options = OSSL_NELEM(cmp_options) - 1;
2216
2217     for (opt = &cmp_options[start_opt], i = start_idx;
2218          opt->name != NULL; i++, opt++)
2219         if (!strcmp(opt->name, OPT_SECTION_STR)
2220                 || !strcmp(opt->name, OPT_MORE_STR))
2221             n_options--;
2222     OPENSSL_assert(OSSL_NELEM(cmp_vars) == n_options
2223                    + OPT_PROV__FIRST + 1 - OPT_PROV__LAST
2224                    + OPT_R__FIRST + 1 - OPT_R__LAST
2225                    + OPT_V__FIRST + 1 - OPT_V__LAST);
2226     for (opt = &cmp_options[start_opt], i = start_idx;
2227          opt->name != NULL; i++, opt++) {
2228         int provider_option = (OPT_PROV__FIRST <= opt->retval
2229                                && opt->retval < OPT_PROV__LAST);
2230         int rand_state_option = (OPT_R__FIRST <= opt->retval
2231                                  && opt->retval < OPT_R__LAST);
2232         int verification_option = (OPT_V__FIRST <= opt->retval
2233                                    && opt->retval < OPT_V__LAST);
2234
2235         if (strcmp(opt->name, OPT_SECTION_STR) == 0
2236                 || strcmp(opt->name, OPT_MORE_STR) == 0) {
2237             i--;
2238             continue;
2239         }
2240         if (provider_option || rand_state_option || verification_option)
2241             i--;
2242         switch (opt->valtype) {
2243         case '-':
2244         case 'p':
2245         case 'n':
2246         case 'N':
2247         case 'l':
2248             if (!conf_get_number_e(conf, opt_section, opt->name, &num)) {
2249                 ERR_clear_error();
2250                 continue; /* option not provided */
2251             }
2252             if (opt->valtype == 'p' && num <= 0) {
2253                 opt_printf_stderr("Non-positive number \"%ld\" for config option -%s\n",
2254                                   num, opt->name);
2255                 return -1;
2256             }
2257             if (opt->valtype == 'N' && num < 0) {
2258                 opt_printf_stderr("Negative number \"%ld\" for config option -%s\n",
2259                                   num, opt->name);
2260                 return -1;
2261             }
2262             break;
2263         case 's':
2264         case '>':
2265         case 'M':
2266             txt = conf_get_string(conf, opt_section, opt->name);
2267             if (txt == NULL) {
2268                 ERR_clear_error();
2269                 continue; /* option not provided */
2270             }
2271             break;
2272         default:
2273             CMP_err2("internal: unsupported type '%c' for option '%s'",
2274                      opt->valtype, opt->name);
2275             return 0;
2276             break;
2277         }
2278         if (provider_option || verification_option) {
2279             int conf_argc = 1;
2280             char *conf_argv[3];
2281             char arg1[82];
2282
2283             BIO_snprintf(arg1, 81, "-%s", (char *)opt->name);
2284             conf_argv[0] = prog;
2285             conf_argv[1] = arg1;
2286             if (opt->valtype == '-') {
2287                 if (num != 0)
2288                     conf_argc = 2;
2289             } else {
2290                 conf_argc = 3;
2291                 conf_argv[2] = conf_get_string(conf, opt_section, opt->name);
2292                 /* not NULL */
2293             }
2294             if (conf_argc > 1) {
2295                 (void)opt_init(conf_argc, conf_argv, cmp_options);
2296
2297                 if (provider_option
2298                     ? !opt_provider(opt_next())
2299                     : !opt_verify(opt_next(), vpm)) {
2300                     CMP_err2("for option '%s' in config file section '%s'",
2301                              opt->name, opt_section);
2302                     return 0;
2303                 }
2304             }
2305         } else {
2306             switch (opt->valtype) {
2307             case '-':
2308             case 'p':
2309             case 'n':
2310             case 'N':
2311                 if (num < INT_MIN || INT_MAX < num) {
2312                     BIO_printf(bio_err,
2313                                "integer value out of range for option '%s'\n",
2314                                opt->name);
2315                     return 0;
2316                 }
2317                 *cmp_vars[i].num = (int)num;
2318                 break;
2319             case 'l':
2320                 *cmp_vars[i].num_long = num;
2321                 break;
2322             default:
2323                 if (txt != NULL && txt[0] == '\0')
2324                     txt = NULL; /* reset option on empty string input */
2325                 *cmp_vars[i].txt = txt;
2326                 break;
2327             }
2328         }
2329     }
2330
2331     return 1;
2332 }
2333
2334 static char *opt_str(void)
2335 {
2336     char *arg = opt_arg();
2337
2338     if (arg[0] == '\0') {
2339         CMP_warn1("%s option argument is empty string, resetting option",
2340                   opt_flag());
2341         arg = NULL;
2342     } else if (arg[0] == '-') {
2343         CMP_warn1("%s option argument starts with hyphen", opt_flag());
2344     }
2345     return arg;
2346 }
2347
2348 /* returns 1 on success, 0 on error, -1 on -help (i.e., stop with success) */
2349 static int get_opts(int argc, char **argv)
2350 {
2351     OPTION_CHOICE o;
2352
2353     prog = opt_init(argc, argv, cmp_options);
2354
2355     while ((o = opt_next()) != OPT_EOF) {
2356         switch (o) {
2357         case OPT_EOF:
2358         case OPT_ERR:
2359  opthelp:
2360             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
2361             return 0;
2362         case OPT_HELP:
2363             opt_help(cmp_options);
2364             return -1;
2365         case OPT_CONFIG: /* has already been handled */
2366         case OPT_SECTION: /* has already been handled */
2367             break;
2368         case OPT_VERBOSITY:
2369             if (!set_verbosity(opt_int_arg()))
2370                 goto opthelp;
2371             break;
2372 #ifndef OPENSSL_NO_SOCK
2373         case OPT_SERVER:
2374             opt_server = opt_str();
2375             break;
2376         case OPT_PROXY:
2377             opt_proxy = opt_str();
2378             break;
2379         case OPT_NO_PROXY:
2380             opt_no_proxy = opt_str();
2381             break;
2382 #endif
2383         case OPT_RECIPIENT:
2384             opt_recipient = opt_str();
2385             break;
2386         case OPT_PATH:
2387             opt_path = opt_str();
2388             break;
2389         case OPT_KEEP_ALIVE:
2390             opt_keep_alive = opt_int_arg();
2391             if (opt_keep_alive > 2) {
2392                 CMP_err("-keep_alive argument must be 0, 1, or 2");
2393                 goto opthelp;
2394             }
2395             break;
2396         case OPT_MSG_TIMEOUT:
2397             opt_msg_timeout = opt_int_arg();
2398             break;
2399         case OPT_TOTAL_TIMEOUT:
2400             opt_total_timeout = opt_int_arg();
2401             break;
2402 #ifndef OPENSSL_NO_SOCK
2403         case OPT_TLS_USED:
2404             opt_tls_used = 1;
2405             break;
2406         case OPT_TLS_CERT:
2407             opt_tls_cert = opt_str();
2408             break;
2409         case OPT_TLS_KEY:
2410             opt_tls_key = opt_str();
2411             break;
2412         case OPT_TLS_KEYPASS:
2413             opt_tls_keypass = opt_str();
2414             break;
2415         case OPT_TLS_EXTRA:
2416             opt_tls_extra = opt_str();
2417             break;
2418         case OPT_TLS_TRUSTED:
2419             opt_tls_trusted = opt_str();
2420             break;
2421         case OPT_TLS_HOST:
2422             opt_tls_host = opt_str();
2423             break;
2424 #endif
2425
2426         case OPT_REF:
2427             opt_ref = opt_str();
2428             break;
2429         case OPT_SECRET:
2430             opt_secret = opt_str();
2431             break;
2432         case OPT_CERT:
2433             opt_cert = opt_str();
2434             break;
2435         case OPT_OWN_TRUSTED:
2436             opt_own_trusted = opt_str();
2437             break;
2438         case OPT_KEY:
2439             opt_key = opt_str();
2440             break;
2441         case OPT_KEYPASS:
2442             opt_keypass = opt_str();
2443             break;
2444         case OPT_DIGEST:
2445             opt_digest = opt_str();
2446             break;
2447         case OPT_MAC:
2448             opt_mac = opt_str();
2449             break;
2450         case OPT_EXTRACERTS:
2451             opt_extracerts = opt_str();
2452             break;
2453         case OPT_UNPROTECTED_REQUESTS:
2454             opt_unprotected_requests = 1;
2455             break;
2456
2457         case OPT_TRUSTED:
2458             opt_trusted = opt_str();
2459             break;
2460         case OPT_UNTRUSTED:
2461             opt_untrusted = opt_str();
2462             break;
2463         case OPT_SRVCERT:
2464             opt_srvcert = opt_str();
2465             break;
2466         case OPT_EXPECT_SENDER:
2467             opt_expect_sender = opt_str();
2468             break;
2469         case OPT_IGNORE_KEYUSAGE:
2470             opt_ignore_keyusage = 1;
2471             break;
2472         case OPT_UNPROTECTED_ERRORS:
2473             opt_unprotected_errors = 1;
2474             break;
2475         case OPT_SRVCERTOUT:
2476             opt_srvcertout = opt_str();
2477             break;
2478         case OPT_EXTRACERTSOUT:
2479             opt_extracertsout = opt_str();
2480             break;
2481         case OPT_CACERTSOUT:
2482             opt_cacertsout = opt_str();
2483             break;
2484
2485         case OPT_V_CASES:
2486             if (!opt_verify(o, vpm))
2487                 goto opthelp;
2488             break;
2489         case OPT_CMD:
2490             opt_cmd_s = opt_str();
2491             break;
2492         case OPT_INFOTYPE:
2493             opt_infotype_s = opt_str();
2494             break;
2495         case OPT_GENINFO:
2496             opt_geninfo = opt_str();
2497             break;
2498
2499         case OPT_NEWKEY:
2500             opt_newkey = opt_str();
2501             break;
2502         case OPT_NEWKEYPASS:
2503             opt_newkeypass = opt_str();
2504             break;
2505         case OPT_SUBJECT:
2506             opt_subject = opt_str();
2507             break;
2508         case OPT_ISSUER:
2509             opt_issuer = opt_str();
2510             break;
2511         case OPT_DAYS:
2512             opt_days = opt_int_arg();
2513             break;
2514         case OPT_REQEXTS:
2515             opt_reqexts = opt_str();
2516             break;
2517         case OPT_SANS:
2518             opt_sans = opt_str();
2519             break;
2520         case OPT_SAN_NODEFAULT:
2521             opt_san_nodefault = 1;
2522             break;
2523         case OPT_POLICIES:
2524             opt_policies = opt_str();
2525             break;
2526         case OPT_POLICY_OIDS:
2527             opt_policy_oids = opt_str();
2528             break;
2529         case OPT_POLICY_OIDS_CRITICAL:
2530             opt_policy_oids_critical = 1;
2531             break;
2532         case OPT_POPO:
2533             opt_popo = opt_int_arg();
2534             if (opt_popo < OSSL_CRMF_POPO_NONE
2535                     || opt_popo > OSSL_CRMF_POPO_KEYENC) {
2536                 CMP_err("invalid popo spec. Valid values are -1 .. 2");
2537                 goto opthelp;
2538             }
2539             break;
2540         case OPT_CSR:
2541             opt_csr = opt_arg();
2542             break;
2543         case OPT_OUT_TRUSTED:
2544             opt_out_trusted = opt_str();
2545             break;
2546         case OPT_IMPLICIT_CONFIRM:
2547             opt_implicit_confirm = 1;
2548             break;
2549         case OPT_DISABLE_CONFIRM:
2550             opt_disable_confirm = 1;
2551             break;
2552         case OPT_CERTOUT:
2553             opt_certout = opt_str();
2554             break;
2555         case OPT_CHAINOUT:
2556             opt_chainout = opt_str();
2557             break;
2558         case OPT_OLDCERT:
2559             opt_oldcert = opt_str();
2560             break;
2561         case OPT_REVREASON:
2562             opt_revreason = opt_int_arg();
2563             if (opt_revreason < CRL_REASON_NONE
2564                     || opt_revreason > CRL_REASON_AA_COMPROMISE
2565                     || opt_revreason == 7) {
2566                 CMP_err("invalid revreason. Valid values are -1 .. 6, 8 .. 10");
2567                 goto opthelp;
2568             }
2569             break;
2570         case OPT_CERTFORM:
2571             opt_certform_s = opt_str();
2572             break;
2573         case OPT_KEYFORM:
2574             opt_keyform_s = opt_str();
2575             break;
2576         case OPT_OTHERPASS:
2577             opt_otherpass = opt_str();
2578             break;
2579 #ifndef OPENSSL_NO_ENGINE
2580         case OPT_ENGINE:
2581             opt_engine = opt_str();
2582             break;
2583 #endif
2584         case OPT_PROV_CASES:
2585             if (!opt_provider(o))
2586                 goto opthelp;
2587             break;
2588         case OPT_R_CASES:
2589             if (!opt_rand(o))
2590                 goto opthelp;
2591             break;
2592
2593         case OPT_BATCH:
2594             opt_batch = 1;
2595             break;
2596         case OPT_REPEAT:
2597             opt_repeat = opt_int_arg();
2598             break;
2599         case OPT_REQIN:
2600             opt_reqin = opt_str();
2601             break;
2602         case OPT_REQIN_NEW_TID:
2603             opt_reqin_new_tid = 1;
2604             break;
2605         case OPT_REQOUT:
2606             opt_reqout = opt_str();
2607             break;
2608         case OPT_RSPIN:
2609             opt_rspin = opt_str();
2610             break;
2611         case OPT_RSPOUT:
2612             opt_rspout = opt_str();
2613             break;
2614         case OPT_USE_MOCK_SRV:
2615             opt_use_mock_srv = 1;
2616             break;
2617
2618 #ifndef OPENSSL_NO_SOCK
2619         case OPT_PORT:
2620             opt_port = opt_str();
2621             break;
2622         case OPT_MAX_MSGS:
2623             opt_max_msgs = opt_int_arg();
2624             break;
2625 #endif
2626         case OPT_SRV_REF:
2627             opt_srv_ref = opt_str();
2628             break;
2629         case OPT_SRV_SECRET:
2630             opt_srv_secret = opt_str();
2631             break;
2632         case OPT_SRV_CERT:
2633             opt_srv_cert = opt_str();
2634             break;
2635         case OPT_SRV_KEY:
2636             opt_srv_key = opt_str();
2637             break;
2638         case OPT_SRV_KEYPASS:
2639             opt_srv_keypass = opt_str();
2640             break;
2641         case OPT_SRV_TRUSTED:
2642             opt_srv_trusted = opt_str();
2643             break;
2644         case OPT_SRV_UNTRUSTED:
2645             opt_srv_untrusted = opt_str();
2646             break;
2647         case OPT_REF_CERT:
2648             opt_ref_cert = opt_str();
2649             break;
2650         case OPT_RSP_CERT:
2651             opt_rsp_cert = opt_str();
2652             break;
2653         case OPT_RSP_EXTRACERTS:
2654             opt_rsp_extracerts = opt_str();
2655             break;
2656         case OPT_RSP_CAPUBS:
2657             opt_rsp_capubs = opt_str();
2658             break;
2659         case OPT_POLL_COUNT:
2660             opt_poll_count = opt_int_arg();
2661             break;
2662         case OPT_CHECK_AFTER:
2663             opt_check_after = opt_int_arg();
2664             break;
2665         case OPT_GRANT_IMPLICITCONF:
2666             opt_grant_implicitconf = 1;
2667             break;
2668         case OPT_PKISTATUS:
2669             opt_pkistatus = opt_int_arg();
2670             break;
2671         case OPT_FAILURE:
2672             opt_failure = opt_int_arg();
2673             break;
2674         case OPT_FAILUREBITS:
2675             opt_failurebits = opt_int_arg();
2676             break;
2677         case OPT_STATUSSTRING:
2678             opt_statusstring = opt_str();
2679             break;
2680         case OPT_SEND_ERROR:
2681             opt_send_error = 1;
2682             break;
2683         case OPT_SEND_UNPROTECTED:
2684             opt_send_unprotected = 1;
2685             break;
2686         case OPT_SEND_UNPROT_ERR:
2687             opt_send_unprot_err = 1;
2688             break;
2689         case OPT_ACCEPT_UNPROTECTED:
2690             opt_accept_unprotected = 1;
2691             break;
2692         case OPT_ACCEPT_UNPROT_ERR:
2693             opt_accept_unprot_err = 1;
2694             break;
2695         case OPT_ACCEPT_RAVERIFIED:
2696             opt_accept_raverified = 1;
2697             break;
2698         }
2699     }
2700
2701     /* No extra args. */
2702     if (!opt_check_rest_arg(NULL))
2703         goto opthelp;
2704     return 1;
2705 }
2706
2707 #ifndef OPENSSL_NO_SOCK
2708 static int cmp_server(OSSL_CMP_CTX *srv_cmp_ctx)
2709 {
2710     BIO *acbio;
2711     BIO *cbio = NULL;
2712     int keep_alive = 0;
2713     int msgs = 0;
2714     int retry = 1;
2715     int ret = 1;
2716
2717     if ((acbio = http_server_init(prog, opt_port, opt_verbosity)) == NULL)
2718         return 0;
2719     while (opt_max_msgs <= 0 || msgs < opt_max_msgs) {
2720         char *path = NULL;
2721         OSSL_CMP_MSG *req = NULL;
2722         OSSL_CMP_MSG *resp = NULL;
2723
2724         ret = http_server_get_asn1_req(ASN1_ITEM_rptr(OSSL_CMP_MSG),
2725                                        (ASN1_VALUE **)&req, &path,
2726                                        &cbio, acbio, &keep_alive,
2727                                        prog, 0, 0);
2728         if (ret == 0) { /* no request yet */
2729             if (retry) {
2730                 OSSL_sleep(1000);
2731                 retry = 0;
2732                 continue;
2733             }
2734             ret = 0;
2735             goto next;
2736         }
2737         if (ret++ == -1) /* fatal error */
2738             break;
2739
2740         ret = 0;
2741         msgs++;
2742         if (req != NULL) {
2743             if (strcmp(path, "") != 0 && strcmp(path, "pkix/") != 0) {
2744                 (void)http_server_send_status(prog, cbio, 404, "Not Found");
2745                 CMP_err1("expecting empty path or 'pkix/' but got '%s'",
2746                          path);
2747                 OPENSSL_free(path);
2748                 OSSL_CMP_MSG_free(req);
2749                 goto next;
2750             }
2751             OPENSSL_free(path);
2752             resp = OSSL_CMP_CTX_server_perform(cmp_ctx, req);
2753             OSSL_CMP_MSG_free(req);
2754             if (resp == NULL) {
2755                 (void)http_server_send_status(prog, cbio,
2756                                               500, "Internal Server Error");
2757                 break; /* treated as fatal error */
2758             }
2759             ret = http_server_send_asn1_resp(prog, cbio, keep_alive,
2760                                              "application/pkixcmp",
2761                                              ASN1_ITEM_rptr(OSSL_CMP_MSG),
2762                                              (const ASN1_VALUE *)resp);
2763             OSSL_CMP_MSG_free(resp);
2764             if (!ret)
2765                 break; /* treated as fatal error */
2766         }
2767     next:
2768         if (!ret) { /* on transmission error, cancel CMP transaction */
2769             (void)OSSL_CMP_CTX_set1_transactionID(srv_cmp_ctx, NULL);
2770             (void)OSSL_CMP_CTX_set1_senderNonce(srv_cmp_ctx, NULL);
2771         }
2772         if (!ret || !keep_alive
2773             || OSSL_CMP_CTX_get_status(srv_cmp_ctx) != OSSL_CMP_PKISTATUS_trans
2774             /* transaction closed by OSSL_CMP_CTX_server_perform() */) {
2775             BIO_free_all(cbio);
2776             cbio = NULL;
2777         }
2778     }
2779
2780     BIO_free_all(cbio);
2781     BIO_free_all(acbio);
2782     return ret;
2783 }
2784 #endif
2785
2786 static void print_status(void)
2787 {
2788     /* print PKIStatusInfo */
2789     int status = OSSL_CMP_CTX_get_status(cmp_ctx);
2790     char *buf = app_malloc(OSSL_CMP_PKISI_BUFLEN, "PKIStatusInfo buf");
2791     const char *string =
2792         OSSL_CMP_CTX_snprint_PKIStatus(cmp_ctx, buf, OSSL_CMP_PKISI_BUFLEN);
2793     const char *from = "", *server = "";
2794
2795 #ifndef OPENSSL_NO_SOCK
2796     if (opt_server != NULL) {
2797         from = " from ";
2798         server = opt_server;
2799     }
2800 #endif
2801     CMP_print(bio_err,
2802               status == OSSL_CMP_PKISTATUS_accepted
2803               ? OSSL_CMP_LOG_INFO :
2804               status == OSSL_CMP_PKISTATUS_rejection
2805               || status == OSSL_CMP_PKISTATUS_waiting
2806               ? OSSL_CMP_LOG_ERR : OSSL_CMP_LOG_WARNING,
2807               status == OSSL_CMP_PKISTATUS_accepted ? "info" :
2808               status == OSSL_CMP_PKISTATUS_rejection ? "server error" :
2809               status == OSSL_CMP_PKISTATUS_waiting ? "internal error"
2810               : "warning", "received%s%s %s", from, server,
2811               string != NULL ? string : "<unknown PKIStatus>");
2812     OPENSSL_free(buf);
2813 }
2814
2815 int cmp_main(int argc, char **argv)
2816 {
2817     char *configfile = NULL;
2818     int i;
2819     X509 *newcert = NULL;
2820     ENGINE *engine = NULL;
2821     OSSL_CMP_CTX *srv_cmp_ctx = NULL;
2822     int ret = 0; /* default: failure */
2823
2824     prog = opt_appname(argv[0]);
2825     if (argc <= 1) {
2826         opt_help(cmp_options);
2827         goto err;
2828     }
2829
2830     /*
2831      * handle options -config, -section, and -verbosity upfront
2832      * to take effect for other options
2833      */
2834     for (i = 1; i < argc - 1; i++) {
2835         if (*argv[i] == '-') {
2836             if (!strcmp(argv[i] + 1, cmp_options[OPT_CONFIG - OPT_HELP].name))
2837                 opt_config = argv[++i];
2838             else if (!strcmp(argv[i] + 1,
2839                              cmp_options[OPT_SECTION - OPT_HELP].name))
2840                 opt_section = argv[++i];
2841             else if (strcmp(argv[i] + 1,
2842                             cmp_options[OPT_VERBOSITY - OPT_HELP].name) == 0
2843                      && !set_verbosity(atoi(argv[++i])))
2844                 goto err;
2845         }
2846     }
2847     if (opt_section[0] == '\0') /* empty string */
2848         opt_section = DEFAULT_SECTION;
2849
2850     vpm = X509_VERIFY_PARAM_new();
2851     if (vpm == NULL) {
2852         CMP_err("out of memory");
2853         goto err;
2854     }
2855
2856     /* read default values for options from config file */
2857     configfile = opt_config != NULL ? opt_config : default_config_file;
2858     if (configfile != NULL && configfile[0] != '\0' /* non-empty string */
2859             && (configfile != default_config_file
2860                 || access(configfile, F_OK) != -1)) {
2861         CMP_info2("using section(s) '%s' of OpenSSL configuration file '%s'",
2862                   opt_section, configfile);
2863         conf = app_load_config(configfile);
2864         if (conf == NULL) {
2865             goto err;
2866         } else {
2867             if (strcmp(opt_section, CMP_SECTION) == 0) { /* default */
2868                 if (!NCONF_get_section(conf, opt_section))
2869                     CMP_info2("no [%s] section found in config file '%s';"
2870                               " will thus use just [default] and unnamed section if present",
2871                               opt_section, configfile);
2872             } else {
2873                 const char *end = opt_section + strlen(opt_section);
2874
2875                 while ((end = prev_item(opt_section, end)) != NULL) {
2876                     if (!NCONF_get_section(conf, opt_item)) {
2877                         CMP_err2("no [%s] section found in config file '%s'",
2878                                  opt_item, configfile);
2879                         goto err;
2880                     }
2881                 }
2882             }
2883             ret = read_config();
2884             if (!set_verbosity(opt_verbosity)) /* just for checking range */
2885                 ret = -1;
2886             if (ret <= 0) {
2887                 if (ret == -1)
2888                     BIO_printf(bio_err, "Use -help for summary.\n");
2889                 goto err;
2890             }
2891         }
2892     }
2893     (void)BIO_flush(bio_err); /* prevent interference with opt_help() */
2894
2895     ret = get_opts(argc, argv);
2896     if (ret <= 0)
2897         goto err;
2898
2899     ret = 0;
2900     if (!app_RAND_load())
2901         goto err;
2902
2903     if (opt_batch)
2904         set_base_ui_method(UI_null());
2905
2906     if (opt_engine != NULL) {
2907         engine = setup_engine_methods(opt_engine,
2908                                       0 /* not: ENGINE_METHOD_ALL */, 0);
2909         if (engine == NULL) {
2910             CMP_err1("cannot load engine %s", opt_engine);
2911             goto err;
2912         }
2913     }
2914
2915     cmp_ctx = OSSL_CMP_CTX_new(app_get0_libctx(), app_get0_propq());
2916     if (cmp_ctx == NULL)
2917         goto err;
2918     OSSL_CMP_CTX_set_log_verbosity(cmp_ctx, opt_verbosity);
2919     if (!OSSL_CMP_CTX_set_log_cb(cmp_ctx, print_to_bio_out)) {
2920         CMP_err1("cannot set up error reporting and logging for %s", prog);
2921         goto err;
2922     }
2923
2924 #ifndef OPENSSL_NO_SOCK
2925     if (opt_tls_cert == NULL && opt_tls_key == NULL && opt_tls_keypass == NULL
2926             && opt_tls_extra == NULL && opt_tls_trusted == NULL
2927             && opt_tls_host == NULL) {
2928         if (opt_tls_used)
2929             CMP_warn("-tls_used given without any other TLS options");
2930     } else if (!opt_tls_used) {
2931         CMP_warn("ignoring TLS options(s) since -tls_used is not given");
2932     }
2933     if (opt_port != NULL) {
2934         if (opt_tls_used) {
2935             CMP_err("-tls_used option not supported with -port option");
2936             goto err;
2937         }
2938         if (opt_server != NULL || opt_use_mock_srv) {
2939             CMP_err("The -port option excludes -server and -use_mock_srv");
2940             goto err;
2941         }
2942         if (opt_reqin != NULL || opt_reqout != NULL) {
2943             CMP_err("The -port option does not support -reqin and -reqout");
2944             goto err;
2945         }
2946         if (opt_rspin != NULL || opt_rspout != NULL) {
2947             CMP_err("The -port option does not support -rspin and -rspout");
2948             goto err;
2949         }
2950     }
2951     if (opt_server != NULL && opt_use_mock_srv) {
2952         CMP_err("cannot use both -server and -use_mock_srv options");
2953         goto err;
2954     }
2955 #endif
2956
2957     if (opt_use_mock_srv
2958 #ifndef OPENSSL_NO_SOCK
2959         || opt_port != NULL
2960 #endif
2961         ) {
2962         OSSL_CMP_SRV_CTX *srv_ctx;
2963
2964         if ((srv_ctx = setup_srv_ctx(engine)) == NULL)
2965             goto err;
2966         srv_cmp_ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx);
2967         OSSL_CMP_CTX_set_transfer_cb_arg(cmp_ctx, srv_ctx);
2968         if (!OSSL_CMP_CTX_set_log_cb(srv_cmp_ctx, print_to_bio_err)) {
2969             CMP_err1("cannot set up error reporting and logging for %s", prog);
2970             goto err;
2971         }
2972         OSSL_CMP_CTX_set_log_verbosity(srv_cmp_ctx, opt_verbosity);
2973     }
2974
2975 #ifndef OPENSSL_NO_SOCK
2976     if (opt_tls_used && (opt_use_mock_srv || opt_server == NULL)) {
2977         CMP_warn("ignoring -tls_used option since -use_mock_srv is given or -server is not given");
2978         opt_tls_used = 0;
2979     }
2980
2981     if (opt_port != NULL) { /* act as very basic CMP HTTP server */
2982         ret = cmp_server(srv_cmp_ctx);
2983         goto err;
2984     }
2985
2986     /* act as CMP client, possibly using internal mock server */
2987
2988     if (opt_rspin != NULL) {
2989         if (opt_server != NULL)
2990             CMP_warn("-server option is not used if enough filenames given for -rspin");
2991         if (opt_use_mock_srv)
2992             CMP_warn("-use_mock_srv option is not used if enough filenames given for -rspin");
2993     }
2994 #endif
2995
2996     if (!setup_client_ctx(cmp_ctx, engine)) {
2997         CMP_err("cannot set up CMP context");
2998         goto err;
2999     }
3000     for (i = 0; i < opt_repeat; i++) {
3001         /* everything is ready, now connect and perform the command! */
3002         switch (opt_cmd) {
3003         case CMP_IR:
3004             newcert = OSSL_CMP_exec_IR_ses(cmp_ctx);
3005             if (newcert != NULL)
3006                 ret = 1;
3007             break;
3008         case CMP_KUR:
3009             newcert = OSSL_CMP_exec_KUR_ses(cmp_ctx);
3010             if (newcert != NULL)
3011                 ret = 1;
3012             break;
3013         case CMP_CR:
3014             newcert = OSSL_CMP_exec_CR_ses(cmp_ctx);
3015             if (newcert != NULL)
3016                 ret = 1;
3017             break;
3018         case CMP_P10CR:
3019             newcert = OSSL_CMP_exec_P10CR_ses(cmp_ctx);
3020             if (newcert != NULL)
3021                 ret = 1;
3022             break;
3023         case CMP_RR:
3024             ret = OSSL_CMP_exec_RR_ses(cmp_ctx);
3025             break;
3026         case CMP_GENM:
3027             {
3028                 STACK_OF(OSSL_CMP_ITAV) *itavs;
3029
3030                 if (opt_infotype != NID_undef) {
3031                     OSSL_CMP_ITAV *itav =
3032                         OSSL_CMP_ITAV_create(OBJ_nid2obj(opt_infotype), NULL);
3033
3034                     if (itav == NULL)
3035                         goto err;
3036                     OSSL_CMP_CTX_push0_genm_ITAV(cmp_ctx, itav);
3037                 }
3038
3039                 if ((itavs = OSSL_CMP_exec_GENM_ses(cmp_ctx)) != NULL) {
3040                     ret = print_itavs(itavs);
3041                     sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free);
3042                 } else {
3043                     CMP_err("could not obtain ITAVs from genp");
3044                 }
3045                 break;
3046             }
3047         default:
3048             break;
3049         }
3050         if (OSSL_CMP_CTX_get_status(cmp_ctx) < OSSL_CMP_PKISTATUS_accepted) {
3051             ret = 0;
3052             goto err; /* we got no response, maybe even did not send request */
3053         }
3054         print_status();
3055         if (!save_cert_or_delete(OSSL_CMP_CTX_get0_validatedSrvCert(cmp_ctx),
3056                                  opt_srvcertout, "validated server"))
3057             ret = 0;
3058         if (!ret)
3059             goto err;
3060         ret = 0;
3061         if (save_free_certs(OSSL_CMP_CTX_get1_extraCertsIn(cmp_ctx),
3062                             opt_extracertsout, "extra") < 0)
3063             goto err;
3064         if (newcert != NULL && (opt_cmd == CMP_IR || opt_cmd == CMP_CR
3065                                 || opt_cmd == CMP_KUR || opt_cmd == CMP_P10CR))
3066             if (!save_cert_or_delete(newcert, opt_certout, "newly enrolled")
3067                 || save_free_certs(OSSL_CMP_CTX_get1_newChain(cmp_ctx),
3068                                    opt_chainout, "chain") < 0
3069                 || save_free_certs(OSSL_CMP_CTX_get1_caPubs(cmp_ctx),
3070                                    opt_cacertsout, "CA") < 0)
3071                 goto err;
3072         if (!OSSL_CMP_CTX_reinit(cmp_ctx))
3073             goto err;
3074     }
3075     ret = 1;
3076
3077  err:
3078     /* in case we ended up here on error without proper cleaning */
3079     cleanse(opt_keypass);
3080     cleanse(opt_newkeypass);
3081     cleanse(opt_otherpass);
3082 #ifndef OPENSSL_NO_SOCK
3083     cleanse(opt_tls_keypass);
3084 #endif
3085     cleanse(opt_secret);
3086     cleanse(opt_srv_keypass);
3087     cleanse(opt_srv_secret);
3088
3089     if (ret != 1)
3090         OSSL_CMP_CTX_print_errors(cmp_ctx);
3091
3092     if (cmp_ctx != NULL) {
3093 #ifndef OPENSSL_NO_SOCK
3094         APP_HTTP_TLS_INFO *info = OSSL_CMP_CTX_get_http_cb_arg(cmp_ctx);
3095
3096 #endif
3097         ossl_cmp_mock_srv_free(OSSL_CMP_CTX_get_transfer_cb_arg(cmp_ctx));
3098         X509_STORE_free(OSSL_CMP_CTX_get_certConf_cb_arg(cmp_ctx));
3099         /* cannot free info already here, as it may be used indirectly by: */
3100         OSSL_CMP_CTX_free(cmp_ctx);
3101 #ifndef OPENSSL_NO_SOCK
3102         APP_HTTP_TLS_INFO_free(info);
3103 #endif
3104     }
3105     X509_VERIFY_PARAM_free(vpm);
3106     release_engine(engine);
3107
3108     NCONF_free(conf); /* must not do as long as opt_... variables are used */
3109     OSSL_CMP_log_close();
3110
3111     return ret == 0 ? EXIT_FAILURE : EXIT_SUCCESS; /* ret == -1 for -help */
3112 }