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