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