cc20bfe529b41b7972bd2efa4f8b133d6b1d7aa3
[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, "-index file        certificate status index file\n");
551                 BIO_printf (bio_err, "-CA file           CA certificate\n");
552                 BIO_printf (bio_err, "-rsigner file      responder certificate to sign requests with\n");
553                 BIO_printf (bio_err, "-rkey file         responder key to sign requests with\n");
554                 BIO_printf (bio_err, "-rother file       other certificates to include in response\n");
555                 BIO_printf (bio_err, "-resp_no_certs     don't include any certificates in response\n");
556                 BIO_printf (bio_err, "-nmin n            number of minutes before next update\n");
557                 BIO_printf (bio_err, "-ndays n           number of days before next update\n");
558                 BIO_printf (bio_err, "-resp_key_id       identify reponse by signing certificate key ID\n");
559                 BIO_printf (bio_err, "-nrequest n        number of requests to accept (default unlimited)\n");
560                 goto end;
561                 }
562
563         if(outfile) out = BIO_new_file(outfile, "w");
564         else out = BIO_new_fp(stdout, BIO_NOCLOSE);
565
566         if(!out)
567                 {
568                 BIO_printf(bio_err, "Error opening output file\n");
569                 goto end;
570                 }
571
572         if (!req && (add_nonce != 2)) add_nonce = 0;
573
574         if (!req && reqin)
575                 {
576                 derbio = BIO_new_file(reqin, "rb");
577                 if (!derbio)
578                         {
579                         BIO_printf(bio_err, "Error Opening OCSP request file\n");
580                         goto end;
581                         }
582                 req = d2i_OCSP_REQUEST_bio(derbio, NULL);
583                 BIO_free(derbio);
584                 if(!req)
585                         {
586                         BIO_printf(bio_err, "Error reading OCSP request\n");
587                         goto end;
588                         }
589                 }
590
591         if (!req && port)
592                 {
593                 acbio = init_responder(port);
594                 if (!acbio)
595                         goto end;
596                 }
597
598         redo_accept:
599
600         if (acbio)
601                 {
602                 if (!do_responder(&req, &cbio, acbio, port))
603                         goto end;
604                 if (!req)
605                         {
606                         resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
607                         send_ocsp_response(cbio, resp);
608                         goto done_resp;
609                         }
610                 }
611
612         if (!req && (signfile || reqout || host || add_nonce || ridx_filename))
613                 {
614                 BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
615                 goto end;
616                 }
617
618         if (req && add_nonce) OCSP_request_add1_nonce(req, NULL, -1);
619
620         if (signfile)
621                 {
622                 if (!keyfile) keyfile = signfile;
623                 signer = load_cert(bio_err, signfile, FORMAT_PEM,
624                         NULL, e, "signer certificate");
625                 if (!signer)
626                         {
627                         BIO_printf(bio_err, "Error loading signer certificate\n");
628                         goto end;
629                         }
630                 if (sign_certfile)
631                         {
632                         sign_other = load_certs(bio_err, sign_certfile, FORMAT_PEM,
633                                 NULL, e, "signer certificates");
634                         if (!sign_other) goto end;
635                         }
636                 key = load_key(bio_err, keyfile, FORMAT_PEM, NULL, NULL,
637                         "signer private key");
638                 if (!key)
639                         goto end;
640                 if (!OCSP_request_sign(req, signer, key, EVP_sha1(), sign_other, sign_flags))
641                         {
642                         BIO_printf(bio_err, "Error signing OCSP request\n");
643                         goto end;
644                         }
645                 }
646
647         if (req_text && req) OCSP_REQUEST_print(out, req, 0);
648
649         if (rsignfile && !rdb)
650                 {
651                 if (!rkeyfile) rkeyfile = rsignfile;
652                 rsigner = load_cert(bio_err, rsignfile, FORMAT_PEM,
653                         NULL, e, "responder certificate");
654                 if (!rsigner)
655                         {
656                         BIO_printf(bio_err, "Error loading responder certificate\n");
657                         goto end;
658                         }
659                 rca_cert = load_cert(bio_err, rca_filename, FORMAT_PEM,
660                         NULL, e, "CA certificate");
661                 if (rcertfile)
662                         {
663                         rother = load_certs(bio_err, sign_certfile, FORMAT_PEM,
664                                 NULL, e, "responder other certificates");
665                         if (!sign_other) goto end;
666                         }
667                 rkey = load_key(bio_err, rkeyfile, FORMAT_PEM, NULL, NULL,
668                         "responder private key");
669                 if (!rkey)
670                         goto end;
671                 }
672
673         if (ridx_filename && (!rkey || !rsigner || !rca_cert))
674                 {
675                 BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n");
676                 goto end;
677                 }
678
679         if (ridx_filename && !rdb)
680                 {
681                 BIO *db_bio = NULL;
682                 db_bio = BIO_new_file(ridx_filename, "r");
683                 if (!db_bio)
684                         {
685                         BIO_printf(bio_err, "Error opening index file %s\n", ridx_filename);
686                         goto end;
687                         }
688                 rdb = TXT_DB_read(db_bio, DB_NUMBER);
689                 BIO_free(db_bio);
690                 if (!rdb)
691                         {
692                         BIO_printf(bio_err, "Error reading index file %s\n", ridx_filename);
693                         goto end;
694                         }
695                 if (!make_serial_index(rdb))
696                         goto end;
697                 }
698
699         if (rdb)
700                 {
701                 i = make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, rother, rflags, nmin, ndays);
702                 if (cbio)
703                         send_ocsp_response(cbio, resp);
704                 }
705         else if (host)
706                 {
707                 cbio = BIO_new_connect(host);
708                 if (!cbio)
709                         {
710                         BIO_printf(bio_err, "Error creating connect BIO\n");
711                         goto end;
712                         }
713                 if (port) BIO_set_conn_port(cbio, port);
714                 if (use_ssl == 1)
715                         {
716                         BIO *sbio;
717                         ctx = SSL_CTX_new(SSLv23_client_method());
718                         SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
719                         sbio = BIO_new_ssl(ctx, 1);
720                         cbio = BIO_push(sbio, cbio);
721                         }
722                 if (BIO_do_connect(cbio) <= 0)
723                         {
724                         BIO_printf(bio_err, "Error connecting BIO\n");
725                         goto end;
726                         }
727                 resp = OCSP_sendreq_bio(cbio, path, req);
728                 BIO_free_all(cbio);
729                 cbio = NULL;
730                 if (!resp)
731                         {
732                         BIO_printf(bio_err, "Error querying OCSP responsder\n");
733                         goto end;
734                         }
735                 }
736         else if (respin)
737                 {
738                 derbio = BIO_new_file(respin, "rb");
739                 if (!derbio)
740                         {
741                         BIO_printf(bio_err, "Error Opening OCSP response file\n");
742                         goto end;
743                         }
744                 resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
745                 BIO_free(derbio);
746                 if(!resp)
747                         {
748                         BIO_printf(bio_err, "Error reading OCSP response\n");
749                         goto end;
750                         }
751         
752                 }
753         else
754                 {
755                 ret = 0;
756                 goto end;
757                 }
758
759         done_resp:
760
761         if (respout)
762                 {
763                 derbio = BIO_new_file(respout, "wb");
764                 if(!derbio)
765                         {
766                         BIO_printf(bio_err, "Error opening file %s\n", respout);
767                         goto end;
768                         }
769                 i2d_OCSP_RESPONSE_bio(derbio, resp);
770                 BIO_free(derbio);
771                 }
772
773         i = OCSP_response_status(resp);
774
775         if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL)
776                 {
777                 BIO_printf(out, "Responder Error: %s (%ld)\n",
778                                 OCSP_response_status_str(i), i);
779                 ret = 0;
780                 goto end;
781                 }
782
783         if (resp_text) OCSP_RESPONSE_print(out, resp, 0);
784
785         /* If running as responder don't verify our own response */
786         if (cbio)
787                 {
788                 if (accept_count > 0)
789                         accept_count--;
790                 /* Redo if more connections needed */
791                 if (accept_count)
792                         {
793                         BIO_free_all(cbio);
794                         cbio = NULL;
795                         OCSP_REQUEST_free(req);
796                         req = NULL;
797                         OCSP_RESPONSE_free(resp);
798                         resp = NULL;
799                         goto redo_accept;
800                         }
801                 goto end;
802                 }
803
804         if (!store)
805                 store = setup_verify(bio_err, CAfile, CApath);
806         if (verify_certfile)
807                 {
808                 verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM,
809                         NULL, e, "validator certificate");
810                 if (!verify_other) goto end;
811                 }
812
813         bs = OCSP_response_get1_basic(resp);
814
815         if (!bs)
816                 {
817                 BIO_printf(bio_err, "Error parsing response\n");
818                 goto end;
819                 }
820
821         if (!noverify)
822                 {
823                 if (req && ((i = OCSP_check_nonce(req, bs)) <= 0))
824                         {
825                         if (i == -1)
826                                 BIO_printf(bio_err, "WARNING: no nonce in response\n");
827                         else
828                                 {
829                                 BIO_printf(bio_err, "Nonce Verify error\n");
830                                 goto end;
831                                 }
832                         }
833
834                 i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
835                 if (i < 0) i = OCSP_basic_verify(bs, NULL, store, 0);
836
837                 if(i <= 0)
838                         {
839                         BIO_printf(bio_err, "Response Verify Failure\n", i);
840                         ERR_print_errors(bio_err);
841                         }
842                 else
843                         BIO_printf(bio_err, "Response verify OK\n");
844
845                 }
846
847         if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
848                 goto end;
849
850         ret = 0;
851
852 end:
853         ERR_print_errors(bio_err);
854         X509_free(signer);
855         X509_STORE_free(store);
856         EVP_PKEY_free(key);
857         EVP_PKEY_free(rkey);
858         X509_free(issuer);
859         X509_free(cert);
860         X509_free(rsigner);
861         X509_free(rca_cert);
862         TXT_DB_free(rdb);
863         BIO_free_all(cbio);
864         BIO_free_all(acbio);
865         BIO_free(out);
866         OCSP_REQUEST_free(req);
867         OCSP_RESPONSE_free(resp);
868         OCSP_BASICRESP_free(bs);
869         sk_free(reqnames);
870         sk_OCSP_CERTID_free(ids);
871         sk_X509_pop_free(sign_other, X509_free);
872         sk_X509_pop_free(verify_other, X509_free);
873
874         if (use_ssl != -1)
875                 {
876                 OPENSSL_free(host);
877                 OPENSSL_free(port);
878                 OPENSSL_free(path);
879                 SSL_CTX_free(ctx);
880                 }
881
882         EXIT(ret);
883 }
884
885 static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, X509 *issuer,
886                                 STACK_OF(OCSP_CERTID) *ids)
887         {
888         OCSP_CERTID *id;
889         if(!issuer)
890                 {
891                 BIO_printf(bio_err, "No issuer certificate specified\n");
892                 return 0;
893                 }
894         if(!*req) *req = OCSP_REQUEST_new();
895         if(!*req) goto err;
896         id = OCSP_cert_to_id(NULL, cert, issuer);
897         if(!id || !sk_OCSP_CERTID_push(ids, id)) goto err;
898         if(!OCSP_request_add0_id(*req, id)) goto err;
899         return 1;
900
901         err:
902         BIO_printf(bio_err, "Error Creating OCSP request\n");
903         return 0;
904         }
905
906 static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, X509 *issuer,
907                                 STACK_OF(OCSP_CERTID) *ids)
908         {
909         OCSP_CERTID *id;
910         X509_NAME *iname;
911         ASN1_BIT_STRING *ikey;
912         ASN1_INTEGER *sno;
913         if(!issuer)
914                 {
915                 BIO_printf(bio_err, "No issuer certificate specified\n");
916                 return 0;
917                 }
918         if(!*req) *req = OCSP_REQUEST_new();
919         if(!*req) goto err;
920         iname = X509_get_subject_name(issuer);
921         ikey = X509_get0_pubkey_bitstr(issuer);
922         sno = s2i_ASN1_INTEGER(NULL, serial);
923         if(!sno)
924                 {
925                 BIO_printf(bio_err, "Error converting serial number %s\n", serial);
926                 return 0;
927                 }
928         id = OCSP_cert_id_new(EVP_sha1(), iname, ikey, sno);
929         ASN1_INTEGER_free(sno);
930         if(!id || !sk_OCSP_CERTID_push(ids, id)) goto err;
931         if(!OCSP_request_add0_id(*req, id)) goto err;
932         return 1;
933
934         err:
935         BIO_printf(bio_err, "Error Creating OCSP request\n");
936         return 0;
937         }
938
939 static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req,
940                                         STACK *names, STACK_OF(OCSP_CERTID) *ids,
941                                         long nsec, long maxage)
942         {
943         OCSP_CERTID *id;
944         char *name;
945         int i;
946
947         int status, reason;
948
949         ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
950
951         if (!bs || !req || !sk_num(names) || !sk_OCSP_CERTID_num(ids))
952                 return 1;
953
954         for (i = 0; i < sk_OCSP_CERTID_num(ids); i++)
955                 {
956                 id = sk_OCSP_CERTID_value(ids, i);
957                 name = sk_value(names, i);
958                 BIO_printf(out, "%s: ", name);
959
960                 if(!OCSP_resp_find_status(bs, id, &status, &reason,
961                                         &rev, &thisupd, &nextupd))
962                         {
963                         BIO_puts(out, "ERROR: No Status found.\n");
964                         continue;
965                         }
966
967                 /* Check validity: if invalid write to output BIO so we
968                  * know which response this refers to.
969                  */
970                 if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage))
971                         {
972                         BIO_puts(out, "WARNING: Status times invalid.\n");
973                         ERR_print_errors(out);
974                         }
975                 BIO_printf(out, "%s\n", OCSP_cert_status_str(status));
976
977                 BIO_puts(out, "\tThis Update: ");
978                 ASN1_GENERALIZEDTIME_print(out, thisupd);
979                 BIO_puts(out, "\n");
980
981                 if(nextupd)
982                         {
983                         BIO_puts(out, "\tNext Update: ");
984                         ASN1_GENERALIZEDTIME_print(out, nextupd);
985                         BIO_puts(out, "\n");
986                         }
987
988                 if (status != V_OCSP_CERTSTATUS_REVOKED)
989                         continue;
990
991                 if (reason != -1)
992                         BIO_printf(out, "\tReason: %s\n",
993                                 OCSP_crl_reason_str(reason));
994
995                 BIO_puts(out, "\tRevocation Time: ");
996                 ASN1_GENERALIZEDTIME_print(out, rev);
997                 BIO_puts(out, "\n");
998                 }
999
1000         return 1;
1001         }
1002
1003
1004 static int make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, TXT_DB *db,
1005                         X509 *ca, X509 *rcert, EVP_PKEY *rkey,
1006                         STACK_OF(X509) *rother, unsigned long flags,
1007                         int nmin, int ndays)
1008         {
1009         ASN1_TIME *thisupd = NULL, *nextupd = NULL;
1010         OCSP_CERTID *cid, *ca_id = NULL;
1011         OCSP_BASICRESP *bs = NULL;
1012         int i, id_count, ret = 1;
1013
1014
1015         id_count = OCSP_request_onereq_count(req);
1016
1017         if (id_count <= 0)
1018                 {
1019                 *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
1020                 goto end;
1021                 }
1022
1023         ca_id = OCSP_cert_to_id(EVP_sha1(), NULL, ca);
1024
1025         bs = OCSP_BASICRESP_new();
1026         thisupd = X509_gmtime_adj(NULL, 0);
1027         if (ndays != -1)
1028                 nextupd = X509_gmtime_adj(NULL, nmin * 60 + ndays * 3600 * 24 );
1029
1030         /* Examine each certificate id in the request */
1031         for (i = 0; i < id_count; i++)
1032                 {
1033                 OCSP_ONEREQ *one;
1034                 ASN1_INTEGER *serial;
1035                 char **inf;
1036                 one = OCSP_request_onereq_get0(req, i);
1037                 cid = OCSP_onereq_get0_id(one);
1038                 /* Is this request about our CA? */
1039                 if (OCSP_id_issuer_cmp(ca_id, cid))
1040                         {
1041                         OCSP_basic_add1_status(bs, cid,
1042                                                 V_OCSP_CERTSTATUS_UNKNOWN,
1043                                                 0, NULL,
1044                                                 thisupd, nextupd);
1045                         continue;
1046                         }
1047                 OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid);
1048                 inf = lookup_serial(db, serial);
1049                 if (!inf)
1050                         OCSP_basic_add1_status(bs, cid,
1051                                                 V_OCSP_CERTSTATUS_UNKNOWN,
1052                                                 0, NULL,
1053                                                 thisupd, nextupd);
1054                 else if (inf[DB_type][0] == DB_TYPE_VAL)
1055                         OCSP_basic_add1_status(bs, cid,
1056                                                 V_OCSP_CERTSTATUS_GOOD,
1057                                                 0, NULL,
1058                                                 thisupd, nextupd);
1059                 else if (inf[DB_type][0] == DB_TYPE_REV)
1060                         {
1061                         ASN1_OBJECT *inst = NULL;
1062                         ASN1_TIME *revtm = NULL;
1063                         ASN1_GENERALIZEDTIME *invtm = NULL;
1064                         OCSP_SINGLERESP *single;
1065                         int reason = -1;
1066                         unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]);
1067                         single = OCSP_basic_add1_status(bs, cid,
1068                                                 V_OCSP_CERTSTATUS_REVOKED,
1069                                                 reason, revtm,
1070                                                 thisupd, nextupd);
1071                         if (invtm)
1072                                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date, invtm, 0, 0);
1073                         else if (inst)
1074                                 OCSP_SINGLERESP_add1_ext_i2d(single, NID_hold_instruction_code, inst, 0, 0);
1075                         ASN1_OBJECT_free(inst);
1076                         ASN1_TIME_free(revtm);
1077                         ASN1_GENERALIZEDTIME_free(invtm);
1078                         }
1079                 }
1080
1081         OCSP_copy_nonce(bs, req);
1082                 
1083         OCSP_basic_sign(bs, rcert, rkey, EVP_sha1(), rother, flags);
1084
1085         *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs);
1086
1087         end:
1088         ASN1_TIME_free(thisupd);
1089         ASN1_TIME_free(nextupd);
1090         OCSP_CERTID_free(ca_id);
1091         OCSP_BASICRESP_free(bs);
1092         return ret;
1093
1094         }
1095
1096 static char **lookup_serial(TXT_DB *db, ASN1_INTEGER *ser)
1097         {
1098         int i;
1099         BIGNUM *bn = NULL;
1100         char *itmp, *row[DB_NUMBER],**rrow;
1101         for (i = 0; i < DB_NUMBER; i++) row[i] = NULL;
1102         bn = ASN1_INTEGER_to_BN(ser,NULL);
1103         itmp = BN_bn2hex(bn);
1104         row[DB_serial] = itmp;
1105         BN_free(bn);
1106         rrow=TXT_DB_get_by_index(db,DB_serial,row);
1107         OPENSSL_free(itmp);
1108         return rrow;
1109         }
1110
1111 /* Quick and dirty OCSP server: read in and parse input request */
1112
1113 static BIO *init_responder(char *port)
1114         {
1115         BIO *acbio = NULL, *bufbio = NULL;
1116         bufbio = BIO_new(BIO_f_buffer());
1117         if (!bufbio) 
1118                 goto err;
1119         acbio = BIO_new_accept(port);
1120         if (!acbio)
1121                 goto err;
1122         BIO_set_accept_bios(acbio, bufbio);
1123         bufbio = NULL;
1124
1125         if (BIO_do_accept(acbio) <= 0)
1126                 {
1127                         BIO_printf(bio_err, "Error setting up accept BIO\n");
1128                         ERR_print_errors(bio_err);
1129                         goto err;
1130                 }
1131         BIO_printf(bio_err, "Waiting for OCSP client connections...\n");
1132
1133         return acbio;
1134
1135         err:
1136         BIO_free_all(acbio);
1137         BIO_free(bufbio);
1138         return NULL;
1139         }
1140
1141 static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, char *port)
1142         {
1143         int have_post = 0, len;
1144         OCSP_REQUEST *req = NULL;
1145         char inbuf[1024];
1146         BIO *cbio = NULL;
1147
1148         if (BIO_do_accept(acbio) <= 0)
1149                 {
1150                         BIO_printf(bio_err, "Error accepting connection\n");
1151                         ERR_print_errors(bio_err);
1152                         return 0;
1153                 }
1154
1155         cbio = BIO_pop(acbio);
1156         *pcbio = cbio;
1157
1158         for(;;)
1159                 {
1160                 len = BIO_gets(cbio, inbuf, 1024);
1161                 if (len <= 0)
1162                         return 1;
1163                 /* Look for "POST" signalling start of query */
1164                 if (!have_post)
1165                         {
1166                         if(strncmp(inbuf, "POST", 4))
1167                                 {
1168                                 BIO_printf(bio_err, "Invalid request\n");
1169                                 return 1;
1170                                 }
1171                         have_post = 1;
1172                         }
1173                 /* Look for end of headers */
1174                 if ((inbuf[0] == '\r') || (inbuf[0] == '\n'))
1175                         break;
1176                 }
1177
1178         /* Try to read OCSP request */
1179
1180         req = d2i_OCSP_REQUEST_bio(cbio, NULL);
1181
1182         if (!req)
1183                 {
1184                 BIO_printf(bio_err, "Error parsing OCSP request\n");
1185                 ERR_print_errors(bio_err);
1186                 }
1187
1188         *preq = req;
1189
1190         return 1;
1191
1192         }
1193
1194 static int send_ocsp_response(BIO *cbio, OCSP_RESPONSE *resp)
1195         {
1196         char http_resp[] = 
1197                 "HTTP/1.0 200 OK\r\nContent-type: application/ocsp-response\r\n"
1198                 "Content-Length: %d\r\n\r\n";
1199         if (!cbio)
1200                 return 0;
1201         BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL));
1202         i2d_OCSP_RESPONSE_bio(cbio, resp);
1203         BIO_flush(cbio);
1204         return 1;
1205         }
1206