coverity 1462556 Resource leak
[openssl.git] / apps / ocsp.c
1 /*
2  * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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
8  */
9
10 #include <openssl/opensslconf.h>
11
12 #ifdef OPENSSL_SYS_VMS
13   /* So fd_set and friends get properly defined on OpenVMS */
14 # define _XOPEN_SOURCE_EXTENDED
15 #endif
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <time.h>
21 #include <ctype.h>
22
23 /* Needs to be included before the openssl headers */
24 #include "apps.h"
25 #include "progs.h"
26 #include "internal/sockets.h"
27 #include <openssl/e_os2.h>
28 #include <openssl/crypto.h>
29 #include <openssl/err.h>
30 #include <openssl/ssl.h>
31 #include <openssl/evp.h>
32 #include <openssl/bn.h>
33 #include <openssl/x509v3.h>
34 #include <openssl/rand.h>
35
36 DEFINE_STACK_OF(OCSP_CERTID)
37 DEFINE_STACK_OF(CONF_VALUE)
38 DEFINE_STACK_OF(X509)
39 DEFINE_STACK_OF_STRING()
40
41 #ifndef HAVE_FORK
42 # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS)
43 #  define HAVE_FORK 0
44 # else
45 #  define HAVE_FORK 1
46 # endif
47 #endif
48
49 #if HAVE_FORK
50 # undef NO_FORK
51 #else
52 # define NO_FORK
53 #endif
54
55 #if !defined(NO_FORK) && !defined(OPENSSL_NO_SOCK) \
56      && !defined(OPENSSL_NO_POSIX_IO)
57 # define OCSP_DAEMON
58 # include <sys/types.h>
59 # include <sys/wait.h>
60 # include <syslog.h>
61 # include <signal.h>
62 # define MAXERRLEN 1000 /* limit error text sent to syslog to 1000 bytes */
63 #else
64 # undef LOG_INFO
65 # undef LOG_WARNING
66 # undef LOG_ERR
67 # define LOG_INFO      0
68 # define LOG_WARNING   1
69 # define LOG_ERR       2
70 #endif
71
72 #if defined(OPENSSL_SYS_VXWORKS)
73 /* not supported */
74 int setpgid(pid_t pid, pid_t pgid)
75 {
76     errno = ENOSYS;
77     return 0;
78 }
79 /* not supported */
80 pid_t fork(void)
81 {
82     errno = ENOSYS;
83     return (pid_t) -1;
84 }
85 #endif
86 /* Maximum leeway in validity period: default 5 minutes */
87 #define MAX_VALIDITY_PERIOD    (5 * 60)
88
89 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
90                          const EVP_MD *cert_id_md, X509 *issuer,
91                          STACK_OF(OCSP_CERTID) *ids);
92 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
93                            const EVP_MD *cert_id_md, X509 *issuer,
94                            STACK_OF(OCSP_CERTID) *ids);
95 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
96                               STACK_OF(OPENSSL_STRING) *names,
97                               STACK_OF(OCSP_CERTID) *ids, long nsec,
98                               long maxage);
99 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
100                               CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
101                               EVP_PKEY *rkey, const EVP_MD *md,
102                               STACK_OF(OPENSSL_STRING) *sigopts,
103                               STACK_OF(X509) *rother, unsigned long flags,
104                               int nmin, int ndays, int badsig,
105                               const EVP_MD *resp_md);
106
107 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
108 static BIO *init_responder(const char *port);
109 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout);
110 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
111 static void log_message(int level, const char *fmt, ...);
112 static char *prog;
113 static int multi = 0;
114
115 #ifdef OCSP_DAEMON
116 static int acfd = (int) INVALID_SOCKET;
117 static int index_changed(CA_DB *);
118 static void spawn_loop(void);
119 static int print_syslog(const char *str, size_t len, void *levPtr);
120 static void socket_timeout(int signum);
121 #endif
122
123 typedef enum OPTION_choice {
124     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
125     OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT,
126     OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE,
127     OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS,
128     OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN,
129     OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER,
130     OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT,
131     OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER,
132     OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE,
133     OPT_NOCAPATH, OPT_NOCASTORE,
134     OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT,
135     OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL,
136     OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER,
137     OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER,
138     OPT_PASSIN,
139     OPT_RCID,
140     OPT_V_ENUM,
141     OPT_MD,
142     OPT_MULTI, OPT_PROV_ENUM
143 } OPTION_CHOICE;
144
145 const OPTIONS ocsp_options[] = {
146     OPT_SECTION("General"),
147     {"help", OPT_HELP, '-', "Display this summary"},
148     {"ignore_err", OPT_IGNORE_ERR, '-',
149      "Ignore error on OCSP request or response and continue running"},
150     {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"},
151     {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"},
152     {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"},
153     {"no-CAfile", OPT_NOCAFILE, '-',
154      "Do not load the default certificates file"},
155     {"no-CApath", OPT_NOCAPATH, '-',
156      "Do not load certificates from the default certificates directory"},
157     {"no-CAstore", OPT_NOCAPATH, '-',
158      "Do not load certificates from the default certificates store"},
159
160     OPT_SECTION("Responder"),
161     {"timeout", OPT_TIMEOUT, 'p',
162      "Connection timeout (in seconds) to the OCSP responder"},
163     {"resp_no_certs", OPT_RESP_NO_CERTS, '-',
164      "Don't include any certificates in response"},
165 #ifdef OCSP_DAEMON
166     {"multi", OPT_MULTI, 'p', "run multiple responder processes"},
167 #endif
168     {"no_certs", OPT_NO_CERTS, '-',
169      "Don't include any certificates in signed request"},
170     {"badsig", OPT_BADSIG, '-',
171         "Corrupt last byte of loaded OSCP response signature (for test)"},
172     {"CA", OPT_CA, '<', "CA certificate"},
173     {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"},
174     {"nrequest", OPT_REQUEST, 'p',
175      "Number of requests to accept (default unlimited)"},
176     {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"},
177     {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"},
178     {"sign_other", OPT_SIGN_OTHER, '<',
179      "Additional certificates to include in signed request"},
180     {"index", OPT_INDEX, '<', "Certificate status index file"},
181     {"ndays", OPT_NDAYS, 'p', "Number of days before next update"},
182     {"rsigner", OPT_RSIGNER, '<',
183      "Responder certificate to sign responses with"},
184     {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"},
185     {"passin", OPT_PASSIN, 's', "Responder key pass phrase source"},
186     {"rother", OPT_ROTHER, '<', "Other certificates to include in response"},
187     {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"},
188     {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"},
189     {"header", OPT_HEADER, 's', "key=value header to add"},
190     {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"},
191     {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"},
192
193     OPT_SECTION("Client"),
194     {"url", OPT_URL, 's', "Responder URL"},
195     {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"},
196     {"port", OPT_PORT, 'p', "Port to run responder on"},
197     {"out", OPT_OUTFILE, '>', "Output filename"},
198     {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"},
199     {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"},
200     {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"},
201     {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-',
202      "Don't check signature on response"},
203     {"resp_key_id", OPT_RESP_KEY_ID, '-',
204      "Identify response by signing certificate key ID"},
205     {"no_cert_verify", OPT_NO_CERT_VERIFY, '-',
206      "Don't check signing certificate"},
207     {"text", OPT_TEXT, '-', "Print text form of request and response"},
208     {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"},
209     {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"},
210     {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"},
211     {"no_cert_checks", OPT_NO_CERT_CHECKS, '-',
212      "Don't do additional checks on signing certificate"},
213     {"no_explicit", OPT_NO_EXPLICIT, '-',
214      "Do not explicitly check the chain, just verify the root"},
215     {"trust_other", OPT_TRUST_OTHER, '-',
216      "Don't verify additional certificates"},
217     {"no_intern", OPT_NO_INTERN, '-',
218      "Don't search certificates contained in response for signer"},
219     {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"},
220     {"VAfile", OPT_VAFILE, '<', "Validator certificates file"},
221     {"verify_other", OPT_VERIFY_OTHER, '<',
222      "Additional certificates to search for signer"},
223     {"path", OPT_PATH, 's', "Path to use in OCSP request"},
224     {"cert", OPT_CERT, '<', "Certificate to check"},
225     {"serial", OPT_SERIAL, 's', "Serial number to check"},
226     {"validity_period", OPT_VALIDITY_PERIOD, 'u',
227      "Maximum validity discrepancy in seconds"},
228     {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"},
229     {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"},
230     {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"},
231     {"issuer", OPT_ISSUER, '<', "Issuer certificate"},
232     {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"},
233
234     OPT_V_OPTIONS,
235     OPT_PROV_OPTIONS,
236     {NULL}
237 };
238
239 int ocsp_main(int argc, char **argv)
240 {
241     BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
242     const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
243     STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL;
244     int trailing_md = 0;
245     CA_DB *rdb = NULL;
246     EVP_PKEY *key = NULL, *rkey = NULL;
247     OCSP_BASICRESP *bs = NULL;
248     OCSP_REQUEST *req = NULL;
249     OCSP_RESPONSE *resp = NULL;
250     STACK_OF(CONF_VALUE) *headers = NULL;
251     STACK_OF(OCSP_CERTID) *ids = NULL;
252     STACK_OF(OPENSSL_STRING) *reqnames = NULL;
253     STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
254     STACK_OF(X509) *issuers = NULL;
255     X509 *issuer = NULL, *cert = NULL;
256     STACK_OF(X509) *rca_cert = NULL;
257     const EVP_MD *resp_certid_md = NULL;
258     X509 *signer = NULL, *rsigner = NULL;
259     X509_STORE *store = NULL;
260     X509_VERIFY_PARAM *vpm = NULL;
261     const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL;
262     char *header, *value;
263     char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
264     char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
265     char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
266     char *rsignfile = NULL, *rkeyfile = NULL;
267     char *passinarg = NULL, *passin = NULL;
268     char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
269     char *signfile = NULL, *keyfile = NULL;
270     char *thost = NULL, *tport = NULL, *tpath = NULL;
271     int noCAfile = 0, noCApath = 0, noCAstore = 0;
272     int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
273     int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
274     int req_text = 0, resp_text = 0, ret = 1;
275     int req_timeout = -1;
276     long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
277     unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
278     OPTION_CHOICE o;
279
280     reqnames = sk_OPENSSL_STRING_new_null();
281     if (reqnames == NULL)
282         goto end;
283     ids = sk_OCSP_CERTID_new_null();
284     if (ids == NULL)
285         goto end;
286     if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
287         return 1;
288
289     prog = opt_init(argc, argv, ocsp_options);
290     while ((o = opt_next()) != OPT_EOF) {
291         switch (o) {
292         case OPT_EOF:
293         case OPT_ERR:
294  opthelp:
295             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
296             goto end;
297         case OPT_HELP:
298             ret = 0;
299             opt_help(ocsp_options);
300             goto end;
301         case OPT_OUTFILE:
302             outfile = opt_arg();
303             break;
304         case OPT_TIMEOUT:
305 #ifndef OPENSSL_NO_SOCK
306             req_timeout = atoi(opt_arg());
307 #endif
308             break;
309         case OPT_URL:
310             OPENSSL_free(thost);
311             OPENSSL_free(tport);
312             OPENSSL_free(tpath);
313             thost = tport = tpath = NULL;
314             if (!OSSL_HTTP_parse_url(opt_arg(),
315                                      &host, &port, &path, &use_ssl)) {
316                 BIO_printf(bio_err, "%s Error parsing URL\n", prog);
317                 goto end;
318             }
319             thost = host;
320             tport = port;
321             tpath = path;
322             break;
323         case OPT_HOST:
324             host = opt_arg();
325             break;
326         case OPT_PORT:
327             port = opt_arg();
328             break;
329         case OPT_IGNORE_ERR:
330             ignore_err = 1;
331             break;
332         case OPT_NOVERIFY:
333             noverify = 1;
334             break;
335         case OPT_NONCE:
336             add_nonce = 2;
337             break;
338         case OPT_NO_NONCE:
339             add_nonce = 0;
340             break;
341         case OPT_RESP_NO_CERTS:
342             rflags |= OCSP_NOCERTS;
343             break;
344         case OPT_RESP_KEY_ID:
345             rflags |= OCSP_RESPID_KEY;
346             break;
347         case OPT_NO_CERTS:
348             sign_flags |= OCSP_NOCERTS;
349             break;
350         case OPT_NO_SIGNATURE_VERIFY:
351             verify_flags |= OCSP_NOSIGS;
352             break;
353         case OPT_NO_CERT_VERIFY:
354             verify_flags |= OCSP_NOVERIFY;
355             break;
356         case OPT_NO_CHAIN:
357             verify_flags |= OCSP_NOCHAIN;
358             break;
359         case OPT_NO_CERT_CHECKS:
360             verify_flags |= OCSP_NOCHECKS;
361             break;
362         case OPT_NO_EXPLICIT:
363             verify_flags |= OCSP_NOEXPLICIT;
364             break;
365         case OPT_TRUST_OTHER:
366             verify_flags |= OCSP_TRUSTOTHER;
367             break;
368         case OPT_NO_INTERN:
369             verify_flags |= OCSP_NOINTERN;
370             break;
371         case OPT_BADSIG:
372             badsig = 1;
373             break;
374         case OPT_TEXT:
375             req_text = resp_text = 1;
376             break;
377         case OPT_REQ_TEXT:
378             req_text = 1;
379             break;
380         case OPT_RESP_TEXT:
381             resp_text = 1;
382             break;
383         case OPT_REQIN:
384             reqin = opt_arg();
385             break;
386         case OPT_RESPIN:
387             respin = opt_arg();
388             break;
389         case OPT_SIGNER:
390             signfile = opt_arg();
391             break;
392         case OPT_VAFILE:
393             verify_certfile = opt_arg();
394             verify_flags |= OCSP_TRUSTOTHER;
395             break;
396         case OPT_SIGN_OTHER:
397             sign_certfile = opt_arg();
398             break;
399         case OPT_VERIFY_OTHER:
400             verify_certfile = opt_arg();
401             break;
402         case OPT_CAFILE:
403             CAfile = opt_arg();
404             break;
405         case OPT_CAPATH:
406             CApath = opt_arg();
407             break;
408         case OPT_CASTORE:
409             CAstore = opt_arg();
410             break;
411         case OPT_NOCAFILE:
412             noCAfile = 1;
413             break;
414         case OPT_NOCAPATH:
415             noCApath = 1;
416             break;
417         case OPT_NOCASTORE:
418             noCAstore = 1;
419             break;
420         case OPT_V_CASES:
421             if (!opt_verify(o, vpm))
422                 goto end;
423             vpmtouched++;
424             break;
425         case OPT_VALIDITY_PERIOD:
426             opt_long(opt_arg(), &nsec);
427             break;
428         case OPT_STATUS_AGE:
429             opt_long(opt_arg(), &maxage);
430             break;
431         case OPT_SIGNKEY:
432             keyfile = opt_arg();
433             break;
434         case OPT_REQOUT:
435             reqout = opt_arg();
436             break;
437         case OPT_RESPOUT:
438             respout = opt_arg();
439             break;
440         case OPT_PATH:
441             path = opt_arg();
442             break;
443         case OPT_ISSUER:
444             issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
445             if (issuer == NULL)
446                 goto end;
447             if (issuers == NULL) {
448                 if ((issuers = sk_X509_new_null()) == NULL)
449                     goto end;
450             }
451             if (!sk_X509_push(issuers, issuer))
452                 goto end;
453             break;
454         case OPT_CERT:
455             X509_free(cert);
456             cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
457             if (cert == NULL)
458                 goto end;
459             if (cert_id_md == NULL)
460                 cert_id_md = EVP_sha1();
461             if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
462                 goto end;
463             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
464                 goto end;
465             trailing_md = 0;
466             break;
467         case OPT_SERIAL:
468             if (cert_id_md == NULL)
469                 cert_id_md = EVP_sha1();
470             if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
471                 goto end;
472             if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
473                 goto end;
474             trailing_md = 0;
475             break;
476         case OPT_INDEX:
477             ridx_filename = opt_arg();
478             break;
479         case OPT_CA:
480             rca_filename = opt_arg();
481             break;
482         case OPT_NMIN:
483             opt_int(opt_arg(), &nmin);
484             if (ndays == -1)
485                 ndays = 0;
486             break;
487         case OPT_REQUEST:
488             opt_int(opt_arg(), &accept_count);
489             break;
490         case OPT_NDAYS:
491             ndays = atoi(opt_arg());
492             break;
493         case OPT_RSIGNER:
494             rsignfile = opt_arg();
495             break;
496         case OPT_RKEY:
497             rkeyfile = opt_arg();
498             break;
499         case OPT_PASSIN:
500             passinarg = opt_arg();
501             break;
502         case OPT_ROTHER:
503             rcertfile = opt_arg();
504             break;
505         case OPT_RMD:   /* Response MessageDigest */
506             if (!opt_md(opt_arg(), &rsign_md))
507                 goto end;
508             break;
509         case OPT_RSIGOPT:
510             if (rsign_sigopts == NULL)
511                 rsign_sigopts = sk_OPENSSL_STRING_new_null();
512             if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg()))
513                 goto end;
514             break;
515         case OPT_HEADER:
516             header = opt_arg();
517             value = strchr(header, '=');
518             if (value == NULL) {
519                 BIO_printf(bio_err, "Missing = in header key=value\n");
520                 goto opthelp;
521             }
522             *value++ = '\0';
523             if (!X509V3_add_value(header, value, &headers))
524                 goto end;
525             break;
526         case OPT_RCID:
527             resp_certid_md = EVP_get_digestbyname(opt_arg());
528             if (resp_certid_md == NULL)
529                 goto opthelp;
530             break;
531         case OPT_MD:
532             if (trailing_md) {
533                 BIO_printf(bio_err,
534                            "%s: Digest must be before -cert or -serial\n",
535                            prog);
536                 goto opthelp;
537             }
538             if (!opt_md(opt_unknown(), &cert_id_md))
539                 goto opthelp;
540             trailing_md = 1;
541             break;
542         case OPT_MULTI:
543 #ifdef OCSP_DAEMON
544             multi = atoi(opt_arg());
545 #endif
546             break;
547         case OPT_PROV_CASES:
548             if (!opt_provider(o))
549                 goto end;
550             break;
551         }
552     }
553     if (trailing_md) {
554         BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
555                    prog);
556         goto opthelp;
557     }
558     argc = opt_num_rest();
559     if (argc != 0)
560         goto opthelp;
561
562     /* Have we anything to do? */
563     if (req == NULL && reqin == NULL
564         && respin == NULL && !(port != NULL && ridx_filename != NULL))
565         goto opthelp;
566
567     out = bio_open_default(outfile, 'w', FORMAT_TEXT);
568     if (out == NULL)
569         goto end;
570
571     if (req == NULL && (add_nonce != 2))
572         add_nonce = 0;
573
574     if (req == NULL && reqin != NULL) {
575         derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
576         if (derbio == NULL)
577             goto end;
578         req = d2i_OCSP_REQUEST_bio(derbio, NULL);
579         BIO_free(derbio);
580         if (req == NULL) {
581             BIO_printf(bio_err, "Error reading OCSP request\n");
582             goto end;
583         }
584     }
585
586     if (req == NULL && port != NULL) {
587         acbio = init_responder(port);
588         if (acbio == NULL)
589             goto end;
590     }
591
592     if (rsignfile != NULL) {
593         if (rkeyfile == NULL)
594             rkeyfile = rsignfile;
595         rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
596         if (rsigner == NULL) {
597             BIO_printf(bio_err, "Error loading responder certificate\n");
598             goto end;
599         }
600         if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
601                         NULL, "CA certificate"))
602             goto end;
603         if (rcertfile != NULL) {
604             if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
605                             "responder other certificates"))
606                 goto end;
607         }
608         if (!app_passwd(passinarg, NULL, &passin, NULL)) {
609             BIO_printf(bio_err, "Error getting password\n");
610             goto end;
611         }
612         rkey = load_key(rkeyfile, FORMAT_PEM, 0, passin, NULL,
613                         "responder private key");
614         if (rkey == NULL)
615             goto end;
616     }
617
618     if (ridx_filename != NULL
619         && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
620         BIO_printf(bio_err,
621                    "Responder mode requires certificate, key, and CA.\n");
622         goto end;
623     }
624
625     if (ridx_filename != NULL) {
626         rdb = load_index(ridx_filename, NULL);
627         if (rdb == NULL || index_index(rdb) <= 0) {
628             ret = 1;
629             goto end;
630         }
631     }
632
633 #ifdef OCSP_DAEMON
634     if (multi && acbio != NULL)
635         spawn_loop();
636     if (acbio != NULL && req_timeout > 0)
637         signal(SIGALRM, socket_timeout);
638 #endif
639
640     if (acbio != NULL)
641         log_message(LOG_INFO, "waiting for OCSP client connections...");
642
643 redo_accept:
644
645     if (acbio != NULL) {
646 #ifdef OCSP_DAEMON
647         if (index_changed(rdb)) {
648             CA_DB *newrdb = load_index(ridx_filename, NULL);
649
650             if (newrdb != NULL && index_index(newrdb) > 0) {
651                 free_index(rdb);
652                 rdb = newrdb;
653             } else {
654                 free_index(newrdb);
655                 log_message(LOG_ERR, "error reloading updated index: %s",
656                             ridx_filename);
657             }
658         }
659 #endif
660
661         req = NULL;
662         if (!do_responder(&req, &cbio, acbio, req_timeout))
663             goto redo_accept;
664
665         if (req == NULL) {
666             resp =
667                 OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
668                                      NULL);
669             send_ocsp_response(cbio, resp);
670             goto done_resp;
671         }
672     }
673
674     if (req == NULL
675         && (signfile != NULL || reqout != NULL
676             || host != NULL || add_nonce || ridx_filename != NULL)) {
677         BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
678         goto end;
679     }
680
681     if (req != NULL && add_nonce) {
682         if (!OCSP_request_add1_nonce(req, NULL, -1))
683             goto end;
684     }
685
686     if (signfile != NULL) {
687         if (keyfile == NULL)
688             keyfile = signfile;
689         signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
690         if (signer == NULL) {
691             BIO_printf(bio_err, "Error loading signer certificate\n");
692             goto end;
693         }
694         if (sign_certfile != NULL) {
695             if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
696                             "signer certificates"))
697                 goto end;
698         }
699         key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
700                        "signer private key");
701         if (key == NULL)
702             goto end;
703
704         if (!OCSP_request_sign
705             (req, signer, key, NULL, sign_other, sign_flags)) {
706             BIO_printf(bio_err, "Error signing OCSP request\n");
707             goto end;
708         }
709     }
710
711     if (req_text && req != NULL)
712         OCSP_REQUEST_print(out, req, 0);
713
714     if (reqout != NULL) {
715         derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
716         if (derbio == NULL)
717             goto end;
718         i2d_OCSP_REQUEST_bio(derbio, req);
719         BIO_free(derbio);
720     }
721
722     if (rdb != NULL) {
723         make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey,
724                            rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig,
725                            resp_certid_md);
726         if (cbio != NULL)
727             send_ocsp_response(cbio, resp);
728     } else if (host != NULL) {
729 #ifndef OPENSSL_NO_SOCK
730         resp = process_responder(req, host, path,
731                                  port, use_ssl, headers, req_timeout);
732         if (resp == NULL)
733             goto end;
734 #else
735         BIO_printf(bio_err,
736                    "Error creating connect BIO - sockets not supported.\n");
737         goto end;
738 #endif
739     } else if (respin != NULL) {
740         derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
741         if (derbio == NULL)
742             goto end;
743         resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
744         BIO_free(derbio);
745         if (resp == NULL) {
746             BIO_printf(bio_err, "Error reading OCSP response\n");
747             goto end;
748         }
749     } else {
750         ret = 0;
751         goto end;
752     }
753
754  done_resp:
755
756     if (respout != NULL) {
757         derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
758         if (derbio == NULL)
759             goto end;
760         i2d_OCSP_RESPONSE_bio(derbio, resp);
761         BIO_free(derbio);
762     }
763
764     i = OCSP_response_status(resp);
765     if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
766         BIO_printf(out, "Responder Error: %s (%d)\n",
767                    OCSP_response_status_str(i), i);
768         if (!ignore_err)
769                 goto end;
770     }
771
772     if (resp_text)
773         OCSP_RESPONSE_print(out, resp, 0);
774
775     /* If running as responder don't verify our own response */
776     if (cbio != NULL) {
777         /* If not unlimited, see if we took all we should. */
778         if (accept_count != -1 && --accept_count <= 0) {
779             ret = 0;
780             goto end;
781         }
782         BIO_free_all(cbio);
783         cbio = NULL;
784         OCSP_REQUEST_free(req);
785         req = NULL;
786         OCSP_RESPONSE_free(resp);
787         resp = NULL;
788         goto redo_accept;
789     }
790     if (ridx_filename != NULL) {
791         ret = 0;
792         goto end;
793     }
794
795     if (store == NULL) {
796         store = setup_verify(CAfile, noCAfile, CApath, noCApath,
797                              CAstore, noCAstore);
798         if (!store)
799             goto end;
800     }
801     if (vpmtouched)
802         X509_STORE_set1_param(store, vpm);
803     if (verify_certfile != NULL) {
804         if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
805                         "validator certificate"))
806             goto end;
807     }
808
809     bs = OCSP_response_get1_basic(resp);
810     if (bs == NULL) {
811         BIO_printf(bio_err, "Error parsing response\n");
812         goto end;
813     }
814
815     ret = 0;
816
817     if (!noverify) {
818         if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
819             if (i == -1)
820                 BIO_printf(bio_err, "WARNING: no nonce in response\n");
821             else {
822                 BIO_printf(bio_err, "Nonce Verify error\n");
823                 ret = 1;
824                 goto end;
825             }
826         }
827
828         i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
829         if (i <= 0 && issuers) {
830             i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
831             if (i > 0)
832                 ERR_clear_error();
833         }
834         if (i <= 0) {
835             BIO_printf(bio_err, "Response Verify Failure\n");
836             ERR_print_errors(bio_err);
837             ret = 1;
838         } else {
839             BIO_printf(bio_err, "Response verify OK\n");
840         }
841     }
842
843     print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);
844
845  end:
846     ERR_print_errors(bio_err);
847     X509_free(signer);
848     X509_STORE_free(store);
849     X509_VERIFY_PARAM_free(vpm);
850     sk_OPENSSL_STRING_free(rsign_sigopts);
851     EVP_PKEY_free(key);
852     EVP_PKEY_free(rkey);
853     X509_free(cert);
854     sk_X509_pop_free(issuers, X509_free);
855     X509_free(rsigner);
856     sk_X509_pop_free(rca_cert, X509_free);
857     free_index(rdb);
858     BIO_free_all(cbio);
859     BIO_free_all(acbio);
860     BIO_free_all(out);
861     OCSP_REQUEST_free(req);
862     OCSP_RESPONSE_free(resp);
863     OCSP_BASICRESP_free(bs);
864     sk_OPENSSL_STRING_free(reqnames);
865     sk_OCSP_CERTID_free(ids);
866     sk_X509_pop_free(sign_other, X509_free);
867     sk_X509_pop_free(verify_other, X509_free);
868     sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
869     OPENSSL_free(thost);
870     OPENSSL_free(tport);
871     OPENSSL_free(tpath);
872
873     return ret;
874 }
875
876 static void
877 log_message(int level, const char *fmt, ...)
878 {
879     va_list ap;
880
881     va_start(ap, fmt);
882 #ifdef OCSP_DAEMON
883     if (multi) {
884         char buf[1024];
885         if (vsnprintf(buf, sizeof(buf), fmt, ap) > 0) {
886             syslog(level, "%s", buf);
887         }
888         if (level >= LOG_ERR)
889             ERR_print_errors_cb(print_syslog, &level);
890     }
891 #endif
892     if (!multi) {
893         BIO_printf(bio_err, "%s: ", prog);
894         BIO_vprintf(bio_err, fmt, ap);
895         BIO_printf(bio_err, "\n");
896     }
897     va_end(ap);
898 }
899
900 #ifdef OCSP_DAEMON
901
902 static int print_syslog(const char *str, size_t len, void *levPtr)
903 {
904     int level = *(int *)levPtr;
905     int ilen = (len > MAXERRLEN) ? MAXERRLEN : len;
906
907     syslog(level, "%.*s", ilen, str);
908
909     return ilen;
910 }
911
912 static int index_changed(CA_DB *rdb)
913 {
914     struct stat sb;
915
916     if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) {
917         if (rdb->dbst.st_mtime != sb.st_mtime
918             || rdb->dbst.st_ctime != sb.st_ctime
919             || rdb->dbst.st_ino != sb.st_ino
920             || rdb->dbst.st_dev != sb.st_dev) {
921             syslog(LOG_INFO, "index file changed, reloading");
922             return 1;
923         }
924     }
925     return 0;
926 }
927
928 static void killall(int ret, pid_t *kidpids)
929 {
930     int i;
931
932     for (i = 0; i < multi; ++i)
933         if (kidpids[i] != 0)
934             (void)kill(kidpids[i], SIGTERM);
935     OPENSSL_free(kidpids);
936     sleep(1);
937     exit(ret);
938 }
939
940 static int termsig = 0;
941
942 static void noteterm (int sig)
943 {
944     termsig = sig;
945 }
946
947 /*
948  * Loop spawning up to `multi` child processes, only child processes return
949  * from this function.  The parent process loops until receiving a termination
950  * signal, kills extant children and exits without returning.
951  */
952 static void spawn_loop(void)
953 {
954     pid_t *kidpids = NULL;
955     int status;
956     int procs = 0;
957     int i;
958
959     openlog(prog, LOG_PID, LOG_DAEMON);
960
961     if (setpgid(0, 0)) {
962         syslog(LOG_ERR, "fatal: error detaching from parent process group: %s",
963                strerror(errno));
964         exit(1);
965     }
966     kidpids = app_malloc(multi * sizeof(*kidpids), "child PID array");
967     for (i = 0; i < multi; ++i)
968         kidpids[i] = 0;
969
970     signal(SIGINT, noteterm);
971     signal(SIGTERM, noteterm);
972
973     while (termsig == 0) {
974         pid_t fpid;
975
976         /*
977          * Wait for a child to replace when we're at the limit.
978          * Slow down if a child exited abnormally or waitpid() < 0
979          */
980         while (termsig == 0 && procs >= multi) {
981             if ((fpid = waitpid(-1, &status, 0)) > 0) {
982                 for (i = 0; i < procs; ++i) {
983                     if (kidpids[i] == fpid) {
984                         kidpids[i] = 0;
985                         --procs;
986                         break;
987                     }
988                 }
989                 if (i >= multi) {
990                     syslog(LOG_ERR, "fatal: internal error: "
991                            "no matching child slot for pid: %ld",
992                            (long) fpid);
993                     killall(1, kidpids);
994                 }
995                 if (status != 0) {
996                     if (WIFEXITED(status))
997                         syslog(LOG_WARNING, "child process: %ld, exit status: %d",
998                                (long)fpid, WEXITSTATUS(status));
999                     else if (WIFSIGNALED(status))
1000                         syslog(LOG_WARNING, "child process: %ld, term signal %d%s",
1001                                (long)fpid, WTERMSIG(status),
1002 #ifdef WCOREDUMP
1003                                WCOREDUMP(status) ? " (core dumped)" :
1004 #endif
1005                                "");
1006                     sleep(1);
1007                 }
1008                 break;
1009             } else if (errno != EINTR) {
1010                 syslog(LOG_ERR, "fatal: waitpid(): %s", strerror(errno));
1011                 killall(1, kidpids);
1012             }
1013         }
1014         if (termsig)
1015             break;
1016
1017         switch(fpid = fork()) {
1018         case -1:            /* error */
1019             /* System critically low on memory, pause and try again later */
1020             sleep(30);
1021             break;
1022         case 0:             /* child */
1023             OPENSSL_free(kidpids);
1024             signal(SIGINT, SIG_DFL);
1025             signal(SIGTERM, SIG_DFL);
1026             if (termsig)
1027                 _exit(0);
1028             if (RAND_poll() <= 0) {
1029                 syslog(LOG_ERR, "fatal: RAND_poll() failed");
1030                 _exit(1);
1031             }
1032             return;
1033         default:            /* parent */
1034             for (i = 0; i < multi; ++i) {
1035                 if (kidpids[i] == 0) {
1036                     kidpids[i] = fpid;
1037                     procs++;
1038                     break;
1039                 }
1040             }
1041             if (i >= multi) {
1042                 syslog(LOG_ERR, "fatal: internal error: no free child slots");
1043                 killall(1, kidpids);
1044             }
1045             break;
1046         }
1047     }
1048
1049     /* The loop above can only break on termsig */
1050     syslog(LOG_INFO, "terminating on signal: %d", termsig);
1051     killall(0, kidpids);
1052 }
1053 #endif
1054
1055 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert,
1056                          const EVP_MD *cert_id_md, X509 *issuer,
1057                          STACK_OF(OCSP_CERTID) *ids)
1058 {
1059     OCSP_CERTID *id;
1060
1061     if (issuer == NULL) {
1062         BIO_printf(bio_err, "No issuer certificate specified\n");
1063         return 0;
1064     }
1065     if (*req == NULL)
1066         *req = OCSP_REQUEST_new();
1067     if (*req == NULL)
1068         goto err;
1069     id = OCSP_cert_to_id(cert_id_md, cert, issuer);
1070     if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1071         goto err;
1072     if (!OCSP_request_add0_id(*req, id))
1073         goto err;
1074     return 1;
1075
1076  err:
1077     BIO_printf(bio_err, "Error Creating OCSP request\n");
1078     return 0;
1079 }
1080
1081 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial,
1082                            const EVP_MD *cert_id_md, X509 *issuer,
1083                            STACK_OF(OCSP_CERTID) *ids)
1084 {
1085     OCSP_CERTID *id;
1086     const X509_NAME *iname;
1087     ASN1_BIT_STRING *ikey;
1088     ASN1_INTEGER *sno;
1089
1090     if (issuer == NULL) {
1091         BIO_printf(bio_err, "No issuer certificate specified\n");
1092         return 0;
1093     }
1094     if (*req == NULL)
1095         *req = OCSP_REQUEST_new();
1096     if (*req == NULL)
1097         goto err;
1098     iname = X509_get_subject_name(issuer);
1099     ikey = X509_get0_pubkey_bitstr(issuer);
1100     sno = s2i_ASN1_INTEGER(NULL, serial);
1101     if (sno == NULL) {
1102         BIO_printf(bio_err, "Error converting serial number %s\n", serial);
1103         return 0;
1104     }
1105     id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno);
1106     ASN1_INTEGER_free(sno);
1107     if (id == NULL || !sk_OCSP_CERTID_push(ids, id))
1108         goto err;
1109     if (!OCSP_request_add0_id(*req, id))
1110         goto err;
1111     return 1;
1112
1113  err:
1114     BIO_printf(bio_err, "Error Creating OCSP request\n");
1115     return 0;
1116 }
1117
1118 static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
1119                               STACK_OF(OPENSSL_STRING) *names,
1120                               STACK_OF(OCSP_CERTID) *ids, long nsec,
1121                               long maxage)
1122 {
1123     OCSP_CERTID *id;
1124     const char *name;
1125     int i, status, reason;
1126     ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1127
1128     if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names)
1129         || !sk_OCSP_CERTID_num(ids))
1130         return;
1131
1132     for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) {
1133         id = sk_OCSP_CERTID_value(ids, i);
1134         name = sk_OPENSSL_STRING_value(names, i);
1135         BIO_printf(out, "%s: ", name);
1136
1137         if (!OCSP_resp_find_status(bs, id, &status, &reason,
1138                                    &rev, &thisupd, &nextupd)) {
1139             BIO_puts(out, "ERROR: No Status found.\n");
1140             continue;
1141         }
1142
1143         /*
1144          * Check validity: if invalid write to output BIO so we know which
1145          * response this refers to.
1146          */
1147         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1148             BIO_puts(out, "WARNING: Status times invalid.\n");
1149             ERR_print_errors(out);
1150         }
1151         BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1152
1153         BIO_puts(out, "\tThis Update: ");
1154         ASN1_GENERALIZEDTIME_print(out, thisupd);
1155         BIO_puts(out, "\n");
1156
1157         if (nextupd) {
1158             BIO_puts(out, "\tNext Update: ");
1159             ASN1_GENERALIZEDTIME_print(out, nextupd);
1160             BIO_puts(out, "\n");
1161         }
1162
1163         if (status != V_OCSP_CERTSTATUS_REVOKED)
1164             continue;
1165
1166         if (reason != -1)
1167             BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason));
1168
1169         BIO_puts(out, "\tRevocation Time: ");
1170         ASN1_GENERALIZEDTIME_print(out, rev);
1171         BIO_puts(out, "\n");
1172     }
1173 }
1174
1175 static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req,
1176                               CA_DB *db, STACK_OF(X509) *ca, X509 *rcert,
1177                               EVP_PKEY *rkey, const EVP_MD *rmd,
1178                               STACK_OF(OPENSSL_STRING) *sigopts,
1179                               STACK_OF(X509) *rother, unsigned long flags,
1180                               int nmin, int ndays, int badsig,
1181                               const EVP_MD *resp_md)
1182 {
1183     ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1184     OCSP_CERTID *cid;
1185     OCSP_BASICRESP *bs = NULL;
1186     int i, id_count;
1187     EVP_MD_CTX *mctx = NULL;
1188     EVP_PKEY_CTX *pkctx = NULL;
1189
1190     id_count = OCSP_request_onereq_count(req);
1191
1192     if (id_count <= 0) {
1193         *resp =
1194             OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1195         goto end;
1196     }
1197
1198     bs = OCSP_BASICRESP_new();
1199     thisupd = X509_gmtime_adj(NULL, 0);
1200     if (ndays != -1)
1201         nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL);
1202
1203     /* Examine each certificate id in the request */
1204     for (i = 0; i < id_count; i++) {
1205         OCSP_ONEREQ *one;
1206         ASN1_INTEGER *serial;
1207         char **inf;
1208         int jj;
1209         int found = 0;
1210         ASN1_OBJECT *cert_id_md_oid;
1211         const EVP_MD *cert_id_md;
1212         OCSP_CERTID *cid_resp_md = NULL;
1213
1214         one = OCSP_request_onereq_get0(req, i);
1215         cid = OCSP_onereq_get0_id(one);
1216
1217         OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid);
1218
1219         cert_id_md = EVP_get_digestbyobj(cert_id_md_oid);
1220         if (cert_id_md == NULL) {
1221             *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1222                                          NULL);
1223             goto end;
1224         }
1225         for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) {
1226             X509 *ca_cert = sk_X509_value(ca, jj);
1227             OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert);
1228
1229             if (OCSP_id_issuer_cmp(ca_id, cid) == 0) {
1230                 found = 1;
1231                 if (resp_md != NULL)
1232                     cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert);
1233             }
1234             OCSP_CERTID_free(ca_id);
1235         }
1236         OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1237         inf = lookup_serial(db, serial);
1238
1239         /* at this point, we can have cid be an alias of cid_resp_md */
1240         cid = (cid_resp_md != NULL) ? cid_resp_md : cid;
1241
1242         if (!found) {
1243             OCSP_basic_add1_status(bs, cid,
1244                                    V_OCSP_CERTSTATUS_UNKNOWN,
1245                                    0, NULL, thisupd, nextupd);
1246             continue;
1247         }
1248         if (inf == NULL) {
1249             OCSP_basic_add1_status(bs, cid,
1250                                    V_OCSP_CERTSTATUS_UNKNOWN,
1251                                    0, NULL, thisupd, nextupd);
1252         } else if (inf[DB_type][0] == DB_TYPE_VAL) {
1253             OCSP_basic_add1_status(bs, cid,
1254                                    V_OCSP_CERTSTATUS_GOOD,
1255                                    0, NULL, thisupd, nextupd);
1256         } else if (inf[DB_type][0] == DB_TYPE_REV) {
1257             ASN1_OBJECT *inst = NULL;
1258             ASN1_TIME *revtm = NULL;
1259             ASN1_GENERALIZEDTIME *invtm = NULL;
1260             OCSP_SINGLERESP *single;
1261             int reason = -1;
1262
1263             unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1264             single = OCSP_basic_add1_status(bs, cid,
1265                                             V_OCSP_CERTSTATUS_REVOKED,
1266                                             reason, revtm, thisupd, nextupd);
1267             if (invtm != NULL)
1268                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date,
1269                                              invtm, 0, 0);
1270             else if (inst != NULL)
1271                 OCSP_SINGLERESP_add1_ext_i2d(single,
1272                                              NID_hold_instruction_code, inst,
1273                                              0, 0);
1274             ASN1_OBJECT_free(inst);
1275             ASN1_TIME_free(revtm);
1276             ASN1_GENERALIZEDTIME_free(invtm);
1277         }
1278         OCSP_CERTID_free(cid_resp_md);
1279     }
1280
1281     OCSP_copy_nonce(bs, req);
1282
1283     mctx = EVP_MD_CTX_new();
1284     if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) {
1285         *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL);
1286         goto end;
1287     }
1288     for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1289         char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1290
1291         if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1292             BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1293             ERR_print_errors(bio_err);
1294             *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR,
1295                                          NULL);
1296             goto end;
1297         }
1298     }
1299     if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) {
1300         *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs);
1301         goto end;
1302     }
1303
1304     if (badsig) {
1305         const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs);
1306         corrupt_signature(sig);
1307     }
1308
1309     *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1310
1311  end:
1312     EVP_MD_CTX_free(mctx);
1313     ASN1_TIME_free(thisupd);
1314     ASN1_TIME_free(nextupd);
1315     OCSP_BASICRESP_free(bs);
1316 }
1317
1318 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1319 {
1320     int i;
1321     BIGNUM *bn = NULL;
1322     char *itmp, *row[DB_NUMBER], **rrow;
1323     for (i = 0; i < DB_NUMBER; i++)
1324         row[i] = NULL;
1325     bn = ASN1_INTEGER_to_BN(ser, NULL);
1326     OPENSSL_assert(bn);         /* FIXME: should report an error at this
1327                                  * point and abort */
1328     if (BN_is_zero(bn))
1329         itmp = OPENSSL_strdup("00");
1330     else
1331         itmp = BN_bn2hex(bn);
1332     row[DB_serial] = itmp;
1333     BN_free(bn);
1334     rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1335     OPENSSL_free(itmp);
1336     return rrow;
1337 }
1338
1339 /* Quick and dirty OCSP server: read in and parse input request */
1340
1341 static BIO *init_responder(const char *port)
1342 {
1343 #ifdef OPENSSL_NO_SOCK
1344     BIO_printf(bio_err,
1345                "Error setting up accept BIO - sockets not supported.\n");
1346     return NULL;
1347 #else
1348     BIO *acbio = NULL, *bufbio = NULL;
1349
1350     bufbio = BIO_new(BIO_f_buffer());
1351     if (bufbio == NULL)
1352         goto err;
1353     acbio = BIO_new(BIO_s_accept());
1354     if (acbio == NULL
1355         || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0
1356         || BIO_set_accept_port(acbio, port) < 0) {
1357         log_message(LOG_ERR, "Error setting up accept BIO");
1358         goto err;
1359     }
1360
1361     BIO_set_accept_bios(acbio, bufbio);
1362     bufbio = NULL;
1363     if (BIO_do_accept(acbio) <= 0) {
1364         log_message(LOG_ERR, "Error starting accept");
1365         goto err;
1366     }
1367
1368     return acbio;
1369
1370  err:
1371     BIO_free_all(acbio);
1372     BIO_free(bufbio);
1373     return NULL;
1374 #endif
1375 }
1376
1377 #ifndef OPENSSL_NO_SOCK
1378 /*
1379  * Decode %xx URL-decoding in-place. Ignores mal-formed sequences.
1380  */
1381 static int urldecode(char *p)
1382 {
1383     unsigned char *out = (unsigned char *)p;
1384     unsigned char *save = out;
1385
1386     for (; *p; p++) {
1387         if (*p != '%')
1388             *out++ = *p;
1389         else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) {
1390             /* Don't check, can't fail because of ixdigit() call. */
1391             *out++ = (OPENSSL_hexchar2int(p[1]) << 4)
1392                    | OPENSSL_hexchar2int(p[2]);
1393             p += 2;
1394         }
1395         else
1396             return -1;
1397     }
1398     *out = '\0';
1399     return (int)(out - save);
1400 }
1401 #endif
1402
1403 #ifdef OCSP_DAEMON
1404 static void socket_timeout(int signum)
1405 {
1406     if (acfd != (int)INVALID_SOCKET)
1407         (void)shutdown(acfd, SHUT_RD);
1408 }
1409 #endif
1410
1411 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio,
1412                         int timeout)
1413 {
1414 #ifdef OPENSSL_NO_SOCK
1415     return 0;
1416 #else
1417     int len;
1418     OCSP_REQUEST *req = NULL;
1419     char inbuf[2048], reqbuf[2048];
1420     char *p, *q;
1421     BIO *cbio = NULL, *getbio = NULL, *b64 = NULL;
1422     const char *client;
1423
1424     *preq = NULL;
1425
1426     /* Connection loss before accept() is routine, ignore silently */
1427     if (BIO_do_accept(acbio) <= 0)
1428         return 0;
1429
1430     cbio = BIO_pop(acbio);
1431     *pcbio = cbio;
1432     client = BIO_get_peer_name(cbio);
1433
1434 # ifdef OCSP_DAEMON
1435     if (timeout > 0) {
1436         (void) BIO_get_fd(cbio, &acfd);
1437         alarm(timeout);
1438     }
1439 # endif
1440
1441     /* Read the request line. */
1442     len = BIO_gets(cbio, reqbuf, sizeof(reqbuf));
1443     if (len <= 0)
1444         goto out;
1445
1446     if (strncmp(reqbuf, "GET ", 4) == 0) {
1447         /* Expecting GET {sp} /URL {sp} HTTP/1.x */
1448         for (p = reqbuf + 4; *p == ' '; ++p)
1449             continue;
1450         if (*p != '/') {
1451             log_message(LOG_INFO, "Invalid request -- bad URL: %s", client);
1452             goto out;
1453         }
1454         p++;
1455
1456         /* Splice off the HTTP version identifier. */
1457         for (q = p; *q; q++)
1458             if (*q == ' ')
1459                 break;
1460         if (strncmp(q, " HTTP/1.", 8) != 0) {
1461             log_message(LOG_INFO,
1462                         "Invalid request -- bad HTTP version: %s", client);
1463             goto out;
1464         }
1465         *q = '\0';
1466
1467         /*
1468          * Skip "GET / HTTP..." requests often used by load-balancers.  Note:
1469          * 'p' was incremented above to point to the first byte *after* the
1470          * leading slash, so with 'GET / ' it is now an empty string.
1471          */
1472         if (p[0] == '\0')
1473             goto out;
1474
1475         len = urldecode(p);
1476         if (len <= 0) {
1477             log_message(LOG_INFO,
1478                         "Invalid request -- bad URL encoding: %s", client);
1479             goto out;
1480         }
1481         if ((getbio = BIO_new_mem_buf(p, len)) == NULL
1482             || (b64 = BIO_new(BIO_f_base64())) == NULL) {
1483             log_message(LOG_ERR, "Could not allocate base64 bio: %s", client);
1484             goto out;
1485         }
1486         BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1487         getbio = BIO_push(b64, getbio);
1488     } else if (strncmp(reqbuf, "POST ", 5) != 0) {
1489         log_message(LOG_INFO, "Invalid request -- bad HTTP verb: %s", client);
1490         goto out;
1491     }
1492
1493     /* Read and skip past the headers. */
1494     for (;;) {
1495         len = BIO_gets(cbio, inbuf, sizeof(inbuf));
1496         if (len <= 0)
1497             goto out;
1498         if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1499             break;
1500     }
1501
1502 # ifdef OCSP_DAEMON
1503     /* Clear alarm before we close the client socket */
1504     alarm(0);
1505     timeout = 0;
1506 # endif
1507
1508     /* Try to read OCSP request */
1509     if (getbio != NULL) {
1510         req = d2i_OCSP_REQUEST_bio(getbio, NULL);
1511         BIO_free_all(getbio);
1512     } else {
1513         req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1514     }
1515
1516     if (req == NULL)
1517         log_message(LOG_ERR, "Error parsing OCSP request");
1518
1519     *preq = req;
1520
1521 out:
1522 # ifdef OCSP_DAEMON
1523     if (timeout > 0)
1524         alarm(0);
1525     acfd = (int)INVALID_SOCKET;
1526 # endif
1527     return 1;
1528 #endif
1529 }
1530
1531 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1532 {
1533     char http_resp[] =
1534         "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1535         "Content-Length: %d\r\n\r\n";
1536     if (cbio == NULL)
1537         return 0;
1538     BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1539     i2d_OCSP_RESPONSE_bio(cbio, resp);
1540     (void)BIO_flush(cbio);
1541     return 1;
1542 }
1543
1544 #ifndef OPENSSL_NO_SOCK
1545 OCSP_RESPONSE *process_responder(OCSP_REQUEST *req,
1546                                  const char *host, const char *path,
1547                                  const char *port, int use_ssl,
1548                                  STACK_OF(CONF_VALUE) *headers,
1549                                  int req_timeout)
1550 {
1551     SSL_CTX *ctx = NULL;
1552     OCSP_RESPONSE *resp = NULL;
1553
1554     if (use_ssl == 1) {
1555         ctx = SSL_CTX_new(TLS_client_method());
1556         if (ctx == NULL) {
1557             BIO_printf(bio_err, "Error creating SSL context.\n");
1558             goto end;
1559         }
1560         SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1561     }
1562
1563     resp = (OCSP_RESPONSE *)
1564         app_http_post_asn1(host, port, path, NULL, NULL /* no proxy used */,
1565                            ctx, headers, "application/ocsp-request",
1566                            (ASN1_VALUE *)req, ASN1_ITEM_rptr(OCSP_REQUEST),
1567                            req_timeout, ASN1_ITEM_rptr(OCSP_RESPONSE));
1568
1569     if (resp == NULL)
1570         BIO_printf(bio_err, "Error querying OCSP responder\n");
1571
1572  end:
1573     SSL_CTX_free(ctx);
1574     return resp;
1575 }
1576 #endif