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