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