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