Make it possible to disable OCSP, the speed application, and the use of sockets.
[openssl.git] / apps / ocsp.c
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                         ctx = SSL_CTX_new(SSLv23_client_method());
742                         SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
743                         sbio = BIO_new_ssl(ctx, 1);
744                         cbio = BIO_push(sbio, cbio);
745                         }
746                 if (BIO_do_connect(cbio) <= 0)
747                         {
748                         BIO_printf(bio_err, "Error connecting BIO\n");
749                         goto end;
750                         }
751                 resp = OCSP_sendreq_bio(cbio, path, req);
752                 BIO_free_all(cbio);
753                 cbio = NULL;
754                 if (!resp)
755                         {
756                         BIO_printf(bio_err, "Error querying OCSP responsder\n");
757                         goto end;
758                         }
759                 }
760         else if (respin)
761                 {
762                 derbio = BIO_new_file(respin, "rb");
763                 if (!derbio)
764                         {
765                         BIO_printf(bio_err, "Error Opening OCSP response file\n");
766                         goto end;
767                         }
768                 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
769                 BIO_free(derbio);
770                 if(!resp)
771                         {
772                         BIO_printf(bio_err, "Error reading OCSP response\n");
773                         goto end;
774                         }
775         
776                 }
777         else
778                 {
779                 ret = 0;
780                 goto end;
781                 }
782
783         done_resp:
784
785         if (respout)
786                 {
787                 derbio = BIO_new_file(respout, "wb");
788                 if(!derbio)
789                         {
790                         BIO_printf(bio_err, "Error opening file %s\n", respout);
791                         goto end;
792                         }
793                 i2d_OCSP_RESPONSE_bio(derbio, resp);
794                 BIO_free(derbio);
795                 }
796
797         i = OCSP_response_status(resp);
798
799         if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL)
800                 {
801                 BIO_printf(out, "Responder Error: %s (%ld)\n",
802                                 OCSP_response_status_str(i), i);
803                 ret = 0;
804                 goto end;
805                 }
806
807         if (resp_text) OCSP_RESPONSE_print(out, resp, 0);
808
809         /* If running as responder don't verify our own response */
810         if (cbio)
811                 {
812                 if (accept_count > 0)
813                         accept_count--;
814                 /* Redo if more connections needed */
815                 if (accept_count)
816                         {
817                         BIO_free_all(cbio);
818                         cbio = NULL;
819                         OCSP_REQUEST_free(req);
820                         req = NULL;
821                         OCSP_RESPONSE_free(resp);
822                         resp = NULL;
823                         goto redo_accept;
824                         }
825                 goto end;
826                 }
827
828         if (!store)
829                 store = setup_verify(bio_err, CAfile, CApath);
830         if (!store)
831                 goto end;
832         if (verify_certfile)
833                 {
834                 verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM,
835                         NULL, e, "validator certificate");
836                 if (!verify_other) goto end;
837                 }
838
839         bs = OCSP_response_get1_basic(resp);
840
841         if (!bs)
842                 {
843                 BIO_printf(bio_err, "Error parsing response\n");
844                 goto end;
845                 }
846
847         if (!noverify)
848                 {
849                 if (req && ((i = OCSP_check_nonce(req, bs)) <= 0))
850                         {
851                         if (i == -1)
852                                 BIO_printf(bio_err, "WARNING: no nonce in response\n");
853                         else
854                                 {
855                                 BIO_printf(bio_err, "Nonce Verify error\n");
856                                 goto end;
857                                 }
858                         }
859
860                 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
861                 if (i < 0) i = OCSP_basic_verify(bs, NULL, store, 0);
862
863                 if(i <= 0)
864                         {
865                         BIO_printf(bio_err, "Response Verify Failure\n", i);
866                         ERR_print_errors(bio_err);
867                         }
868                 else
869                         BIO_printf(bio_err, "Response verify OK\n");
870
871                 }
872
873         if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
874                 goto end;
875
876         ret = 0;
877
878 end:
879         ERR_print_errors(bio_err);
880         X509_free(signer);
881         X509_STORE_free(store);
882         EVP_PKEY_free(key);
883         EVP_PKEY_free(rkey);
884         X509_free(issuer);
885         X509_free(cert);
886         X509_free(rsigner);
887         X509_free(rca_cert);
888         TXT_DB_free(rdb);
889         BIO_free_all(cbio);
890         BIO_free_all(acbio);
891         BIO_free(out);
892         OCSP_REQUEST_free(req);
893         OCSP_RESPONSE_free(resp);
894         OCSP_BASICRESP_free(bs);
895         sk_free(reqnames);
896         sk_OCSP_CERTID_free(ids);
897         sk_X509_pop_free(sign_other, X509_free);
898         sk_X509_pop_free(verify_other, X509_free);
899
900         if (use_ssl != -1)
901                 {
902                 OPENSSL_free(host);
903                 OPENSSL_free(port);
904                 OPENSSL_free(path);
905                 SSL_CTX_free(ctx);
906                 }
907
908         OPENSSL_EXIT(ret);
909 }
910
911 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, X509 *issuer,
912                                 STACK_OF(OCSP_CERTID) *ids)
913         {
914         OCSP_CERTID *id;
915         if(!issuer)
916                 {
917                 BIO_printf(bio_err, "No issuer certificate specified\n");
918                 return 0;
919                 }
920         if(!*req) *req = OCSP_REQUEST_new();
921         if(!*req) goto err;
922         id = OCSP_cert_to_id(NULL, cert, issuer);
923         if(!id || !sk_OCSP_CERTID_push(ids, id)) goto err;
924         if(!OCSP_request_add0_id(*req, id)) goto err;
925         return 1;
926
927         err:
928         BIO_printf(bio_err, "Error Creating OCSP request\n");
929         return 0;
930         }
931
932 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, X509 *issuer,
933                                 STACK_OF(OCSP_CERTID) *ids)
934         {
935         OCSP_CERTID *id;
936         X509_NAME *iname;
937         ASN1_BIT_STRING *ikey;
938         ASN1_INTEGER *sno;
939         if(!issuer)
940                 {
941                 BIO_printf(bio_err, "No issuer certificate specified\n");
942                 return 0;
943                 }
944         if(!*req) *req = OCSP_REQUEST_new();
945         if(!*req) goto err;
946         iname = X509_get_subject_name(issuer);
947         ikey = X509_get0_pubkey_bitstr(issuer);
948         sno = s2i_ASN1_INTEGER(NULL, serial);
949         if(!sno)
950                 {
951                 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
952                 return 0;
953                 }
954         id = OCSP_cert_id_new(EVP_sha1(), iname, ikey, sno);
955         ASN1_INTEGER_free(sno);
956         if(!id || !sk_OCSP_CERTID_push(ids, id)) goto err;
957         if(!OCSP_request_add0_id(*req, id)) goto err;
958         return 1;
959
960         err:
961         BIO_printf(bio_err, "Error Creating OCSP request\n");
962         return 0;
963         }
964
965 static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
966                                         STACK *names, STACK_OF(OCSP_CERTID) *ids,
967                                         long nsec, long maxage)
968         {
969         OCSP_CERTID *id;
970         char *name;
971         int i;
972
973         int status, reason;
974
975         ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
976
977         if (!bs || !req || !sk_num(names) || !sk_OCSP_CERTID_num(ids))
978                 return 1;
979
980         for (i = 0; i < sk_OCSP_CERTID_num(ids); i++)
981                 {
982                 id = sk_OCSP_CERTID_value(ids, i);
983                 name = sk_value(names, i);
984                 BIO_printf(out, "%s: ", name);
985
986                 if(!OCSP_resp_find_status(bs, id, &status, &reason,
987                                         &rev, &thisupd, &nextupd))
988                         {
989                         BIO_puts(out, "ERROR: No Status found.\n");
990                         continue;
991                         }
992
993                 /* Check validity: if invalid write to output BIO so we
994                  * know which response this refers to.
995                  */
996                 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage))
997                         {
998                         BIO_puts(out, "WARNING: Status times invalid.\n");
999                         ERR_print_errors(out);
1000                         }
1001                 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1002
1003                 BIO_puts(out, "\tThis Update: ");
1004                 ASN1_GENERALIZEDTIME_print(out, thisupd);
1005                 BIO_puts(out, "\n");
1006
1007                 if(nextupd)
1008                         {
1009                         BIO_puts(out, "\tNext Update: ");
1010                         ASN1_GENERALIZEDTIME_print(out, nextupd);
1011                         BIO_puts(out, "\n");
1012                         }
1013
1014                 if (status != V_OCSP_CERTSTATUS_REVOKED)
1015                         continue;
1016
1017                 if (reason != -1)
1018                         BIO_printf(out, "\tReason: %s\n",
1019                                 OCSP_crl_reason_str(reason));
1020
1021                 BIO_puts(out, "\tRevocation Time: ");
1022                 ASN1_GENERALIZEDTIME_print(out, rev);
1023                 BIO_puts(out, "\n");
1024                 }
1025
1026         return 1;
1027         }
1028
1029
1030 static int make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, TXT_DB *db,
1031                         X509 *ca, X509 *rcert, EVP_PKEY *rkey,
1032                         STACK_OF(X509) *rother, unsigned long flags,
1033                         int nmin, int ndays)
1034         {
1035         ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1036         OCSP_CERTID *cid, *ca_id = NULL;
1037         OCSP_BASICRESP *bs = NULL;
1038         int i, id_count, ret = 1;
1039
1040
1041         id_count = OCSP_request_onereq_count(req);
1042
1043         if (id_count <= 0)
1044                 {
1045                 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1046                 goto end;
1047                 }
1048
1049         ca_id = OCSP_cert_to_id(EVP_sha1(), NULL, ca);
1050
1051         bs = OCSP_BASICRESP_new();
1052         thisupd = X509_gmtime_adj(NULL, 0);
1053         if (ndays != -1)
1054                 nextupd = X509_gmtime_adj(NULL, nmin * 60 + ndays * 3600 * 24 );
1055
1056         /* Examine each certificate id in the request */
1057         for (i = 0; i < id_count; i++)
1058                 {
1059                 OCSP_ONEREQ *one;
1060                 ASN1_INTEGER *serial;
1061                 char **inf;
1062                 one = OCSP_request_onereq_get0(req, i);
1063                 cid = OCSP_onereq_get0_id(one);
1064                 /* Is this request about our CA? */
1065                 if (OCSP_id_issuer_cmp(ca_id, cid))
1066                         {
1067                         OCSP_basic_add1_status(bs, cid,
1068                                                 V_OCSP_CERTSTATUS_UNKNOWN,
1069                                                 0, NULL,
1070                                                 thisupd, nextupd);
1071                         continue;
1072                         }
1073                 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1074                 inf = lookup_serial(db, serial);
1075                 if (!inf)
1076                         OCSP_basic_add1_status(bs, cid,
1077                                                 V_OCSP_CERTSTATUS_UNKNOWN,
1078                                                 0, NULL,
1079                                                 thisupd, nextupd);
1080                 else if (inf[DB_type][0] == DB_TYPE_VAL)
1081                         OCSP_basic_add1_status(bs, cid,
1082                                                 V_OCSP_CERTSTATUS_GOOD,
1083                                                 0, NULL,
1084                                                 thisupd, nextupd);
1085                 else if (inf[DB_type][0] == DB_TYPE_REV)
1086                         {
1087                         ASN1_OBJECT *inst = NULL;
1088                         ASN1_TIME *revtm = NULL;
1089                         ASN1_GENERALIZEDTIME *invtm = NULL;
1090                         OCSP_SINGLERESP *single;
1091                         int reason = -1;
1092                         unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1093                         single = OCSP_basic_add1_status(bs, cid,
1094                                                 V_OCSP_CERTSTATUS_REVOKED,
1095                                                 reason, revtm,
1096                                                 thisupd, nextupd);
1097                         if (invtm)
1098                                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date, invtm, 0, 0);
1099                         else if (inst)
1100                                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_hold_instruction_code, inst, 0, 0);
1101                         ASN1_OBJECT_free(inst);
1102                         ASN1_TIME_free(revtm);
1103                         ASN1_GENERALIZEDTIME_free(invtm);
1104                         }
1105                 }
1106
1107         OCSP_copy_nonce(bs, req);
1108                 
1109         OCSP_basic_sign(bs, rcert, rkey, EVP_sha1(), rother, flags);
1110
1111         *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1112
1113         end:
1114         ASN1_TIME_free(thisupd);
1115         ASN1_TIME_free(nextupd);
1116         OCSP_CERTID_free(ca_id);
1117         OCSP_BASICRESP_free(bs);
1118         return ret;
1119
1120         }
1121
1122 static char **lookup_serial(TXT_DB *db, ASN1_INTEGER *ser)
1123         {
1124         int i;
1125         BIGNUM *bn = NULL;
1126         char *itmp, *row[DB_NUMBER],**rrow;
1127         for (i = 0; i < DB_NUMBER; i++) row[i] = NULL;
1128         bn = ASN1_INTEGER_to_BN(ser,NULL);
1129         if (BN_is_zero(bn))
1130                 itmp = BUF_strdup("00");
1131         else
1132                 itmp = BN_bn2hex(bn);
1133         row[DB_serial] = itmp;
1134         BN_free(bn);
1135         rrow=TXT_DB_get_by_index(db,DB_serial,row);
1136         OPENSSL_free(itmp);
1137         return rrow;
1138         }
1139
1140 /* Quick and dirty OCSP server: read in and parse input request */
1141
1142 static BIO *init_responder(char *port)
1143         {
1144         BIO *acbio = NULL, *bufbio = NULL;
1145         bufbio = BIO_new(BIO_f_buffer());
1146         if (!bufbio) 
1147                 goto err;
1148 #ifndef OPENSSL_NO_SOCK
1149         acbio = BIO_new_accept(port);
1150 #else
1151         BIO_printf(bio_err, "Error setting up accept BIO - sockets not supported.\n");
1152 #endif
1153         if (!acbio)
1154                 goto err;
1155         BIO_set_accept_bios(acbio, bufbio);
1156         bufbio = NULL;
1157
1158         if (BIO_do_accept(acbio) <= 0)
1159                 {
1160                         BIO_printf(bio_err, "Error setting up accept BIO\n");
1161                         ERR_print_errors(bio_err);
1162                         goto err;
1163                 }
1164
1165         return acbio;
1166
1167         err:
1168         BIO_free_all(acbio);
1169         BIO_free(bufbio);
1170         return NULL;
1171         }
1172
1173 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, char *port)
1174         {
1175         int have_post = 0, len;
1176         OCSP_REQUEST *req = NULL;
1177         char inbuf[1024];
1178         BIO *cbio = NULL;
1179
1180         if (BIO_do_accept(acbio) <= 0)
1181                 {
1182                         BIO_printf(bio_err, "Error accepting connection\n");
1183                         ERR_print_errors(bio_err);
1184                         return 0;
1185                 }
1186
1187         cbio = BIO_pop(acbio);
1188         *pcbio = cbio;
1189
1190         for(;;)
1191                 {
1192                 len = BIO_gets(cbio, inbuf, sizeof inbuf);
1193                 if (len <= 0)
1194                         return 1;
1195                 /* Look for "POST" signalling start of query */
1196                 if (!have_post)
1197                         {
1198                         if(strncmp(inbuf, "POST", 4))
1199                                 {
1200                                 BIO_printf(bio_err, "Invalid request\n");
1201                                 return 1;
1202                                 }
1203                         have_post = 1;
1204                         }
1205                 /* Look for end of headers */
1206                 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1207                         break;
1208                 }
1209
1210         /* Try to read OCSP request */
1211
1212         req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1213
1214         if (!req)
1215                 {
1216                 BIO_printf(bio_err, "Error parsing OCSP request\n");
1217                 ERR_print_errors(bio_err);
1218                 }
1219
1220         *preq = req;
1221
1222         return 1;
1223
1224         }
1225
1226 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1227         {
1228         char http_resp[] = 
1229                 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1230                 "Content-Length: %d\r\n\r\n";
1231         if (!cbio)
1232                 return 0;
1233         BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1234         i2d_OCSP_RESPONSE_bio(cbio, resp);
1235         BIO_flush(cbio);
1236         return 1;
1237         }
1238
1239 #endif