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