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