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