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