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