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