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 /* Maximum leeway in validity period: default 5 minutes */
57 # define MAX_VALIDITY_PERIOD (5 * 60)
59 static int add_ocsp_cert(OCSP_REQUEST
**req
, X509
*cert
,
60 const EVP_MD
*cert_id_md
, X509
*issuer
,
61 STACK_OF(OCSP_CERTID
) *ids
);
62 static int add_ocsp_serial(OCSP_REQUEST
**req
, char *serial
,
63 const EVP_MD
*cert_id_md
, X509
*issuer
,
64 STACK_OF(OCSP_CERTID
) *ids
);
65 static void print_ocsp_summary(BIO
*out
, OCSP_BASICRESP
*bs
, OCSP_REQUEST
*req
,
66 STACK_OF(OPENSSL_STRING
) *names
,
67 STACK_OF(OCSP_CERTID
) *ids
, long nsec
,
69 static void make_ocsp_response(BIO
*err
, OCSP_RESPONSE
**resp
, OCSP_REQUEST
*req
,
70 CA_DB
*db
, STACK_OF(X509
) *ca
, X509
*rcert
,
71 EVP_PKEY
*rkey
, const EVP_MD
*md
,
72 STACK_OF(OPENSSL_STRING
) *sigopts
,
73 STACK_OF(X509
) *rother
, unsigned long flags
,
74 int nmin
, int ndays
, int badsig
);
76 static char **lookup_serial(CA_DB
*db
, ASN1_INTEGER
*ser
);
77 static BIO
*init_responder(const char *port
);
78 static int do_responder(OCSP_REQUEST
**preq
, BIO
**pcbio
, BIO
*acbio
, int timeout
);
79 static int send_ocsp_response(BIO
*cbio
, OCSP_RESPONSE
*resp
);
80 static void log_message(int level
, const char *fmt
, ...);
85 static int acfd
= (int) INVALID_SOCKET
;
86 static int index_changed(CA_DB
*);
87 static void spawn_loop(void);
88 static int print_syslog(const char *str
, size_t len
, void *levPtr
);
89 static void sock_timeout(int signum
);
92 # ifndef OPENSSL_NO_SOCK
93 static OCSP_RESPONSE
*query_responder(BIO
*cbio
, const char *host
,
95 const STACK_OF(CONF_VALUE
) *headers
,
96 OCSP_REQUEST
*req
, int req_timeout
);
99 typedef enum OPTION_choice
{
100 OPT_ERR
= -1, OPT_EOF
= 0, OPT_HELP
,
101 OPT_OUTFILE
, OPT_TIMEOUT
, OPT_URL
, OPT_HOST
, OPT_PORT
,
102 OPT_IGNORE_ERR
, OPT_NOVERIFY
, OPT_NONCE
, OPT_NO_NONCE
,
103 OPT_RESP_NO_CERTS
, OPT_RESP_KEY_ID
, OPT_NO_CERTS
,
104 OPT_NO_SIGNATURE_VERIFY
, OPT_NO_CERT_VERIFY
, OPT_NO_CHAIN
,
105 OPT_NO_CERT_CHECKS
, OPT_NO_EXPLICIT
, OPT_TRUST_OTHER
,
106 OPT_NO_INTERN
, OPT_BADSIG
, OPT_TEXT
, OPT_REQ_TEXT
, OPT_RESP_TEXT
,
107 OPT_REQIN
, OPT_RESPIN
, OPT_SIGNER
, OPT_VAFILE
, OPT_SIGN_OTHER
,
108 OPT_VERIFY_OTHER
, OPT_CAFILE
, OPT_CAPATH
, OPT_NOCAFILE
, OPT_NOCAPATH
,
109 OPT_VALIDITY_PERIOD
, OPT_STATUS_AGE
, OPT_SIGNKEY
, OPT_REQOUT
,
110 OPT_RESPOUT
, OPT_PATH
, OPT_ISSUER
, OPT_CERT
, OPT_SERIAL
,
111 OPT_INDEX
, OPT_CA
, OPT_NMIN
, OPT_REQUEST
, OPT_NDAYS
, OPT_RSIGNER
,
112 OPT_RKEY
, OPT_ROTHER
, OPT_RMD
, OPT_RSIGOPT
, OPT_HEADER
,
118 const OPTIONS ocsp_options
[] = {
119 {"help", OPT_HELP
, '-', "Display this summary"},
120 {"out", OPT_OUTFILE
, '>', "Output filename"},
121 {"timeout", OPT_TIMEOUT
, 'p',
122 "Connection timeout (in seconds) to the OCSP responder"},
123 {"url", OPT_URL
, 's', "Responder URL"},
124 {"host", OPT_HOST
, 's', "TCP/IP hostname:port to connect to"},
125 {"port", OPT_PORT
, 'p', "Port to run responder on"},
126 {"ignore_err", OPT_IGNORE_ERR
, '-',
127 "Ignore error on OCSP request or response and continue running"},
128 {"noverify", OPT_NOVERIFY
, '-', "Don't verify response at all"},
129 {"nonce", OPT_NONCE
, '-', "Add OCSP nonce to request"},
130 {"no_nonce", OPT_NO_NONCE
, '-', "Don't add OCSP nonce to request"},
131 {"resp_no_certs", OPT_RESP_NO_CERTS
, '-',
132 "Don't include any certificates in response"},
133 {"resp_key_id", OPT_RESP_KEY_ID
, '-',
134 "Identify response by signing certificate key ID"},
136 {"multi", OPT_MULTI
, 'p', "run multiple responder processes"},
138 {"no_certs", OPT_NO_CERTS
, '-',
139 "Don't include any certificates in signed request"},
140 {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY
, '-',
141 "Don't check signature on response"},
142 {"no_cert_verify", OPT_NO_CERT_VERIFY
, '-',
143 "Don't check signing certificate"},
144 {"no_chain", OPT_NO_CHAIN
, '-', "Don't chain verify response"},
145 {"no_cert_checks", OPT_NO_CERT_CHECKS
, '-',
146 "Don't do additional checks on signing certificate"},
147 {"no_explicit", OPT_NO_EXPLICIT
, '-',
148 "Do not explicitly check the chain, just verify the root"},
149 {"trust_other", OPT_TRUST_OTHER
, '-',
150 "Don't verify additional certificates"},
151 {"no_intern", OPT_NO_INTERN
, '-',
152 "Don't search certificates contained in response for signer"},
153 {"badsig", OPT_BADSIG
, '-',
154 "Corrupt last byte of loaded OSCP response signature (for test)"},
155 {"text", OPT_TEXT
, '-', "Print text form of request and response"},
156 {"req_text", OPT_REQ_TEXT
, '-', "Print text form of request"},
157 {"resp_text", OPT_RESP_TEXT
, '-', "Print text form of response"},
158 {"reqin", OPT_REQIN
, 's', "File with the DER-encoded request"},
159 {"respin", OPT_RESPIN
, 's', "File with the DER-encoded response"},
160 {"signer", OPT_SIGNER
, '<', "Certificate to sign OCSP request with"},
161 {"VAfile", OPT_VAFILE
, '<', "Validator certificates file"},
162 {"sign_other", OPT_SIGN_OTHER
, '<',
163 "Additional certificates to include in signed request"},
164 {"verify_other", OPT_VERIFY_OTHER
, '<',
165 "Additional certificates to search for signer"},
166 {"CAfile", OPT_CAFILE
, '<', "Trusted certificates file"},
167 {"CApath", OPT_CAPATH
, '<', "Trusted certificates directory"},
168 {"no-CAfile", OPT_NOCAFILE
, '-',
169 "Do not load the default certificates file"},
170 {"no-CApath", OPT_NOCAPATH
, '-',
171 "Do not load certificates from the default certificates directory"},
172 {"validity_period", OPT_VALIDITY_PERIOD
, 'u',
173 "Maximum validity discrepancy in seconds"},
174 {"status_age", OPT_STATUS_AGE
, 'p', "Maximum status age in seconds"},
175 {"signkey", OPT_SIGNKEY
, 's', "Private key to sign OCSP request with"},
176 {"reqout", OPT_REQOUT
, 's', "Output file for the DER-encoded request"},
177 {"respout", OPT_RESPOUT
, 's', "Output file for the DER-encoded response"},
178 {"path", OPT_PATH
, 's', "Path to use in OCSP request"},
179 {"issuer", OPT_ISSUER
, '<', "Issuer certificate"},
180 {"cert", OPT_CERT
, '<', "Certificate to check"},
181 {"serial", OPT_SERIAL
, 's', "Serial number to check"},
182 {"index", OPT_INDEX
, '<', "Certificate status index file"},
183 {"CA", OPT_CA
, '<', "CA certificate"},
184 {"nmin", OPT_NMIN
, 'p', "Number of minutes before next update"},
185 {"nrequest", OPT_REQUEST
, 'p',
186 "Number of requests to accept (default unlimited)"},
187 {"ndays", OPT_NDAYS
, 'p', "Number of days before next update"},
188 {"rsigner", OPT_RSIGNER
, '<',
189 "Responder certificate to sign responses with"},
190 {"rkey", OPT_RKEY
, '<', "Responder key to sign responses with"},
191 {"rother", OPT_ROTHER
, '<', "Other certificates to include in response"},
192 {"rmd", OPT_RMD
, 's', "Digest Algorithm to use in signature of OCSP response"},
193 {"rsigopt", OPT_RSIGOPT
, 's', "OCSP response signature parameter in n:v form"},
194 {"header", OPT_HEADER
, 's', "key=value header to add"},
195 {"", OPT_MD
, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
200 int ocsp_main(int argc
, char **argv
)
202 BIO
*acbio
= NULL
, *cbio
= NULL
, *derbio
= NULL
, *out
= NULL
;
203 const EVP_MD
*cert_id_md
= NULL
, *rsign_md
= NULL
;
204 STACK_OF(OPENSSL_STRING
) *rsign_sigopts
= NULL
;
207 EVP_PKEY
*key
= NULL
, *rkey
= NULL
;
208 OCSP_BASICRESP
*bs
= NULL
;
209 OCSP_REQUEST
*req
= NULL
;
210 OCSP_RESPONSE
*resp
= NULL
;
211 STACK_OF(CONF_VALUE
) *headers
= NULL
;
212 STACK_OF(OCSP_CERTID
) *ids
= NULL
;
213 STACK_OF(OPENSSL_STRING
) *reqnames
= NULL
;
214 STACK_OF(X509
) *sign_other
= NULL
, *verify_other
= NULL
, *rother
= NULL
;
215 STACK_OF(X509
) *issuers
= NULL
;
216 X509
*issuer
= NULL
, *cert
= NULL
;
217 STACK_OF(X509
) *rca_cert
= NULL
;
218 X509
*signer
= NULL
, *rsigner
= NULL
;
219 X509_STORE
*store
= NULL
;
220 X509_VERIFY_PARAM
*vpm
= NULL
;
221 const char *CAfile
= NULL
, *CApath
= NULL
;
222 char *header
, *value
;
223 char *host
= NULL
, *port
= NULL
, *path
= "/", *outfile
= NULL
;
224 char *rca_filename
= NULL
, *reqin
= NULL
, *respin
= NULL
;
225 char *reqout
= NULL
, *respout
= NULL
, *ridx_filename
= NULL
;
226 char *rsignfile
= NULL
, *rkeyfile
= NULL
;
227 char *sign_certfile
= NULL
, *verify_certfile
= NULL
, *rcertfile
= NULL
;
228 char *signfile
= NULL
, *keyfile
= NULL
;
229 char *thost
= NULL
, *tport
= NULL
, *tpath
= NULL
;
230 int noCAfile
= 0, noCApath
= 0;
231 int accept_count
= -1, add_nonce
= 1, noverify
= 0, use_ssl
= -1;
232 int vpmtouched
= 0, badsig
= 0, i
, ignore_err
= 0, nmin
= 0, ndays
= -1;
233 int req_text
= 0, resp_text
= 0, ret
= 1;
234 int req_timeout
= -1;
235 long nsec
= MAX_VALIDITY_PERIOD
, maxage
= -1;
236 unsigned long sign_flags
= 0, verify_flags
= 0, rflags
= 0;
239 reqnames
= sk_OPENSSL_STRING_new_null();
240 if (reqnames
== NULL
)
242 ids
= sk_OCSP_CERTID_new_null();
245 if ((vpm
= X509_VERIFY_PARAM_new()) == NULL
)
248 prog
= opt_init(argc
, argv
, ocsp_options
);
249 while ((o
= opt_next()) != OPT_EOF
) {
254 BIO_printf(bio_err
, "%s: Use -help for summary.\n", prog
);
258 opt_help(ocsp_options
);
264 #ifndef OPENSSL_NO_SOCK
265 req_timeout
= atoi(opt_arg());
272 thost
= tport
= tpath
= NULL
;
273 if (!OCSP_parse_url(opt_arg(), &host
, &port
, &path
, &use_ssl
)) {
274 BIO_printf(bio_err
, "%s Error parsing URL\n", prog
);
299 case OPT_RESP_NO_CERTS
:
300 rflags
|= OCSP_NOCERTS
;
302 case OPT_RESP_KEY_ID
:
303 rflags
|= OCSP_RESPID_KEY
;
306 sign_flags
|= OCSP_NOCERTS
;
308 case OPT_NO_SIGNATURE_VERIFY
:
309 verify_flags
|= OCSP_NOSIGS
;
311 case OPT_NO_CERT_VERIFY
:
312 verify_flags
|= OCSP_NOVERIFY
;
315 verify_flags
|= OCSP_NOCHAIN
;
317 case OPT_NO_CERT_CHECKS
:
318 verify_flags
|= OCSP_NOCHECKS
;
320 case OPT_NO_EXPLICIT
:
321 verify_flags
|= OCSP_NOEXPLICIT
;
323 case OPT_TRUST_OTHER
:
324 verify_flags
|= OCSP_TRUSTOTHER
;
327 verify_flags
|= OCSP_NOINTERN
;
333 req_text
= resp_text
= 1;
348 signfile
= opt_arg();
351 verify_certfile
= opt_arg();
352 verify_flags
|= OCSP_TRUSTOTHER
;
355 sign_certfile
= opt_arg();
357 case OPT_VERIFY_OTHER
:
358 verify_certfile
= opt_arg();
373 if (!opt_verify(o
, vpm
))
377 case OPT_VALIDITY_PERIOD
:
378 opt_long(opt_arg(), &nsec
);
381 opt_long(opt_arg(), &maxage
);
396 issuer
= load_cert(opt_arg(), FORMAT_PEM
, "issuer certificate");
399 if (issuers
== NULL
) {
400 if ((issuers
= sk_X509_new_null()) == NULL
)
403 sk_X509_push(issuers
, issuer
);
407 cert
= load_cert(opt_arg(), FORMAT_PEM
, "certificate");
410 if (cert_id_md
== NULL
)
411 cert_id_md
= EVP_sha1();
412 if (!add_ocsp_cert(&req
, cert
, cert_id_md
, issuer
, ids
))
414 if (!sk_OPENSSL_STRING_push(reqnames
, opt_arg()))
419 if (cert_id_md
== NULL
)
420 cert_id_md
= EVP_sha1();
421 if (!add_ocsp_serial(&req
, opt_arg(), cert_id_md
, issuer
, ids
))
423 if (!sk_OPENSSL_STRING_push(reqnames
, opt_arg()))
428 ridx_filename
= opt_arg();
431 rca_filename
= opt_arg();
434 opt_int(opt_arg(), &nmin
);
439 opt_int(opt_arg(), &accept_count
);
442 ndays
= atoi(opt_arg());
445 rsignfile
= opt_arg();
448 rkeyfile
= opt_arg();
451 rcertfile
= opt_arg();
453 case OPT_RMD
: /* Response MessageDigest */
454 if (!opt_md(opt_arg(), &rsign_md
))
458 if (rsign_sigopts
== NULL
)
459 rsign_sigopts
= sk_OPENSSL_STRING_new_null();
460 if (rsign_sigopts
== NULL
|| !sk_OPENSSL_STRING_push(rsign_sigopts
, opt_arg()))
465 value
= strchr(header
, '=');
467 BIO_printf(bio_err
, "Missing = in header key=value\n");
471 if (!X509V3_add_value(header
, value
, &headers
))
477 "%s: Digest must be before -cert or -serial\n",
481 if (!opt_md(opt_unknown(), &cert_id_md
))
487 multi
= atoi(opt_arg());
493 BIO_printf(bio_err
, "%s: Digest must be before -cert or -serial\n",
497 argc
= opt_num_rest();
501 /* Have we anything to do? */
502 if (req
== NULL
&& reqin
== NULL
503 && respin
== NULL
&& !(port
!= NULL
&& ridx_filename
!= NULL
))
506 out
= bio_open_default(outfile
, 'w', FORMAT_TEXT
);
510 if (req
== NULL
&& (add_nonce
!= 2))
513 if (req
== NULL
&& reqin
!= NULL
) {
514 derbio
= bio_open_default(reqin
, 'r', FORMAT_ASN1
);
517 req
= d2i_OCSP_REQUEST_bio(derbio
, NULL
);
520 BIO_printf(bio_err
, "Error reading OCSP request\n");
525 if (req
== NULL
&& port
!= NULL
) {
526 acbio
= init_responder(port
);
531 if (rsignfile
!= NULL
) {
532 if (rkeyfile
== NULL
)
533 rkeyfile
= rsignfile
;
534 rsigner
= load_cert(rsignfile
, FORMAT_PEM
, "responder certificate");
535 if (rsigner
== NULL
) {
536 BIO_printf(bio_err
, "Error loading responder certificate\n");
539 if (!load_certs(rca_filename
, &rca_cert
, FORMAT_PEM
,
540 NULL
, "CA certificate"))
542 if (rcertfile
!= NULL
) {
543 if (!load_certs(rcertfile
, &rother
, FORMAT_PEM
, NULL
,
544 "responder other certificates"))
547 rkey
= load_key(rkeyfile
, FORMAT_PEM
, 0, NULL
, NULL
,
548 "responder private key");
553 if (ridx_filename
!= NULL
554 && (rkey
== NULL
|| rsigner
== NULL
|| rca_cert
== NULL
)) {
556 "Responder mode requires certificate, key, and CA.\n");
560 if (ridx_filename
!= NULL
) {
561 rdb
= load_index(ridx_filename
, NULL
);
562 if (rdb
== NULL
|| index_index(rdb
) <= 0) {
569 if (multi
&& acbio
!= NULL
)
571 if (acbio
!= NULL
&& req_timeout
> 0)
572 signal(SIGALRM
, sock_timeout
);
576 log_message(LOG_INFO
, "waiting for OCSP client connections...");
582 if (index_changed(rdb
)) {
583 CA_DB
*newrdb
= load_index(ridx_filename
, NULL
);
585 if (newrdb
!= NULL
&& index_index(newrdb
) > 0) {
590 log_message(LOG_ERR
, "error reloading updated index: %s",
597 if (!do_responder(&req
, &cbio
, acbio
, req_timeout
))
602 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST
,
604 send_ocsp_response(cbio
, resp
);
610 && (signfile
!= NULL
|| reqout
!= NULL
611 || host
!= NULL
|| add_nonce
|| ridx_filename
!= NULL
)) {
612 BIO_printf(bio_err
, "Need an OCSP request for this operation!\n");
616 if (req
!= NULL
&& add_nonce
)
617 OCSP_request_add1_nonce(req
, NULL
, -1);
619 if (signfile
!= NULL
) {
622 signer
= load_cert(signfile
, FORMAT_PEM
, "signer certificate");
623 if (signer
== NULL
) {
624 BIO_printf(bio_err
, "Error loading signer certificate\n");
627 if (sign_certfile
!= NULL
) {
628 if (!load_certs(sign_certfile
, &sign_other
, FORMAT_PEM
, NULL
,
629 "signer certificates"))
632 key
= load_key(keyfile
, FORMAT_PEM
, 0, NULL
, NULL
,
633 "signer private key");
637 if (!OCSP_request_sign
638 (req
, signer
, key
, NULL
, sign_other
, sign_flags
)) {
639 BIO_printf(bio_err
, "Error signing OCSP request\n");
644 if (req_text
&& req
!= NULL
)
645 OCSP_REQUEST_print(out
, req
, 0);
647 if (reqout
!= NULL
) {
648 derbio
= bio_open_default(reqout
, 'w', FORMAT_ASN1
);
651 i2d_OCSP_REQUEST_bio(derbio
, req
);
656 make_ocsp_response(bio_err
, &resp
, req
, rdb
, rca_cert
, rsigner
, rkey
,
657 rsign_md
, rsign_sigopts
, rother
, rflags
, nmin
, ndays
, badsig
);
659 send_ocsp_response(cbio
, resp
);
660 } else if (host
!= NULL
) {
661 # ifndef OPENSSL_NO_SOCK
662 resp
= process_responder(req
, host
, path
,
663 port
, use_ssl
, headers
, req_timeout
);
668 "Error creating connect BIO - sockets not supported.\n");
671 } else if (respin
!= NULL
) {
672 derbio
= bio_open_default(respin
, 'r', FORMAT_ASN1
);
675 resp
= d2i_OCSP_RESPONSE_bio(derbio
, NULL
);
678 BIO_printf(bio_err
, "Error reading OCSP response\n");
688 if (respout
!= NULL
) {
689 derbio
= bio_open_default(respout
, 'w', FORMAT_ASN1
);
692 i2d_OCSP_RESPONSE_bio(derbio
, resp
);
696 i
= OCSP_response_status(resp
);
697 if (i
!= OCSP_RESPONSE_STATUS_SUCCESSFUL
) {
698 BIO_printf(out
, "Responder Error: %s (%d)\n",
699 OCSP_response_status_str(i
), i
);
707 OCSP_RESPONSE_print(out
, resp
, 0);
709 /* If running as responder don't verify our own response */
711 /* If not unlimited, see if we took all we should. */
712 if (accept_count
!= -1 && --accept_count
<= 0) {
718 OCSP_REQUEST_free(req
);
720 OCSP_RESPONSE_free(resp
);
724 if (ridx_filename
!= NULL
) {
730 store
= setup_verify(CAfile
, CApath
, noCAfile
, noCApath
);
735 X509_STORE_set1_param(store
, vpm
);
736 if (verify_certfile
!= NULL
) {
737 if (!load_certs(verify_certfile
, &verify_other
, FORMAT_PEM
, NULL
,
738 "validator certificate"))
742 bs
= OCSP_response_get1_basic(resp
);
744 BIO_printf(bio_err
, "Error parsing response\n");
751 if (req
!= NULL
&& ((i
= OCSP_check_nonce(req
, bs
)) <= 0)) {
753 BIO_printf(bio_err
, "WARNING: no nonce in response\n");
755 BIO_printf(bio_err
, "Nonce Verify error\n");
761 i
= OCSP_basic_verify(bs
, verify_other
, store
, verify_flags
);
762 if (i
<= 0 && issuers
) {
763 i
= OCSP_basic_verify(bs
, issuers
, store
, OCSP_TRUSTOTHER
);
768 BIO_printf(bio_err
, "Response Verify Failure\n");
769 ERR_print_errors(bio_err
);
772 BIO_printf(bio_err
, "Response verify OK\n");
776 print_ocsp_summary(out
, bs
, req
, reqnames
, ids
, nsec
, maxage
);
779 ERR_print_errors(bio_err
);
781 X509_STORE_free(store
);
782 X509_VERIFY_PARAM_free(vpm
);
783 sk_OPENSSL_STRING_free(rsign_sigopts
);
787 sk_X509_pop_free(issuers
, X509_free
);
789 sk_X509_pop_free(rca_cert
, X509_free
);
794 OCSP_REQUEST_free(req
);
795 OCSP_RESPONSE_free(resp
);
796 OCSP_BASICRESP_free(bs
);
797 sk_OPENSSL_STRING_free(reqnames
);
798 sk_OCSP_CERTID_free(ids
);
799 sk_X509_pop_free(sign_other
, X509_free
);
800 sk_X509_pop_free(verify_other
, X509_free
);
801 sk_CONF_VALUE_pop_free(headers
, X509V3_conf_free
);
810 log_message(int level
, const char *fmt
, ...)
818 if (vsnprintf(buf
, sizeof(buf
), fmt
, ap
) > 0) {
819 syslog(level
, "%s", buf
);
821 if (level
>= LOG_ERR
)
822 ERR_print_errors_cb(print_syslog
, &level
);
826 BIO_printf(bio_err
, "%s: ", prog
);
827 BIO_vprintf(bio_err
, fmt
, ap
);
828 BIO_printf(bio_err
, "\n");
835 static int print_syslog(const char *str
, size_t len
, void *levPtr
)
837 int level
= *(int *)levPtr
;
838 int ilen
= (len
> MAXERRLEN
) ? MAXERRLEN
: len
;
840 syslog(level
, "%.*s", ilen
, str
);
845 static int index_changed(CA_DB
*rdb
)
849 if (rdb
!= NULL
&& stat(rdb
->dbfname
, &sb
) != -1) {
850 if (rdb
->dbst
.st_mtime
!= sb
.st_mtime
851 || rdb
->dbst
.st_ctime
!= sb
.st_ctime
852 || rdb
->dbst
.st_ino
!= sb
.st_ino
853 || rdb
->dbst
.st_dev
!= sb
.st_dev
) {
854 syslog(LOG_INFO
, "index file changed, reloading");
861 static void killall(int ret
, pid_t
*kidpids
)
865 for (i
= 0; i
< multi
; ++i
)
867 (void)kill(kidpids
[i
], SIGTERM
);
872 static int termsig
= 0;
874 static void noteterm (int sig
)
880 * Loop spawning up to `multi` child processes, only child processes return
881 * from this function. The parent process loops until receiving a termination
882 * signal, kills extant children and exits without returning.
884 static void spawn_loop(void)
886 pid_t
*kidpids
= NULL
;
891 openlog(prog
, LOG_PID
, LOG_DAEMON
);
894 syslog(LOG_ERR
, "fatal: error detaching from parent process group: %s",
898 kidpids
= app_malloc(multi
* sizeof(*kidpids
), "child PID array");
899 for (i
= 0; i
< multi
; ++i
)
902 signal(SIGINT
, noteterm
);
903 signal(SIGTERM
, noteterm
);
905 while (termsig
== 0) {
909 * Wait for a child to replace when we're at the limit.
910 * Slow down if a child exited abnormally or waitpid() < 0
912 while (termsig
== 0 && procs
>= multi
) {
913 if ((fpid
= waitpid(-1, &status
, 0)) > 0) {
914 for (i
= 0; i
< procs
; ++i
) {
915 if (kidpids
[i
] == fpid
) {
922 syslog(LOG_ERR
, "fatal: internal error: "
923 "no matching child slot for pid: %ld",
928 if (WIFEXITED(status
))
929 syslog(LOG_WARNING
, "child process: %ld, exit status: %d",
930 (long)fpid
, WEXITSTATUS(status
));
931 else if (WIFSIGNALED(status
))
932 syslog(LOG_WARNING
, "child process: %ld, term signal %d%s",
933 (long)fpid
, WTERMSIG(status
),
935 WCOREDUMP(status
) ? " (core dumped)" :
941 } else if (errno
!= EINTR
) {
942 syslog(LOG_ERR
, "fatal: waitpid(): %s", strerror(errno
));
949 switch(fpid
= fork()) {
951 /* System critically low on memory, pause and try again later */
955 signal(SIGINT
, SIG_DFL
);
956 signal(SIGTERM
, SIG_DFL
);
959 if (RAND_poll() <= 0) {
960 syslog(LOG_ERR
, "fatal: RAND_poll() failed");
964 default: /* parent */
965 for (i
= 0; i
< multi
; ++i
) {
966 if (kidpids
[i
] == 0) {
973 syslog(LOG_ERR
, "fatal: internal error: no free child slots");
980 /* The loop above can only break on termsig */
981 syslog(LOG_INFO
, "terminating on signal: %d", termsig
);
986 static int add_ocsp_cert(OCSP_REQUEST
**req
, X509
*cert
,
987 const EVP_MD
*cert_id_md
, X509
*issuer
,
988 STACK_OF(OCSP_CERTID
) *ids
)
992 if (issuer
== NULL
) {
993 BIO_printf(bio_err
, "No issuer certificate specified\n");
997 *req
= OCSP_REQUEST_new();
1000 id
= OCSP_cert_to_id(cert_id_md
, cert
, issuer
);
1001 if (id
== NULL
|| !sk_OCSP_CERTID_push(ids
, id
))
1003 if (!OCSP_request_add0_id(*req
, id
))
1008 BIO_printf(bio_err
, "Error Creating OCSP request\n");
1012 static int add_ocsp_serial(OCSP_REQUEST
**req
, char *serial
,
1013 const EVP_MD
*cert_id_md
, X509
*issuer
,
1014 STACK_OF(OCSP_CERTID
) *ids
)
1018 ASN1_BIT_STRING
*ikey
;
1021 if (issuer
== NULL
) {
1022 BIO_printf(bio_err
, "No issuer certificate specified\n");
1026 *req
= OCSP_REQUEST_new();
1029 iname
= X509_get_subject_name(issuer
);
1030 ikey
= X509_get0_pubkey_bitstr(issuer
);
1031 sno
= s2i_ASN1_INTEGER(NULL
, serial
);
1033 BIO_printf(bio_err
, "Error converting serial number %s\n", serial
);
1036 id
= OCSP_cert_id_new(cert_id_md
, iname
, ikey
, sno
);
1037 ASN1_INTEGER_free(sno
);
1038 if (id
== NULL
|| !sk_OCSP_CERTID_push(ids
, id
))
1040 if (!OCSP_request_add0_id(*req
, id
))
1045 BIO_printf(bio_err
, "Error Creating OCSP request\n");
1049 static void print_ocsp_summary(BIO
*out
, OCSP_BASICRESP
*bs
, OCSP_REQUEST
*req
,
1050 STACK_OF(OPENSSL_STRING
) *names
,
1051 STACK_OF(OCSP_CERTID
) *ids
, long nsec
,
1056 int i
, status
, reason
;
1057 ASN1_GENERALIZEDTIME
*rev
, *thisupd
, *nextupd
;
1059 if (bs
== NULL
|| req
== NULL
|| !sk_OPENSSL_STRING_num(names
)
1060 || !sk_OCSP_CERTID_num(ids
))
1063 for (i
= 0; i
< sk_OCSP_CERTID_num(ids
); i
++) {
1064 id
= sk_OCSP_CERTID_value(ids
, i
);
1065 name
= sk_OPENSSL_STRING_value(names
, i
);
1066 BIO_printf(out
, "%s: ", name
);
1068 if (!OCSP_resp_find_status(bs
, id
, &status
, &reason
,
1069 &rev
, &thisupd
, &nextupd
)) {
1070 BIO_puts(out
, "ERROR: No Status found.\n");
1075 * Check validity: if invalid write to output BIO so we know which
1076 * response this refers to.
1078 if (!OCSP_check_validity(thisupd
, nextupd
, nsec
, maxage
)) {
1079 BIO_puts(out
, "WARNING: Status times invalid.\n");
1080 ERR_print_errors(out
);
1082 BIO_printf(out
, "%s\n", OCSP_cert_status_str(status
));
1084 BIO_puts(out
, "\tThis Update: ");
1085 ASN1_GENERALIZEDTIME_print(out
, thisupd
);
1086 BIO_puts(out
, "\n");
1089 BIO_puts(out
, "\tNext Update: ");
1090 ASN1_GENERALIZEDTIME_print(out
, nextupd
);
1091 BIO_puts(out
, "\n");
1094 if (status
!= V_OCSP_CERTSTATUS_REVOKED
)
1098 BIO_printf(out
, "\tReason: %s\n", OCSP_crl_reason_str(reason
));
1100 BIO_puts(out
, "\tRevocation Time: ");
1101 ASN1_GENERALIZEDTIME_print(out
, rev
);
1102 BIO_puts(out
, "\n");
1106 static void make_ocsp_response(BIO
*err
, OCSP_RESPONSE
**resp
, OCSP_REQUEST
*req
,
1107 CA_DB
*db
, STACK_OF(X509
) *ca
, X509
*rcert
,
1108 EVP_PKEY
*rkey
, const EVP_MD
*rmd
,
1109 STACK_OF(OPENSSL_STRING
) *sigopts
,
1110 STACK_OF(X509
) *rother
, unsigned long flags
,
1111 int nmin
, int ndays
, int badsig
)
1113 ASN1_TIME
*thisupd
= NULL
, *nextupd
= NULL
;
1115 OCSP_BASICRESP
*bs
= NULL
;
1117 EVP_MD_CTX
*mctx
= NULL
;
1118 EVP_PKEY_CTX
*pkctx
= NULL
;
1120 id_count
= OCSP_request_onereq_count(req
);
1122 if (id_count
<= 0) {
1124 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST
, NULL
);
1128 bs
= OCSP_BASICRESP_new();
1129 thisupd
= X509_gmtime_adj(NULL
, 0);
1131 nextupd
= X509_time_adj_ex(NULL
, ndays
, nmin
* 60, NULL
);
1133 /* Examine each certificate id in the request */
1134 for (i
= 0; i
< id_count
; i
++) {
1136 ASN1_INTEGER
*serial
;
1140 ASN1_OBJECT
*cert_id_md_oid
;
1141 const EVP_MD
*cert_id_md
;
1142 one
= OCSP_request_onereq_get0(req
, i
);
1143 cid
= OCSP_onereq_get0_id(one
);
1145 OCSP_id_get0_info(NULL
, &cert_id_md_oid
, NULL
, NULL
, cid
);
1147 cert_id_md
= EVP_get_digestbyobj(cert_id_md_oid
);
1148 if (cert_id_md
== NULL
) {
1149 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR
,
1153 for (jj
= 0; jj
< sk_X509_num(ca
) && !found
; jj
++) {
1154 X509
*ca_cert
= sk_X509_value(ca
, jj
);
1155 OCSP_CERTID
*ca_id
= OCSP_cert_to_id(cert_id_md
, NULL
, ca_cert
);
1157 if (OCSP_id_issuer_cmp(ca_id
, cid
) == 0)
1160 OCSP_CERTID_free(ca_id
);
1164 OCSP_basic_add1_status(bs
, cid
,
1165 V_OCSP_CERTSTATUS_UNKNOWN
,
1166 0, NULL
, thisupd
, nextupd
);
1169 OCSP_id_get0_info(NULL
, NULL
, NULL
, &serial
, cid
);
1170 inf
= lookup_serial(db
, serial
);
1172 OCSP_basic_add1_status(bs
, cid
,
1173 V_OCSP_CERTSTATUS_UNKNOWN
,
1174 0, NULL
, thisupd
, nextupd
);
1175 } else if (inf
[DB_type
][0] == DB_TYPE_VAL
) {
1176 OCSP_basic_add1_status(bs
, cid
,
1177 V_OCSP_CERTSTATUS_GOOD
,
1178 0, NULL
, thisupd
, nextupd
);
1179 } else if (inf
[DB_type
][0] == DB_TYPE_REV
) {
1180 ASN1_OBJECT
*inst
= NULL
;
1181 ASN1_TIME
*revtm
= NULL
;
1182 ASN1_GENERALIZEDTIME
*invtm
= NULL
;
1183 OCSP_SINGLERESP
*single
;
1185 unpack_revinfo(&revtm
, &reason
, &inst
, &invtm
, inf
[DB_rev_date
]);
1186 single
= OCSP_basic_add1_status(bs
, cid
,
1187 V_OCSP_CERTSTATUS_REVOKED
,
1188 reason
, revtm
, thisupd
, nextupd
);
1190 OCSP_SINGLERESP_add1_ext_i2d(single
, NID_invalidity_date
,
1192 else if (inst
!= NULL
)
1193 OCSP_SINGLERESP_add1_ext_i2d(single
,
1194 NID_hold_instruction_code
, inst
,
1196 ASN1_OBJECT_free(inst
);
1197 ASN1_TIME_free(revtm
);
1198 ASN1_GENERALIZEDTIME_free(invtm
);
1202 OCSP_copy_nonce(bs
, req
);
1204 mctx
= EVP_MD_CTX_new();
1205 if ( mctx
== NULL
|| !EVP_DigestSignInit(mctx
, &pkctx
, rmd
, NULL
, rkey
)) {
1206 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR
, NULL
);
1209 for (i
= 0; i
< sk_OPENSSL_STRING_num(sigopts
); i
++) {
1210 char *sigopt
= sk_OPENSSL_STRING_value(sigopts
, i
);
1212 if (pkey_ctrl_string(pkctx
, sigopt
) <= 0) {
1213 BIO_printf(err
, "parameter error \"%s\"\n", sigopt
);
1214 ERR_print_errors(bio_err
);
1215 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR
,
1220 OCSP_basic_sign_ctx(bs
, rcert
, mctx
, rother
, flags
);
1223 const ASN1_OCTET_STRING
*sig
= OCSP_resp_get0_signature(bs
);
1224 corrupt_signature(sig
);
1227 *resp
= OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL
, bs
);
1230 EVP_MD_CTX_free(mctx
);
1231 ASN1_TIME_free(thisupd
);
1232 ASN1_TIME_free(nextupd
);
1233 OCSP_BASICRESP_free(bs
);
1236 static char **lookup_serial(CA_DB
*db
, ASN1_INTEGER
*ser
)
1240 char *itmp
, *row
[DB_NUMBER
], **rrow
;
1241 for (i
= 0; i
< DB_NUMBER
; i
++)
1243 bn
= ASN1_INTEGER_to_BN(ser
, NULL
);
1244 OPENSSL_assert(bn
); /* FIXME: should report an error at this
1245 * point and abort */
1247 itmp
= OPENSSL_strdup("00");
1249 itmp
= BN_bn2hex(bn
);
1250 row
[DB_serial
] = itmp
;
1252 rrow
= TXT_DB_get_by_index(db
->db
, DB_serial
, row
);
1257 /* Quick and dirty OCSP server: read in and parse input request */
1259 static BIO
*init_responder(const char *port
)
1261 # ifdef OPENSSL_NO_SOCK
1263 "Error setting up accept BIO - sockets not supported.\n");
1266 BIO
*acbio
= NULL
, *bufbio
= NULL
;
1268 bufbio
= BIO_new(BIO_f_buffer());
1271 acbio
= BIO_new(BIO_s_accept());
1273 || BIO_set_bind_mode(acbio
, BIO_BIND_REUSEADDR
) < 0
1274 || BIO_set_accept_port(acbio
, port
) < 0) {
1275 log_message(LOG_ERR
, "Error setting up accept BIO");
1279 BIO_set_accept_bios(acbio
, bufbio
);
1281 if (BIO_do_accept(acbio
) <= 0) {
1282 log_message(LOG_ERR
, "Error starting accept");
1289 BIO_free_all(acbio
);
1295 # ifndef OPENSSL_NO_SOCK
1297 * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1299 static int urldecode(char *p
)
1301 unsigned char *out
= (unsigned char *)p
;
1302 unsigned char *save
= out
;
1307 else if (isxdigit(_UC(p
[1])) && isxdigit(_UC(p
[2]))) {
1308 /* Don't check, can't fail because of ixdigit() call. */
1309 *out
++ = (OPENSSL_hexchar2int(p
[1]) << 4)
1310 | OPENSSL_hexchar2int(p
[2]);
1317 return (int)(out
- save
);
1322 static void sock_timeout(int signum
)
1324 if (acfd
!= (int)INVALID_SOCKET
)
1325 (void)shutdown(acfd
, SHUT_RD
);
1329 static int do_responder(OCSP_REQUEST
**preq
, BIO
**pcbio
, BIO
*acbio
,
1332 # ifdef OPENSSL_NO_SOCK
1336 OCSP_REQUEST
*req
= NULL
;
1337 char inbuf
[2048], reqbuf
[2048];
1339 BIO
*cbio
= NULL
, *getbio
= NULL
, *b64
= NULL
;
1344 /* Connection loss before accept() is routine, ignore silently */
1345 if (BIO_do_accept(acbio
) <= 0)
1348 cbio
= BIO_pop(acbio
);
1350 client
= BIO_get_peer_name(cbio
);
1354 (void) BIO_get_fd(cbio
, &acfd
);
1359 /* Read the request line. */
1360 len
= BIO_gets(cbio
, reqbuf
, sizeof(reqbuf
));
1364 if (strncmp(reqbuf
, "GET ", 4) == 0) {
1365 /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1366 for (p
= reqbuf
+ 4; *p
== ' '; ++p
)
1369 log_message(LOG_INFO
, "Invalid request -- bad URL: %s", client
);
1374 /* Splice off the HTTP version identifier. */
1375 for (q
= p
; *q
; q
++)
1378 if (strncmp(q
, " HTTP/1.", 8) != 0) {
1379 log_message(LOG_INFO
,
1380 "Invalid request -- bad HTTP version: %s", client
);
1386 * Skip "GET / HTTP..." requests often used by load-balancers
1393 log_message(LOG_INFO
,
1394 "Invalid request -- bad URL encoding: %s", client
);
1397 if ((getbio
= BIO_new_mem_buf(p
, len
)) == NULL
1398 || (b64
= BIO_new(BIO_f_base64())) == NULL
) {
1399 log_message(LOG_ERR
, "Could not allocate base64 bio: %s", client
);
1402 BIO_set_flags(b64
, BIO_FLAGS_BASE64_NO_NL
);
1403 getbio
= BIO_push(b64
, getbio
);
1404 } else if (strncmp(reqbuf
, "POST ", 5) != 0) {
1405 log_message(LOG_INFO
, "Invalid request -- bad HTTP verb: %s", client
);
1409 /* Read and skip past the headers. */
1411 len
= BIO_gets(cbio
, inbuf
, sizeof(inbuf
));
1414 if ((inbuf
[0] == '\r') || (inbuf
[0] == '\n'))
1419 /* Clear alarm before we close the client socket */
1424 /* Try to read OCSP request */
1425 if (getbio
!= NULL
) {
1426 req
= d2i_OCSP_REQUEST_bio(getbio
, NULL
);
1427 BIO_free_all(getbio
);
1429 req
= d2i_OCSP_REQUEST_bio(cbio
, NULL
);
1433 log_message(LOG_ERR
, "Error parsing OCSP request");
1441 acfd
= (int)INVALID_SOCKET
;
1447 static int send_ocsp_response(BIO
*cbio
, OCSP_RESPONSE
*resp
)
1450 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1451 "Content-Length: %d\r\n\r\n";
1454 BIO_printf(cbio
, http_resp
, i2d_OCSP_RESPONSE(resp
, NULL
));
1455 i2d_OCSP_RESPONSE_bio(cbio
, resp
);
1456 (void)BIO_flush(cbio
);
1460 # ifndef OPENSSL_NO_SOCK
1461 static OCSP_RESPONSE
*query_responder(BIO
*cbio
, const char *host
,
1463 const STACK_OF(CONF_VALUE
) *headers
,
1464 OCSP_REQUEST
*req
, int req_timeout
)
1470 OCSP_REQ_CTX
*ctx
= NULL
;
1471 OCSP_RESPONSE
*rsp
= NULL
;
1475 if (req_timeout
!= -1)
1476 BIO_set_nbio(cbio
, 1);
1478 rv
= BIO_do_connect(cbio
);
1480 if ((rv
<= 0) && ((req_timeout
== -1) || !BIO_should_retry(cbio
))) {
1481 BIO_puts(bio_err
, "Error connecting BIO\n");
1485 if (BIO_get_fd(cbio
, &fd
) < 0) {
1486 BIO_puts(bio_err
, "Can't get connection fd\n");
1490 if (req_timeout
!= -1 && rv
<= 0) {
1492 openssl_fdset(fd
, &confds
);
1494 tv
.tv_sec
= req_timeout
;
1495 rv
= select(fd
+ 1, NULL
, (void *)&confds
, NULL
, &tv
);
1497 BIO_puts(bio_err
, "Timeout on connect\n");
1502 ctx
= OCSP_sendreq_new(cbio
, path
, NULL
, -1);
1506 for (i
= 0; i
< sk_CONF_VALUE_num(headers
); i
++) {
1507 CONF_VALUE
*hdr
= sk_CONF_VALUE_value(headers
, i
);
1508 if (add_host
== 1 && strcasecmp("host", hdr
->name
) == 0)
1510 if (!OCSP_REQ_CTX_add1_header(ctx
, hdr
->name
, hdr
->value
))
1514 if (add_host
== 1 && OCSP_REQ_CTX_add1_header(ctx
, "Host", host
) == 0)
1517 if (!OCSP_REQ_CTX_set1_req(ctx
, req
))
1521 rv
= OCSP_sendreq_nbio(&rsp
, ctx
);
1524 if (req_timeout
== -1)
1527 openssl_fdset(fd
, &confds
);
1529 tv
.tv_sec
= req_timeout
;
1530 if (BIO_should_read(cbio
)) {
1531 rv
= select(fd
+ 1, (void *)&confds
, NULL
, NULL
, &tv
);
1532 } else if (BIO_should_write(cbio
)) {
1533 rv
= select(fd
+ 1, NULL
, (void *)&confds
, NULL
, &tv
);
1535 BIO_puts(bio_err
, "Unexpected retry condition\n");
1539 BIO_puts(bio_err
, "Timeout on request\n");
1543 BIO_puts(bio_err
, "Select error\n");
1549 OCSP_REQ_CTX_free(ctx
);
1554 OCSP_RESPONSE
*process_responder(OCSP_REQUEST
*req
,
1555 const char *host
, const char *path
,
1556 const char *port
, int use_ssl
,
1557 STACK_OF(CONF_VALUE
) *headers
,
1561 SSL_CTX
*ctx
= NULL
;
1562 OCSP_RESPONSE
*resp
= NULL
;
1564 cbio
= BIO_new_connect(host
);
1566 BIO_printf(bio_err
, "Error creating connect BIO\n");
1570 BIO_set_conn_port(cbio
, port
);
1573 ctx
= SSL_CTX_new(TLS_client_method());
1575 BIO_printf(bio_err
, "Error creating SSL context.\n");
1578 SSL_CTX_set_mode(ctx
, SSL_MODE_AUTO_RETRY
);
1579 sbio
= BIO_new_ssl(ctx
, 1);
1580 cbio
= BIO_push(sbio
, cbio
);
1583 resp
= query_responder(cbio
, host
, path
, headers
, req
, req_timeout
);
1585 BIO_printf(bio_err
, "Error querying OCSP responder\n");