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