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