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