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