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