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