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