2 * Copyright 2001-2019 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include <openssl/opensslconf.h>
12 #ifdef OPENSSL_NO_OCSP
13 NON_EMPTY_TRANSLATION_UNIT
15 # ifdef OPENSSL_SYS_VMS
16 # define _XOPEN_SOURCE_EXTENDED/* So fd_set and friends get properly defined
26 /* Needs to be included before the openssl headers */
29 # include "internal/sockets.h"
30 # include <openssl/e_os2.h>
31 # include <openssl/crypto.h>
32 # include <openssl/err.h>
33 # include <openssl/ssl.h>
34 # include <openssl/evp.h>
35 # include <openssl/bn.h>
36 # include <openssl/x509v3.h>
37 # include <openssl/rand.h>
40 # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS)
53 # if !defined(NO_FORK) && !defined(OPENSSL_NO_SOCK) \
54 && !defined(OPENSSL_NO_POSIX_IO)
56 # include <sys/types.h>
57 # include <sys/wait.h>
60 # define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
66 # define LOG_WARNING 1
70 # if defined(OPENSSL_SYS_VXWORKS)
72 int setpgid(pid_t pid
, pid_t pgid
)
84 /* Maximum leeway in validity period: default 5 minutes */
85 # define MAX_VALIDITY_PERIOD (5 * 60)
87 static int add_ocsp_cert(OCSP_REQUEST
**req
, X509
*cert
,
88 const EVP_MD
*cert_id_md
, X509
*issuer
,
89 STACK_OF(OCSP_CERTID
) *ids
);
90 static int add_ocsp_serial(OCSP_REQUEST
**req
, char *serial
,
91 const EVP_MD
*cert_id_md
, X509
*issuer
,
92 STACK_OF(OCSP_CERTID
) *ids
);
93 static void print_ocsp_summary(BIO
*out
, OCSP_BASICRESP
*bs
, OCSP_REQUEST
*req
,
94 STACK_OF(OPENSSL_STRING
) *names
,
95 STACK_OF(OCSP_CERTID
) *ids
, long nsec
,
97 static void make_ocsp_response(BIO
*err
, OCSP_RESPONSE
**resp
, OCSP_REQUEST
*req
,
98 CA_DB
*db
, STACK_OF(X509
) *ca
, X509
*rcert
,
99 EVP_PKEY
*rkey
, const EVP_MD
*md
,
100 STACK_OF(OPENSSL_STRING
) *sigopts
,
101 STACK_OF(X509
) *rother
, unsigned long flags
,
102 int nmin
, int ndays
, int badsig
);
104 static char **lookup_serial(CA_DB
*db
, ASN1_INTEGER
*ser
);
105 static BIO
*init_responder(const char *port
);
106 static int do_responder(OCSP_REQUEST
**preq
, BIO
**pcbio
, BIO
*acbio
, int timeout
);
107 static int send_ocsp_response(BIO
*cbio
, OCSP_RESPONSE
*resp
);
108 static void log_message(int level
, const char *fmt
, ...);
110 static int multi
= 0;
113 static int acfd
= (int) INVALID_SOCKET
;
114 static int index_changed(CA_DB
*);
115 static void spawn_loop(void);
116 static int print_syslog(const char *str
, size_t len
, void *levPtr
);
117 static void socket_timeout(int signum
);
120 # ifndef OPENSSL_NO_SOCK
121 static OCSP_RESPONSE
*query_responder(BIO
*cbio
, const char *host
,
123 const STACK_OF(CONF_VALUE
) *headers
,
124 OCSP_REQUEST
*req
, int req_timeout
);
127 typedef enum OPTION_choice
{
128 OPT_ERR
= -1, OPT_EOF
= 0, OPT_HELP
,
129 OPT_OUTFILE
, OPT_TIMEOUT
, OPT_URL
, OPT_HOST
, OPT_PORT
,
130 OPT_IGNORE_ERR
, OPT_NOVERIFY
, OPT_NONCE
, OPT_NO_NONCE
,
131 OPT_RESP_NO_CERTS
, OPT_RESP_KEY_ID
, OPT_NO_CERTS
,
132 OPT_NO_SIGNATURE_VERIFY
, OPT_NO_CERT_VERIFY
, OPT_NO_CHAIN
,
133 OPT_NO_CERT_CHECKS
, OPT_NO_EXPLICIT
, OPT_TRUST_OTHER
,
134 OPT_NO_INTERN
, OPT_BADSIG
, OPT_TEXT
, OPT_REQ_TEXT
, OPT_RESP_TEXT
,
135 OPT_REQIN
, OPT_RESPIN
, OPT_SIGNER
, OPT_VAFILE
, OPT_SIGN_OTHER
,
136 OPT_VERIFY_OTHER
, OPT_CAFILE
, OPT_CAPATH
, OPT_NOCAFILE
, OPT_NOCAPATH
,
137 OPT_VALIDITY_PERIOD
, OPT_STATUS_AGE
, OPT_SIGNKEY
, OPT_REQOUT
,
138 OPT_RESPOUT
, OPT_PATH
, OPT_ISSUER
, OPT_CERT
, OPT_SERIAL
,
139 OPT_INDEX
, OPT_CA
, OPT_NMIN
, OPT_REQUEST
, OPT_NDAYS
, OPT_RSIGNER
,
140 OPT_RKEY
, OPT_ROTHER
, OPT_RMD
, OPT_RSIGOPT
, OPT_HEADER
,
146 const OPTIONS ocsp_options
[] = {
147 {"help", OPT_HELP
, '-', "Display this summary"},
148 {"out", OPT_OUTFILE
, '>', "Output filename"},
149 {"timeout", OPT_TIMEOUT
, 'p',
150 "Connection timeout (in seconds) to the OCSP responder"},
151 {"url", OPT_URL
, 's', "Responder URL"},
152 {"host", OPT_HOST
, 's', "TCP/IP hostname:port to connect to"},
153 {"port", OPT_PORT
, 'p', "Port to run responder on"},
154 {"ignore_err", OPT_IGNORE_ERR
, '-',
155 "Ignore error on OCSP request or response and continue running"},
156 {"noverify", OPT_NOVERIFY
, '-', "Don't verify response at all"},
157 {"nonce", OPT_NONCE
, '-', "Add OCSP nonce to request"},
158 {"no_nonce", OPT_NO_NONCE
, '-', "Don't add OCSP nonce to request"},
159 {"resp_no_certs", OPT_RESP_NO_CERTS
, '-',
160 "Don't include any certificates in response"},
161 {"resp_key_id", OPT_RESP_KEY_ID
, '-',
162 "Identify response by signing certificate key ID"},
164 {"multi", OPT_MULTI
, 'p', "run multiple responder processes"},
166 {"no_certs", OPT_NO_CERTS
, '-',
167 "Don't include any certificates in signed request"},
168 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY
, '-',
169 "Don't check signature on response"},
170 {"no_cert_verify", OPT_NO_CERT_VERIFY
, '-',
171 "Don't check signing certificate"},
172 {"no_chain", OPT_NO_CHAIN
, '-', "Don't chain verify response"},
173 {"no_cert_checks", OPT_NO_CERT_CHECKS
, '-',
174 "Don't do additional checks on signing certificate"},
175 {"no_explicit", OPT_NO_EXPLICIT
, '-',
176 "Do not explicitly check the chain, just verify the root"},
177 {"trust_other", OPT_TRUST_OTHER
, '-',
178 "Don't verify additional certificates"},
179 {"no_intern", OPT_NO_INTERN
, '-',
180 "Don't search certificates contained in response for signer"},
181 {"badsig", OPT_BADSIG
, '-',
182 "Corrupt last byte of loaded OSCP response signature (for test)"},
183 {"text", OPT_TEXT
, '-', "Print text form of request and response"},
184 {"req_text", OPT_REQ_TEXT
, '-', "Print text form of request"},
185 {"resp_text", OPT_RESP_TEXT
, '-', "Print text form of response"},
186 {"reqin", OPT_REQIN
, 's', "File with the DER-encoded request"},
187 {"respin", OPT_RESPIN
, 's', "File with the DER-encoded response"},
188 {"signer", OPT_SIGNER
, '<', "Certificate to sign OCSP request with"},
189 {"VAfile", OPT_VAFILE
, '<', "Validator certificates file"},
190 {"sign_other", OPT_SIGN_OTHER
, '<',
191 "Additional certificates to include in signed request"},
192 {"verify_other", OPT_VERIFY_OTHER
, '<',
193 "Additional certificates to search for signer"},
194 {"CAfile", OPT_CAFILE
, '<', "Trusted certificates file"},
195 {"CApath", OPT_CAPATH
, '<', "Trusted certificates directory"},
196 {"no-CAfile", OPT_NOCAFILE
, '-',
197 "Do not load the default certificates file"},
198 {"no-CApath", OPT_NOCAPATH
, '-',
199 "Do not load certificates from the default certificates directory"},
200 {"validity_period", OPT_VALIDITY_PERIOD
, 'u',
201 "Maximum validity discrepancy in seconds"},
202 {"status_age", OPT_STATUS_AGE
, 'p', "Maximum status age in seconds"},
203 {"signkey", OPT_SIGNKEY
, 's', "Private key to sign OCSP request with"},
204 {"reqout", OPT_REQOUT
, 's', "Output file for the DER-encoded request"},
205 {"respout", OPT_RESPOUT
, 's', "Output file for the DER-encoded response"},
206 {"path", OPT_PATH
, 's', "Path to use in OCSP request"},
207 {"issuer", OPT_ISSUER
, '<', "Issuer certificate"},
208 {"cert", OPT_CERT
, '<', "Certificate to check"},
209 {"serial", OPT_SERIAL
, 's', "Serial number to check"},
210 {"index", OPT_INDEX
, '<', "Certificate status index file"},
211 {"CA", OPT_CA
, '<', "CA certificate"},
212 {"nmin", OPT_NMIN
, 'p', "Number of minutes before next update"},
213 {"nrequest", OPT_REQUEST
, 'p',
214 "Number of requests to accept (default unlimited)"},
215 {"ndays", OPT_NDAYS
, 'p', "Number of days before next update"},
216 {"rsigner", OPT_RSIGNER
, '<',
217 "Responder certificate to sign responses with"},
218 {"rkey", OPT_RKEY
, '<', "Responder key to sign responses with"},
219 {"rother", OPT_ROTHER
, '<', "Other certificates to include in response"},
220 {"rmd", OPT_RMD
, 's', "Digest Algorithm to use in signature of OCSP response"},
221 {"rsigopt", OPT_RSIGOPT
, 's', "OCSP response signature parameter in n:v form"},
222 {"header", OPT_HEADER
, 's', "key=value header to add"},
223 {"", OPT_MD
, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
228 int ocsp_main(int argc
, char **argv
)
230 BIO
*acbio
= NULL
, *cbio
= NULL
, *derbio
= NULL
, *out
= NULL
;
231 const EVP_MD
*cert_id_md
= NULL
, *rsign_md
= NULL
;
232 STACK_OF(OPENSSL_STRING
) *rsign_sigopts
= NULL
;
235 EVP_PKEY
*key
= NULL
, *rkey
= NULL
;
236 OCSP_BASICRESP
*bs
= NULL
;
237 OCSP_REQUEST
*req
= NULL
;
238 OCSP_RESPONSE
*resp
= NULL
;
239 STACK_OF(CONF_VALUE
) *headers
= NULL
;
240 STACK_OF(OCSP_CERTID
) *ids
= NULL
;
241 STACK_OF(OPENSSL_STRING
) *reqnames
= NULL
;
242 STACK_OF(X509
) *sign_other
= NULL
, *verify_other
= NULL
, *rother
= NULL
;
243 STACK_OF(X509
) *issuers
= NULL
;
244 X509
*issuer
= NULL
, *cert
= NULL
;
245 STACK_OF(X509
) *rca_cert
= NULL
;
246 X509
*signer
= NULL
, *rsigner
= NULL
;
247 X509_STORE
*store
= NULL
;
248 X509_VERIFY_PARAM
*vpm
= NULL
;
249 const char *CAfile
= NULL
, *CApath
= NULL
;
250 char *header
, *value
;
251 char *host
= NULL
, *port
= NULL
, *path
= "/", *outfile
= NULL
;
252 char *rca_filename
= NULL
, *reqin
= NULL
, *respin
= NULL
;
253 char *reqout
= NULL
, *respout
= NULL
, *ridx_filename
= NULL
;
254 char *rsignfile
= NULL
, *rkeyfile
= NULL
;
255 char *sign_certfile
= NULL
, *verify_certfile
= NULL
, *rcertfile
= NULL
;
256 char *signfile
= NULL
, *keyfile
= NULL
;
257 char *thost
= NULL
, *tport
= NULL
, *tpath
= NULL
;
258 int noCAfile
= 0, noCApath
= 0;
259 int accept_count
= -1, add_nonce
= 1, noverify
= 0, use_ssl
= -1;
260 int vpmtouched
= 0, badsig
= 0, i
, ignore_err
= 0, nmin
= 0, ndays
= -1;
261 int req_text
= 0, resp_text
= 0, ret
= 1;
262 int req_timeout
= -1;
263 long nsec
= MAX_VALIDITY_PERIOD
, maxage
= -1;
264 unsigned long sign_flags
= 0, verify_flags
= 0, rflags
= 0;
267 reqnames
= sk_OPENSSL_STRING_new_null();
268 if (reqnames
== NULL
)
270 ids
= sk_OCSP_CERTID_new_null();
273 if ((vpm
= X509_VERIFY_PARAM_new()) == NULL
)
276 prog
= opt_init(argc
, argv
, ocsp_options
);
277 while ((o
= opt_next()) != OPT_EOF
) {
282 BIO_printf(bio_err
, "%s: Use -help for summary.\n", prog
);
286 opt_help(ocsp_options
);
292 #ifndef OPENSSL_NO_SOCK
293 req_timeout
= atoi(opt_arg());
300 thost
= tport
= tpath
= NULL
;
301 if (!OCSP_parse_url(opt_arg(), &host
, &port
, &path
, &use_ssl
)) {
302 BIO_printf(bio_err
, "%s Error parsing URL\n", prog
);
327 case OPT_RESP_NO_CERTS
:
328 rflags
|= OCSP_NOCERTS
;
330 case OPT_RESP_KEY_ID
:
331 rflags
|= OCSP_RESPID_KEY
;
334 sign_flags
|= OCSP_NOCERTS
;
336 case OPT_NO_SIGNATURE_VERIFY
:
337 verify_flags
|= OCSP_NOSIGS
;
339 case OPT_NO_CERT_VERIFY
:
340 verify_flags
|= OCSP_NOVERIFY
;
343 verify_flags
|= OCSP_NOCHAIN
;
345 case OPT_NO_CERT_CHECKS
:
346 verify_flags
|= OCSP_NOCHECKS
;
348 case OPT_NO_EXPLICIT
:
349 verify_flags
|= OCSP_NOEXPLICIT
;
351 case OPT_TRUST_OTHER
:
352 verify_flags
|= OCSP_TRUSTOTHER
;
355 verify_flags
|= OCSP_NOINTERN
;
361 req_text
= resp_text
= 1;
376 signfile
= opt_arg();
379 verify_certfile
= opt_arg();
380 verify_flags
|= OCSP_TRUSTOTHER
;
383 sign_certfile
= opt_arg();
385 case OPT_VERIFY_OTHER
:
386 verify_certfile
= opt_arg();
401 if (!opt_verify(o
, vpm
))
405 case OPT_VALIDITY_PERIOD
:
406 opt_long(opt_arg(), &nsec
);
409 opt_long(opt_arg(), &maxage
);
424 issuer
= load_cert(opt_arg(), FORMAT_PEM
, "issuer certificate");
427 if (issuers
== NULL
) {
428 if ((issuers
= sk_X509_new_null()) == NULL
)
431 sk_X509_push(issuers
, issuer
);
435 cert
= load_cert(opt_arg(), FORMAT_PEM
, "certificate");
438 if (cert_id_md
== NULL
)
439 cert_id_md
= EVP_sha1();
440 if (!add_ocsp_cert(&req
, cert
, cert_id_md
, issuer
, ids
))
442 if (!sk_OPENSSL_STRING_push(reqnames
, opt_arg()))
447 if (cert_id_md
== NULL
)
448 cert_id_md
= EVP_sha1();
449 if (!add_ocsp_serial(&req
, opt_arg(), cert_id_md
, issuer
, ids
))
451 if (!sk_OPENSSL_STRING_push(reqnames
, opt_arg()))
456 ridx_filename
= opt_arg();
459 rca_filename
= opt_arg();
462 opt_int(opt_arg(), &nmin
);
467 opt_int(opt_arg(), &accept_count
);
470 ndays
= atoi(opt_arg());
473 rsignfile
= opt_arg();
476 rkeyfile
= opt_arg();
479 rcertfile
= opt_arg();
481 case OPT_RMD
: /* Response MessageDigest */
482 if (!opt_md(opt_arg(), &rsign_md
))
486 if (rsign_sigopts
== NULL
)
487 rsign_sigopts
= sk_OPENSSL_STRING_new_null();
488 if (rsign_sigopts
== NULL
|| !sk_OPENSSL_STRING_push(rsign_sigopts
, opt_arg()))
493 value
= strchr(header
, '=');
495 BIO_printf(bio_err
, "Missing = in header key=value\n");
499 if (!X509V3_add_value(header
, value
, &headers
))
505 "%s: Digest must be before -cert or -serial\n",
509 if (!opt_md(opt_unknown(), &cert_id_md
))
515 multi
= atoi(opt_arg());
521 BIO_printf(bio_err
, "%s: Digest must be before -cert or -serial\n",
525 argc
= opt_num_rest();
529 /* Have we anything to do? */
530 if (req
== NULL
&& reqin
== NULL
531 && respin
== NULL
&& !(port
!= NULL
&& ridx_filename
!= NULL
))
534 out
= bio_open_default(outfile
, 'w', FORMAT_TEXT
);
538 if (req
== NULL
&& (add_nonce
!= 2))
541 if (req
== NULL
&& reqin
!= NULL
) {
542 derbio
= bio_open_default(reqin
, 'r', FORMAT_ASN1
);
545 req
= d2i_OCSP_REQUEST_bio(derbio
, NULL
);
548 BIO_printf(bio_err
, "Error reading OCSP request\n");
553 if (req
== NULL
&& port
!= NULL
) {
554 acbio
= init_responder(port
);
559 if (rsignfile
!= NULL
) {
560 if (rkeyfile
== NULL
)
561 rkeyfile
= rsignfile
;
562 rsigner
= load_cert(rsignfile
, FORMAT_PEM
, "responder certificate");
563 if (rsigner
== NULL
) {
564 BIO_printf(bio_err
, "Error loading responder certificate\n");
567 if (!load_certs(rca_filename
, &rca_cert
, FORMAT_PEM
,
568 NULL
, "CA certificate"))
570 if (rcertfile
!= NULL
) {
571 if (!load_certs(rcertfile
, &rother
, FORMAT_PEM
, NULL
,
572 "responder other certificates"))
575 rkey
= load_key(rkeyfile
, FORMAT_PEM
, 0, NULL
, NULL
,
576 "responder private key");
581 if (ridx_filename
!= NULL
582 && (rkey
== NULL
|| rsigner
== NULL
|| rca_cert
== NULL
)) {
584 "Responder mode requires certificate, key, and CA.\n");
588 if (ridx_filename
!= NULL
) {
589 rdb
= load_index(ridx_filename
, NULL
);
590 if (rdb
== NULL
|| index_index(rdb
) <= 0) {
597 if (multi
&& acbio
!= NULL
)
599 if (acbio
!= NULL
&& req_timeout
> 0)
600 signal(SIGALRM
, socket_timeout
);
604 log_message(LOG_INFO
, "waiting for OCSP client connections...");
610 if (index_changed(rdb
)) {
611 CA_DB
*newrdb
= load_index(ridx_filename
, NULL
);
613 if (newrdb
!= NULL
&& index_index(newrdb
) > 0) {
618 log_message(LOG_ERR
, "error reloading updated index: %s",
625 if (!do_responder(&req
, &cbio
, acbio
, req_timeout
))
630 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST
,
632 send_ocsp_response(cbio
, resp
);
638 && (signfile
!= NULL
|| reqout
!= NULL
639 || host
!= NULL
|| add_nonce
|| ridx_filename
!= NULL
)) {
640 BIO_printf(bio_err
, "Need an OCSP request for this operation!\n");
644 if (req
!= NULL
&& add_nonce
) {
645 if (!OCSP_request_add1_nonce(req
, NULL
, -1))
649 if (signfile
!= NULL
) {
652 signer
= load_cert(signfile
, FORMAT_PEM
, "signer certificate");
653 if (signer
== NULL
) {
654 BIO_printf(bio_err
, "Error loading signer certificate\n");
657 if (sign_certfile
!= NULL
) {
658 if (!load_certs(sign_certfile
, &sign_other
, FORMAT_PEM
, NULL
,
659 "signer certificates"))
662 key
= load_key(keyfile
, FORMAT_PEM
, 0, NULL
, NULL
,
663 "signer private key");
667 if (!OCSP_request_sign
668 (req
, signer
, key
, NULL
, sign_other
, sign_flags
)) {
669 BIO_printf(bio_err
, "Error signing OCSP request\n");
674 if (req_text
&& req
!= NULL
)
675 OCSP_REQUEST_print(out
, req
, 0);
677 if (reqout
!= NULL
) {
678 derbio
= bio_open_default(reqout
, 'w', FORMAT_ASN1
);
681 i2d_OCSP_REQUEST_bio(derbio
, req
);
686 make_ocsp_response(bio_err
, &resp
, req
, rdb
, rca_cert
, rsigner
, rkey
,
687 rsign_md
, rsign_sigopts
, rother
, rflags
, nmin
, ndays
, badsig
);
689 send_ocsp_response(cbio
, resp
);
690 } else if (host
!= NULL
) {
691 # ifndef OPENSSL_NO_SOCK
692 resp
= process_responder(req
, host
, path
,
693 port
, use_ssl
, headers
, req_timeout
);
698 "Error creating connect BIO - sockets not supported.\n");
701 } else if (respin
!= NULL
) {
702 derbio
= bio_open_default(respin
, 'r', FORMAT_ASN1
);
705 resp
= d2i_OCSP_RESPONSE_bio(derbio
, NULL
);
708 BIO_printf(bio_err
, "Error reading OCSP response\n");
718 if (respout
!= NULL
) {
719 derbio
= bio_open_default(respout
, 'w', FORMAT_ASN1
);
722 i2d_OCSP_RESPONSE_bio(derbio
, resp
);
726 i
= OCSP_response_status(resp
);
727 if (i
!= OCSP_RESPONSE_STATUS_SUCCESSFUL
) {
728 BIO_printf(out
, "Responder Error: %s (%d)\n",
729 OCSP_response_status_str(i
), i
);
735 OCSP_RESPONSE_print(out
, resp
, 0);
737 /* If running as responder don't verify our own response */
739 /* If not unlimited, see if we took all we should. */
740 if (accept_count
!= -1 && --accept_count
<= 0) {
746 OCSP_REQUEST_free(req
);
748 OCSP_RESPONSE_free(resp
);
752 if (ridx_filename
!= NULL
) {
758 store
= setup_verify(CAfile
, CApath
, noCAfile
, noCApath
);
763 X509_STORE_set1_param(store
, vpm
);
764 if (verify_certfile
!= NULL
) {
765 if (!load_certs(verify_certfile
, &verify_other
, FORMAT_PEM
, NULL
,
766 "validator certificate"))
770 bs
= OCSP_response_get1_basic(resp
);
772 BIO_printf(bio_err
, "Error parsing response\n");
779 if (req
!= NULL
&& ((i
= OCSP_check_nonce(req
, bs
)) <= 0)) {
781 BIO_printf(bio_err
, "WARNING: no nonce in response\n");
783 BIO_printf(bio_err
, "Nonce Verify error\n");
789 i
= OCSP_basic_verify(bs
, verify_other
, store
, verify_flags
);
790 if (i
<= 0 && issuers
) {
791 i
= OCSP_basic_verify(bs
, issuers
, store
, OCSP_TRUSTOTHER
);
796 BIO_printf(bio_err
, "Response Verify Failure\n");
797 ERR_print_errors(bio_err
);
800 BIO_printf(bio_err
, "Response verify OK\n");
804 print_ocsp_summary(out
, bs
, req
, reqnames
, ids
, nsec
, maxage
);
807 ERR_print_errors(bio_err
);
809 X509_STORE_free(store
);
810 X509_VERIFY_PARAM_free(vpm
);
811 sk_OPENSSL_STRING_free(rsign_sigopts
);
815 sk_X509_pop_free(issuers
, X509_free
);
817 sk_X509_pop_free(rca_cert
, X509_free
);
822 OCSP_REQUEST_free(req
);
823 OCSP_RESPONSE_free(resp
);
824 OCSP_BASICRESP_free(bs
);
825 sk_OPENSSL_STRING_free(reqnames
);
826 sk_OCSP_CERTID_free(ids
);
827 sk_X509_pop_free(sign_other
, X509_free
);
828 sk_X509_pop_free(verify_other
, X509_free
);
829 sk_CONF_VALUE_pop_free(headers
, X509V3_conf_free
);
838 log_message(int level
, const char *fmt
, ...)
846 if (vsnprintf(buf
, sizeof(buf
), fmt
, ap
) > 0) {
847 syslog(level
, "%s", buf
);
849 if (level
>= LOG_ERR
)
850 ERR_print_errors_cb(print_syslog
, &level
);
854 BIO_printf(bio_err
, "%s: ", prog
);
855 BIO_vprintf(bio_err
, fmt
, ap
);
856 BIO_printf(bio_err
, "\n");
863 static int print_syslog(const char *str
, size_t len
, void *levPtr
)
865 int level
= *(int *)levPtr
;
866 int ilen
= (len
> MAXERRLEN
) ? MAXERRLEN
: len
;
868 syslog(level
, "%.*s", ilen
, str
);
873 static int index_changed(CA_DB
*rdb
)
877 if (rdb
!= NULL
&& stat(rdb
->dbfname
, &sb
) != -1) {
878 if (rdb
->dbst
.st_mtime
!= sb
.st_mtime
879 || rdb
->dbst
.st_ctime
!= sb
.st_ctime
880 || rdb
->dbst
.st_ino
!= sb
.st_ino
881 || rdb
->dbst
.st_dev
!= sb
.st_dev
) {
882 syslog(LOG_INFO
, "index file changed, reloading");
889 static void killall(int ret
, pid_t
*kidpids
)
893 for (i
= 0; i
< multi
; ++i
)
895 (void)kill(kidpids
[i
], SIGTERM
);
896 OPENSSL_free(kidpids
);
901 static int termsig
= 0;
903 static void noteterm (int sig
)
909 * Loop spawning up to `multi` child processes, only child processes return
910 * from this function. The parent process loops until receiving a termination
911 * signal, kills extant children and exits without returning.
913 static void spawn_loop(void)
915 pid_t
*kidpids
= NULL
;
920 openlog(prog
, LOG_PID
, LOG_DAEMON
);
923 syslog(LOG_ERR
, "fatal: error detaching from parent process group: %s",
927 kidpids
= app_malloc(multi
* sizeof(*kidpids
), "child PID array");
928 for (i
= 0; i
< multi
; ++i
)
931 signal(SIGINT
, noteterm
);
932 signal(SIGTERM
, noteterm
);
934 while (termsig
== 0) {
938 * Wait for a child to replace when we're at the limit.
939 * Slow down if a child exited abnormally or waitpid() < 0
941 while (termsig
== 0 && procs
>= multi
) {
942 if ((fpid
= waitpid(-1, &status
, 0)) > 0) {
943 for (i
= 0; i
< procs
; ++i
) {
944 if (kidpids
[i
] == fpid
) {
951 syslog(LOG_ERR
, "fatal: internal error: "
952 "no matching child slot for pid: %ld",
957 if (WIFEXITED(status
))
958 syslog(LOG_WARNING
, "child process: %ld, exit status: %d",
959 (long)fpid
, WEXITSTATUS(status
));
960 else if (WIFSIGNALED(status
))
961 syslog(LOG_WARNING
, "child process: %ld, term signal %d%s",
962 (long)fpid
, WTERMSIG(status
),
964 WCOREDUMP(status
) ? " (core dumped)" :
970 } else if (errno
!= EINTR
) {
971 syslog(LOG_ERR
, "fatal: waitpid(): %s", strerror(errno
));
978 switch(fpid
= fork()) {
980 /* System critically low on memory, pause and try again later */
984 OPENSSL_free(kidpids
);
985 signal(SIGINT
, SIG_DFL
);
986 signal(SIGTERM
, SIG_DFL
);
989 if (RAND_poll() <= 0) {
990 syslog(LOG_ERR
, "fatal: RAND_poll() failed");
994 default: /* parent */
995 for (i
= 0; i
< multi
; ++i
) {
996 if (kidpids
[i
] == 0) {
1003 syslog(LOG_ERR
, "fatal: internal error: no free child slots");
1004 killall(1, kidpids
);
1010 /* The loop above can only break on termsig */
1011 syslog(LOG_INFO
, "terminating on signal: %d", termsig
);
1012 killall(0, kidpids
);
1016 static int add_ocsp_cert(OCSP_REQUEST
**req
, X509
*cert
,
1017 const EVP_MD
*cert_id_md
, X509
*issuer
,
1018 STACK_OF(OCSP_CERTID
) *ids
)
1022 if (issuer
== NULL
) {
1023 BIO_printf(bio_err
, "No issuer certificate specified\n");
1027 *req
= OCSP_REQUEST_new();
1030 id
= OCSP_cert_to_id(cert_id_md
, cert
, issuer
);
1031 if (id
== NULL
|| !sk_OCSP_CERTID_push(ids
, id
))
1033 if (!OCSP_request_add0_id(*req
, id
))
1038 BIO_printf(bio_err
, "Error Creating OCSP request\n");
1042 static int add_ocsp_serial(OCSP_REQUEST
**req
, char *serial
,
1043 const EVP_MD
*cert_id_md
, X509
*issuer
,
1044 STACK_OF(OCSP_CERTID
) *ids
)
1048 ASN1_BIT_STRING
*ikey
;
1051 if (issuer
== NULL
) {
1052 BIO_printf(bio_err
, "No issuer certificate specified\n");
1056 *req
= OCSP_REQUEST_new();
1059 iname
= X509_get_subject_name(issuer
);
1060 ikey
= X509_get0_pubkey_bitstr(issuer
);
1061 sno
= s2i_ASN1_INTEGER(NULL
, serial
);
1063 BIO_printf(bio_err
, "Error converting serial number %s\n", serial
);
1066 id
= OCSP_cert_id_new(cert_id_md
, iname
, ikey
, sno
);
1067 ASN1_INTEGER_free(sno
);
1068 if (id
== NULL
|| !sk_OCSP_CERTID_push(ids
, id
))
1070 if (!OCSP_request_add0_id(*req
, id
))
1075 BIO_printf(bio_err
, "Error Creating OCSP request\n");
1079 static void print_ocsp_summary(BIO
*out
, OCSP_BASICRESP
*bs
, OCSP_REQUEST
*req
,
1080 STACK_OF(OPENSSL_STRING
) *names
,
1081 STACK_OF(OCSP_CERTID
) *ids
, long nsec
,
1086 int i
, status
, reason
;
1087 ASN1_GENERALIZEDTIME
*rev
, *thisupd
, *nextupd
;
1089 if (bs
== NULL
|| req
== NULL
|| !sk_OPENSSL_STRING_num(names
)
1090 || !sk_OCSP_CERTID_num(ids
))
1093 for (i
= 0; i
< sk_OCSP_CERTID_num(ids
); i
++) {
1094 id
= sk_OCSP_CERTID_value(ids
, i
);
1095 name
= sk_OPENSSL_STRING_value(names
, i
);
1096 BIO_printf(out
, "%s: ", name
);
1098 if (!OCSP_resp_find_status(bs
, id
, &status
, &reason
,
1099 &rev
, &thisupd
, &nextupd
)) {
1100 BIO_puts(out
, "ERROR: No Status found.\n");
1105 * Check validity: if invalid write to output BIO so we know which
1106 * response this refers to.
1108 if (!OCSP_check_validity(thisupd
, nextupd
, nsec
, maxage
)) {
1109 BIO_puts(out
, "WARNING: Status times invalid.\n");
1110 ERR_print_errors(out
);
1112 BIO_printf(out
, "%s\n", OCSP_cert_status_str(status
));
1114 BIO_puts(out
, "\tThis Update: ");
1115 ASN1_GENERALIZEDTIME_print(out
, thisupd
);
1116 BIO_puts(out
, "\n");
1119 BIO_puts(out
, "\tNext Update: ");
1120 ASN1_GENERALIZEDTIME_print(out
, nextupd
);
1121 BIO_puts(out
, "\n");
1124 if (status
!= V_OCSP_CERTSTATUS_REVOKED
)
1128 BIO_printf(out
, "\tReason: %s\n", OCSP_crl_reason_str(reason
));
1130 BIO_puts(out
, "\tRevocation Time: ");
1131 ASN1_GENERALIZEDTIME_print(out
, rev
);
1132 BIO_puts(out
, "\n");
1136 static void make_ocsp_response(BIO
*err
, OCSP_RESPONSE
**resp
, OCSP_REQUEST
*req
,
1137 CA_DB
*db
, STACK_OF(X509
) *ca
, X509
*rcert
,
1138 EVP_PKEY
*rkey
, const EVP_MD
*rmd
,
1139 STACK_OF(OPENSSL_STRING
) *sigopts
,
1140 STACK_OF(X509
) *rother
, unsigned long flags
,
1141 int nmin
, int ndays
, int badsig
)
1143 ASN1_TIME
*thisupd
= NULL
, *nextupd
= NULL
;
1145 OCSP_BASICRESP
*bs
= NULL
;
1147 EVP_MD_CTX
*mctx
= NULL
;
1148 EVP_PKEY_CTX
*pkctx
= NULL
;
1150 id_count
= OCSP_request_onereq_count(req
);
1152 if (id_count
<= 0) {
1154 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST
, NULL
);
1158 bs
= OCSP_BASICRESP_new();
1159 thisupd
= X509_gmtime_adj(NULL
, 0);
1161 nextupd
= X509_time_adj_ex(NULL
, ndays
, nmin
* 60, NULL
);
1163 /* Examine each certificate id in the request */
1164 for (i
= 0; i
< id_count
; i
++) {
1166 ASN1_INTEGER
*serial
;
1170 ASN1_OBJECT
*cert_id_md_oid
;
1171 const EVP_MD
*cert_id_md
;
1172 one
= OCSP_request_onereq_get0(req
, i
);
1173 cid
= OCSP_onereq_get0_id(one
);
1175 OCSP_id_get0_info(NULL
, &cert_id_md_oid
, NULL
, NULL
, cid
);
1177 cert_id_md
= EVP_get_digestbyobj(cert_id_md_oid
);
1178 if (cert_id_md
== NULL
) {
1179 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR
,
1183 for (jj
= 0; jj
< sk_X509_num(ca
) && !found
; jj
++) {
1184 X509
*ca_cert
= sk_X509_value(ca
, jj
);
1185 OCSP_CERTID
*ca_id
= OCSP_cert_to_id(cert_id_md
, NULL
, ca_cert
);
1187 if (OCSP_id_issuer_cmp(ca_id
, cid
) == 0)
1190 OCSP_CERTID_free(ca_id
);
1194 OCSP_basic_add1_status(bs
, cid
,
1195 V_OCSP_CERTSTATUS_UNKNOWN
,
1196 0, NULL
, thisupd
, nextupd
);
1199 OCSP_id_get0_info(NULL
, NULL
, NULL
, &serial
, cid
);
1200 inf
= lookup_serial(db
, serial
);
1202 OCSP_basic_add1_status(bs
, cid
,
1203 V_OCSP_CERTSTATUS_UNKNOWN
,
1204 0, NULL
, thisupd
, nextupd
);
1205 } else if (inf
[DB_type
][0] == DB_TYPE_VAL
) {
1206 OCSP_basic_add1_status(bs
, cid
,
1207 V_OCSP_CERTSTATUS_GOOD
,
1208 0, NULL
, thisupd
, nextupd
);
1209 } else if (inf
[DB_type
][0] == DB_TYPE_REV
) {
1210 ASN1_OBJECT
*inst
= NULL
;
1211 ASN1_TIME
*revtm
= NULL
;
1212 ASN1_GENERALIZEDTIME
*invtm
= NULL
;
1213 OCSP_SINGLERESP
*single
;
1215 unpack_revinfo(&revtm
, &reason
, &inst
, &invtm
, inf
[DB_rev_date
]);
1216 single
= OCSP_basic_add1_status(bs
, cid
,
1217 V_OCSP_CERTSTATUS_REVOKED
,
1218 reason
, revtm
, thisupd
, nextupd
);
1220 OCSP_SINGLERESP_add1_ext_i2d(single
, NID_invalidity_date
,
1222 else if (inst
!= NULL
)
1223 OCSP_SINGLERESP_add1_ext_i2d(single
,
1224 NID_hold_instruction_code
, inst
,
1226 ASN1_OBJECT_free(inst
);
1227 ASN1_TIME_free(revtm
);
1228 ASN1_GENERALIZEDTIME_free(invtm
);
1232 OCSP_copy_nonce(bs
, req
);
1234 mctx
= EVP_MD_CTX_new();
1235 if ( mctx
== NULL
|| !EVP_DigestSignInit(mctx
, &pkctx
, rmd
, NULL
, rkey
)) {
1236 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR
, NULL
);
1239 for (i
= 0; i
< sk_OPENSSL_STRING_num(sigopts
); i
++) {
1240 char *sigopt
= sk_OPENSSL_STRING_value(sigopts
, i
);
1242 if (pkey_ctrl_string(pkctx
, sigopt
) <= 0) {
1243 BIO_printf(err
, "parameter error \"%s\"\n", sigopt
);
1244 ERR_print_errors(bio_err
);
1245 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR
,
1250 if (!OCSP_basic_sign_ctx(bs
, rcert
, mctx
, rother
, flags
)) {
1251 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR
, bs
);
1256 const ASN1_OCTET_STRING
*sig
= OCSP_resp_get0_signature(bs
);
1257 corrupt_signature(sig
);
1260 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL
, bs
);
1263 EVP_MD_CTX_free(mctx
);
1264 ASN1_TIME_free(thisupd
);
1265 ASN1_TIME_free(nextupd
);
1266 OCSP_BASICRESP_free(bs
);
1269 static char **lookup_serial(CA_DB
*db
, ASN1_INTEGER
*ser
)
1273 char *itmp
, *row
[DB_NUMBER
], **rrow
;
1274 for (i
= 0; i
< DB_NUMBER
; i
++)
1276 bn
= ASN1_INTEGER_to_BN(ser
, NULL
);
1277 OPENSSL_assert(bn
); /* FIXME: should report an error at this
1278 * point and abort */
1280 itmp
= OPENSSL_strdup("00");
1282 itmp
= BN_bn2hex(bn
);
1283 row
[DB_serial
] = itmp
;
1285 rrow
= TXT_DB_get_by_index(db
->db
, DB_serial
, row
);
1290 /* Quick and dirty OCSP server: read in and parse input request */
1292 static BIO
*init_responder(const char *port
)
1294 # ifdef OPENSSL_NO_SOCK
1296 "Error setting up accept BIO - sockets not supported.\n");
1299 BIO
*acbio
= NULL
, *bufbio
= NULL
;
1301 bufbio
= BIO_new(BIO_f_buffer());
1304 acbio
= BIO_new(BIO_s_accept());
1306 || BIO_set_bind_mode(acbio
, BIO_BIND_REUSEADDR
) < 0
1307 || BIO_set_accept_port(acbio
, port
) < 0) {
1308 log_message(LOG_ERR
, "Error setting up accept BIO");
1312 BIO_set_accept_bios(acbio
, bufbio
);
1314 if (BIO_do_accept(acbio
) <= 0) {
1315 log_message(LOG_ERR
, "Error starting accept");
1322 BIO_free_all(acbio
);
1328 # ifndef OPENSSL_NO_SOCK
1330 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1332 static int urldecode(char *p
)
1334 unsigned char *out
= (unsigned char *)p
;
1335 unsigned char *save
= out
;
1340 else if (isxdigit(_UC(p
[1])) && isxdigit(_UC(p
[2]))) {
1341 /* Don't check, can't fail because of ixdigit() call. */
1342 *out
++ = (OPENSSL_hexchar2int(p
[1]) << 4)
1343 | OPENSSL_hexchar2int(p
[2]);
1350 return (int)(out
- save
);
1355 static void socket_timeout(int signum
)
1357 if (acfd
!= (int)INVALID_SOCKET
)
1358 (void)shutdown(acfd
, SHUT_RD
);
1362 static int do_responder(OCSP_REQUEST
**preq
, BIO
**pcbio
, BIO
*acbio
,
1365 # ifdef OPENSSL_NO_SOCK
1369 OCSP_REQUEST
*req
= NULL
;
1370 char inbuf
[2048], reqbuf
[2048];
1372 BIO
*cbio
= NULL
, *getbio
= NULL
, *b64
= NULL
;
1377 /* Connection loss before accept() is routine, ignore silently */
1378 if (BIO_do_accept(acbio
) <= 0)
1381 cbio
= BIO_pop(acbio
);
1383 client
= BIO_get_peer_name(cbio
);
1387 (void) BIO_get_fd(cbio
, &acfd
);
1392 /* Read the request line. */
1393 len
= BIO_gets(cbio
, reqbuf
, sizeof(reqbuf
));
1397 if (strncmp(reqbuf
, "GET ", 4) == 0) {
1398 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1399 for (p
= reqbuf
+ 4; *p
== ' '; ++p
)
1402 log_message(LOG_INFO
, "Invalid request -- bad URL: %s", client
);
1407 /* Splice off the HTTP version identifier. */
1408 for (q
= p
; *q
; q
++)
1411 if (strncmp(q
, " HTTP/1.", 8) != 0) {
1412 log_message(LOG_INFO
,
1413 "Invalid request -- bad HTTP version: %s", client
);
1419 * Skip "GET / HTTP..." requests often used by load-balancers. Note:
1420 * 'p' was incremented above to point to the first byte *after* the
1421 * leading slash, so with 'GET / ' it is now an empty string.
1428 log_message(LOG_INFO
,
1429 "Invalid request -- bad URL encoding: %s", client
);
1432 if ((getbio
= BIO_new_mem_buf(p
, len
)) == NULL
1433 || (b64
= BIO_new(BIO_f_base64())) == NULL
) {
1434 log_message(LOG_ERR
, "Could not allocate base64 bio: %s", client
);
1437 BIO_set_flags(b64
, BIO_FLAGS_BASE64_NO_NL
);
1438 getbio
= BIO_push(b64
, getbio
);
1439 } else if (strncmp(reqbuf
, "POST ", 5) != 0) {
1440 log_message(LOG_INFO
, "Invalid request -- bad HTTP verb: %s", client
);
1444 /* Read and skip past the headers. */
1446 len
= BIO_gets(cbio
, inbuf
, sizeof(inbuf
));
1449 if ((inbuf
[0] == '\r') || (inbuf
[0] == '\n'))
1454 /* Clear alarm before we close the client socket */
1459 /* Try to read OCSP request */
1460 if (getbio
!= NULL
) {
1461 req
= d2i_OCSP_REQUEST_bio(getbio
, NULL
);
1462 BIO_free_all(getbio
);
1464 req
= d2i_OCSP_REQUEST_bio(cbio
, NULL
);
1468 log_message(LOG_ERR
, "Error parsing OCSP request");
1476 acfd
= (int)INVALID_SOCKET
;
1482 static int send_ocsp_response(BIO
*cbio
, OCSP_RESPONSE
*resp
)
1485 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1486 "Content-Length: %d\r\n\r\n";
1489 BIO_printf(cbio
, http_resp
, i2d_OCSP_RESPONSE(resp
, NULL
));
1490 i2d_OCSP_RESPONSE_bio(cbio
, resp
);
1491 (void)BIO_flush(cbio
);
1495 # ifndef OPENSSL_NO_SOCK
1496 static OCSP_RESPONSE
*query_responder(BIO
*cbio
, const char *host
,
1498 const STACK_OF(CONF_VALUE
) *headers
,
1499 OCSP_REQUEST
*req
, int req_timeout
)
1505 OCSP_REQ_CTX
*ctx
= NULL
;
1506 OCSP_RESPONSE
*rsp
= NULL
;
1510 if (req_timeout
!= -1)
1511 BIO_set_nbio(cbio
, 1);
1513 rv
= BIO_do_connect(cbio
);
1515 if ((rv
<= 0) && ((req_timeout
== -1) || !BIO_should_retry(cbio
))) {
1516 BIO_puts(bio_err
, "Error connecting BIO\n");
1520 if (BIO_get_fd(cbio
, &fd
) < 0) {
1521 BIO_puts(bio_err
, "Can't get connection fd\n");
1525 if (req_timeout
!= -1 && rv
<= 0) {
1527 openssl_fdset(fd
, &confds
);
1529 tv
.tv_sec
= req_timeout
;
1530 rv
= select(fd
+ 1, NULL
, (void *)&confds
, NULL
, &tv
);
1532 BIO_puts(bio_err
, "Timeout on connect\n");
1537 ctx
= OCSP_sendreq_new(cbio
, path
, NULL
, -1);
1541 for (i
= 0; i
< sk_CONF_VALUE_num(headers
); i
++) {
1542 CONF_VALUE
*hdr
= sk_CONF_VALUE_value(headers
, i
);
1543 if (add_host
== 1 && strcasecmp("host", hdr
->name
) == 0)
1545 if (!OCSP_REQ_CTX_add1_header(ctx
, hdr
->name
, hdr
->value
))
1549 if (add_host
== 1 && OCSP_REQ_CTX_add1_header(ctx
, "Host", host
) == 0)
1552 if (!OCSP_REQ_CTX_set1_req(ctx
, req
))
1556 rv
= OCSP_sendreq_nbio(&rsp
, ctx
);
1559 if (req_timeout
== -1)
1562 openssl_fdset(fd
, &confds
);
1564 tv
.tv_sec
= req_timeout
;
1565 if (BIO_should_read(cbio
)) {
1566 rv
= select(fd
+ 1, (void *)&confds
, NULL
, NULL
, &tv
);
1567 } else if (BIO_should_write(cbio
)) {
1568 rv
= select(fd
+ 1, NULL
, (void *)&confds
, NULL
, &tv
);
1570 BIO_puts(bio_err
, "Unexpected retry condition\n");
1574 BIO_puts(bio_err
, "Timeout on request\n");
1578 BIO_puts(bio_err
, "Select error\n");
1584 OCSP_REQ_CTX_free(ctx
);
1589 OCSP_RESPONSE
*process_responder(OCSP_REQUEST
*req
,
1590 const char *host
, const char *path
,
1591 const char *port
, int use_ssl
,
1592 STACK_OF(CONF_VALUE
) *headers
,
1596 SSL_CTX
*ctx
= NULL
;
1597 OCSP_RESPONSE
*resp
= NULL
;
1599 cbio
= BIO_new_connect(host
);
1601 BIO_printf(bio_err
, "Error creating connect BIO\n");
1605 BIO_set_conn_port(cbio
, port
);
1608 ctx
= SSL_CTX_new(TLS_client_method());
1610 BIO_printf(bio_err
, "Error creating SSL context.\n");
1613 SSL_CTX_set_mode(ctx
, SSL_MODE_AUTO_RETRY
);
1614 sbio
= BIO_new_ssl(ctx
, 1);
1615 cbio
= BIO_push(sbio
, cbio
);
1618 resp
= query_responder(cbio
, host
, path
, headers
, req
, req_timeout
);
1620 BIO_printf(bio_err
, "Error querying OCSP responder\n");