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