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