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