ensure the pointer is valid before using it
[openssl.git] / apps / ts.c
1 /* apps/ts.c */
2 /* Written by Zoltan Glozik (zglozik@stones.com) for the OpenSSL
3  * project 2002.
4  */
5 /* ====================================================================
6  * Copyright (c) 2001 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 <stdlib.h>
61 #include <string.h>
62 #include "apps.h"
63 #include <openssl/bio.h>
64 #include <openssl/err.h>
65 #include <openssl/pem.h>
66 #include <openssl/rand.h>
67 #include <openssl/ts.h>
68
69 #undef PROG
70 #define PROG    ts_main
71
72 /* Length of the nonce of the request in bits (must be a multiple of 8). */
73 #define NONCE_LENGTH            64
74
75 /* Macro definitions for the configuration file. */
76 #define ENV_OID_FILE            "oid_file"
77
78 /* Local function declarations. */
79
80 static ASN1_OBJECT *txt2obj(const char *oid);
81 static CONF *load_config_file(const char *configfile);
82
83 /* Query related functions. */
84 static int query_command(const char *data, char *digest,
85                          const EVP_MD *md, const char *policy, int no_nonce, 
86                          int cert, const char *in, const char *out, int text);
87 static BIO *BIO_open_with_default(const char *file, const char *mode, 
88                                   FILE *default_fp);
89 static TS_REQ *create_query(BIO *data_bio, char *digest, const EVP_MD *md,
90                             const char *policy, int no_nonce, int cert);
91 static int create_digest(BIO *input, char *digest,
92                          const EVP_MD *md, unsigned char **md_value);
93 static ASN1_INTEGER *create_nonce(int bits);
94
95 /* Reply related functions. */
96 static int reply_command(CONF *conf, char *section, char *engine, 
97                          char *queryfile, char *passin, char *inkey, 
98                          char *signer, char *chain, const char *policy, 
99                          char *in, int token_in, char *out, int token_out,
100                          int text);
101 static TS_RESP *read_PKCS7(BIO *in_bio);
102 static TS_RESP *create_response(CONF *conf, const char *section, char *engine,
103                                 char *queryfile, char *passin, char *inkey,
104                                 char *signer, char *chain, const char *policy);
105 static ASN1_INTEGER * MS_CALLBACK serial_cb(TS_RESP_CTX *ctx, void *data);
106 static ASN1_INTEGER *next_serial(const char *serialfile);
107 static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial);
108
109 /* Verify related functions. */
110 static int verify_command(char *data, char *digest, char *queryfile,
111                           char *in, int token_in,
112                           char *ca_path, char *ca_file, char *untrusted);
113 static TS_VERIFY_CTX *create_verify_ctx(char *data, char *digest, 
114                                         char *queryfile, 
115                                         char *ca_path, char *ca_file,
116                                         char *untrusted);
117 static X509_STORE *create_cert_store(char *ca_path, char *ca_file);
118 static int MS_CALLBACK verify_cb(int ok, X509_STORE_CTX *ctx);
119
120 /* Main function definition. */
121 int MAIN(int, char **);
122
123 int MAIN(int argc, char **argv)
124         {
125         int ret = 1;
126         char *configfile = NULL;
127         char *section = NULL;
128         CONF *conf = NULL;
129         enum mode {
130         CMD_NONE, CMD_QUERY, CMD_REPLY, CMD_VERIFY 
131         } mode = CMD_NONE;
132         char *data = NULL;
133         char *digest = NULL;
134         const EVP_MD *md = NULL;
135         char *rnd = NULL;
136         char *policy = NULL;
137         int no_nonce = 0;
138         int cert = 0;
139         char *in = NULL;
140         char *out = NULL;
141         int text = 0;
142         char *queryfile = NULL;
143         char *passin = NULL;    /* Password source. */
144         char *password =NULL;   /* Password itself. */
145         char *inkey = NULL;
146         char *signer = NULL;
147         char *chain = NULL;
148         char *ca_path = NULL;
149         char *ca_file = NULL;
150         char *untrusted = NULL;
151         char *engine = NULL;
152         /* Input is ContentInfo instead of TimeStampResp. */
153         int token_in = 0;       
154         /* Output is ContentInfo instead of TimeStampResp. */
155         int token_out = 0;
156         int free_bio_err = 0;
157
158         ERR_load_crypto_strings();
159         apps_startup();
160
161         if (bio_err == NULL && (bio_err = BIO_new(BIO_s_file())) != NULL)
162                 {
163                 free_bio_err = 1;
164                 BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
165                 }
166
167         for (argc--, argv++; argc > 0; argc--, argv++)
168                 {
169                 if (strcmp(*argv, "-config") == 0)
170                         {
171                         if (argc-- < 1) goto usage;
172                         configfile = *++argv;
173                         }
174                 else if (strcmp(*argv, "-section") == 0)
175                         {
176                         if (argc-- < 1) goto usage;
177                         section = *++argv;
178                         }
179                 else if (strcmp(*argv, "-query") == 0)
180                         {
181                         if (mode != CMD_NONE) goto usage;
182                         mode = CMD_QUERY;
183                         }
184                 else if (strcmp(*argv, "-data") == 0)
185                         {
186                         if (argc-- < 1) goto usage;
187                         data = *++argv;
188                         }
189                 else if (strcmp(*argv, "-digest") == 0)
190                         {
191                         if (argc-- < 1) goto usage;
192                         digest = *++argv;
193                         }
194                 else if (strcmp(*argv, "-rand") == 0)
195                         {
196                         if (argc-- < 1) goto usage;
197                         rnd = *++argv;
198                         }
199                 else if (strcmp(*argv, "-policy") == 0)
200                         {
201                         if (argc-- < 1) goto usage;
202                         policy = *++argv;
203                         }
204                 else if (strcmp(*argv, "-no_nonce") == 0)
205                         {
206                         no_nonce = 1;
207                         }
208                 else if (strcmp(*argv, "-cert") == 0)
209                         {
210                         cert = 1;
211                         }
212                 else if (strcmp(*argv, "-in") == 0)
213                         {
214                         if (argc-- < 1) goto usage;
215                         in = *++argv;
216                         }
217                 else if (strcmp(*argv, "-token_in") == 0)
218                         {
219                         token_in = 1;
220                         }
221                 else if (strcmp(*argv, "-out") == 0)
222                         {
223                         if (argc-- < 1) goto usage;
224                         out = *++argv;
225                         }
226                 else if (strcmp(*argv, "-token_out") == 0)
227                         {
228                         token_out = 1;
229                         }
230                 else if (strcmp(*argv, "-text") == 0)
231                         {
232                         text = 1;
233                         }
234                 else if (strcmp(*argv, "-reply") == 0)
235                         {
236                         if (mode != CMD_NONE) goto usage;
237                         mode = CMD_REPLY;
238                         }
239                 else if (strcmp(*argv, "-queryfile") == 0)
240                         {
241                         if (argc-- < 1) goto usage;
242                         queryfile = *++argv;
243                         }
244                 else if (strcmp(*argv, "-passin") == 0)
245                         {
246                         if (argc-- < 1) goto usage;
247                         passin = *++argv;
248                         }
249                 else if (strcmp(*argv, "-inkey") == 0)
250                         {
251                         if (argc-- < 1) goto usage;
252                         inkey = *++argv;
253                         }
254                 else if (strcmp(*argv, "-signer") == 0)
255                         {
256                         if (argc-- < 1) goto usage;
257                         signer = *++argv;
258                         }
259                 else if (strcmp(*argv, "-chain") == 0)
260                         {
261                         if (argc-- < 1) goto usage;
262                         chain = *++argv;
263                         }
264                 else if (strcmp(*argv, "-verify") == 0)
265                         {
266                         if (mode != CMD_NONE) goto usage;
267                         mode = CMD_VERIFY;
268                         }
269                 else if (strcmp(*argv, "-CApath") == 0)
270                         {
271                         if (argc-- < 1) goto usage;
272                         ca_path = *++argv;
273                         }
274                 else if (strcmp(*argv, "-CAfile") == 0)
275                         {
276                         if (argc-- < 1) goto usage;
277                         ca_file = *++argv;
278                         }
279                 else if (strcmp(*argv, "-untrusted") == 0)
280                         {
281                         if (argc-- < 1) goto usage;
282                         untrusted = *++argv;
283                         }
284                 else if (strcmp(*argv, "-engine") == 0)
285                         {
286                         if (argc-- < 1) goto usage;
287                         engine = *++argv;
288                         }
289                 else if ((md = EVP_get_digestbyname(*argv + 1)) != NULL)
290                         {
291                         /* empty. */
292                         }
293                 else
294                         goto usage;
295                 }
296         
297         /* Seed the random number generator if it is going to be used. */
298         if (mode == CMD_QUERY && !no_nonce)
299                 {
300                 if (!app_RAND_load_file(NULL, bio_err, 1) && rnd == NULL)
301                         BIO_printf(bio_err, "warning, not much extra random "
302                                    "data, consider using the -rand option\n");
303                 if (rnd != NULL)
304                         BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
305                                    app_RAND_load_files(rnd));
306                 }
307
308         /* Get the password if required. */
309         if(mode == CMD_REPLY && passin &&
310            !app_passwd(bio_err, passin, NULL, &password, NULL))
311                 {
312                 BIO_printf(bio_err,"Error getting password.\n");
313                 goto cleanup;
314                 }
315
316         /* Check consistency of parameters and execute 
317            the appropriate function. */
318         switch (mode)
319                 {
320         case CMD_NONE:
321                 goto usage;
322         case CMD_QUERY:
323                 /* Data file and message imprint cannot be specified
324                    at the same time. */
325                 ret = data != NULL && digest != NULL;
326                 if (ret) goto usage;
327                 /* Load the config file for possible policy OIDs. */
328                 conf = load_config_file(configfile);
329                 ret = !query_command(data, digest, md, policy, no_nonce, cert,
330                                      in, out, text);
331                 break;
332         case CMD_REPLY:
333                 conf = load_config_file(configfile);
334                 if (in == NULL)
335                         {
336                         ret = !(queryfile != NULL && conf != NULL && !token_in);
337                         if (ret) goto usage;
338                         }
339                 else
340                         {
341                         /* 'in' and 'queryfile' are exclusive. */
342                         ret = !(queryfile == NULL);
343                         if (ret) goto usage;
344                         }
345
346                 ret = !reply_command(conf, section, engine, queryfile, 
347                                      password, inkey, signer, chain, policy, 
348                                      in, token_in, out, token_out, text);
349                 break;
350         case CMD_VERIFY:
351                 ret = !(((queryfile && !data && !digest)
352                          || (!queryfile && data && !digest)
353                          || (!queryfile && !data && digest))
354                         && in != NULL);
355                 if (ret) goto usage;
356
357                 ret = !verify_command(data, digest, queryfile, in, token_in,
358                                       ca_path, ca_file, untrusted);
359                 }
360
361         goto cleanup;
362
363  usage:
364         BIO_printf(bio_err, "usage:\n"
365                    "ts -query [-rand file%cfile%c...] [-config configfile] "
366                    "[-data file_to_hash] [-digest digest_bytes]"
367                    "[-md2|-md4|-md5|-sha|-sha1|-mdc2|-ripemd160] "
368                    "[-policy object_id] [-no_nonce] [-cert] "
369                    "[-in request.tsq] [-out request.tsq] [-text]\n",
370                    LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
371         BIO_printf(bio_err, "or\n"
372                    "ts -reply [-config configfile] [-section tsa_section] "
373                    "[-queryfile request.tsq] [-passin password] "
374                    "[-signer tsa_cert.pem] [-inkey private_key.pem] "
375                    "[-chain certs_file.pem] [-policy object_id] "
376                    "[-in response.tsr] [-token_in] "
377                    "[-out response.tsr] [-token_out] [-text] [-engine id]\n");
378         BIO_printf(bio_err, "or\n"
379                    "ts -verify [-data file_to_hash] [-digest digest_bytes] "
380                    "[-queryfile request.tsq] "
381                    "-in response.tsr [-token_in] "
382                    "-CApath ca_path -CAfile ca_file.pem "
383                    "-untrusted cert_file.pem\n");
384  cleanup:
385         /* Clean up. */
386         app_RAND_write_file(NULL, bio_err);
387         NCONF_free(conf);
388         OPENSSL_free(password);
389         OBJ_cleanup();
390         if (free_bio_err)
391                 {
392                 BIO_free_all(bio_err);
393                 bio_err = NULL;
394                 }
395
396         OPENSSL_EXIT(ret);
397         }
398
399 /*
400  * Configuration file-related function definitions.
401  */
402
403 static ASN1_OBJECT *txt2obj(const char *oid)
404         {
405         ASN1_OBJECT *oid_obj = NULL;
406
407         if (!(oid_obj = OBJ_txt2obj(oid, 0)))
408                 BIO_printf(bio_err, "cannot convert %s to OID\n", oid);
409
410         return oid_obj;
411         }
412
413 static CONF *load_config_file(const char *configfile)
414         {
415         CONF *conf = NULL;
416         long errorline = -1;
417
418         if (!configfile) configfile = getenv("OPENSSL_CONF");
419         if (!configfile) configfile = getenv("SSLEAY_CONF");
420
421         if (configfile &&
422             (!(conf = NCONF_new(NULL)) ||
423              NCONF_load(conf, configfile, &errorline) <= 0))
424                 {
425                 if (errorline <= 0)
426                         BIO_printf(bio_err, "error loading the config file "
427                                    "'%s'\n", configfile);
428                 else
429                         BIO_printf(bio_err, "error on line %ld of config file "
430                                    "'%s'\n", errorline, configfile);
431                 }
432
433         if (conf != NULL)
434                 {
435                 const char *p;
436
437                 BIO_printf(bio_err,"Using configuration from %s\n", configfile);
438                 p = NCONF_get_string(conf, NULL, ENV_OID_FILE);
439                 if (p != NULL)
440                         {
441                         BIO *oid_bio = BIO_new_file(p, "r");
442                         if (!oid_bio) 
443                                 ERR_print_errors(bio_err);
444                         else
445                                 {
446                                 OBJ_create_objects(oid_bio);
447                                 BIO_free_all(oid_bio);
448                                 }
449                         }
450                 else
451                         ERR_clear_error();
452                 if(!add_oid_section(bio_err, conf)) 
453                         ERR_print_errors(bio_err);
454                 }
455         return conf;
456         }
457
458 /*
459  * Query-related method definitions.
460  */
461
462 static int query_command(const char *data, char *digest, const EVP_MD *md,
463                          const char *policy, int no_nonce, 
464                          int cert, const char *in, const char *out, int text)
465         {
466         int ret = 0;
467         TS_REQ *query = NULL;
468         BIO *in_bio = NULL;
469         BIO *data_bio = NULL;
470         BIO *out_bio = NULL;
471
472         /* Build query object either from file or from scratch. */
473         if (in != NULL)
474                 {
475                 if ((in_bio = BIO_new_file(in, "rb")) == NULL) goto end;
476                 query = d2i_TS_REQ_bio(in_bio, NULL);
477                 }
478         else
479                 {
480                 /* Open the file if no explicit digest bytes were specified. */
481                 if (!digest 
482                     && !(data_bio = BIO_open_with_default(data, "rb", stdin)))
483                         goto end;
484                 /* Creating the query object. */
485                 query = create_query(data_bio, digest, md,
486                                      policy, no_nonce, cert);
487                 /* Saving the random number generator state. */
488                 }
489         if (query == NULL) goto end;
490
491         /* Write query either in ASN.1 or in text format. */
492         if ((out_bio = BIO_open_with_default(out, "wb", stdout)) == NULL)
493                 goto end;
494         if (text)
495                 {
496                 /* Text output. */
497                 if (!TS_REQ_print_bio(out_bio, query))
498                         goto end;
499                 }
500         else
501                 {
502                 /* ASN.1 output. */
503                 if (!i2d_TS_REQ_bio(out_bio, query))
504                         goto end;
505                 }
506
507         ret = 1;
508
509  end:
510         ERR_print_errors(bio_err);
511
512         /* Clean up. */
513         BIO_free_all(in_bio);
514         BIO_free_all(data_bio);
515         BIO_free_all(out_bio);
516         TS_REQ_free(query);
517
518         return ret;
519         }
520
521 static BIO *BIO_open_with_default(const char *file, const char *mode, 
522                                   FILE *default_fp)
523         {
524         return file == NULL ? 
525                 BIO_new_fp(default_fp, BIO_NOCLOSE) 
526                 : BIO_new_file(file, mode);
527         }
528
529 static TS_REQ *create_query(BIO *data_bio, char *digest, const EVP_MD *md,
530                             const char *policy, int no_nonce, int cert)
531         {
532         int ret = 0;
533         TS_REQ *ts_req = NULL;
534         int len;
535         TS_MSG_IMPRINT *msg_imprint = NULL;
536         X509_ALGOR *algo = NULL;
537         unsigned char *data = NULL;
538         ASN1_OBJECT *policy_obj = NULL;
539         ASN1_INTEGER *nonce_asn1 = NULL;
540
541         /* Setting default message digest. */
542         if (!md && !(md = EVP_get_digestbyname("sha1"))) goto err;
543
544         /* Creating request object. */
545         if (!(ts_req = TS_REQ_new())) goto err;
546
547         /* Setting version. */
548         if (!TS_REQ_set_version(ts_req, 1)) goto err;
549
550         /* Creating and adding MSG_IMPRINT object. */
551         if (!(msg_imprint = TS_MSG_IMPRINT_new())) goto err;
552
553         /* Adding algorithm. */
554         if (!(algo = X509_ALGOR_new())) goto err;
555         if (!(algo->algorithm = OBJ_nid2obj(EVP_MD_type(md)))) goto err;
556         if (!(algo->parameter = ASN1_TYPE_new())) goto err;
557         algo->parameter->type = V_ASN1_NULL;
558         if (!TS_MSG_IMPRINT_set_algo(msg_imprint, algo)) goto err;
559
560         /* Adding message digest. */
561         if ((len = create_digest(data_bio, digest, md, &data)) == 0)
562                 goto err;
563         if (!TS_MSG_IMPRINT_set_msg(msg_imprint, data, len)) goto err;
564
565         if (!TS_REQ_set_msg_imprint(ts_req, msg_imprint)) goto err;
566         
567         /* Setting policy if requested. */
568         if (policy && !(policy_obj = txt2obj(policy))) goto err;
569         if (policy_obj && !TS_REQ_set_policy_id(ts_req, policy_obj)) goto err;
570
571         /* Setting nonce if requested. */
572         if (!no_nonce && !(nonce_asn1 = create_nonce(NONCE_LENGTH))) goto err;
573         if (nonce_asn1 && !TS_REQ_set_nonce(ts_req, nonce_asn1)) goto err;
574
575         /* Setting certificate request flag if requested. */
576         if (!TS_REQ_set_cert_req(ts_req, cert)) goto err;
577
578         ret = 1;
579  err:
580         if (!ret)
581                 {
582                 TS_REQ_free(ts_req);
583                 ts_req = NULL;
584                 BIO_printf(bio_err, "could not create query\n");
585                 }
586         TS_MSG_IMPRINT_free(msg_imprint);
587         X509_ALGOR_free(algo);
588         OPENSSL_free(data);
589         ASN1_OBJECT_free(policy_obj);
590         ASN1_INTEGER_free(nonce_asn1);
591         return ts_req;
592         }
593
594 static int create_digest(BIO *input, char *digest, const EVP_MD *md,
595                          unsigned char **md_value)
596         {
597         int md_value_len;
598
599         md_value_len = EVP_MD_size(md);
600         if (input)
601                 {
602                 /* Digest must be computed from an input file. */
603                 EVP_MD_CTX md_ctx;
604                 unsigned char buffer[4096];
605                 int length;
606
607                 *md_value = OPENSSL_malloc(md_value_len);
608                 if (*md_value == 0) goto err;
609
610                 EVP_DigestInit(&md_ctx, md);
611                 while ((length = BIO_read(input, buffer, sizeof(buffer))) > 0)
612                         {
613                         EVP_DigestUpdate(&md_ctx, buffer, length);
614                         }
615                 EVP_DigestFinal(&md_ctx, *md_value, NULL);
616                 }
617         else
618                 {
619                 /* Digest bytes are specified with digest. */
620                 long digest_len;
621                 *md_value = string_to_hex(digest, &digest_len);
622                 if (!*md_value || md_value_len != digest_len)
623                         {
624                         OPENSSL_free(*md_value);
625                         *md_value = NULL;
626                         BIO_printf(bio_err, "bad digest, %d bytes "
627                                    "must be specified\n", md_value_len);
628                         goto err;
629                         }
630                 }
631
632         return md_value_len;
633  err:
634         return 0;
635         }
636
637 static ASN1_INTEGER *create_nonce(int bits)
638         {
639         unsigned char buf[20];
640         ASN1_INTEGER *nonce = NULL;
641         int len = (bits - 1) / 8 + 1;
642         int i;
643
644         /* Generating random byte sequence. */
645         if (len > (int)sizeof(buf)) goto err;
646         if (!RAND_bytes(buf, len)) goto err;
647
648         /* Find the first non-zero byte and creating ASN1_INTEGER object. */
649         for (i = 0; i < len && !buf[i]; ++i);
650         if (!(nonce = ASN1_INTEGER_new())) goto err;
651         OPENSSL_free(nonce->data);
652         /* Allocate at least one byte. */
653         nonce->length = len - i;
654         if (!(nonce->data = OPENSSL_malloc(nonce->length + 1))) goto err;
655         memcpy(nonce->data, buf + i, nonce->length);
656
657         return nonce;
658  err:
659         BIO_printf(bio_err, "could not create nonce\n");
660         ASN1_INTEGER_free(nonce);
661         return NULL;
662         }
663 /*
664  * Reply-related method definitions.
665  */
666
667 static int reply_command(CONF *conf, char *section, char *engine, 
668                          char *queryfile, char *passin, char *inkey,
669                          char *signer, char *chain, const char *policy, 
670                          char *in, int token_in,
671                          char *out, int token_out, int text)
672         {
673         int ret = 0;
674         TS_RESP *response = NULL;
675         BIO *in_bio = NULL;
676         BIO *query_bio = NULL;
677         BIO *inkey_bio = NULL;
678         BIO *signer_bio = NULL;
679         BIO *out_bio = NULL;
680
681         /* Build response object either from response or query. */
682         if (in != NULL)
683                 {
684                 if ((in_bio = BIO_new_file(in, "rb")) == NULL) goto end;
685                 if (token_in)
686                         {
687                         /* We have a ContentInfo (PKCS7) object, add
688                            'granted' status info around it. */
689                         response = read_PKCS7(in_bio);
690                         }
691                 else
692                         {
693                         /* We have a ready-made TS_RESP object. */
694                         response = d2i_TS_RESP_bio(in_bio, NULL);
695                         }
696                 }
697         else
698                 {
699                 response = create_response(conf, section, engine, queryfile,
700                                            passin, inkey, signer, chain,
701                                            policy);
702                 if (response)
703                         BIO_printf(bio_err, "Response has been generated.\n");
704                 else
705                         BIO_printf(bio_err, "Response is not generated.\n");
706                 }
707         if (response == NULL) goto end;
708
709         /* Write response either in ASN.1 or text format. */
710         if ((out_bio = BIO_open_with_default(out, "wb", stdout)) == NULL)
711                 goto end;
712         if (text)
713                 {
714                 /* Text output. */
715                 if (token_out)
716                         {
717                         TS_TST_INFO *tst_info = TS_RESP_get_tst_info(response);
718                         if (!TS_TST_INFO_print_bio(out_bio, tst_info)) goto end;
719                         }
720                 else
721                         {
722                         if (!TS_RESP_print_bio(out_bio, response)) goto end;
723                         }
724                 }
725         else
726                 {
727                 /* ASN.1 DER output. */
728                 if (token_out)
729                         {
730                         PKCS7 *token = TS_RESP_get_token(response);
731                         if (!i2d_PKCS7_bio(out_bio, token)) goto end;
732                         }
733                 else
734                         {
735                         if (!i2d_TS_RESP_bio(out_bio, response)) goto end;
736                         }
737                 }
738
739         ret = 1;
740
741  end:
742         ERR_print_errors(bio_err);
743
744         /* Clean up. */
745         BIO_free_all(in_bio);
746         BIO_free_all(query_bio);
747         BIO_free_all(inkey_bio);
748         BIO_free_all(signer_bio);
749         BIO_free_all(out_bio);
750         TS_RESP_free(response);
751
752         return ret;
753         }
754
755 /* Reads a PKCS7 token and adds default 'granted' status info to it. */
756 static TS_RESP *read_PKCS7(BIO *in_bio)
757         {
758         int ret = 0;
759         PKCS7 *token = NULL;
760         TS_TST_INFO *tst_info = NULL;
761         TS_RESP *resp = NULL;
762         TS_STATUS_INFO *si = NULL;
763
764         /* Read PKCS7 object and extract the signed time stamp info. */
765         if (!(token = d2i_PKCS7_bio(in_bio, NULL))) goto end;
766         if (!(tst_info = PKCS7_to_TS_TST_INFO(token))) goto end;
767
768         /* Creating response object. */
769         if (!(resp = TS_RESP_new())) goto end;
770
771         /* Create granted status info. */
772         if (!(si = TS_STATUS_INFO_new())) goto end;
773         if (!(ASN1_INTEGER_set(si->status, TS_STATUS_GRANTED))) goto end;
774         if (!TS_RESP_set_status_info(resp, si)) goto end;
775
776         /* Setting encapsulated token. */
777         TS_RESP_set_tst_info(resp, token, tst_info);
778         token = NULL;           /* Ownership is lost. */
779         tst_info = NULL;        /* Ownership is lost. */
780
781         ret = 1;
782  end:
783         PKCS7_free(token);
784         TS_TST_INFO_free(tst_info);
785         if (!ret)
786                 {
787                 TS_RESP_free(resp);
788                 resp = NULL;
789                 }
790         TS_STATUS_INFO_free(si);
791         return resp;
792         }
793
794 static TS_RESP *create_response(CONF *conf, const char *section, char *engine, 
795                                 char *queryfile, char *passin, char *inkey,
796                                 char *signer, char *chain, const char *policy)
797         {
798         int ret = 0;
799         TS_RESP *response = NULL;
800         BIO *query_bio = NULL;
801         TS_RESP_CTX *resp_ctx = NULL;
802
803         if (!(query_bio = BIO_new_file(queryfile, "rb")))
804                 goto end;
805
806         /* Getting TSA configuration section. */
807         if (!(section = TS_CONF_get_tsa_section(conf, section)))
808                 goto end;
809
810         /* Setting up response generation context. */
811         if (!(resp_ctx = TS_RESP_CTX_new())) goto end;
812
813         /* Setting serial number provider callback. */
814         if (!TS_CONF_set_serial(conf, section, serial_cb, resp_ctx)) goto end;
815
816         /* Setting default OpenSSL engine. */
817         if (!TS_CONF_set_crypto_device(conf, section, engine)) goto end;
818
819         /* Setting TSA signer certificate. */
820         if (!TS_CONF_set_signer_cert(conf, section, signer, resp_ctx)) goto end;
821
822         /* Setting TSA signer certificate chain. */
823         if (!TS_CONF_set_certs(conf, section, chain, resp_ctx)) goto end;
824
825         /* Setting TSA signer private key. */
826         if (!TS_CONF_set_signer_key(conf, section, inkey, passin, resp_ctx))
827                 goto end;
828
829         /* Setting default policy OID. */
830         if (!TS_CONF_set_def_policy(conf, section, policy, resp_ctx)) goto end;
831
832         /* Setting acceptable policy OIDs. */
833         if (!TS_CONF_set_policies(conf, section, resp_ctx)) goto end;
834
835         /* Setting the acceptable one-way hash algorithms. */
836         if (!TS_CONF_set_digests(conf, section, resp_ctx)) goto end;
837
838         /* Setting guaranteed time stamp accuracy. */
839         if (!TS_CONF_set_accuracy(conf, section, resp_ctx)) goto end;
840
841         /* Setting the precision of the time. */
842         if (!TS_CONF_set_clock_precision_digits(conf, section, resp_ctx))
843                 goto end;
844
845         /* Setting the ordering flaf if requested. */
846         if (!TS_CONF_set_ordering(conf, section, resp_ctx)) goto end;
847
848         /* Setting the TSA name required flag if requested. */
849         if (!TS_CONF_set_tsa_name(conf, section, resp_ctx)) goto end;
850
851         /* Setting the ESS cert id chain flag if requested. */
852         if (!TS_CONF_set_ess_cert_id_chain(conf, section, resp_ctx)) goto end;
853
854         /* Creating the response. */
855         if (!(response = TS_RESP_create_response(resp_ctx, query_bio)))
856                 goto end;
857
858         ret = 1;
859  end:
860         if (!ret) 
861                 {
862                 TS_RESP_free(response);
863                 response = NULL;
864                 }
865         TS_RESP_CTX_free(resp_ctx);
866         BIO_free_all(query_bio);
867
868         return response;
869         }
870
871 static ASN1_INTEGER * MS_CALLBACK serial_cb(TS_RESP_CTX *ctx, void *data)
872         {
873         const char *serial_file = (const char *) data;
874         ASN1_INTEGER *serial = next_serial(serial_file);
875
876         if (!serial)
877                 {
878                 TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION,
879                                             "Error during serial number "
880                                             "generation.");
881                 TS_RESP_CTX_add_failure_info(ctx,
882                                              TS_INFO_ADD_INFO_NOT_AVAILABLE);
883                 }
884         else
885                 save_ts_serial(serial_file, serial);
886
887         return serial;
888         }
889
890 static ASN1_INTEGER *next_serial(const char *serialfile)
891         {
892         int ret = 0;
893         BIO *in = NULL;
894         ASN1_INTEGER *serial = NULL;
895         BIGNUM *bn = NULL;
896
897         if (!(serial = ASN1_INTEGER_new())) goto err;
898
899         if (!(in = BIO_new_file(serialfile, "r"))) 
900                 {
901                 ERR_clear_error();
902                 BIO_printf(bio_err, "Warning: could not open file %s for "
903                            "reading, using serial number: 1\n", serialfile);
904                 if (!ASN1_INTEGER_set(serial, 1)) goto err;
905                 }
906         else
907                 {
908                 char buf[1024];
909                 if (!a2i_ASN1_INTEGER(in, serial, buf, sizeof(buf)))
910                         {
911                         BIO_printf(bio_err, "unable to load number from %s\n",
912                                    serialfile);
913                         goto err;
914                         }
915                 if (!(bn = ASN1_INTEGER_to_BN(serial, NULL))) goto err;
916                 ASN1_INTEGER_free(serial);
917                 serial = NULL;
918                 if (!BN_add_word(bn, 1)) goto err;
919                 if (!(serial = BN_to_ASN1_INTEGER(bn, NULL))) goto err;
920                 }
921         ret = 1;
922  err:
923         if (!ret)
924                 {
925                 ASN1_INTEGER_free(serial);
926                 serial = NULL;
927                 }
928         BIO_free_all(in);
929         BN_free(bn);
930         return serial;
931         }
932
933 static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial)
934         {
935         int ret = 0;
936         BIO *out = NULL;
937
938         if (!(out = BIO_new_file(serialfile, "w"))) goto err;
939         if (i2a_ASN1_INTEGER(out, serial) <= 0) goto err;
940         if (BIO_puts(out, "\n") <= 0) goto err;
941         ret = 1;
942  err:
943         if (!ret)
944                 BIO_printf(bio_err, "could not save serial number to %s\n",
945                            serialfile);
946         BIO_free_all(out);
947         return ret;
948         }
949
950 /*
951  * Verify-related method definitions.
952  */
953
954 static int verify_command(char *data, char *digest, char *queryfile,
955                           char *in, int token_in,
956                           char *ca_path, char *ca_file, char *untrusted)
957         {
958         BIO *in_bio = NULL;
959         PKCS7 *token = NULL;
960         TS_RESP *response = NULL;
961         TS_VERIFY_CTX *verify_ctx = NULL;
962         int ret = 0;
963
964         /* Decode the token (PKCS7) or response (TS_RESP) files. */
965         if (!(in_bio = BIO_new_file(in, "rb"))) goto end;
966         if (token_in)
967                 {
968                 if (!(token = d2i_PKCS7_bio(in_bio, NULL))) goto end;
969                 }
970         else
971                 {
972                 if (!(response = d2i_TS_RESP_bio(in_bio, NULL))) goto end;
973                 }
974
975         if (!(verify_ctx = create_verify_ctx(data, digest, queryfile, 
976                                              ca_path, ca_file, untrusted)))
977                 goto end;
978
979         /* Checking the token or response against the request. */
980         ret = token_in ?
981                 TS_RESP_verify_token(verify_ctx, token) :
982                 TS_RESP_verify_response(verify_ctx, response);
983
984  end:
985         printf("Verification: ");
986         if (ret)
987                 printf("OK\n");
988         else
989                 {
990                 printf("FAILED\n");
991                 /* Print errors, if there are any. */
992                 ERR_print_errors(bio_err);
993                 }
994         
995         /* Clean up. */
996         BIO_free_all(in_bio);
997         PKCS7_free(token);
998         TS_RESP_free(response);
999         TS_VERIFY_CTX_free(verify_ctx);
1000         return ret;
1001         }
1002
1003 static TS_VERIFY_CTX *create_verify_ctx(char *data, char *digest, 
1004                                         char *queryfile, 
1005                                         char *ca_path, char *ca_file,
1006                                         char *untrusted)
1007         {
1008         TS_VERIFY_CTX *ctx = NULL;
1009         BIO *input = NULL;
1010         TS_REQ *request = NULL;
1011         int ret = 0;
1012
1013         if (data != NULL || digest != NULL)
1014                 {
1015                 if (!(ctx = TS_VERIFY_CTX_new())) goto err;
1016                 ctx->flags = TS_VFY_VERSION | TS_VFY_SIGNER;
1017                 if (data != NULL)
1018                         {
1019                         ctx->flags |= TS_VFY_DATA;
1020                         if (!(ctx->data = BIO_new_file(data, "rb"))) goto err;
1021                         }
1022                 else if (digest != NULL)
1023                         {
1024                         long imprint_len;
1025                         ctx->flags |= TS_VFY_IMPRINT;
1026                         if (!(ctx->imprint = string_to_hex(digest,
1027                                                            &imprint_len)))
1028                                 {
1029                                 BIO_printf(bio_err, "invalid digest string\n");
1030                                 goto err;
1031                                 }
1032                         ctx->imprint_len = imprint_len;
1033                         }
1034                 
1035                 }
1036         else if (queryfile != NULL)
1037                 {
1038                 /* The request has just to be read, decoded and converted to
1039                    a verify context object. */
1040                 if (!(input = BIO_new_file(queryfile, "rb"))) goto err;
1041                 if (!(request = d2i_TS_REQ_bio(input, NULL))) goto err;
1042                 if (!(ctx = TS_REQ_to_TS_VERIFY_CTX(request, NULL))) goto err;
1043                 }
1044         else
1045                 return NULL;
1046
1047         /* Add the signature verification flag and arguments. */
1048         ctx->flags |= TS_VFY_SIGNATURE;
1049
1050         /* Initialising the X509_STORE object. */
1051         if (!(ctx->store = create_cert_store(ca_path, ca_file))) goto err;
1052
1053         /* Loading untrusted certificates. */
1054         if (untrusted && !(ctx->certs = TS_CONF_load_certs(untrusted))) 
1055                 goto err;
1056
1057         ret = 1;
1058  err:
1059         if (!ret)
1060                 {
1061                 TS_VERIFY_CTX_free(ctx);
1062                 ctx = NULL;
1063                 }
1064         BIO_free_all(input);
1065         TS_REQ_free(request);
1066         return ctx;
1067         }
1068
1069 static X509_STORE *create_cert_store(char *ca_path, char *ca_file)
1070         {
1071         X509_STORE *cert_ctx = NULL;
1072         X509_LOOKUP *lookup = NULL;
1073         int i;
1074
1075         /* Creating the X509_STORE object. */
1076         cert_ctx = X509_STORE_new();
1077
1078         /* Setting the callback for certificate chain verification. */
1079         X509_STORE_set_verify_cb_func(cert_ctx, verify_cb);
1080
1081         /* Adding a trusted certificate directory source. */
1082         if (ca_path)
1083                 {
1084                 lookup = X509_STORE_add_lookup(cert_ctx,
1085                                                X509_LOOKUP_hash_dir());
1086                 if (lookup == NULL)
1087                         {
1088                         BIO_printf(bio_err, "memory allocation failure\n");
1089                         goto err;
1090                         }
1091                 i = X509_LOOKUP_add_dir(lookup, ca_path, X509_FILETYPE_PEM);
1092                 if (!i)
1093                         {
1094                         BIO_printf(bio_err, "Error loading directory %s\n",
1095                                    ca_path);
1096                         goto err;
1097                         }
1098                 }
1099
1100         /* Adding a trusted certificate file source. */
1101         if (ca_file)
1102                 {
1103                 lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
1104                 if (lookup == NULL)
1105                         {
1106                         BIO_printf(bio_err, "memory allocation failure\n");
1107                         goto err;
1108                         }
1109                 i = X509_LOOKUP_load_file(lookup, ca_file, X509_FILETYPE_PEM);
1110                 if (!i)
1111                         {
1112                         BIO_printf(bio_err, "Error loading file %s\n", ca_file);
1113                         goto err;
1114                         }
1115                 }
1116
1117         return cert_ctx;
1118  err:
1119         X509_STORE_free(cert_ctx);
1120         return NULL;
1121         }
1122
1123 static int MS_CALLBACK verify_cb(int ok, X509_STORE_CTX *ctx)
1124         {
1125         /*
1126         char buf[256];
1127
1128         if (!ok)
1129                 {
1130                 X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),
1131                                   buf, sizeof(buf));
1132                 printf("%s\n", buf);
1133                 printf("error %d at %d depth lookup: %s\n",
1134                        ctx->error, ctx->error_depth,
1135                         X509_verify_cert_error_string(ctx->error));
1136                 }
1137         */
1138
1139         return ok;
1140         }