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