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