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