Don't free a NULL. Coverity ID 112.
[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 #define _XOPEN_SOURCE_EXTENDED  1 /* Or fd_set, select() and so on won't be
63                                      declared properly on Compaq platforms
64                                      (at least with DEC C).
65                                   */
66 #ifdef OPENSSL_SYS_VMS
67 # include <time.h>
68 #else
69 # include <sys/time.h>
70 # include <sys/select.h>
71 #endif
72 #include "apps.h"
73 #include <openssl/pem.h>
74 #include <openssl/ocsp.h>
75 #include <openssl/err.h>
76 #include <openssl/ssl.h>
77 #include <openssl/bn.h>
78
79 /* Maximum leeway in validity period: default 5 minutes */
80 #define MAX_VALIDITY_PERIOD     (5 * 60)
81
82 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, X509 *issuer,
83                                 STACK_OF(OCSP_CERTID) *ids);
84 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, X509 *issuer,
85                                 STACK_OF(OCSP_CERTID) *ids);
86 static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
87                                 STACK *names, STACK_OF(OCSP_CERTID) *ids,
88                                 long nsec, long maxage);
89
90 static int make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, CA_DB *db,
91                         X509 *ca, X509 *rcert, EVP_PKEY *rkey,
92                         STACK_OF(X509) *rother, unsigned long flags,
93                         int nmin, int ndays);
94
95 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser);
96 static BIO *init_responder(char *port);
97 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, char *port);
98 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp);
99 static OCSP_RESPONSE *query_responder(BIO *err, BIO *cbio, char *path,
100                                 OCSP_REQUEST *req, int req_timeout);
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_timeout = -1;
128         int req_text = 0, resp_text = 0;
129         long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
130         char *CAfile = NULL, *CApath = NULL;
131         X509_STORE *store = NULL;
132         SSL_CTX *ctx = NULL;
133         STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
134         char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
135         unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
136         int ret = 1;
137         int accept_count = -1;
138         int badarg = 0;
139         int i;
140         int ignore_err = 0;
141         STACK *reqnames = NULL;
142         STACK_OF(OCSP_CERTID) *ids = NULL;
143
144         X509 *rca_cert = NULL;
145         char *ridx_filename = NULL;
146         char *rca_filename = NULL;
147         CA_DB *rdb = NULL;
148         int nmin = 0, ndays = -1;
149
150         if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
151
152         if (!load_config(bio_err, NULL))
153                 goto end;
154         SSL_load_error_strings();
155         OpenSSL_add_ssl_algorithms();
156         args = argv + 1;
157         reqnames = sk_new_null();
158         ids = sk_OCSP_CERTID_new_null();
159         while (!badarg && *args && *args[0] == '-')
160                 {
161                 if (!strcmp(*args, "-out"))
162                         {
163                         if (args[1])
164                                 {
165                                 args++;
166                                 outfile = *args;
167                                 }
168                         else badarg = 1;
169                         }
170                 else if (!strcmp(*args, "-timeout"))
171                         {
172                         if (args[1])
173                                 {
174                                 args++;
175                                 req_timeout = atol(*args);
176                                 if (req_timeout < 0)
177                                         {
178                                         BIO_printf(bio_err,
179                                                 "Illegal timeout value %s\n",
180                                                 *args);
181                                         badarg = 1;
182                                         }
183                                 }
184                         else badarg = 1;
185                         }
186                 else if (!strcmp(*args, "-url"))
187                         {
188                         if (args[1])
189                                 {
190                                 args++;
191                                 if (!OCSP_parse_url(*args, &host, &port, &path, &use_ssl))
192                                         {
193                                         BIO_printf(bio_err, "Error parsing URL\n");
194                                         badarg = 1;
195                                         }
196                                 }
197                         else badarg = 1;
198                         }
199                 else if (!strcmp(*args, "-host"))
200                         {
201                         if (args[1])
202                                 {
203                                 args++;
204                                 host = *args;
205                                 }
206                         else badarg = 1;
207                         }
208                 else if (!strcmp(*args, "-port"))
209                         {
210                         if (args[1])
211                                 {
212                                 args++;
213                                 port = *args;
214                                 }
215                         else badarg = 1;
216                         }
217                 else if (!strcmp(*args, "-ignore_err"))
218                         ignore_err = 1;
219                 else if (!strcmp(*args, "-noverify"))
220                         noverify = 1;
221                 else if (!strcmp(*args, "-nonce"))
222                         add_nonce = 2;
223                 else if (!strcmp(*args, "-no_nonce"))
224                         add_nonce = 0;
225                 else if (!strcmp(*args, "-resp_no_certs"))
226                         rflags |= OCSP_NOCERTS;
227                 else if (!strcmp(*args, "-resp_key_id"))
228                         rflags |= OCSP_RESPID_KEY;
229                 else if (!strcmp(*args, "-no_certs"))
230                         sign_flags |= OCSP_NOCERTS;
231                 else if (!strcmp(*args, "-no_signature_verify"))
232                         verify_flags |= OCSP_NOSIGS;
233                 else if (!strcmp(*args, "-no_cert_verify"))
234                         verify_flags |= OCSP_NOVERIFY;
235                 else if (!strcmp(*args, "-no_chain"))
236                         verify_flags |= OCSP_NOCHAIN;
237                 else if (!strcmp(*args, "-no_cert_checks"))
238                         verify_flags |= OCSP_NOCHECKS;
239                 else if (!strcmp(*args, "-no_explicit"))
240                         verify_flags |= OCSP_NOEXPLICIT;
241                 else if (!strcmp(*args, "-trust_other"))
242                         verify_flags |= OCSP_TRUSTOTHER;
243                 else if (!strcmp(*args, "-no_intern"))
244                         verify_flags |= OCSP_NOINTERN;
245                 else if (!strcmp(*args, "-text"))
246                         {
247                         req_text = 1;
248                         resp_text = 1;
249                         }
250                 else if (!strcmp(*args, "-req_text"))
251                         req_text = 1;
252                 else if (!strcmp(*args, "-resp_text"))
253                         resp_text = 1;
254                 else if (!strcmp(*args, "-reqin"))
255                         {
256                         if (args[1])
257                                 {
258                                 args++;
259                                 reqin = *args;
260                                 }
261                         else badarg = 1;
262                         }
263                 else if (!strcmp(*args, "-respin"))
264                         {
265                         if (args[1])
266                                 {
267                                 args++;
268                                 respin = *args;
269                                 }
270                         else badarg = 1;
271                         }
272                 else if (!strcmp(*args, "-signer"))
273                         {
274                         if (args[1])
275                                 {
276                                 args++;
277                                 signfile = *args;
278                                 }
279                         else badarg = 1;
280                         }
281                 else if (!strcmp (*args, "-VAfile"))
282                         {
283                         if (args[1])
284                                 {
285                                 args++;
286                                 verify_certfile = *args;
287                                 verify_flags |= OCSP_TRUSTOTHER;
288                                 }
289                         else badarg = 1;
290                         }
291                 else if (!strcmp(*args, "-sign_other"))
292                         {
293                         if (args[1])
294                                 {
295                                 args++;
296                                 sign_certfile = *args;
297                                 }
298                         else badarg = 1;
299                         }
300                 else if (!strcmp(*args, "-verify_other"))
301                         {
302                         if (args[1])
303                                 {
304                                 args++;
305                                 verify_certfile = *args;
306                                 }
307                         else badarg = 1;
308                         }
309                 else if (!strcmp (*args, "-CAfile"))
310                         {
311                         if (args[1])
312                                 {
313                                 args++;
314                                 CAfile = *args;
315                                 }
316                         else badarg = 1;
317                         }
318                 else if (!strcmp (*args, "-CApath"))
319                         {
320                         if (args[1])
321                                 {
322                                 args++;
323                                 CApath = *args;
324                                 }
325                         else badarg = 1;
326                         }
327                 else if (!strcmp (*args, "-validity_period"))
328                         {
329                         if (args[1])
330                                 {
331                                 args++;
332                                 nsec = atol(*args);
333                                 if (nsec < 0)
334                                         {
335                                         BIO_printf(bio_err,
336                                                 "Illegal validity period %s\n",
337                                                 *args);
338                                         badarg = 1;
339                                         }
340                                 }
341                         else badarg = 1;
342                         }
343                 else if (!strcmp (*args, "-status_age"))
344                         {
345                         if (args[1])
346                                 {
347                                 args++;
348                                 maxage = atol(*args);
349                                 if (maxage < 0)
350                                         {
351                                         BIO_printf(bio_err,
352                                                 "Illegal validity age %s\n",
353                                                 *args);
354                                         badarg = 1;
355                                         }
356                                 }
357                         else badarg = 1;
358                         }
359                  else if (!strcmp(*args, "-signkey"))
360                         {
361                         if (args[1])
362                                 {
363                                 args++;
364                                 keyfile = *args;
365                                 }
366                         else badarg = 1;
367                         }
368                 else if (!strcmp(*args, "-reqout"))
369                         {
370                         if (args[1])
371                                 {
372                                 args++;
373                                 reqout = *args;
374                                 }
375                         else badarg = 1;
376                         }
377                 else if (!strcmp(*args, "-respout"))
378                         {
379                         if (args[1])
380                                 {
381                                 args++;
382                                 respout = *args;
383                                 }
384                         else badarg = 1;
385                         }
386                  else if (!strcmp(*args, "-path"))
387                         {
388                         if (args[1])
389                                 {
390                                 args++;
391                                 path = *args;
392                                 }
393                         else badarg = 1;
394                         }
395                 else if (!strcmp(*args, "-issuer"))
396                         {
397                         if (args[1])
398                                 {
399                                 args++;
400                                 X509_free(issuer);
401                                 issuer = load_cert(bio_err, *args, FORMAT_PEM,
402                                         NULL, e, "issuer certificate");
403                                 if(!issuer) goto end;
404                                 }
405                         else badarg = 1;
406                         }
407                 else if (!strcmp (*args, "-cert"))
408                         {
409                         if (args[1])
410                                 {
411                                 args++;
412                                 X509_free(cert);
413                                 cert = load_cert(bio_err, *args, FORMAT_PEM,
414                                         NULL, e, "certificate");
415                                 if(!cert) goto end;
416                                 if(!add_ocsp_cert(&req, cert, issuer, ids))
417                                         goto end;
418                                 if(!sk_push(reqnames, *args))
419                                         goto end;
420                                 }
421                         else badarg = 1;
422                         }
423                 else if (!strcmp(*args, "-serial"))
424                         {
425                         if (args[1])
426                                 {
427                                 args++;
428                                 if(!add_ocsp_serial(&req, *args, issuer, ids))
429                                         goto end;
430                                 if(!sk_push(reqnames, *args))
431                                         goto end;
432                                 }
433                         else badarg = 1;
434                         }
435                 else if (!strcmp(*args, "-index"))
436                         {
437                         if (args[1])
438                                 {
439                                 args++;
440                                 ridx_filename = *args;
441                                 }
442                         else badarg = 1;
443                         }
444                 else if (!strcmp(*args, "-CA"))
445                         {
446                         if (args[1])
447                                 {
448                                 args++;
449                                 rca_filename = *args;
450                                 }
451                         else badarg = 1;
452                         }
453                 else if (!strcmp (*args, "-nmin"))
454                         {
455                         if (args[1])
456                                 {
457                                 args++;
458                                 nmin = atol(*args);
459                                 if (nmin < 0)
460                                         {
461                                         BIO_printf(bio_err,
462                                                 "Illegal update period %s\n",
463                                                 *args);
464                                         badarg = 1;
465                                         }
466                                 }
467                                 if (ndays == -1)
468                                         ndays = 0;
469                         else badarg = 1;
470                         }
471                 else if (!strcmp (*args, "-nrequest"))
472                         {
473                         if (args[1])
474                                 {
475                                 args++;
476                                 accept_count = atol(*args);
477                                 if (accept_count < 0)
478                                         {
479                                         BIO_printf(bio_err,
480                                                 "Illegal accept count %s\n",
481                                                 *args);
482                                         badarg = 1;
483                                         }
484                                 }
485                         else badarg = 1;
486                         }
487                 else if (!strcmp (*args, "-ndays"))
488                         {
489                         if (args[1])
490                                 {
491                                 args++;
492                                 ndays = atol(*args);
493                                 if (ndays < 0)
494                                         {
495                                         BIO_printf(bio_err,
496                                                 "Illegal update period %s\n",
497                                                 *args);
498                                         badarg = 1;
499                                         }
500                                 }
501                         else badarg = 1;
502                         }
503                 else if (!strcmp(*args, "-rsigner"))
504                         {
505                         if (args[1])
506                                 {
507                                 args++;
508                                 rsignfile = *args;
509                                 }
510                         else badarg = 1;
511                         }
512                 else if (!strcmp(*args, "-rkey"))
513                         {
514                         if (args[1])
515                                 {
516                                 args++;
517                                 rkeyfile = *args;
518                                 }
519                         else badarg = 1;
520                         }
521                 else if (!strcmp(*args, "-rother"))
522                         {
523                         if (args[1])
524                                 {
525                                 args++;
526                                 rcertfile = *args;
527                                 }
528                         else badarg = 1;
529                         }
530                 else badarg = 1;
531                 args++;
532                 }
533
534         /* Have we anything to do? */
535         if (!req && !reqin && !respin && !(port && ridx_filename)) badarg = 1;
536
537         if (badarg)
538                 {
539                 BIO_printf (bio_err, "OCSP utility\n");
540                 BIO_printf (bio_err, "Usage ocsp [options]\n");
541                 BIO_printf (bio_err, "where options are\n");
542                 BIO_printf (bio_err, "-out file          output filename\n");
543                 BIO_printf (bio_err, "-issuer file       issuer certificate\n");
544                 BIO_printf (bio_err, "-cert file         certificate to check\n");
545                 BIO_printf (bio_err, "-serial n          serial number to check\n");
546                 BIO_printf (bio_err, "-signer file       certificate to sign OCSP request with\n");
547                 BIO_printf (bio_err, "-signkey file      private key to sign OCSP request with\n");
548                 BIO_printf (bio_err, "-sign_other file   additional certificates to include in signed request\n");
549                 BIO_printf (bio_err, "-no_certs          don't include any certificates in signed request\n");
550                 BIO_printf (bio_err, "-req_text          print text form of request\n");
551                 BIO_printf (bio_err, "-resp_text         print text form of response\n");
552                 BIO_printf (bio_err, "-text              print text form of request and response\n");
553                 BIO_printf (bio_err, "-reqout file       write DER encoded OCSP request to \"file\"\n");
554                 BIO_printf (bio_err, "-respout file      write DER encoded OCSP reponse to \"file\"\n");
555                 BIO_printf (bio_err, "-reqin file        read DER encoded OCSP request from \"file\"\n");
556                 BIO_printf (bio_err, "-respin file       read DER encoded OCSP reponse from \"file\"\n");
557                 BIO_printf (bio_err, "-nonce             add OCSP nonce to request\n");
558                 BIO_printf (bio_err, "-no_nonce          don't add OCSP nonce to request\n");
559                 BIO_printf (bio_err, "-url URL           OCSP responder URL\n");
560                 BIO_printf (bio_err, "-host host:n       send OCSP request to host on port n\n");
561                 BIO_printf (bio_err, "-path              path to use in OCSP request\n");
562                 BIO_printf (bio_err, "-CApath dir        trusted certificates directory\n");
563                 BIO_printf (bio_err, "-CAfile file       trusted certificates file\n");
564                 BIO_printf (bio_err, "-VAfile file       validator certificates file\n");
565                 BIO_printf (bio_err, "-validity_period n maximum validity discrepancy in seconds\n");
566                 BIO_printf (bio_err, "-status_age n      maximum status age in seconds\n");
567                 BIO_printf (bio_err, "-noverify          don't verify response at all\n");
568                 BIO_printf (bio_err, "-verify_other file additional certificates to search for signer\n");
569                 BIO_printf (bio_err, "-trust_other       don't verify additional certificates\n");
570                 BIO_printf (bio_err, "-no_intern         don't search certificates contained in response for signer\n");
571                 BIO_printf (bio_err, "-no_signature_verify don't check signature on response\n");
572                 BIO_printf (bio_err, "-no_cert_verify    don't check signing certificate\n");
573                 BIO_printf (bio_err, "-no_chain          don't chain verify response\n");
574                 BIO_printf (bio_err, "-no_cert_checks    don't do additional checks on signing certificate\n");
575                 BIO_printf (bio_err, "-port num          port to run responder on\n");
576                 BIO_printf (bio_err, "-index file        certificate status index file\n");
577                 BIO_printf (bio_err, "-CA file           CA certificate\n");
578                 BIO_printf (bio_err, "-rsigner file      responder certificate to sign responses with\n");
579                 BIO_printf (bio_err, "-rkey file         responder key to sign responses with\n");
580                 BIO_printf (bio_err, "-rother file       other certificates to include in response\n");
581                 BIO_printf (bio_err, "-resp_no_certs     don't include any certificates in response\n");
582                 BIO_printf (bio_err, "-nmin n            number of minutes before next update\n");
583                 BIO_printf (bio_err, "-ndays n           number of days before next update\n");
584                 BIO_printf (bio_err, "-resp_key_id       identify reponse by signing certificate key ID\n");
585                 BIO_printf (bio_err, "-nrequest n        number of requests to accept (default unlimited)\n");
586                 goto end;
587                 }
588
589         if(outfile) out = BIO_new_file(outfile, "w");
590         else out = BIO_new_fp(stdout, BIO_NOCLOSE);
591
592         if(!out)
593                 {
594                 BIO_printf(bio_err, "Error opening output file\n");
595                 goto end;
596                 }
597
598         if (!req && (add_nonce != 2)) add_nonce = 0;
599
600         if (!req && reqin)
601                 {
602                 derbio = BIO_new_file(reqin, "rb");
603                 if (!derbio)
604                         {
605                         BIO_printf(bio_err, "Error Opening OCSP request file\n");
606                         goto end;
607                         }
608                 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
609                 BIO_free(derbio);
610                 if(!req)
611                         {
612                         BIO_printf(bio_err, "Error reading OCSP request\n");
613                         goto end;
614                         }
615                 }
616
617         if (!req && port)
618                 {
619                 acbio = init_responder(port);
620                 if (!acbio)
621                         goto end;
622                 }
623
624         if (rsignfile && !rdb)
625                 {
626                 if (!rkeyfile) rkeyfile = rsignfile;
627                 rsigner = load_cert(bio_err, rsignfile, FORMAT_PEM,
628                         NULL, e, "responder certificate");
629                 if (!rsigner)
630                         {
631                         BIO_printf(bio_err, "Error loading responder certificate\n");
632                         goto end;
633                         }
634                 rca_cert = load_cert(bio_err, rca_filename, FORMAT_PEM,
635                         NULL, e, "CA certificate");
636                 if (rcertfile)
637                         {
638                         rother = load_certs(bio_err, rcertfile, FORMAT_PEM,
639                                 NULL, e, "responder other certificates");
640                         if (!rother) goto end;
641                         }
642                 rkey = load_key(bio_err, rkeyfile, FORMAT_PEM, 0, NULL, NULL,
643                         "responder private key");
644                 if (!rkey)
645                         goto end;
646                 }
647         if(acbio)
648                 BIO_printf(bio_err, "Waiting for OCSP client connections...\n");
649
650         redo_accept:
651
652         if (acbio)
653                 {
654                 if (!do_responder(&req, &cbio, acbio, port))
655                         goto end;
656                 if (!req)
657                         {
658                         resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
659                         send_ocsp_response(cbio, resp);
660                         goto done_resp;
661                         }
662                 }
663
664         if (!req && (signfile || reqout || host || add_nonce || ridx_filename))
665                 {
666                 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
667                 goto end;
668                 }
669
670         if (req && add_nonce) OCSP_request_add1_nonce(req, NULL, -1);
671
672         if (signfile)
673                 {
674                 if (!keyfile) keyfile = signfile;
675                 signer = load_cert(bio_err, signfile, FORMAT_PEM,
676                         NULL, e, "signer certificate");
677                 if (!signer)
678                         {
679                         BIO_printf(bio_err, "Error loading signer certificate\n");
680                         goto end;
681                         }
682                 if (sign_certfile)
683                         {
684                         sign_other = load_certs(bio_err, sign_certfile, FORMAT_PEM,
685                                 NULL, e, "signer certificates");
686                         if (!sign_other) goto end;
687                         }
688                 key = load_key(bio_err, keyfile, FORMAT_PEM, 0, NULL, NULL,
689                         "signer private key");
690                 if (!key)
691                         goto end;
692                 if (!OCSP_request_sign(req, signer, key, EVP_sha1(), sign_other, sign_flags))
693                         {
694                         BIO_printf(bio_err, "Error signing OCSP request\n");
695                         goto end;
696                         }
697                 }
698
699         if (req_text && req) OCSP_REQUEST_print(out, req, 0);
700
701         if (reqout)
702                 {
703                 derbio = BIO_new_file(reqout, "wb");
704                 if(!derbio)
705                         {
706                         BIO_printf(bio_err, "Error opening file %s\n", reqout);
707                         goto end;
708                         }
709                 i2d_OCSP_REQUEST_bio(derbio, req);
710                 BIO_free(derbio);
711                 }
712
713         if (ridx_filename && (!rkey || !rsigner || !rca_cert))
714                 {
715                 BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n");
716                 goto end;
717                 }
718
719         if (ridx_filename && !rdb)
720                 {
721                 rdb = load_index(ridx_filename, NULL);
722                 if (!rdb) goto end;
723                 if (!index_index(rdb)) goto end;
724                 }
725
726         if (rdb)
727                 {
728                 i = make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, rother, rflags, nmin, ndays);
729                 if (cbio)
730                         send_ocsp_response(cbio, resp);
731                 }
732         else if (host)
733                 {
734 #ifndef OPENSSL_NO_SOCK
735                 cbio = BIO_new_connect(host);
736 #else
737                 BIO_printf(bio_err, "Error creating connect BIO - sockets not supported.\n");
738                 goto end;
739 #endif
740                 if (!cbio)
741                         {
742                         BIO_printf(bio_err, "Error creating connect BIO\n");
743                         goto end;
744                         }
745                 if (port) BIO_set_conn_port(cbio, port);
746                 if (use_ssl == 1)
747                         {
748                         BIO *sbio;
749 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
750                         ctx = SSL_CTX_new(SSLv23_client_method());
751 #elif !defined(OPENSSL_NO_SSL3)
752                         ctx = SSL_CTX_new(SSLv3_client_method());
753 #elif !defined(OPENSSL_NO_SSL2)
754                         ctx = SSL_CTX_new(SSLv2_client_method());
755 #else
756                         BIO_printf(bio_err, "SSL is disabled\n");
757                         goto end;
758 #endif
759                         if (ctx == NULL)
760                                 {
761                                 BIO_printf(bio_err, "Error creating SSL context.\n");
762                                 goto end;
763                                 }
764                         SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
765                         sbio = BIO_new_ssl(ctx, 1);
766                         cbio = BIO_push(sbio, cbio);
767                         }
768
769                 resp = query_responder(bio_err, cbio, path, req, req_timeout);
770                 BIO_free_all(cbio);
771                 cbio = NULL;
772                 if (!resp)
773                         {
774                         BIO_printf(bio_err, "Error querying OCSP responsder\n");
775                         goto end;
776                         }
777                 }
778         else if (respin)
779                 {
780                 derbio = BIO_new_file(respin, "rb");
781                 if (!derbio)
782                         {
783                         BIO_printf(bio_err, "Error Opening OCSP response file\n");
784                         goto end;
785                         }
786                 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
787                 BIO_free(derbio);
788                 if(!resp)
789                         {
790                         BIO_printf(bio_err, "Error reading OCSP response\n");
791                         goto end;
792                         }
793         
794                 }
795         else
796                 {
797                 ret = 0;
798                 goto end;
799                 }
800
801         done_resp:
802
803         if (respout)
804                 {
805                 derbio = BIO_new_file(respout, "wb");
806                 if(!derbio)
807                         {
808                         BIO_printf(bio_err, "Error opening file %s\n", respout);
809                         goto end;
810                         }
811                 i2d_OCSP_RESPONSE_bio(derbio, resp);
812                 BIO_free(derbio);
813                 }
814
815         i = OCSP_response_status(resp);
816
817         if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL)
818                 {
819                 BIO_printf(out, "Responder Error: %s (%d)\n",
820                                 OCSP_response_status_str(i), i);
821                 if (ignore_err)
822                         goto redo_accept;
823                 ret = 0;
824                 goto end;
825                 }
826
827         if (resp_text) OCSP_RESPONSE_print(out, resp, 0);
828
829         /* If running as responder don't verify our own response */
830         if (cbio)
831                 {
832                 if (accept_count > 0)
833                         accept_count--;
834                 /* Redo if more connections needed */
835                 if (accept_count)
836                         {
837                         BIO_free_all(cbio);
838                         cbio = NULL;
839                         OCSP_REQUEST_free(req);
840                         req = NULL;
841                         OCSP_RESPONSE_free(resp);
842                         resp = NULL;
843                         goto redo_accept;
844                         }
845                 goto end;
846                 }
847
848         if (!store)
849                 store = setup_verify(bio_err, CAfile, CApath);
850         if (!store)
851                 goto end;
852         if (verify_certfile)
853                 {
854                 verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM,
855                         NULL, e, "validator certificate");
856                 if (!verify_other) goto end;
857                 }
858
859         bs = OCSP_response_get1_basic(resp);
860
861         if (!bs)
862                 {
863                 BIO_printf(bio_err, "Error parsing response\n");
864                 goto end;
865                 }
866
867         if (!noverify)
868                 {
869                 if (req && ((i = OCSP_check_nonce(req, bs)) <= 0))
870                         {
871                         if (i == -1)
872                                 BIO_printf(bio_err, "WARNING: no nonce in response\n");
873                         else
874                                 {
875                                 BIO_printf(bio_err, "Nonce Verify error\n");
876                                 goto end;
877                                 }
878                         }
879
880                 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
881                 if (i < 0) i = OCSP_basic_verify(bs, NULL, store, 0);
882
883                 if(i <= 0)
884                         {
885                         BIO_printf(bio_err, "Response Verify Failure\n");
886                         ERR_print_errors(bio_err);
887                         }
888                 else
889                         BIO_printf(bio_err, "Response verify OK\n");
890
891                 }
892
893         if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
894                 goto end;
895
896         ret = 0;
897
898 end:
899         ERR_print_errors(bio_err);
900         X509_free(signer);
901         X509_STORE_free(store);
902         EVP_PKEY_free(key);
903         EVP_PKEY_free(rkey);
904         X509_free(issuer);
905         X509_free(cert);
906         X509_free(rsigner);
907         X509_free(rca_cert);
908         free_index(rdb);
909         BIO_free_all(cbio);
910         BIO_free_all(acbio);
911         BIO_free(out);
912         OCSP_REQUEST_free(req);
913         OCSP_RESPONSE_free(resp);
914         OCSP_BASICRESP_free(bs);
915         sk_free(reqnames);
916         sk_OCSP_CERTID_free(ids);
917         sk_X509_pop_free(sign_other, X509_free);
918         sk_X509_pop_free(verify_other, X509_free);
919
920         if (use_ssl != -1)
921                 {
922                 OPENSSL_free(host);
923                 OPENSSL_free(port);
924                 OPENSSL_free(path);
925                 SSL_CTX_free(ctx);
926                 }
927
928         OPENSSL_EXIT(ret);
929 }
930
931 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, X509 *issuer,
932                                 STACK_OF(OCSP_CERTID) *ids)
933         {
934         OCSP_CERTID *id;
935         if(!issuer)
936                 {
937                 BIO_printf(bio_err, "No issuer certificate specified\n");
938                 return 0;
939                 }
940         if(!*req) *req = OCSP_REQUEST_new();
941         if(!*req) goto err;
942         id = OCSP_cert_to_id(NULL, cert, issuer);
943         if(!id || !sk_OCSP_CERTID_push(ids, id)) goto err;
944         if(!OCSP_request_add0_id(*req, id)) goto err;
945         return 1;
946
947         err:
948         BIO_printf(bio_err, "Error Creating OCSP request\n");
949         return 0;
950         }
951
952 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, X509 *issuer,
953                                 STACK_OF(OCSP_CERTID) *ids)
954         {
955         OCSP_CERTID *id;
956         X509_NAME *iname;
957         ASN1_BIT_STRING *ikey;
958         ASN1_INTEGER *sno;
959         if(!issuer)
960                 {
961                 BIO_printf(bio_err, "No issuer certificate specified\n");
962                 return 0;
963                 }
964         if(!*req) *req = OCSP_REQUEST_new();
965         if(!*req) goto err;
966         iname = X509_get_subject_name(issuer);
967         ikey = X509_get0_pubkey_bitstr(issuer);
968         sno = s2i_ASN1_INTEGER(NULL, serial);
969         if(!sno)
970                 {
971                 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
972                 return 0;
973                 }
974         id = OCSP_cert_id_new(EVP_sha1(), iname, ikey, sno);
975         ASN1_INTEGER_free(sno);
976         if(!id || !sk_OCSP_CERTID_push(ids, id)) goto err;
977         if(!OCSP_request_add0_id(*req, id)) goto err;
978         return 1;
979
980         err:
981         BIO_printf(bio_err, "Error Creating OCSP request\n");
982         return 0;
983         }
984
985 static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
986                                         STACK *names, STACK_OF(OCSP_CERTID) *ids,
987                                         long nsec, long maxage)
988         {
989         OCSP_CERTID *id;
990         char *name;
991         int i;
992
993         int status, reason;
994
995         ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
996
997         if (!bs || !req || !sk_num(names) || !sk_OCSP_CERTID_num(ids))
998                 return 1;
999
1000         for (i = 0; i < sk_OCSP_CERTID_num(ids); i++)
1001                 {
1002                 id = sk_OCSP_CERTID_value(ids, i);
1003                 name = sk_value(names, i);
1004                 BIO_printf(out, "%s: ", name);
1005
1006                 if(!OCSP_resp_find_status(bs, id, &status, &reason,
1007                                         &rev, &thisupd, &nextupd))
1008                         {
1009                         BIO_puts(out, "ERROR: No Status found.\n");
1010                         continue;
1011                         }
1012
1013                 /* Check validity: if invalid write to output BIO so we
1014                  * know which response this refers to.
1015                  */
1016                 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage))
1017                         {
1018                         BIO_puts(out, "WARNING: Status times invalid.\n");
1019                         ERR_print_errors(out);
1020                         }
1021                 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
1022
1023                 BIO_puts(out, "\tThis Update: ");
1024                 ASN1_GENERALIZEDTIME_print(out, thisupd);
1025                 BIO_puts(out, "\n");
1026
1027                 if(nextupd)
1028                         {
1029                         BIO_puts(out, "\tNext Update: ");
1030                         ASN1_GENERALIZEDTIME_print(out, nextupd);
1031                         BIO_puts(out, "\n");
1032                         }
1033
1034                 if (status != V_OCSP_CERTSTATUS_REVOKED)
1035                         continue;
1036
1037                 if (reason != -1)
1038                         BIO_printf(out, "\tReason: %s\n",
1039                                 OCSP_crl_reason_str(reason));
1040
1041                 BIO_puts(out, "\tRevocation Time: ");
1042                 ASN1_GENERALIZEDTIME_print(out, rev);
1043                 BIO_puts(out, "\n");
1044                 }
1045
1046         return 1;
1047         }
1048
1049
1050 static int make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, CA_DB *db,
1051                         X509 *ca, X509 *rcert, EVP_PKEY *rkey,
1052                         STACK_OF(X509) *rother, unsigned long flags,
1053                         int nmin, int ndays)
1054         {
1055         ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1056         OCSP_CERTID *cid, *ca_id = NULL;
1057         OCSP_BASICRESP *bs = NULL;
1058         int i, id_count, ret = 1;
1059
1060
1061         id_count = OCSP_request_onereq_count(req);
1062
1063         if (id_count <= 0)
1064                 {
1065                 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1066                 goto end;
1067                 }
1068
1069         ca_id = OCSP_cert_to_id(EVP_sha1(), NULL, ca);
1070
1071         bs = OCSP_BASICRESP_new();
1072         thisupd = X509_gmtime_adj(NULL, 0);
1073         if (ndays != -1)
1074                 nextupd = X509_gmtime_adj(NULL, nmin * 60 + ndays * 3600 * 24 );
1075
1076         /* Examine each certificate id in the request */
1077         for (i = 0; i < id_count; i++)
1078                 {
1079                 OCSP_ONEREQ *one;
1080                 ASN1_INTEGER *serial;
1081                 char **inf;
1082                 one = OCSP_request_onereq_get0(req, i);
1083                 cid = OCSP_onereq_get0_id(one);
1084                 /* Is this request about our CA? */
1085                 if (OCSP_id_issuer_cmp(ca_id, cid))
1086                         {
1087                         OCSP_basic_add1_status(bs, cid,
1088                                                 V_OCSP_CERTSTATUS_UNKNOWN,
1089                                                 0, NULL,
1090                                                 thisupd, nextupd);
1091                         continue;
1092                         }
1093                 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1094                 inf = lookup_serial(db, serial);
1095                 if (!inf)
1096                         OCSP_basic_add1_status(bs, cid,
1097                                                 V_OCSP_CERTSTATUS_UNKNOWN,
1098                                                 0, NULL,
1099                                                 thisupd, nextupd);
1100                 else if (inf[DB_type][0] == DB_TYPE_VAL)
1101                         OCSP_basic_add1_status(bs, cid,
1102                                                 V_OCSP_CERTSTATUS_GOOD,
1103                                                 0, NULL,
1104                                                 thisupd, nextupd);
1105                 else if (inf[DB_type][0] == DB_TYPE_REV)
1106                         {
1107                         ASN1_OBJECT *inst = NULL;
1108                         ASN1_TIME *revtm = NULL;
1109                         ASN1_GENERALIZEDTIME *invtm = NULL;
1110                         OCSP_SINGLERESP *single;
1111                         int reason = -1;
1112                         unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1113                         single = OCSP_basic_add1_status(bs, cid,
1114                                                 V_OCSP_CERTSTATUS_REVOKED,
1115                                                 reason, revtm,
1116                                                 thisupd, nextupd);
1117                         if (invtm)
1118                                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date, invtm, 0, 0);
1119                         else if (inst)
1120                                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_hold_instruction_code, inst, 0, 0);
1121                         ASN1_OBJECT_free(inst);
1122                         ASN1_TIME_free(revtm);
1123                         ASN1_GENERALIZEDTIME_free(invtm);
1124                         }
1125                 }
1126
1127         OCSP_copy_nonce(bs, req);
1128                 
1129         OCSP_basic_sign(bs, rcert, rkey, EVP_sha1(), rother, flags);
1130
1131         *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1132
1133         end:
1134         ASN1_TIME_free(thisupd);
1135         ASN1_TIME_free(nextupd);
1136         OCSP_CERTID_free(ca_id);
1137         OCSP_BASICRESP_free(bs);
1138         return ret;
1139
1140         }
1141
1142 static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser)
1143         {
1144         int i;
1145         BIGNUM *bn = NULL;
1146         char *itmp, *row[DB_NUMBER],**rrow;
1147         for (i = 0; i < DB_NUMBER; i++) row[i] = NULL;
1148         bn = ASN1_INTEGER_to_BN(ser,NULL);
1149         OPENSSL_assert(bn); /* FIXME: should report an error at this point and abort */
1150         if (BN_is_zero(bn))
1151                 itmp = BUF_strdup("00");
1152         else
1153                 itmp = BN_bn2hex(bn);
1154         row[DB_serial] = itmp;
1155         BN_free(bn);
1156         rrow=TXT_DB_get_by_index(db->db,DB_serial,row);
1157         OPENSSL_free(itmp);
1158         return rrow;
1159         }
1160
1161 /* Quick and dirty OCSP server: read in and parse input request */
1162
1163 static BIO *init_responder(char *port)
1164         {
1165         BIO *acbio = NULL, *bufbio = NULL;
1166         bufbio = BIO_new(BIO_f_buffer());
1167         if (!bufbio) 
1168                 goto err;
1169 #ifndef OPENSSL_NO_SOCK
1170         acbio = BIO_new_accept(port);
1171 #else
1172         BIO_printf(bio_err, "Error setting up accept BIO - sockets not supported.\n");
1173 #endif
1174         if (!acbio)
1175                 goto err;
1176         BIO_set_accept_bios(acbio, bufbio);
1177         bufbio = NULL;
1178
1179         if (BIO_do_accept(acbio) <= 0)
1180                 {
1181                         BIO_printf(bio_err, "Error setting up accept BIO\n");
1182                         ERR_print_errors(bio_err);
1183                         goto err;
1184                 }
1185
1186         return acbio;
1187
1188         err:
1189         BIO_free_all(acbio);
1190         BIO_free(bufbio);
1191         return NULL;
1192         }
1193
1194 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, char *port)
1195         {
1196         int have_post = 0, len;
1197         OCSP_REQUEST *req = NULL;
1198         char inbuf[1024];
1199         BIO *cbio = NULL;
1200
1201         if (BIO_do_accept(acbio) <= 0)
1202                 {
1203                         BIO_printf(bio_err, "Error accepting connection\n");
1204                         ERR_print_errors(bio_err);
1205                         return 0;
1206                 }
1207
1208         cbio = BIO_pop(acbio);
1209         *pcbio = cbio;
1210
1211         for(;;)
1212                 {
1213                 len = BIO_gets(cbio, inbuf, sizeof inbuf);
1214                 if (len <= 0)
1215                         return 1;
1216                 /* Look for "POST" signalling start of query */
1217                 if (!have_post)
1218                         {
1219                         if(strncmp(inbuf, "POST", 4))
1220                                 {
1221                                 BIO_printf(bio_err, "Invalid request\n");
1222                                 return 1;
1223                                 }
1224                         have_post = 1;
1225                         }
1226                 /* Look for end of headers */
1227                 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1228                         break;
1229                 }
1230
1231         /* Try to read OCSP request */
1232
1233         req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1234
1235         if (!req)
1236                 {
1237                 BIO_printf(bio_err, "Error parsing OCSP request\n");
1238                 ERR_print_errors(bio_err);
1239                 }
1240
1241         *preq = req;
1242
1243         return 1;
1244
1245         }
1246
1247 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1248         {
1249         char http_resp[] = 
1250                 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1251                 "Content-Length: %d\r\n\r\n";
1252         if (!cbio)
1253                 return 0;
1254         BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1255         i2d_OCSP_RESPONSE_bio(cbio, resp);
1256         BIO_flush(cbio);
1257         return 1;
1258         }
1259
1260 static OCSP_RESPONSE *query_responder(BIO *err, BIO *cbio, char *path,
1261                                 OCSP_REQUEST *req, int req_timeout)
1262         {
1263         int fd;
1264         int rv;
1265         OCSP_REQ_CTX *ctx = NULL;
1266         OCSP_RESPONSE *rsp = NULL;
1267         fd_set confds;
1268         struct timeval tv;
1269
1270         if (req_timeout != -1)
1271                 BIO_set_nbio(cbio, 1);
1272
1273         rv = BIO_do_connect(cbio);
1274
1275         if ((rv <= 0) && ((req_timeout == -1) || !BIO_should_retry(cbio)))
1276                 {
1277                 BIO_puts(err, "Error connecting BIO\n");
1278                 return NULL;
1279                 }
1280
1281         if (req_timeout == -1)
1282                 return OCSP_sendreq_bio(cbio, path, req);
1283
1284         if (BIO_get_fd(cbio, &fd) <= 0)
1285                 {
1286                 BIO_puts(err, "Can't get connection fd\n");
1287                 goto err;
1288                 }
1289
1290         if (rv <= 0)
1291                 {
1292                 FD_ZERO(&confds);
1293                 openssl_fdset(fd, &confds);
1294                 tv.tv_usec = 0;
1295                 tv.tv_sec = req_timeout;
1296                 rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1297                 if (rv == 0)
1298                         {
1299                         BIO_puts(err, "Timeout on connect\n");
1300                         return NULL;
1301                         }
1302                 }
1303
1304
1305         ctx = OCSP_sendreq_new(cbio, path, req, -1);
1306         if (!ctx)
1307                 return NULL;
1308         
1309         for (;;)
1310                 {
1311                 rv = OCSP_sendreq_nbio(&rsp, ctx);
1312                 if (rv != -1)
1313                         break;
1314                 FD_ZERO(&confds);
1315                 openssl_fdset(fd, &confds);
1316                 tv.tv_usec = 0;
1317                 tv.tv_sec = req_timeout;
1318                 if (BIO_should_read(cbio))
1319                         rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv);
1320                 else if (BIO_should_write(cbio))
1321                         rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv);
1322                 else
1323                         {
1324                         BIO_puts(err, "Unexpected retry condition\n");
1325                         goto err;
1326                         }
1327                 if (rv == 0)
1328                         {
1329                         BIO_puts(err, "Timeout on request\n");
1330                         break;
1331                         }
1332                 if (rv == -1)
1333                         {
1334                         BIO_puts(err, "Select error\n");
1335                         break;
1336                         }
1337                         
1338                 }
1339         err:
1340         if (ctx)
1341                 OCSP_REQ_CTX_free(ctx);
1342
1343         return rsp;
1344         }
1345
1346 #endif