xref: /freebsd/crypto/openssl/apps/ocsp.c (revision f9218d3d4fd34f082473b3a021c6d4d109fb47cf)
1 /* ocsp.c */
2 /* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
3  * project 2000.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58 #ifndef OPENSSL_NO_OCSP
59 
60 #include <stdio.h>
61 #include <string.h>
62 #include "apps.h"
63 #include <openssl/pem.h>
64 #include <openssl/ocsp.h>
65 #include <openssl/err.h>
66 #include <openssl/ssl.h>
67 
68 /* Maximum leeway in validity period: default 5 minutes */
69 #define MAX_VALIDITY_PERIOD	(5 * 60)
70 
71 /* CA index.txt definitions */
72 #define DB_type         0
73 #define DB_exp_date     1
74 #define DB_rev_date     2
75 #define DB_serial       3       /* index - unique */
76 #define DB_file         4
77 #define DB_name         5       /* index - unique for active */
78 #define DB_NUMBER       6
79 
80 #define DB_TYPE_REV	'R'
81 #define DB_TYPE_EXP	'E'
82 #define DB_TYPE_VAL	'V'
83 
84 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, X509 *issuer,
85 				STACK_OF(OCSP_CERTID) *ids);
86 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, X509 *issuer,
87 				STACK_OF(OCSP_CERTID) *ids);
88 static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
89 				STACK *names, STACK_OF(OCSP_CERTID) *ids,
90 				long nsec, long maxage);
91 
92 static int make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, TXT_DB *db,
93 			X509 *ca, X509 *rcert, EVP_PKEY *rkey,
94 			STACK_OF(X509) *rother, unsigned long flags,
95 			int nmin, int ndays);
96 
97 static char **lookup_serial(TXT_DB *db, ASN1_INTEGER *ser);
98 static BIO *init_responder(char *port);
99 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, char *port);
100 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
101 
102 #undef PROG
103 #define PROG ocsp_main
104 
105 int MAIN(int, char **);
106 
107 int MAIN(int argc, char **argv)
108 	{
109 	ENGINE *e = NULL;
110 	char **args;
111 	char *host = NULL, *port = NULL, *path = "/";
112 	char *reqin = NULL, *respin = NULL;
113 	char *reqout = NULL, *respout = NULL;
114 	char *signfile = NULL, *keyfile = NULL;
115 	char *rsignfile = NULL, *rkeyfile = NULL;
116 	char *outfile = NULL;
117 	int add_nonce = 1, noverify = 0, use_ssl = -1;
118 	OCSP_REQUEST *req = NULL;
119 	OCSP_RESPONSE *resp = NULL;
120 	OCSP_BASICRESP *bs = NULL;
121 	X509 *issuer = NULL, *cert = NULL;
122 	X509 *signer = NULL, *rsigner = NULL;
123 	EVP_PKEY *key = NULL, *rkey = NULL;
124 	BIO *acbio = NULL, *cbio = NULL;
125 	BIO *derbio = NULL;
126 	BIO *out = NULL;
127 	int req_text = 0, resp_text = 0;
128 	long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
129 	char *CAfile = NULL, *CApath = NULL;
130 	X509_STORE *store = NULL;
131 	SSL_CTX *ctx = NULL;
132 	STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
133 	char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
134 	unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
135 	int ret = 1;
136 	int accept_count = -1;
137 	int badarg = 0;
138 	int i;
139 	STACK *reqnames = NULL;
140 	STACK_OF(OCSP_CERTID) *ids = NULL;
141 
142 	X509 *rca_cert = NULL;
143 	char *ridx_filename = NULL;
144 	char *rca_filename = NULL;
145 	TXT_DB *rdb = NULL;
146 	int nmin = 0, ndays = -1;
147 
148 	if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
149 
150 	if (!load_config(bio_err, NULL))
151 		goto end;
152 	SSL_load_error_strings();
153 	args = argv + 1;
154 	reqnames = sk_new_null();
155 	ids = sk_OCSP_CERTID_new_null();
156 	while (!badarg && *args && *args[0] == '-')
157 		{
158 		if (!strcmp(*args, "-out"))
159 			{
160 			if (args[1])
161 				{
162 				args++;
163 				outfile = *args;
164 				}
165 			else badarg = 1;
166 			}
167 		else if (!strcmp(*args, "-url"))
168 			{
169 			if (args[1])
170 				{
171 				args++;
172 				if (!OCSP_parse_url(*args, &host, &port, &path, &use_ssl))
173 					{
174 					BIO_printf(bio_err, "Error parsing URL\n");
175 					badarg = 1;
176 					}
177 				}
178 			else badarg = 1;
179 			}
180 		else if (!strcmp(*args, "-host"))
181 			{
182 			if (args[1])
183 				{
184 				args++;
185 				host = *args;
186 				}
187 			else badarg = 1;
188 			}
189 		else if (!strcmp(*args, "-port"))
190 			{
191 			if (args[1])
192 				{
193 				args++;
194 				port = *args;
195 				}
196 			else badarg = 1;
197 			}
198 		else if (!strcmp(*args, "-noverify"))
199 			noverify = 1;
200 		else if (!strcmp(*args, "-nonce"))
201 			add_nonce = 2;
202 		else if (!strcmp(*args, "-no_nonce"))
203 			add_nonce = 0;
204 		else if (!strcmp(*args, "-resp_no_certs"))
205 			rflags |= OCSP_NOCERTS;
206 		else if (!strcmp(*args, "-resp_key_id"))
207 			rflags |= OCSP_RESPID_KEY;
208 		else if (!strcmp(*args, "-no_certs"))
209 			sign_flags |= OCSP_NOCERTS;
210 		else if (!strcmp(*args, "-no_signature_verify"))
211 			verify_flags |= OCSP_NOSIGS;
212 		else if (!strcmp(*args, "-no_cert_verify"))
213 			verify_flags |= OCSP_NOVERIFY;
214 		else if (!strcmp(*args, "-no_chain"))
215 			verify_flags |= OCSP_NOCHAIN;
216 		else if (!strcmp(*args, "-no_cert_checks"))
217 			verify_flags |= OCSP_NOCHECKS;
218 		else if (!strcmp(*args, "-no_explicit"))
219 			verify_flags |= OCSP_NOEXPLICIT;
220 		else if (!strcmp(*args, "-trust_other"))
221 			verify_flags |= OCSP_TRUSTOTHER;
222 		else if (!strcmp(*args, "-no_intern"))
223 			verify_flags |= OCSP_NOINTERN;
224 		else if (!strcmp(*args, "-text"))
225 			{
226 			req_text = 1;
227 			resp_text = 1;
228 			}
229 		else if (!strcmp(*args, "-req_text"))
230 			req_text = 1;
231 		else if (!strcmp(*args, "-resp_text"))
232 			resp_text = 1;
233 		else if (!strcmp(*args, "-reqin"))
234 			{
235 			if (args[1])
236 				{
237 				args++;
238 				reqin = *args;
239 				}
240 			else badarg = 1;
241 			}
242 		else if (!strcmp(*args, "-respin"))
243 			{
244 			if (args[1])
245 				{
246 				args++;
247 				respin = *args;
248 				}
249 			else badarg = 1;
250 			}
251 		else if (!strcmp(*args, "-signer"))
252 			{
253 			if (args[1])
254 				{
255 				args++;
256 				signfile = *args;
257 				}
258 			else badarg = 1;
259 			}
260 		else if (!strcmp (*args, "-VAfile"))
261 			{
262 			if (args[1])
263 				{
264 				args++;
265 				verify_certfile = *args;
266 				verify_flags |= OCSP_TRUSTOTHER;
267 				}
268 			else badarg = 1;
269 			}
270 		else if (!strcmp(*args, "-sign_other"))
271 			{
272 			if (args[1])
273 				{
274 				args++;
275 				sign_certfile = *args;
276 				}
277 			else badarg = 1;
278 			}
279 		else if (!strcmp(*args, "-verify_other"))
280 			{
281 			if (args[1])
282 				{
283 				args++;
284 				verify_certfile = *args;
285 				}
286 			else badarg = 1;
287 			}
288 		else if (!strcmp (*args, "-CAfile"))
289 			{
290 			if (args[1])
291 				{
292 				args++;
293 				CAfile = *args;
294 				}
295 			else badarg = 1;
296 			}
297 		else if (!strcmp (*args, "-CApath"))
298 			{
299 			if (args[1])
300 				{
301 				args++;
302 				CApath = *args;
303 				}
304 			else badarg = 1;
305 			}
306 		else if (!strcmp (*args, "-validity_period"))
307 			{
308 			if (args[1])
309 				{
310 				args++;
311 				nsec = atol(*args);
312 				if (nsec < 0)
313 					{
314 					BIO_printf(bio_err,
315 						"Illegal validity period %s\n",
316 						*args);
317 					badarg = 1;
318 					}
319 				}
320 			else badarg = 1;
321 			}
322 		else if (!strcmp (*args, "-status_age"))
323 			{
324 			if (args[1])
325 				{
326 				args++;
327 				maxage = atol(*args);
328 				if (maxage < 0)
329 					{
330 					BIO_printf(bio_err,
331 						"Illegal validity age %s\n",
332 						*args);
333 					badarg = 1;
334 					}
335 				}
336 			else badarg = 1;
337 			}
338 		 else if (!strcmp(*args, "-signkey"))
339 			{
340 			if (args[1])
341 				{
342 				args++;
343 				keyfile = *args;
344 				}
345 			else badarg = 1;
346 			}
347 		else if (!strcmp(*args, "-reqout"))
348 			{
349 			if (args[1])
350 				{
351 				args++;
352 				reqout = *args;
353 				}
354 			else badarg = 1;
355 			}
356 		else if (!strcmp(*args, "-respout"))
357 			{
358 			if (args[1])
359 				{
360 				args++;
361 				respout = *args;
362 				}
363 			else badarg = 1;
364 			}
365 		 else if (!strcmp(*args, "-path"))
366 			{
367 			if (args[1])
368 				{
369 				args++;
370 				path = *args;
371 				}
372 			else badarg = 1;
373 			}
374 		else if (!strcmp(*args, "-issuer"))
375 			{
376 			if (args[1])
377 				{
378 				args++;
379 				X509_free(issuer);
380 				issuer = load_cert(bio_err, *args, FORMAT_PEM,
381 					NULL, e, "issuer certificate");
382 				if(!issuer) goto end;
383 				}
384 			else badarg = 1;
385 			}
386 		else if (!strcmp (*args, "-cert"))
387 			{
388 			if (args[1])
389 				{
390 				args++;
391 				X509_free(cert);
392 				cert = load_cert(bio_err, *args, FORMAT_PEM,
393 					NULL, e, "certificate");
394 				if(!cert) goto end;
395 				if(!add_ocsp_cert(&req, cert, issuer, ids))
396 					goto end;
397 				if(!sk_push(reqnames, *args))
398 					goto end;
399 				}
400 			else badarg = 1;
401 			}
402 		else if (!strcmp(*args, "-serial"))
403 			{
404 			if (args[1])
405 				{
406 				args++;
407 				if(!add_ocsp_serial(&req, *args, issuer, ids))
408 					goto end;
409 				if(!sk_push(reqnames, *args))
410 					goto end;
411 				}
412 			else badarg = 1;
413 			}
414 		else if (!strcmp(*args, "-index"))
415 			{
416 			if (args[1])
417 				{
418 				args++;
419 				ridx_filename = *args;
420 				}
421 			else badarg = 1;
422 			}
423 		else if (!strcmp(*args, "-CA"))
424 			{
425 			if (args[1])
426 				{
427 				args++;
428 				rca_filename = *args;
429 				}
430 			else badarg = 1;
431 			}
432 		else if (!strcmp (*args, "-nmin"))
433 			{
434 			if (args[1])
435 				{
436 				args++;
437 				nmin = atol(*args);
438 				if (nmin < 0)
439 					{
440 					BIO_printf(bio_err,
441 						"Illegal update period %s\n",
442 						*args);
443 					badarg = 1;
444 					}
445 				}
446 				if (ndays == -1)
447 					ndays = 0;
448 			else badarg = 1;
449 			}
450 		else if (!strcmp (*args, "-nrequest"))
451 			{
452 			if (args[1])
453 				{
454 				args++;
455 				accept_count = atol(*args);
456 				if (accept_count < 0)
457 					{
458 					BIO_printf(bio_err,
459 						"Illegal accept count %s\n",
460 						*args);
461 					badarg = 1;
462 					}
463 				}
464 			else badarg = 1;
465 			}
466 		else if (!strcmp (*args, "-ndays"))
467 			{
468 			if (args[1])
469 				{
470 				args++;
471 				ndays = atol(*args);
472 				if (ndays < 0)
473 					{
474 					BIO_printf(bio_err,
475 						"Illegal update period %s\n",
476 						*args);
477 					badarg = 1;
478 					}
479 				}
480 			else badarg = 1;
481 			}
482 		else if (!strcmp(*args, "-rsigner"))
483 			{
484 			if (args[1])
485 				{
486 				args++;
487 				rsignfile = *args;
488 				}
489 			else badarg = 1;
490 			}
491 		else if (!strcmp(*args, "-rkey"))
492 			{
493 			if (args[1])
494 				{
495 				args++;
496 				rkeyfile = *args;
497 				}
498 			else badarg = 1;
499 			}
500 		else if (!strcmp(*args, "-rother"))
501 			{
502 			if (args[1])
503 				{
504 				args++;
505 				rcertfile = *args;
506 				}
507 			else badarg = 1;
508 			}
509 		else badarg = 1;
510 		args++;
511 		}
512 
513 	/* Have we anything to do? */
514 	if (!req && !reqin && !respin && !(port && ridx_filename)) badarg = 1;
515 
516 	if (badarg)
517 		{
518 		BIO_printf (bio_err, "OCSP utility\n");
519 		BIO_printf (bio_err, "Usage ocsp [options]\n");
520 		BIO_printf (bio_err, "where options are\n");
521 		BIO_printf (bio_err, "-out file          output filename\n");
522 		BIO_printf (bio_err, "-issuer file       issuer certificate\n");
523 		BIO_printf (bio_err, "-cert file         certificate to check\n");
524 		BIO_printf (bio_err, "-serial n          serial number to check\n");
525 		BIO_printf (bio_err, "-signer file       certificate to sign OCSP request with\n");
526 		BIO_printf (bio_err, "-signkey file      private key to sign OCSP request with\n");
527 		BIO_printf (bio_err, "-sign_certs file   additional certificates to include in signed request\n");
528 		BIO_printf (bio_err, "-no_certs          don't include any certificates in signed request\n");
529 		BIO_printf (bio_err, "-req_text          print text form of request\n");
530 		BIO_printf (bio_err, "-resp_text         print text form of response\n");
531 		BIO_printf (bio_err, "-text              print text form of request and response\n");
532 		BIO_printf (bio_err, "-reqout file       write DER encoded OCSP request to \"file\"\n");
533 		BIO_printf (bio_err, "-respout file      write DER encoded OCSP reponse to \"file\"\n");
534 		BIO_printf (bio_err, "-reqin file        read DER encoded OCSP request from \"file\"\n");
535 		BIO_printf (bio_err, "-respin file       read DER encoded OCSP reponse from \"file\"\n");
536 		BIO_printf (bio_err, "-nonce             add OCSP nonce to request\n");
537 		BIO_printf (bio_err, "-no_nonce          don't add OCSP nonce to request\n");
538 		BIO_printf (bio_err, "-url URL           OCSP responder URL\n");
539 		BIO_printf (bio_err, "-host host:n       send OCSP request to host on port n\n");
540 		BIO_printf (bio_err, "-path              path to use in OCSP request\n");
541 		BIO_printf (bio_err, "-CApath dir        trusted certificates directory\n");
542 		BIO_printf (bio_err, "-CAfile file       trusted certificates file\n");
543 		BIO_printf (bio_err, "-VAfile file       validator certificates file\n");
544 		BIO_printf (bio_err, "-validity_period n maximum validity discrepancy in seconds\n");
545 		BIO_printf (bio_err, "-status_age n      maximum status age in seconds\n");
546 		BIO_printf (bio_err, "-noverify          don't verify response at all\n");
547 		BIO_printf (bio_err, "-verify_certs file additional certificates to search for signer\n");
548 		BIO_printf (bio_err, "-trust_other       don't verify additional certificates\n");
549 		BIO_printf (bio_err, "-no_intern         don't search certificates contained in response for signer\n");
550 		BIO_printf (bio_err, "-no_sig_verify     don't check signature on response\n");
551 		BIO_printf (bio_err, "-no_cert_verify    don't check signing certificate\n");
552 		BIO_printf (bio_err, "-no_chain          don't chain verify response\n");
553 		BIO_printf (bio_err, "-no_cert_checks    don't do additional checks on signing certificate\n");
554 		BIO_printf (bio_err, "-port num		 port to run responder on\n");
555 		BIO_printf (bio_err, "-index file	 certificate status index file\n");
556 		BIO_printf (bio_err, "-CA file		 CA certificate\n");
557 		BIO_printf (bio_err, "-rsigner file	 responder certificate to sign responses with\n");
558 		BIO_printf (bio_err, "-rkey file	 responder key to sign responses with\n");
559 		BIO_printf (bio_err, "-rother file	 other certificates to include in response\n");
560 		BIO_printf (bio_err, "-resp_no_certs     don't include any certificates in response\n");
561 		BIO_printf (bio_err, "-nmin n	 	 number of minutes before next update\n");
562 		BIO_printf (bio_err, "-ndays n	 	 number of days before next update\n");
563 		BIO_printf (bio_err, "-resp_key_id       identify reponse by signing certificate key ID\n");
564 		BIO_printf (bio_err, "-nrequest n        number of requests to accept (default unlimited)\n");
565 		goto end;
566 		}
567 
568 	if(outfile) out = BIO_new_file(outfile, "w");
569 	else out = BIO_new_fp(stdout, BIO_NOCLOSE);
570 
571 	if(!out)
572 		{
573 		BIO_printf(bio_err, "Error opening output file\n");
574 		goto end;
575 		}
576 
577 	if (!req && (add_nonce != 2)) add_nonce = 0;
578 
579 	if (!req && reqin)
580 		{
581 		derbio = BIO_new_file(reqin, "rb");
582 		if (!derbio)
583 			{
584 			BIO_printf(bio_err, "Error Opening OCSP request file\n");
585 			goto end;
586 			}
587 		req = d2i_OCSP_REQUEST_bio(derbio, NULL);
588 		BIO_free(derbio);
589 		if(!req)
590 			{
591 			BIO_printf(bio_err, "Error reading OCSP request\n");
592 			goto end;
593 			}
594 		}
595 
596 	if (!req && port)
597 		{
598 		acbio = init_responder(port);
599 		if (!acbio)
600 			goto end;
601 		}
602 
603 	if (rsignfile && !rdb)
604 		{
605 		if (!rkeyfile) rkeyfile = rsignfile;
606 		rsigner = load_cert(bio_err, rsignfile, FORMAT_PEM,
607 			NULL, e, "responder certificate");
608 		if (!rsigner)
609 			{
610 			BIO_printf(bio_err, "Error loading responder certificate\n");
611 			goto end;
612 			}
613 		rca_cert = load_cert(bio_err, rca_filename, FORMAT_PEM,
614 			NULL, e, "CA certificate");
615 		if (rcertfile)
616 			{
617 			rother = load_certs(bio_err, rcertfile, FORMAT_PEM,
618 				NULL, e, "responder other certificates");
619 			if (!rother) goto end;
620 			}
621 		rkey = load_key(bio_err, rkeyfile, FORMAT_PEM, 0, NULL, NULL,
622 			"responder private key");
623 		if (!rkey)
624 			goto end;
625 		}
626 	if(acbio)
627 		BIO_printf(bio_err, "Waiting for OCSP client connections...\n");
628 
629 	redo_accept:
630 
631 	if (acbio)
632 		{
633 		if (!do_responder(&req, &cbio, acbio, port))
634 			goto end;
635 		if (!req)
636 			{
637 			resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
638 			send_ocsp_response(cbio, resp);
639 			goto done_resp;
640 			}
641 		}
642 
643 	if (!req && (signfile || reqout || host || add_nonce || ridx_filename))
644 		{
645 		BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
646 		goto end;
647 		}
648 
649 	if (req && add_nonce) OCSP_request_add1_nonce(req, NULL, -1);
650 
651 	if (signfile)
652 		{
653 		if (!keyfile) keyfile = signfile;
654 		signer = load_cert(bio_err, signfile, FORMAT_PEM,
655 			NULL, e, "signer certificate");
656 		if (!signer)
657 			{
658 			BIO_printf(bio_err, "Error loading signer certificate\n");
659 			goto end;
660 			}
661 		if (sign_certfile)
662 			{
663 			sign_other = load_certs(bio_err, sign_certfile, FORMAT_PEM,
664 				NULL, e, "signer certificates");
665 			if (!sign_other) goto end;
666 			}
667 		key = load_key(bio_err, keyfile, FORMAT_PEM, 0, NULL, NULL,
668 			"signer private key");
669 		if (!key)
670 			goto end;
671 		if (!OCSP_request_sign(req, signer, key, EVP_sha1(), sign_other, sign_flags))
672 			{
673 			BIO_printf(bio_err, "Error signing OCSP request\n");
674 			goto end;
675 			}
676 		}
677 
678 	if (req_text && req) OCSP_REQUEST_print(out, req, 0);
679 
680 	if (reqout)
681 		{
682 		derbio = BIO_new_file(reqout, "wb");
683 		if(!derbio)
684 			{
685 			BIO_printf(bio_err, "Error opening file %s\n", reqout);
686 			goto end;
687 			}
688 		i2d_OCSP_REQUEST_bio(derbio, req);
689 		BIO_free(derbio);
690 		}
691 
692 	if (ridx_filename && (!rkey || !rsigner || !rca_cert))
693 		{
694 		BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n");
695 		goto end;
696 		}
697 
698 	if (ridx_filename && !rdb)
699 		{
700 		BIO *db_bio = NULL;
701 		db_bio = BIO_new_file(ridx_filename, "r");
702 		if (!db_bio)
703 			{
704 			BIO_printf(bio_err, "Error opening index file %s\n", ridx_filename);
705 			goto end;
706 			}
707 		rdb = TXT_DB_read(db_bio, DB_NUMBER);
708 		BIO_free(db_bio);
709 		if (!rdb)
710 			{
711 			BIO_printf(bio_err, "Error reading index file %s\n", ridx_filename);
712 			goto end;
713 			}
714 		if (!make_serial_index(rdb))
715 			goto end;
716 		}
717 
718 	if (rdb)
719 		{
720 		i = make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, rother, rflags, nmin, ndays);
721 		if (cbio)
722 			send_ocsp_response(cbio, resp);
723 		}
724 	else if (host)
725 		{
726 #ifndef OPENSSL_NO_SOCK
727 		cbio = BIO_new_connect(host);
728 #else
729 		BIO_printf(bio_err, "Error creating connect BIO - sockets not supported.\n");
730 		goto end;
731 #endif
732 		if (!cbio)
733 			{
734 			BIO_printf(bio_err, "Error creating connect BIO\n");
735 			goto end;
736 			}
737 		if (port) BIO_set_conn_port(cbio, port);
738 		if (use_ssl == 1)
739 			{
740 			BIO *sbio;
741 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
742 			ctx = SSL_CTX_new(SSLv23_client_method());
743 #elif !defined(OPENSSL_NO_SSL3)
744 			ctx = SSL_CTX_new(SSLv3_client_method());
745 #elif !defined(OPENSSL_NO_SSL2)
746 			ctx = SSL_CTX_new(SSLv2_client_method());
747 #else
748 			BIO_printf(bio_err, "SSL is disabled\n");
749 			goto end;
750 #endif
751 			SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
752 			sbio = BIO_new_ssl(ctx, 1);
753 			cbio = BIO_push(sbio, cbio);
754 			}
755 		if (BIO_do_connect(cbio) <= 0)
756 			{
757 			BIO_printf(bio_err, "Error connecting BIO\n");
758 			goto end;
759 			}
760 		resp = OCSP_sendreq_bio(cbio, path, req);
761 		BIO_free_all(cbio);
762 		cbio = NULL;
763 		if (!resp)
764 			{
765 			BIO_printf(bio_err, "Error querying OCSP responsder\n");
766 			goto end;
767 			}
768 		}
769 	else if (respin)
770 		{
771 		derbio = BIO_new_file(respin, "rb");
772 		if (!derbio)
773 			{
774 			BIO_printf(bio_err, "Error Opening OCSP response file\n");
775 			goto end;
776 			}
777 		resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
778 		BIO_free(derbio);
779 		if(!resp)
780 			{
781 			BIO_printf(bio_err, "Error reading OCSP response\n");
782 			goto end;
783 			}
784 
785 		}
786 	else
787 		{
788 		ret = 0;
789 		goto end;
790 		}
791 
792 	done_resp:
793 
794 	if (respout)
795 		{
796 		derbio = BIO_new_file(respout, "wb");
797 		if(!derbio)
798 			{
799 			BIO_printf(bio_err, "Error opening file %s\n", respout);
800 			goto end;
801 			}
802 		i2d_OCSP_RESPONSE_bio(derbio, resp);
803 		BIO_free(derbio);
804 		}
805 
806 	i = OCSP_response_status(resp);
807 
808 	if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL)
809 		{
810 		BIO_printf(out, "Responder Error: %s (%ld)\n",
811 				OCSP_response_status_str(i), i);
812 		ret = 0;
813 		goto end;
814 		}
815 
816 	if (resp_text) OCSP_RESPONSE_print(out, resp, 0);
817 
818 	/* If running as responder don't verify our own response */
819 	if (cbio)
820 		{
821 		if (accept_count > 0)
822 			accept_count--;
823 		/* Redo if more connections needed */
824 		if (accept_count)
825 			{
826 			BIO_free_all(cbio);
827 			cbio = NULL;
828 			OCSP_REQUEST_free(req);
829 			req = NULL;
830 			OCSP_RESPONSE_free(resp);
831 			resp = NULL;
832 			goto redo_accept;
833 			}
834 		goto end;
835 		}
836 
837 	if (!store)
838 		store = setup_verify(bio_err, CAfile, CApath);
839 	if (!store)
840 		goto end;
841 	if (verify_certfile)
842 		{
843 		verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM,
844 			NULL, e, "validator certificate");
845 		if (!verify_other) goto end;
846 		}
847 
848 	bs = OCSP_response_get1_basic(resp);
849 
850 	if (!bs)
851 		{
852 		BIO_printf(bio_err, "Error parsing response\n");
853 		goto end;
854 		}
855 
856 	if (!noverify)
857 		{
858 		if (req && ((i = OCSP_check_nonce(req, bs)) <= 0))
859 			{
860 			if (i == -1)
861 				BIO_printf(bio_err, "WARNING: no nonce in response\n");
862 			else
863 				{
864 				BIO_printf(bio_err, "Nonce Verify error\n");
865 				goto end;
866 				}
867 			}
868 
869 		i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
870                 if (i < 0) i = OCSP_basic_verify(bs, NULL, store, 0);
871 
872 		if(i <= 0)
873 			{
874 			BIO_printf(bio_err, "Response Verify Failure\n", i);
875 			ERR_print_errors(bio_err);
876 			}
877 		else
878 			BIO_printf(bio_err, "Response verify OK\n");
879 
880 		}
881 
882 	if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
883 		goto end;
884 
885 	ret = 0;
886 
887 end:
888 	ERR_print_errors(bio_err);
889 	X509_free(signer);
890 	X509_STORE_free(store);
891 	EVP_PKEY_free(key);
892 	EVP_PKEY_free(rkey);
893 	X509_free(issuer);
894 	X509_free(cert);
895 	X509_free(rsigner);
896 	X509_free(rca_cert);
897 	TXT_DB_free(rdb);
898 	BIO_free_all(cbio);
899 	BIO_free_all(acbio);
900 	BIO_free(out);
901 	OCSP_REQUEST_free(req);
902 	OCSP_RESPONSE_free(resp);
903 	OCSP_BASICRESP_free(bs);
904 	sk_free(reqnames);
905 	sk_OCSP_CERTID_free(ids);
906 	sk_X509_pop_free(sign_other, X509_free);
907 	sk_X509_pop_free(verify_other, X509_free);
908 
909 	if (use_ssl != -1)
910 		{
911 		OPENSSL_free(host);
912 		OPENSSL_free(port);
913 		OPENSSL_free(path);
914 		SSL_CTX_free(ctx);
915 		}
916 
917 	OPENSSL_EXIT(ret);
918 }
919 
920 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, X509 *issuer,
921 				STACK_OF(OCSP_CERTID) *ids)
922 	{
923 	OCSP_CERTID *id;
924 	if(!issuer)
925 		{
926 		BIO_printf(bio_err, "No issuer certificate specified\n");
927 		return 0;
928 		}
929 	if(!*req) *req = OCSP_REQUEST_new();
930 	if(!*req) goto err;
931 	id = OCSP_cert_to_id(NULL, cert, issuer);
932 	if(!id || !sk_OCSP_CERTID_push(ids, id)) goto err;
933 	if(!OCSP_request_add0_id(*req, id)) goto err;
934 	return 1;
935 
936 	err:
937 	BIO_printf(bio_err, "Error Creating OCSP request\n");
938 	return 0;
939 	}
940 
941 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, X509 *issuer,
942 				STACK_OF(OCSP_CERTID) *ids)
943 	{
944 	OCSP_CERTID *id;
945 	X509_NAME *iname;
946 	ASN1_BIT_STRING *ikey;
947 	ASN1_INTEGER *sno;
948 	if(!issuer)
949 		{
950 		BIO_printf(bio_err, "No issuer certificate specified\n");
951 		return 0;
952 		}
953 	if(!*req) *req = OCSP_REQUEST_new();
954 	if(!*req) goto err;
955 	iname = X509_get_subject_name(issuer);
956 	ikey = X509_get0_pubkey_bitstr(issuer);
957 	sno = s2i_ASN1_INTEGER(NULL, serial);
958 	if(!sno)
959 		{
960 		BIO_printf(bio_err, "Error converting serial number %s\n", serial);
961 		return 0;
962 		}
963 	id = OCSP_cert_id_new(EVP_sha1(), iname, ikey, sno);
964 	ASN1_INTEGER_free(sno);
965 	if(!id || !sk_OCSP_CERTID_push(ids, id)) goto err;
966 	if(!OCSP_request_add0_id(*req, id)) goto err;
967 	return 1;
968 
969 	err:
970 	BIO_printf(bio_err, "Error Creating OCSP request\n");
971 	return 0;
972 	}
973 
974 static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
975 					STACK *names, STACK_OF(OCSP_CERTID) *ids,
976 					long nsec, long maxage)
977 	{
978 	OCSP_CERTID *id;
979 	char *name;
980 	int i;
981 
982 	int status, reason;
983 
984 	ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
985 
986 	if (!bs || !req || !sk_num(names) || !sk_OCSP_CERTID_num(ids))
987 		return 1;
988 
989 	for (i = 0; i < sk_OCSP_CERTID_num(ids); i++)
990 		{
991 		id = sk_OCSP_CERTID_value(ids, i);
992 		name = sk_value(names, i);
993 		BIO_printf(out, "%s: ", name);
994 
995 		if(!OCSP_resp_find_status(bs, id, &status, &reason,
996 					&rev, &thisupd, &nextupd))
997 			{
998 			BIO_puts(out, "ERROR: No Status found.\n");
999 			continue;
1000 			}
1001 
1002 		/* Check validity: if invalid write to output BIO so we
1003 		 * know which response this refers to.
1004 		 */
1005 		if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage))
1006 			{
1007 			BIO_puts(out, "WARNING: Status times invalid.\n");
1008 			ERR_print_errors(out);
1009 			}
1010 		BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1011 
1012 		BIO_puts(out, "\tThis Update: ");
1013 		ASN1_GENERALIZEDTIME_print(out, thisupd);
1014 		BIO_puts(out, "\n");
1015 
1016 		if(nextupd)
1017 			{
1018 			BIO_puts(out, "\tNext Update: ");
1019 			ASN1_GENERALIZEDTIME_print(out, nextupd);
1020 			BIO_puts(out, "\n");
1021 			}
1022 
1023 		if (status != V_OCSP_CERTSTATUS_REVOKED)
1024 			continue;
1025 
1026 		if (reason != -1)
1027 			BIO_printf(out, "\tReason: %s\n",
1028 				OCSP_crl_reason_str(reason));
1029 
1030 		BIO_puts(out, "\tRevocation Time: ");
1031 		ASN1_GENERALIZEDTIME_print(out, rev);
1032 		BIO_puts(out, "\n");
1033 		}
1034 
1035 	return 1;
1036 	}
1037 
1038 
1039 static int make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, TXT_DB *db,
1040 			X509 *ca, X509 *rcert, EVP_PKEY *rkey,
1041 			STACK_OF(X509) *rother, unsigned long flags,
1042 			int nmin, int ndays)
1043 	{
1044 	ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1045 	OCSP_CERTID *cid, *ca_id = NULL;
1046 	OCSP_BASICRESP *bs = NULL;
1047 	int i, id_count, ret = 1;
1048 
1049 
1050 	id_count = OCSP_request_onereq_count(req);
1051 
1052 	if (id_count <= 0)
1053 		{
1054 		*resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1055 		goto end;
1056 		}
1057 
1058 	ca_id = OCSP_cert_to_id(EVP_sha1(), NULL, ca);
1059 
1060 	bs = OCSP_BASICRESP_new();
1061 	thisupd = X509_gmtime_adj(NULL, 0);
1062 	if (ndays != -1)
1063 		nextupd = X509_gmtime_adj(NULL, nmin * 60 + ndays * 3600 * 24 );
1064 
1065 	/* Examine each certificate id in the request */
1066 	for (i = 0; i < id_count; i++)
1067 		{
1068 		OCSP_ONEREQ *one;
1069 		ASN1_INTEGER *serial;
1070 		char **inf;
1071 		one = OCSP_request_onereq_get0(req, i);
1072 		cid = OCSP_onereq_get0_id(one);
1073 		/* Is this request about our CA? */
1074 		if (OCSP_id_issuer_cmp(ca_id, cid))
1075 			{
1076 			OCSP_basic_add1_status(bs, cid,
1077 						V_OCSP_CERTSTATUS_UNKNOWN,
1078 						0, NULL,
1079 						thisupd, nextupd);
1080 			continue;
1081 			}
1082 		OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1083 		inf = lookup_serial(db, serial);
1084 		if (!inf)
1085 			OCSP_basic_add1_status(bs, cid,
1086 						V_OCSP_CERTSTATUS_UNKNOWN,
1087 						0, NULL,
1088 						thisupd, nextupd);
1089 		else if (inf[DB_type][0] == DB_TYPE_VAL)
1090 			OCSP_basic_add1_status(bs, cid,
1091 						V_OCSP_CERTSTATUS_GOOD,
1092 						0, NULL,
1093 						thisupd, nextupd);
1094 		else if (inf[DB_type][0] == DB_TYPE_REV)
1095 			{
1096 			ASN1_OBJECT *inst = NULL;
1097 			ASN1_TIME *revtm = NULL;
1098 			ASN1_GENERALIZEDTIME *invtm = NULL;
1099 			OCSP_SINGLERESP *single;
1100 			int reason = -1;
1101 			unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1102 			single = OCSP_basic_add1_status(bs, cid,
1103 						V_OCSP_CERTSTATUS_REVOKED,
1104 						reason, revtm,
1105 						thisupd, nextupd);
1106 			if (invtm)
1107 				OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date, invtm, 0, 0);
1108 			else if (inst)
1109 				OCSP_SINGLERESP_add1_ext_i2d(single, NID_hold_instruction_code, inst, 0, 0);
1110 			ASN1_OBJECT_free(inst);
1111 			ASN1_TIME_free(revtm);
1112 			ASN1_GENERALIZEDTIME_free(invtm);
1113 			}
1114 		}
1115 
1116 	OCSP_copy_nonce(bs, req);
1117 
1118 	OCSP_basic_sign(bs, rcert, rkey, EVP_sha1(), rother, flags);
1119 
1120 	*resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1121 
1122 	end:
1123 	ASN1_TIME_free(thisupd);
1124 	ASN1_TIME_free(nextupd);
1125 	OCSP_CERTID_free(ca_id);
1126 	OCSP_BASICRESP_free(bs);
1127 	return ret;
1128 
1129 	}
1130 
1131 static char **lookup_serial(TXT_DB *db, ASN1_INTEGER *ser)
1132 	{
1133 	int i;
1134 	BIGNUM *bn = NULL;
1135 	char *itmp, *row[DB_NUMBER],**rrow;
1136 	for (i = 0; i < DB_NUMBER; i++) row[i] = NULL;
1137 	bn = ASN1_INTEGER_to_BN(ser,NULL);
1138 	if (BN_is_zero(bn))
1139 		itmp = BUF_strdup("00");
1140 	else
1141 		itmp = BN_bn2hex(bn);
1142 	row[DB_serial] = itmp;
1143 	BN_free(bn);
1144 	rrow=TXT_DB_get_by_index(db,DB_serial,row);
1145 	OPENSSL_free(itmp);
1146 	return rrow;
1147 	}
1148 
1149 /* Quick and dirty OCSP server: read in and parse input request */
1150 
1151 static BIO *init_responder(char *port)
1152 	{
1153 	BIO *acbio = NULL, *bufbio = NULL;
1154 	bufbio = BIO_new(BIO_f_buffer());
1155 	if (!bufbio)
1156 		goto err;
1157 #ifndef OPENSSL_NO_SOCK
1158 	acbio = BIO_new_accept(port);
1159 #else
1160 	BIO_printf(bio_err, "Error setting up accept BIO - sockets not supported.\n");
1161 #endif
1162 	if (!acbio)
1163 		goto err;
1164 	BIO_set_accept_bios(acbio, bufbio);
1165 	bufbio = NULL;
1166 
1167 	if (BIO_do_accept(acbio) <= 0)
1168 		{
1169 			BIO_printf(bio_err, "Error setting up accept BIO\n");
1170 			ERR_print_errors(bio_err);
1171 			goto err;
1172 		}
1173 
1174 	return acbio;
1175 
1176 	err:
1177 	BIO_free_all(acbio);
1178 	BIO_free(bufbio);
1179 	return NULL;
1180 	}
1181 
1182 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, char *port)
1183 	{
1184 	int have_post = 0, len;
1185 	OCSP_REQUEST *req = NULL;
1186 	char inbuf[1024];
1187 	BIO *cbio = NULL;
1188 
1189 	if (BIO_do_accept(acbio) <= 0)
1190 		{
1191 			BIO_printf(bio_err, "Error accepting connection\n");
1192 			ERR_print_errors(bio_err);
1193 			return 0;
1194 		}
1195 
1196 	cbio = BIO_pop(acbio);
1197 	*pcbio = cbio;
1198 
1199 	for(;;)
1200 		{
1201 		len = BIO_gets(cbio, inbuf, sizeof inbuf);
1202 		if (len <= 0)
1203 			return 1;
1204 		/* Look for "POST" signalling start of query */
1205 		if (!have_post)
1206 			{
1207 			if(strncmp(inbuf, "POST", 4))
1208 				{
1209 				BIO_printf(bio_err, "Invalid request\n");
1210 				return 1;
1211 				}
1212 			have_post = 1;
1213 			}
1214 		/* Look for end of headers */
1215 		if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1216 			break;
1217 		}
1218 
1219 	/* Try to read OCSP request */
1220 
1221 	req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1222 
1223 	if (!req)
1224 		{
1225 		BIO_printf(bio_err, "Error parsing OCSP request\n");
1226 		ERR_print_errors(bio_err);
1227 		}
1228 
1229 	*preq = req;
1230 
1231 	return 1;
1232 
1233 	}
1234 
1235 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1236 	{
1237 	char http_resp[] =
1238 		"HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1239 		"Content-Length: %d\r\n\r\n";
1240 	if (!cbio)
1241 		return 0;
1242 	BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1243 	i2d_OCSP_RESPONSE_bio(cbio, resp);
1244 	BIO_flush(cbio);
1245 	return 1;
1246 	}
1247 
1248 #endif
1249