2 * Copyright 2001-2018 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>
39 # if defined(OPENSSL_SYS_UNIX) && !defined(OPENSSL_NO_SOCK) \
40 && !defined(OPENSSL_NO_POSIX_IO)
42 # include <sys/types.h>
43 # include <sys/wait.h>
46 # define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
52 # define LOG_WARNING 1
56 # if defined(OPENSSL_SYS_VXWORKS)
58 int setpgid(pid_t pid
, pid_t pgid
)
70 /* Maximum leeway in validity period: default 5 minutes */
71 # define MAX_VALIDITY_PERIOD (5 * 60)
73 static int add_ocsp_cert(OCSP_REQUEST
**req
, X509
*cert
,
74 const EVP_MD
*cert_id_md
, X509
*issuer
,
75 STACK_OF(OCSP_CERTID
) *ids
);
76 static int add_ocsp_serial(OCSP_REQUEST
**req
, char *serial
,
77 const EVP_MD
*cert_id_md
, X509
*issuer
,
78 STACK_OF(OCSP_CERTID
) *ids
);
79 static void print_ocsp_summary(BIO
*out
, OCSP_BASICRESP
*bs
, OCSP_REQUEST
*req
,
80 STACK_OF(OPENSSL_STRING
) *names
,
81 STACK_OF(OCSP_CERTID
) *ids
, long nsec
,
83 static void make_ocsp_response(BIO
*err
, OCSP_RESPONSE
**resp
, OCSP_REQUEST
*req
,
84 CA_DB
*db
, STACK_OF(X509
) *ca
, X509
*rcert
,
85 EVP_PKEY
*rkey
, const EVP_MD
*md
,
86 STACK_OF(OPENSSL_STRING
) *sigopts
,
87 STACK_OF(X509
) *rother
, unsigned long flags
,
88 int nmin
, int ndays
, int badsig
);
90 static char **lookup_serial(CA_DB
*db
, ASN1_INTEGER
*ser
);
91 static BIO
*init_responder(const char *port
);
92 static int do_responder(OCSP_REQUEST
**preq
, BIO
**pcbio
, BIO
*acbio
, int timeout
);
93 static int send_ocsp_response(BIO
*cbio
, OCSP_RESPONSE
*resp
);
94 static void log_message(int level
, const char *fmt
, ...);
99 static int acfd
= (int) INVALID_SOCKET
;
100 static int index_changed(CA_DB
*);
101 static void spawn_loop(void);
102 static int print_syslog(const char *str
, size_t len
, void *levPtr
);
103 static void sock_timeout(int signum
);
106 # ifndef OPENSSL_NO_SOCK
107 static OCSP_RESPONSE
*query_responder(BIO
*cbio
, const char *host
,
109 const STACK_OF(CONF_VALUE
) *headers
,
110 OCSP_REQUEST
*req
, int req_timeout
);
113 typedef enum OPTION_choice
{
114 OPT_ERR
= -1, OPT_EOF
= 0, OPT_HELP
,
115 OPT_OUTFILE
, OPT_TIMEOUT
, OPT_URL
, OPT_HOST
, OPT_PORT
,
116 OPT_IGNORE_ERR
, OPT_NOVERIFY
, OPT_NONCE
, OPT_NO_NONCE
,
117 OPT_RESP_NO_CERTS
, OPT_RESP_KEY_ID
, OPT_NO_CERTS
,
118 OPT_NO_SIGNATURE_VERIFY
, OPT_NO_CERT_VERIFY
, OPT_NO_CHAIN
,
119 OPT_NO_CERT_CHECKS
, OPT_NO_EXPLICIT
, OPT_TRUST_OTHER
,
120 OPT_NO_INTERN
, OPT_BADSIG
, OPT_TEXT
, OPT_REQ_TEXT
, OPT_RESP_TEXT
,
121 OPT_REQIN
, OPT_RESPIN
, OPT_SIGNER
, OPT_VAFILE
, OPT_SIGN_OTHER
,
122 OPT_VERIFY_OTHER
, OPT_CAFILE
, OPT_CAPATH
, OPT_NOCAFILE
, OPT_NOCAPATH
,
123 OPT_VALIDITY_PERIOD
, OPT_STATUS_AGE
, OPT_SIGNKEY
, OPT_REQOUT
,
124 OPT_RESPOUT
, OPT_PATH
, OPT_ISSUER
, OPT_CERT
, OPT_SERIAL
,
125 OPT_INDEX
, OPT_CA
, OPT_NMIN
, OPT_REQUEST
, OPT_NDAYS
, OPT_RSIGNER
,
126 OPT_RKEY
, OPT_ROTHER
, OPT_RMD
, OPT_RSIGOPT
, OPT_HEADER
,
132 const OPTIONS ocsp_options
[] = {
133 {"help", OPT_HELP
, '-', "Display this summary"},
134 {"out", OPT_OUTFILE
, '>', "Output filename"},
135 {"timeout", OPT_TIMEOUT
, 'p',
136 "Connection timeout (in seconds) to the OCSP responder"},
137 {"url", OPT_URL
, 's', "Responder URL"},
138 {"host", OPT_HOST
, 's', "TCP/IP hostname:port to connect to"},
139 {"port", OPT_PORT
, 'p', "Port to run responder on"},
140 {"ignore_err", OPT_IGNORE_ERR
, '-',
141 "Ignore error on OCSP request or response and continue running"},
142 {"noverify", OPT_NOVERIFY
, '-', "Don't verify response at all"},
143 {"nonce", OPT_NONCE
, '-', "Add OCSP nonce to request"},
144 {"no_nonce", OPT_NO_NONCE
, '-', "Don't add OCSP nonce to request"},
145 {"resp_no_certs", OPT_RESP_NO_CERTS
, '-',
146 "Don't include any certificates in response"},
147 {"resp_key_id", OPT_RESP_KEY_ID
, '-',
148 "Identify response by signing certificate key ID"},
150 {"multi", OPT_MULTI
, 'p', "run multiple responder processes"},
152 {"no_certs", OPT_NO_CERTS
, '-',
153 "Don't include any certificates in signed request"},
154 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY
, '-',
155 "Don't check signature on response"},
156 {"no_cert_verify", OPT_NO_CERT_VERIFY
, '-',
157 "Don't check signing certificate"},
158 {"no_chain", OPT_NO_CHAIN
, '-', "Don't chain verify response"},
159 {"no_cert_checks", OPT_NO_CERT_CHECKS
, '-',
160 "Don't do additional checks on signing certificate"},
161 {"no_explicit", OPT_NO_EXPLICIT
, '-',
162 "Do not explicitly check the chain, just verify the root"},
163 {"trust_other", OPT_TRUST_OTHER
, '-',
164 "Don't verify additional certificates"},
165 {"no_intern", OPT_NO_INTERN
, '-',
166 "Don't search certificates contained in response for signer"},
167 {"badsig", OPT_BADSIG
, '-',
168 "Corrupt last byte of loaded OSCP response signature (for test)"},
169 {"text", OPT_TEXT
, '-', "Print text form of request and response"},
170 {"req_text", OPT_REQ_TEXT
, '-', "Print text form of request"},
171 {"resp_text", OPT_RESP_TEXT
, '-', "Print text form of response"},
172 {"reqin", OPT_REQIN
, 's', "File with the DER-encoded request"},
173 {"respin", OPT_RESPIN
, 's', "File with the DER-encoded response"},
174 {"signer", OPT_SIGNER
, '<', "Certificate to sign OCSP request with"},
175 {"VAfile", OPT_VAFILE
, '<', "Validator certificates file"},
176 {"sign_other", OPT_SIGN_OTHER
, '<',
177 "Additional certificates to include in signed request"},
178 {"verify_other", OPT_VERIFY_OTHER
, '<',
179 "Additional certificates to search for signer"},
180 {"CAfile", OPT_CAFILE
, '<', "Trusted certificates file"},
181 {"CApath", OPT_CAPATH
, '<', "Trusted certificates directory"},
182 {"no-CAfile", OPT_NOCAFILE
, '-',
183 "Do not load the default certificates file"},
184 {"no-CApath", OPT_NOCAPATH
, '-',
185 "Do not load certificates from the default certificates directory"},
186 {"validity_period", OPT_VALIDITY_PERIOD
, 'u',
187 "Maximum validity discrepancy in seconds"},
188 {"status_age", OPT_STATUS_AGE
, 'p', "Maximum status age in seconds"},
189 {"signkey", OPT_SIGNKEY
, 's', "Private key to sign OCSP request with"},
190 {"reqout", OPT_REQOUT
, 's', "Output file for the DER-encoded request"},
191 {"respout", OPT_RESPOUT
, 's', "Output file for the DER-encoded response"},
192 {"path", OPT_PATH
, 's', "Path to use in OCSP request"},
193 {"issuer", OPT_ISSUER
, '<', "Issuer certificate"},
194 {"cert", OPT_CERT
, '<', "Certificate to check"},
195 {"serial", OPT_SERIAL
, 's', "Serial number to check"},
196 {"index", OPT_INDEX
, '<', "Certificate status index file"},
197 {"CA", OPT_CA
, '<', "CA certificate"},
198 {"nmin", OPT_NMIN
, 'p', "Number of minutes before next update"},
199 {"nrequest", OPT_REQUEST
, 'p',
200 "Number of requests to accept (default unlimited)"},
201 {"ndays", OPT_NDAYS
, 'p', "Number of days before next update"},
202 {"rsigner", OPT_RSIGNER
, '<',
203 "Responder certificate to sign responses with"},
204 {"rkey", OPT_RKEY
, '<', "Responder key to sign responses with"},
205 {"rother", OPT_ROTHER
, '<', "Other certificates to include in response"},
206 {"rmd", OPT_RMD
, 's', "Digest Algorithm to use in signature of OCSP response"},
207 {"rsigopt", OPT_RSIGOPT
, 's', "OCSP response signature parameter in n:v form"},
208 {"header", OPT_HEADER
, 's', "key=value header to add"},
209 {"", OPT_MD
, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
214 int ocsp_main(int argc
, char **argv
)
216 BIO
*acbio
= NULL
, *cbio
= NULL
, *derbio
= NULL
, *out
= NULL
;
217 const EVP_MD
*cert_id_md
= NULL
, *rsign_md
= NULL
;
218 STACK_OF(OPENSSL_STRING
) *rsign_sigopts
= NULL
;
221 EVP_PKEY
*key
= NULL
, *rkey
= NULL
;
222 OCSP_BASICRESP
*bs
= NULL
;
223 OCSP_REQUEST
*req
= NULL
;
224 OCSP_RESPONSE
*resp
= NULL
;
225 STACK_OF(CONF_VALUE
) *headers
= NULL
;
226 STACK_OF(OCSP_CERTID
) *ids
= NULL
;
227 STACK_OF(OPENSSL_STRING
) *reqnames
= NULL
;
228 STACK_OF(X509
) *sign_other
= NULL
, *verify_other
= NULL
, *rother
= NULL
;
229 STACK_OF(X509
) *issuers
= NULL
;
230 X509
*issuer
= NULL
, *cert
= NULL
;
231 STACK_OF(X509
) *rca_cert
= NULL
;
232 X509
*signer
= NULL
, *rsigner
= NULL
;
233 X509_STORE
*store
= NULL
;
234 X509_VERIFY_PARAM
*vpm
= NULL
;
235 const char *CAfile
= NULL
, *CApath
= NULL
;
236 char *header
, *value
;
237 char *host
= NULL
, *port
= NULL
, *path
= "/", *outfile
= NULL
;
238 char *rca_filename
= NULL
, *reqin
= NULL
, *respin
= NULL
;
239 char *reqout
= NULL
, *respout
= NULL
, *ridx_filename
= NULL
;
240 char *rsignfile
= NULL
, *rkeyfile
= NULL
;
241 char *sign_certfile
= NULL
, *verify_certfile
= NULL
, *rcertfile
= NULL
;
242 char *signfile
= NULL
, *keyfile
= NULL
;
243 char *thost
= NULL
, *tport
= NULL
, *tpath
= NULL
;
244 int noCAfile
= 0, noCApath
= 0;
245 int accept_count
= -1, add_nonce
= 1, noverify
= 0, use_ssl
= -1;
246 int vpmtouched
= 0, badsig
= 0, i
, ignore_err
= 0, nmin
= 0, ndays
= -1;
247 int req_text
= 0, resp_text
= 0, ret
= 1;
248 int req_timeout
= -1;
249 long nsec
= MAX_VALIDITY_PERIOD
, maxage
= -1;
250 unsigned long sign_flags
= 0, verify_flags
= 0, rflags
= 0;
253 reqnames
= sk_OPENSSL_STRING_new_null();
254 if (reqnames
== NULL
)
256 ids
= sk_OCSP_CERTID_new_null();
259 if ((vpm
= X509_VERIFY_PARAM_new()) == NULL
)
262 prog
= opt_init(argc
, argv
, ocsp_options
);
263 while ((o
= opt_next()) != OPT_EOF
) {
268 BIO_printf(bio_err
, "%s: Use -help for summary.\n", prog
);
272 opt_help(ocsp_options
);
278 #ifndef OPENSSL_NO_SOCK
279 req_timeout
= atoi(opt_arg());
286 thost
= tport
= tpath
= NULL
;
287 if (!OCSP_parse_url(opt_arg(), &host
, &port
, &path
, &use_ssl
)) {
288 BIO_printf(bio_err
, "%s Error parsing URL\n", prog
);
313 case OPT_RESP_NO_CERTS
:
314 rflags
|= OCSP_NOCERTS
;
316 case OPT_RESP_KEY_ID
:
317 rflags
|= OCSP_RESPID_KEY
;
320 sign_flags
|= OCSP_NOCERTS
;
322 case OPT_NO_SIGNATURE_VERIFY
:
323 verify_flags
|= OCSP_NOSIGS
;
325 case OPT_NO_CERT_VERIFY
:
326 verify_flags
|= OCSP_NOVERIFY
;
329 verify_flags
|= OCSP_NOCHAIN
;
331 case OPT_NO_CERT_CHECKS
:
332 verify_flags
|= OCSP_NOCHECKS
;
334 case OPT_NO_EXPLICIT
:
335 verify_flags
|= OCSP_NOEXPLICIT
;
337 case OPT_TRUST_OTHER
:
338 verify_flags
|= OCSP_TRUSTOTHER
;
341 verify_flags
|= OCSP_NOINTERN
;
347 req_text
= resp_text
= 1;
362 signfile
= opt_arg();
365 verify_certfile
= opt_arg();
366 verify_flags
|= OCSP_TRUSTOTHER
;
369 sign_certfile
= opt_arg();
371 case OPT_VERIFY_OTHER
:
372 verify_certfile
= opt_arg();
387 if (!opt_verify(o
, vpm
))
391 case OPT_VALIDITY_PERIOD
:
392 opt_long(opt_arg(), &nsec
);
395 opt_long(opt_arg(), &maxage
);
410 issuer
= load_cert(opt_arg(), FORMAT_PEM
, "issuer certificate");
413 if (issuers
== NULL
) {
414 if ((issuers
= sk_X509_new_null()) == NULL
)
417 sk_X509_push(issuers
, issuer
);
421 cert
= load_cert(opt_arg(), FORMAT_PEM
, "certificate");
424 if (cert_id_md
== NULL
)
425 cert_id_md
= EVP_sha1();
426 if (!add_ocsp_cert(&req
, cert
, cert_id_md
, issuer
, ids
))
428 if (!sk_OPENSSL_STRING_push(reqnames
, opt_arg()))
433 if (cert_id_md
== NULL
)
434 cert_id_md
= EVP_sha1();
435 if (!add_ocsp_serial(&req
, opt_arg(), cert_id_md
, issuer
, ids
))
437 if (!sk_OPENSSL_STRING_push(reqnames
, opt_arg()))
442 ridx_filename
= opt_arg();
445 rca_filename
= opt_arg();
448 opt_int(opt_arg(), &nmin
);
453 opt_int(opt_arg(), &accept_count
);
456 ndays
= atoi(opt_arg());
459 rsignfile
= opt_arg();
462 rkeyfile
= opt_arg();
465 rcertfile
= opt_arg();
467 case OPT_RMD
: /* Response MessageDigest */
468 if (!opt_md(opt_arg(), &rsign_md
))
472 if (rsign_sigopts
== NULL
)
473 rsign_sigopts
= sk_OPENSSL_STRING_new_null();
474 if (rsign_sigopts
== NULL
|| !sk_OPENSSL_STRING_push(rsign_sigopts
, opt_arg()))
479 value
= strchr(header
, '=');
481 BIO_printf(bio_err
, "Missing = in header key=value\n");
485 if (!X509V3_add_value(header
, value
, &headers
))
491 "%s: Digest must be before -cert or -serial\n",
495 if (!opt_md(opt_unknown(), &cert_id_md
))
501 multi
= atoi(opt_arg());
507 BIO_printf(bio_err
, "%s: Digest must be before -cert or -serial\n",
511 argc
= opt_num_rest();
515 /* Have we anything to do? */
516 if (req
== NULL
&& reqin
== NULL
517 && respin
== NULL
&& !(port
!= NULL
&& ridx_filename
!= NULL
))
520 out
= bio_open_default(outfile
, 'w', FORMAT_TEXT
);
524 if (req
== NULL
&& (add_nonce
!= 2))
527 if (req
== NULL
&& reqin
!= NULL
) {
528 derbio
= bio_open_default(reqin
, 'r', FORMAT_ASN1
);
531 req
= d2i_OCSP_REQUEST_bio(derbio
, NULL
);
534 BIO_printf(bio_err
, "Error reading OCSP request\n");
539 if (req
== NULL
&& port
!= NULL
) {
540 acbio
= init_responder(port
);
545 if (rsignfile
!= NULL
) {
546 if (rkeyfile
== NULL
)
547 rkeyfile
= rsignfile
;
548 rsigner
= load_cert(rsignfile
, FORMAT_PEM
, "responder certificate");
549 if (rsigner
== NULL
) {
550 BIO_printf(bio_err
, "Error loading responder certificate\n");
553 if (!load_certs(rca_filename
, &rca_cert
, FORMAT_PEM
,
554 NULL
, "CA certificate"))
556 if (rcertfile
!= NULL
) {
557 if (!load_certs(rcertfile
, &rother
, FORMAT_PEM
, NULL
,
558 "responder other certificates"))
561 rkey
= load_key(rkeyfile
, FORMAT_PEM
, 0, NULL
, NULL
,
562 "responder private key");
567 if (ridx_filename
!= NULL
568 && (rkey
== NULL
|| rsigner
== NULL
|| rca_cert
== NULL
)) {
570 "Responder mode requires certificate, key, and CA.\n");
574 if (ridx_filename
!= NULL
) {
575 rdb
= load_index(ridx_filename
, NULL
);
576 if (rdb
== NULL
|| index_index(rdb
) <= 0) {
583 if (multi
&& acbio
!= NULL
)
585 if (acbio
!= NULL
&& req_timeout
> 0)
586 signal(SIGALRM
, sock_timeout
);
590 log_message(LOG_INFO
, "waiting for OCSP client connections...");
596 if (index_changed(rdb
)) {
597 CA_DB
*newrdb
= load_index(ridx_filename
, NULL
);
599 if (newrdb
!= NULL
&& index_index(newrdb
) > 0) {
604 log_message(LOG_ERR
, "error reloading updated index: %s",
611 if (!do_responder(&req
, &cbio
, acbio
, req_timeout
))
616 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST
,
618 send_ocsp_response(cbio
, resp
);
624 && (signfile
!= NULL
|| reqout
!= NULL
625 || host
!= NULL
|| add_nonce
|| ridx_filename
!= NULL
)) {
626 BIO_printf(bio_err
, "Need an OCSP request for this operation!\n");
630 if (req
!= NULL
&& add_nonce
)
631 OCSP_request_add1_nonce(req
, NULL
, -1);
633 if (signfile
!= NULL
) {
636 signer
= load_cert(signfile
, FORMAT_PEM
, "signer certificate");
637 if (signer
== NULL
) {
638 BIO_printf(bio_err
, "Error loading signer certificate\n");
641 if (sign_certfile
!= NULL
) {
642 if (!load_certs(sign_certfile
, &sign_other
, FORMAT_PEM
, NULL
,
643 "signer certificates"))
646 key
= load_key(keyfile
, FORMAT_PEM
, 0, NULL
, NULL
,
647 "signer private key");
651 if (!OCSP_request_sign
652 (req
, signer
, key
, NULL
, sign_other
, sign_flags
)) {
653 BIO_printf(bio_err
, "Error signing OCSP request\n");
658 if (req_text
&& req
!= NULL
)
659 OCSP_REQUEST_print(out
, req
, 0);
661 if (reqout
!= NULL
) {
662 derbio
= bio_open_default(reqout
, 'w', FORMAT_ASN1
);
665 i2d_OCSP_REQUEST_bio(derbio
, req
);
670 make_ocsp_response(bio_err
, &resp
, req
, rdb
, rca_cert
, rsigner
, rkey
,
671 rsign_md
, rsign_sigopts
, rother
, rflags
, nmin
, ndays
, badsig
);
673 send_ocsp_response(cbio
, resp
);
674 } else if (host
!= NULL
) {
675 # ifndef OPENSSL_NO_SOCK
676 resp
= process_responder(req
, host
, path
,
677 port
, use_ssl
, headers
, req_timeout
);
682 "Error creating connect BIO - sockets not supported.\n");
685 } else if (respin
!= NULL
) {
686 derbio
= bio_open_default(respin
, 'r', FORMAT_ASN1
);
689 resp
= d2i_OCSP_RESPONSE_bio(derbio
, NULL
);
692 BIO_printf(bio_err
, "Error reading OCSP response\n");
702 if (respout
!= NULL
) {
703 derbio
= bio_open_default(respout
, 'w', FORMAT_ASN1
);
706 i2d_OCSP_RESPONSE_bio(derbio
, resp
);
710 i
= OCSP_response_status(resp
);
711 if (i
!= OCSP_RESPONSE_STATUS_SUCCESSFUL
) {
712 BIO_printf(out
, "Responder Error: %s (%d)\n",
713 OCSP_response_status_str(i
), i
);
719 OCSP_RESPONSE_print(out
, resp
, 0);
721 /* If running as responder don't verify our own response */
723 /* If not unlimited, see if we took all we should. */
724 if (accept_count
!= -1 && --accept_count
<= 0) {
730 OCSP_REQUEST_free(req
);
732 OCSP_RESPONSE_free(resp
);
736 if (ridx_filename
!= NULL
) {
742 store
= setup_verify(CAfile
, CApath
, noCAfile
, noCApath
);
747 X509_STORE_set1_param(store
, vpm
);
748 if (verify_certfile
!= NULL
) {
749 if (!load_certs(verify_certfile
, &verify_other
, FORMAT_PEM
, NULL
,
750 "validator certificate"))
754 bs
= OCSP_response_get1_basic(resp
);
756 BIO_printf(bio_err
, "Error parsing response\n");
763 if (req
!= NULL
&& ((i
= OCSP_check_nonce(req
, bs
)) <= 0)) {
765 BIO_printf(bio_err
, "WARNING: no nonce in response\n");
767 BIO_printf(bio_err
, "Nonce Verify error\n");
773 i
= OCSP_basic_verify(bs
, verify_other
, store
, verify_flags
);
774 if (i
<= 0 && issuers
) {
775 i
= OCSP_basic_verify(bs
, issuers
, store
, OCSP_TRUSTOTHER
);
780 BIO_printf(bio_err
, "Response Verify Failure\n");
781 ERR_print_errors(bio_err
);
784 BIO_printf(bio_err
, "Response verify OK\n");
788 print_ocsp_summary(out
, bs
, req
, reqnames
, ids
, nsec
, maxage
);
791 ERR_print_errors(bio_err
);
793 X509_STORE_free(store
);
794 X509_VERIFY_PARAM_free(vpm
);
795 sk_OPENSSL_STRING_free(rsign_sigopts
);
799 sk_X509_pop_free(issuers
, X509_free
);
801 sk_X509_pop_free(rca_cert
, X509_free
);
806 OCSP_REQUEST_free(req
);
807 OCSP_RESPONSE_free(resp
);
808 OCSP_BASICRESP_free(bs
);
809 sk_OPENSSL_STRING_free(reqnames
);
810 sk_OCSP_CERTID_free(ids
);
811 sk_X509_pop_free(sign_other
, X509_free
);
812 sk_X509_pop_free(verify_other
, X509_free
);
813 sk_CONF_VALUE_pop_free(headers
, X509V3_conf_free
);
822 log_message(int level
, const char *fmt
, ...)
830 if (vsnprintf(buf
, sizeof(buf
), fmt
, ap
) > 0) {
831 syslog(level
, "%s", buf
);
833 if (level
>= LOG_ERR
)
834 ERR_print_errors_cb(print_syslog
, &level
);
838 BIO_printf(bio_err
, "%s: ", prog
);
839 BIO_vprintf(bio_err
, fmt
, ap
);
840 BIO_printf(bio_err
, "\n");
847 static int print_syslog(const char *str
, size_t len
, void *levPtr
)
849 int level
= *(int *)levPtr
;
850 int ilen
= (len
> MAXERRLEN
) ? MAXERRLEN
: len
;
852 syslog(level
, "%.*s", ilen
, str
);
857 static int index_changed(CA_DB
*rdb
)
861 if (rdb
!= NULL
&& stat(rdb
->dbfname
, &sb
) != -1) {
862 if (rdb
->dbst
.st_mtime
!= sb
.st_mtime
863 || rdb
->dbst
.st_ctime
!= sb
.st_ctime
864 || rdb
->dbst
.st_ino
!= sb
.st_ino
865 || rdb
->dbst
.st_dev
!= sb
.st_dev
) {
866 syslog(LOG_INFO
, "index file changed, reloading");
873 static void killall(int ret
, pid_t
*kidpids
)
877 for (i
= 0; i
< multi
; ++i
)
879 (void)kill(kidpids
[i
], SIGTERM
);
880 OPENSSL_free(kidpids
);
885 static int termsig
= 0;
887 static void noteterm (int sig
)
893 * Loop spawning up to `multi` child processes, only child processes return
894 * from this function. The parent process loops until receiving a termination
895 * signal, kills extant children and exits without returning.
897 static void spawn_loop(void)
899 pid_t
*kidpids
= NULL
;
904 openlog(prog
, LOG_PID
, LOG_DAEMON
);
907 syslog(LOG_ERR
, "fatal: error detaching from parent process group: %s",
911 kidpids
= app_malloc(multi
* sizeof(*kidpids
), "child PID array");
912 for (i
= 0; i
< multi
; ++i
)
915 signal(SIGINT
, noteterm
);
916 signal(SIGTERM
, noteterm
);
918 while (termsig
== 0) {
922 * Wait for a child to replace when we're at the limit.
923 * Slow down if a child exited abnormally or waitpid() < 0
925 while (termsig
== 0 && procs
>= multi
) {
926 if ((fpid
= waitpid(-1, &status
, 0)) > 0) {
927 for (i
= 0; i
< procs
; ++i
) {
928 if (kidpids
[i
] == fpid
) {
935 syslog(LOG_ERR
, "fatal: internal error: "
936 "no matching child slot for pid: %ld",
941 if (WIFEXITED(status
))
942 syslog(LOG_WARNING
, "child process: %ld, exit status: %d",
943 (long)fpid
, WEXITSTATUS(status
));
944 else if (WIFSIGNALED(status
))
945 syslog(LOG_WARNING
, "child process: %ld, term signal %d%s",
946 (long)fpid
, WTERMSIG(status
),
948 WCOREDUMP(status
) ? " (core dumped)" :
954 } else if (errno
!= EINTR
) {
955 syslog(LOG_ERR
, "fatal: waitpid(): %s", strerror(errno
));
962 switch(fpid
= fork()) {
964 /* System critically low on memory, pause and try again later */
968 OPENSSL_free(kidpids
);
969 signal(SIGINT
, SIG_DFL
);
970 signal(SIGTERM
, SIG_DFL
);
973 if (RAND_poll() <= 0) {
974 syslog(LOG_ERR
, "fatal: RAND_poll() failed");
978 default: /* parent */
979 for (i
= 0; i
< multi
; ++i
) {
980 if (kidpids
[i
] == 0) {
987 syslog(LOG_ERR
, "fatal: internal error: no free child slots");
994 /* The loop above can only break on termsig */
995 syslog(LOG_INFO
, "terminating on signal: %d", termsig
);
1000 static int add_ocsp_cert(OCSP_REQUEST
**req
, X509
*cert
,
1001 const EVP_MD
*cert_id_md
, X509
*issuer
,
1002 STACK_OF(OCSP_CERTID
) *ids
)
1006 if (issuer
== NULL
) {
1007 BIO_printf(bio_err
, "No issuer certificate specified\n");
1011 *req
= OCSP_REQUEST_new();
1014 id
= OCSP_cert_to_id(cert_id_md
, cert
, issuer
);
1015 if (id
== NULL
|| !sk_OCSP_CERTID_push(ids
, id
))
1017 if (!OCSP_request_add0_id(*req
, id
))
1022 BIO_printf(bio_err
, "Error Creating OCSP request\n");
1026 static int add_ocsp_serial(OCSP_REQUEST
**req
, char *serial
,
1027 const EVP_MD
*cert_id_md
, X509
*issuer
,
1028 STACK_OF(OCSP_CERTID
) *ids
)
1032 ASN1_BIT_STRING
*ikey
;
1035 if (issuer
== NULL
) {
1036 BIO_printf(bio_err
, "No issuer certificate specified\n");
1040 *req
= OCSP_REQUEST_new();
1043 iname
= X509_get_subject_name(issuer
);
1044 ikey
= X509_get0_pubkey_bitstr(issuer
);
1045 sno
= s2i_ASN1_INTEGER(NULL
, serial
);
1047 BIO_printf(bio_err
, "Error converting serial number %s\n", serial
);
1050 id
= OCSP_cert_id_new(cert_id_md
, iname
, ikey
, sno
);
1051 ASN1_INTEGER_free(sno
);
1052 if (id
== NULL
|| !sk_OCSP_CERTID_push(ids
, id
))
1054 if (!OCSP_request_add0_id(*req
, id
))
1059 BIO_printf(bio_err
, "Error Creating OCSP request\n");
1063 static void print_ocsp_summary(BIO
*out
, OCSP_BASICRESP
*bs
, OCSP_REQUEST
*req
,
1064 STACK_OF(OPENSSL_STRING
) *names
,
1065 STACK_OF(OCSP_CERTID
) *ids
, long nsec
,
1070 int i
, status
, reason
;
1071 ASN1_GENERALIZEDTIME
*rev
, *thisupd
, *nextupd
;
1073 if (bs
== NULL
|| req
== NULL
|| !sk_OPENSSL_STRING_num(names
)
1074 || !sk_OCSP_CERTID_num(ids
))
1077 for (i
= 0; i
< sk_OCSP_CERTID_num(ids
); i
++) {
1078 id
= sk_OCSP_CERTID_value(ids
, i
);
1079 name
= sk_OPENSSL_STRING_value(names
, i
);
1080 BIO_printf(out
, "%s: ", name
);
1082 if (!OCSP_resp_find_status(bs
, id
, &status
, &reason
,
1083 &rev
, &thisupd
, &nextupd
)) {
1084 BIO_puts(out
, "ERROR: No Status found.\n");
1089 * Check validity: if invalid write to output BIO so we know which
1090 * response this refers to.
1092 if (!OCSP_check_validity(thisupd
, nextupd
, nsec
, maxage
)) {
1093 BIO_puts(out
, "WARNING: Status times invalid.\n");
1094 ERR_print_errors(out
);
1096 BIO_printf(out
, "%s\n", OCSP_cert_status_str(status
));
1098 BIO_puts(out
, "\tThis Update: ");
1099 ASN1_GENERALIZEDTIME_print(out
, thisupd
);
1100 BIO_puts(out
, "\n");
1103 BIO_puts(out
, "\tNext Update: ");
1104 ASN1_GENERALIZEDTIME_print(out
, nextupd
);
1105 BIO_puts(out
, "\n");
1108 if (status
!= V_OCSP_CERTSTATUS_REVOKED
)
1112 BIO_printf(out
, "\tReason: %s\n", OCSP_crl_reason_str(reason
));
1114 BIO_puts(out
, "\tRevocation Time: ");
1115 ASN1_GENERALIZEDTIME_print(out
, rev
);
1116 BIO_puts(out
, "\n");
1120 static void make_ocsp_response(BIO
*err
, OCSP_RESPONSE
**resp
, OCSP_REQUEST
*req
,
1121 CA_DB
*db
, STACK_OF(X509
) *ca
, X509
*rcert
,
1122 EVP_PKEY
*rkey
, const EVP_MD
*rmd
,
1123 STACK_OF(OPENSSL_STRING
) *sigopts
,
1124 STACK_OF(X509
) *rother
, unsigned long flags
,
1125 int nmin
, int ndays
, int badsig
)
1127 ASN1_TIME
*thisupd
= NULL
, *nextupd
= NULL
;
1129 OCSP_BASICRESP
*bs
= NULL
;
1131 EVP_MD_CTX
*mctx
= NULL
;
1132 EVP_PKEY_CTX
*pkctx
= NULL
;
1134 id_count
= OCSP_request_onereq_count(req
);
1136 if (id_count
<= 0) {
1138 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST
, NULL
);
1142 bs
= OCSP_BASICRESP_new();
1143 thisupd
= X509_gmtime_adj(NULL
, 0);
1145 nextupd
= X509_time_adj_ex(NULL
, ndays
, nmin
* 60, NULL
);
1147 /* Examine each certificate id in the request */
1148 for (i
= 0; i
< id_count
; i
++) {
1150 ASN1_INTEGER
*serial
;
1154 ASN1_OBJECT
*cert_id_md_oid
;
1155 const EVP_MD
*cert_id_md
;
1156 one
= OCSP_request_onereq_get0(req
, i
);
1157 cid
= OCSP_onereq_get0_id(one
);
1159 OCSP_id_get0_info(NULL
, &cert_id_md_oid
, NULL
, NULL
, cid
);
1161 cert_id_md
= EVP_get_digestbyobj(cert_id_md_oid
);
1162 if (cert_id_md
== NULL
) {
1163 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR
,
1167 for (jj
= 0; jj
< sk_X509_num(ca
) && !found
; jj
++) {
1168 X509
*ca_cert
= sk_X509_value(ca
, jj
);
1169 OCSP_CERTID
*ca_id
= OCSP_cert_to_id(cert_id_md
, NULL
, ca_cert
);
1171 if (OCSP_id_issuer_cmp(ca_id
, cid
) == 0)
1174 OCSP_CERTID_free(ca_id
);
1178 OCSP_basic_add1_status(bs
, cid
,
1179 V_OCSP_CERTSTATUS_UNKNOWN
,
1180 0, NULL
, thisupd
, nextupd
);
1183 OCSP_id_get0_info(NULL
, NULL
, NULL
, &serial
, cid
);
1184 inf
= lookup_serial(db
, serial
);
1186 OCSP_basic_add1_status(bs
, cid
,
1187 V_OCSP_CERTSTATUS_UNKNOWN
,
1188 0, NULL
, thisupd
, nextupd
);
1189 } else if (inf
[DB_type
][0] == DB_TYPE_VAL
) {
1190 OCSP_basic_add1_status(bs
, cid
,
1191 V_OCSP_CERTSTATUS_GOOD
,
1192 0, NULL
, thisupd
, nextupd
);
1193 } else if (inf
[DB_type
][0] == DB_TYPE_REV
) {
1194 ASN1_OBJECT
*inst
= NULL
;
1195 ASN1_TIME
*revtm
= NULL
;
1196 ASN1_GENERALIZEDTIME
*invtm
= NULL
;
1197 OCSP_SINGLERESP
*single
;
1199 unpack_revinfo(&revtm
, &reason
, &inst
, &invtm
, inf
[DB_rev_date
]);
1200 single
= OCSP_basic_add1_status(bs
, cid
,
1201 V_OCSP_CERTSTATUS_REVOKED
,
1202 reason
, revtm
, thisupd
, nextupd
);
1204 OCSP_SINGLERESP_add1_ext_i2d(single
, NID_invalidity_date
,
1206 else if (inst
!= NULL
)
1207 OCSP_SINGLERESP_add1_ext_i2d(single
,
1208 NID_hold_instruction_code
, inst
,
1210 ASN1_OBJECT_free(inst
);
1211 ASN1_TIME_free(revtm
);
1212 ASN1_GENERALIZEDTIME_free(invtm
);
1216 OCSP_copy_nonce(bs
, req
);
1218 mctx
= EVP_MD_CTX_new();
1219 if ( mctx
== NULL
|| !EVP_DigestSignInit(mctx
, &pkctx
, rmd
, NULL
, rkey
)) {
1220 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR
, NULL
);
1223 for (i
= 0; i
< sk_OPENSSL_STRING_num(sigopts
); i
++) {
1224 char *sigopt
= sk_OPENSSL_STRING_value(sigopts
, i
);
1226 if (pkey_ctrl_string(pkctx
, sigopt
) <= 0) {
1227 BIO_printf(err
, "parameter error \"%s\"\n", sigopt
);
1228 ERR_print_errors(bio_err
);
1229 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR
,
1234 OCSP_basic_sign_ctx(bs
, rcert
, mctx
, rother
, flags
);
1237 const ASN1_OCTET_STRING
*sig
= OCSP_resp_get0_signature(bs
);
1238 corrupt_signature(sig
);
1241 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL
, bs
);
1244 EVP_MD_CTX_free(mctx
);
1245 ASN1_TIME_free(thisupd
);
1246 ASN1_TIME_free(nextupd
);
1247 OCSP_BASICRESP_free(bs
);
1250 static char **lookup_serial(CA_DB
*db
, ASN1_INTEGER
*ser
)
1254 char *itmp
, *row
[DB_NUMBER
], **rrow
;
1255 for (i
= 0; i
< DB_NUMBER
; i
++)
1257 bn
= ASN1_INTEGER_to_BN(ser
, NULL
);
1258 OPENSSL_assert(bn
); /* FIXME: should report an error at this
1259 * point and abort */
1261 itmp
= OPENSSL_strdup("00");
1263 itmp
= BN_bn2hex(bn
);
1264 row
[DB_serial
] = itmp
;
1266 rrow
= TXT_DB_get_by_index(db
->db
, DB_serial
, row
);
1271 /* Quick and dirty OCSP server: read in and parse input request */
1273 static BIO
*init_responder(const char *port
)
1275 # ifdef OPENSSL_NO_SOCK
1277 "Error setting up accept BIO - sockets not supported.\n");
1280 BIO
*acbio
= NULL
, *bufbio
= NULL
;
1282 bufbio
= BIO_new(BIO_f_buffer());
1285 acbio
= BIO_new(BIO_s_accept());
1287 || BIO_set_bind_mode(acbio
, BIO_BIND_REUSEADDR
) < 0
1288 || BIO_set_accept_port(acbio
, port
) < 0) {
1289 log_message(LOG_ERR
, "Error setting up accept BIO");
1293 BIO_set_accept_bios(acbio
, bufbio
);
1295 if (BIO_do_accept(acbio
) <= 0) {
1296 log_message(LOG_ERR
, "Error starting accept");
1303 BIO_free_all(acbio
);
1309 # ifndef OPENSSL_NO_SOCK
1311 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1313 static int urldecode(char *p
)
1315 unsigned char *out
= (unsigned char *)p
;
1316 unsigned char *save
= out
;
1321 else if (isxdigit(_UC(p
[1])) && isxdigit(_UC(p
[2]))) {
1322 /* Don't check, can't fail because of ixdigit() call. */
1323 *out
++ = (OPENSSL_hexchar2int(p
[1]) << 4)
1324 | OPENSSL_hexchar2int(p
[2]);
1331 return (int)(out
- save
);
1336 static void sock_timeout(int signum
)
1338 if (acfd
!= (int)INVALID_SOCKET
)
1339 (void)shutdown(acfd
, SHUT_RD
);
1343 static int do_responder(OCSP_REQUEST
**preq
, BIO
**pcbio
, BIO
*acbio
,
1346 # ifdef OPENSSL_NO_SOCK
1350 OCSP_REQUEST
*req
= NULL
;
1351 char inbuf
[2048], reqbuf
[2048];
1353 BIO
*cbio
= NULL
, *getbio
= NULL
, *b64
= NULL
;
1358 /* Connection loss before accept() is routine, ignore silently */
1359 if (BIO_do_accept(acbio
) <= 0)
1362 cbio
= BIO_pop(acbio
);
1364 client
= BIO_get_peer_name(cbio
);
1368 (void) BIO_get_fd(cbio
, &acfd
);
1373 /* Read the request line. */
1374 len
= BIO_gets(cbio
, reqbuf
, sizeof(reqbuf
));
1378 if (strncmp(reqbuf
, "GET ", 4) == 0) {
1379 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1380 for (p
= reqbuf
+ 4; *p
== ' '; ++p
)
1383 log_message(LOG_INFO
, "Invalid request -- bad URL: %s", client
);
1388 /* Splice off the HTTP version identifier. */
1389 for (q
= p
; *q
; q
++)
1392 if (strncmp(q
, " HTTP/1.", 8) != 0) {
1393 log_message(LOG_INFO
,
1394 "Invalid request -- bad HTTP version: %s", client
);
1400 * Skip "GET / HTTP..." requests often used by load-balancers
1407 log_message(LOG_INFO
,
1408 "Invalid request -- bad URL encoding: %s", client
);
1411 if ((getbio
= BIO_new_mem_buf(p
, len
)) == NULL
1412 || (b64
= BIO_new(BIO_f_base64())) == NULL
) {
1413 log_message(LOG_ERR
, "Could not allocate base64 bio: %s", client
);
1416 BIO_set_flags(b64
, BIO_FLAGS_BASE64_NO_NL
);
1417 getbio
= BIO_push(b64
, getbio
);
1418 } else if (strncmp(reqbuf
, "POST ", 5) != 0) {
1419 log_message(LOG_INFO
, "Invalid request -- bad HTTP verb: %s", client
);
1423 /* Read and skip past the headers. */
1425 len
= BIO_gets(cbio
, inbuf
, sizeof(inbuf
));
1428 if ((inbuf
[0] == '\r') || (inbuf
[0] == '\n'))
1433 /* Clear alarm before we close the client socket */
1438 /* Try to read OCSP request */
1439 if (getbio
!= NULL
) {
1440 req
= d2i_OCSP_REQUEST_bio(getbio
, NULL
);
1441 BIO_free_all(getbio
);
1443 req
= d2i_OCSP_REQUEST_bio(cbio
, NULL
);
1447 log_message(LOG_ERR
, "Error parsing OCSP request");
1455 acfd
= (int)INVALID_SOCKET
;
1461 static int send_ocsp_response(BIO
*cbio
, OCSP_RESPONSE
*resp
)
1464 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1465 "Content-Length: %d\r\n\r\n";
1468 BIO_printf(cbio
, http_resp
, i2d_OCSP_RESPONSE(resp
, NULL
));
1469 i2d_OCSP_RESPONSE_bio(cbio
, resp
);
1470 (void)BIO_flush(cbio
);
1474 # ifndef OPENSSL_NO_SOCK
1475 static OCSP_RESPONSE
*query_responder(BIO
*cbio
, const char *host
,
1477 const STACK_OF(CONF_VALUE
) *headers
,
1478 OCSP_REQUEST
*req
, int req_timeout
)
1484 OCSP_REQ_CTX
*ctx
= NULL
;
1485 OCSP_RESPONSE
*rsp
= NULL
;
1489 if (req_timeout
!= -1)
1490 BIO_set_nbio(cbio
, 1);
1492 rv
= BIO_do_connect(cbio
);
1494 if ((rv
<= 0) && ((req_timeout
== -1) || !BIO_should_retry(cbio
))) {
1495 BIO_puts(bio_err
, "Error connecting BIO\n");
1499 if (BIO_get_fd(cbio
, &fd
) < 0) {
1500 BIO_puts(bio_err
, "Can't get connection fd\n");
1504 if (req_timeout
!= -1 && rv
<= 0) {
1506 openssl_fdset(fd
, &confds
);
1508 tv
.tv_sec
= req_timeout
;
1509 rv
= select(fd
+ 1, NULL
, (void *)&confds
, NULL
, &tv
);
1511 BIO_puts(bio_err
, "Timeout on connect\n");
1516 ctx
= OCSP_sendreq_new(cbio
, path
, NULL
, -1);
1520 for (i
= 0; i
< sk_CONF_VALUE_num(headers
); i
++) {
1521 CONF_VALUE
*hdr
= sk_CONF_VALUE_value(headers
, i
);
1522 if (add_host
== 1 && strcasecmp("host", hdr
->name
) == 0)
1524 if (!OCSP_REQ_CTX_add1_header(ctx
, hdr
->name
, hdr
->value
))
1528 if (add_host
== 1 && OCSP_REQ_CTX_add1_header(ctx
, "Host", host
) == 0)
1531 if (!OCSP_REQ_CTX_set1_req(ctx
, req
))
1535 rv
= OCSP_sendreq_nbio(&rsp
, ctx
);
1538 if (req_timeout
== -1)
1541 openssl_fdset(fd
, &confds
);
1543 tv
.tv_sec
= req_timeout
;
1544 if (BIO_should_read(cbio
)) {
1545 rv
= select(fd
+ 1, (void *)&confds
, NULL
, NULL
, &tv
);
1546 } else if (BIO_should_write(cbio
)) {
1547 rv
= select(fd
+ 1, NULL
, (void *)&confds
, NULL
, &tv
);
1549 BIO_puts(bio_err
, "Unexpected retry condition\n");
1553 BIO_puts(bio_err
, "Timeout on request\n");
1557 BIO_puts(bio_err
, "Select error\n");
1563 OCSP_REQ_CTX_free(ctx
);
1568 OCSP_RESPONSE
*process_responder(OCSP_REQUEST
*req
,
1569 const char *host
, const char *path
,
1570 const char *port
, int use_ssl
,
1571 STACK_OF(CONF_VALUE
) *headers
,
1575 SSL_CTX
*ctx
= NULL
;
1576 OCSP_RESPONSE
*resp
= NULL
;
1578 cbio
= BIO_new_connect(host
);
1580 BIO_printf(bio_err
, "Error creating connect BIO\n");
1584 BIO_set_conn_port(cbio
, port
);
1587 ctx
= SSL_CTX_new(TLS_client_method());
1589 BIO_printf(bio_err
, "Error creating SSL context.\n");
1592 SSL_CTX_set_mode(ctx
, SSL_MODE_AUTO_RETRY
);
1593 sbio
= BIO_new_ssl(ctx
, 1);
1594 cbio
= BIO_push(sbio
, cbio
);
1597 resp
= query_responder(cbio
, host
, path
, headers
, req
, req_timeout
);
1599 BIO_printf(bio_err
, "Error querying OCSP responder\n");