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