Support SM2 certificate verification
[openssl.git] / apps / verify.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include "apps.h"
14 #include "progs.h"
15 #include <openssl/bio.h>
16 #include <openssl/err.h>
17 #include <openssl/x509.h>
18 #include <openssl/x509v3.h>
19 #include <openssl/pem.h>
20
21 static int cb(int ok, X509_STORE_CTX *ctx);
22 static int check(X509_STORE *ctx, const char *file,
23                  STACK_OF(X509) *uchain, STACK_OF(X509) *tchain,
24                  STACK_OF(X509_CRL) *crls, int show_chain,
25                  unsigned char *sm2id, size_t sm2idlen);
26 static int v_verbose = 0, vflags = 0;
27
28 typedef enum OPTION_choice {
29     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
30     OPT_ENGINE, OPT_CAPATH, OPT_CAFILE, OPT_NOCAPATH, OPT_NOCAFILE,
31     OPT_UNTRUSTED, OPT_TRUSTED, OPT_CRLFILE, OPT_CRL_DOWNLOAD, OPT_SHOW_CHAIN,
32     OPT_V_ENUM, OPT_NAMEOPT,
33     OPT_VERBOSE, OPT_SM2ID, OPT_SM2HEXID
34 } OPTION_CHOICE;
35
36 const OPTIONS verify_options[] = {
37     {OPT_HELP_STR, 1, '-', "Usage: %s [options] cert.pem...\n"},
38     {OPT_HELP_STR, 1, '-', "Valid options are:\n"},
39     {"help", OPT_HELP, '-', "Display this summary"},
40     {"verbose", OPT_VERBOSE, '-',
41         "Print extra information about the operations being performed."},
42     {"CApath", OPT_CAPATH, '/', "A directory of trusted certificates"},
43     {"CAfile", OPT_CAFILE, '<', "A file of trusted certificates"},
44     {"no-CAfile", OPT_NOCAFILE, '-',
45      "Do not load the default certificates file"},
46     {"no-CApath", OPT_NOCAPATH, '-',
47      "Do not load certificates from the default certificates directory"},
48     {"untrusted", OPT_UNTRUSTED, '<', "A file of untrusted certificates"},
49     {"trusted", OPT_TRUSTED, '<', "A file of trusted certificates"},
50     {"CRLfile", OPT_CRLFILE, '<',
51         "File containing one or more CRL's (in PEM format) to load"},
52     {"crl_download", OPT_CRL_DOWNLOAD, '-',
53         "Attempt to download CRL information for this certificate"},
54     {"show_chain", OPT_SHOW_CHAIN, '-',
55         "Display information about the certificate chain"},
56     {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
57     OPT_V_OPTIONS,
58 #ifndef OPENSSL_NO_ENGINE
59     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
60 #endif
61 #ifndef OPENSSL_NO_SM2
62     {"sm2-id", OPT_SM2ID, 's',
63      "Specify an ID string to verify an SM2 certificate"},
64     {"sm2-hex-id", OPT_SM2HEXID, 's',
65      "Specify a hex ID string to verify an SM2 certificate"},
66 #endif
67     {NULL}
68 };
69
70 int verify_main(int argc, char **argv)
71 {
72     ENGINE *e = NULL;
73     STACK_OF(X509) *untrusted = NULL, *trusted = NULL;
74     STACK_OF(X509_CRL) *crls = NULL;
75     X509_STORE *store = NULL;
76     X509_VERIFY_PARAM *vpm = NULL;
77     const char *prog, *CApath = NULL, *CAfile = NULL;
78     int noCApath = 0, noCAfile = 0;
79     int vpmtouched = 0, crl_download = 0, show_chain = 0, i = 0, ret = 1;
80     OPTION_CHOICE o;
81     unsigned char *sm2_id = NULL;
82     size_t sm2_idlen = 0;
83
84     if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
85         goto end;
86
87     prog = opt_init(argc, argv, verify_options);
88     while ((o = opt_next()) != OPT_EOF) {
89         switch (o) {
90         case OPT_EOF:
91         case OPT_ERR:
92             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
93             goto end;
94         case OPT_HELP:
95             opt_help(verify_options);
96             BIO_printf(bio_err, "Recognized usages:\n");
97             for (i = 0; i < X509_PURPOSE_get_count(); i++) {
98                 X509_PURPOSE *ptmp;
99                 ptmp = X509_PURPOSE_get0(i);
100                 BIO_printf(bio_err, "\t%-10s\t%s\n",
101                         X509_PURPOSE_get0_sname(ptmp),
102                         X509_PURPOSE_get0_name(ptmp));
103             }
104
105             BIO_printf(bio_err, "Recognized verify names:\n");
106             for (i = 0; i < X509_VERIFY_PARAM_get_count(); i++) {
107                 const X509_VERIFY_PARAM *vptmp;
108                 vptmp = X509_VERIFY_PARAM_get0(i);
109                 BIO_printf(bio_err, "\t%-10s\n",
110                         X509_VERIFY_PARAM_get0_name(vptmp));
111             }
112             ret = 0;
113             goto end;
114         case OPT_V_CASES:
115             if (!opt_verify(o, vpm))
116                 goto end;
117             vpmtouched++;
118             break;
119         case OPT_CAPATH:
120             CApath = opt_arg();
121             break;
122         case OPT_CAFILE:
123             CAfile = opt_arg();
124             break;
125         case OPT_NOCAPATH:
126             noCApath = 1;
127             break;
128         case OPT_NOCAFILE:
129             noCAfile = 1;
130             break;
131         case OPT_UNTRUSTED:
132             /* Zero or more times */
133             if (!load_certs(opt_arg(), &untrusted, FORMAT_PEM, NULL,
134                             "untrusted certificates"))
135                 goto end;
136             break;
137         case OPT_TRUSTED:
138             /* Zero or more times */
139             noCAfile = 1;
140             noCApath = 1;
141             if (!load_certs(opt_arg(), &trusted, FORMAT_PEM, NULL,
142                             "trusted certificates"))
143                 goto end;
144             break;
145         case OPT_CRLFILE:
146             /* Zero or more times */
147             if (!load_crls(opt_arg(), &crls, FORMAT_PEM, NULL,
148                            "other CRLs"))
149                 goto end;
150             break;
151         case OPT_CRL_DOWNLOAD:
152             crl_download = 1;
153             break;
154         case OPT_ENGINE:
155             if ((e = setup_engine(opt_arg(), 0)) == NULL) {
156                 /* Failure message already displayed */
157                 goto end;
158             }
159             break;
160         case OPT_SHOW_CHAIN:
161             show_chain = 1;
162             break;
163         case OPT_NAMEOPT:
164             if (!set_nameopt(opt_arg()))
165                 goto end;
166             break;
167         case OPT_VERBOSE:
168             v_verbose = 1;
169             break;
170         case OPT_SM2ID:
171             /* we assume the input is not a hex string */
172             sm2_id = (unsigned char *)opt_arg();
173             sm2_idlen = strlen((const char *)sm2_id);
174             break;
175         case OPT_SM2HEXID:
176             /* try to parse the input as hex string first */
177             sm2_id = OPENSSL_hexstr2buf(opt_arg(), (long *)&sm2_idlen);
178             if (sm2_id == NULL) {
179                 BIO_printf(bio_err, "Invalid hex string input\n");
180                 goto end;
181             }
182             break;
183         }
184     }
185     argc = opt_num_rest();
186     argv = opt_rest();
187     if (trusted != NULL && (CAfile || CApath)) {
188         BIO_printf(bio_err,
189                    "%s: Cannot use -trusted with -CAfile or -CApath\n",
190                    prog);
191         goto end;
192     }
193
194     if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath)) == NULL)
195         goto end;
196     X509_STORE_set_verify_cb(store, cb);
197
198     if (vpmtouched)
199         X509_STORE_set1_param(store, vpm);
200
201     ERR_clear_error();
202
203     if (crl_download)
204         store_setup_crl_download(store);
205
206     ret = 0;
207     if (argc < 1) {
208         if (check(store, NULL, untrusted, trusted, crls, show_chain,
209                   sm2_id, sm2_idlen) != 1)
210             ret = -1;
211     } else {
212         for (i = 0; i < argc; i++)
213             if (check(store, argv[i], untrusted, trusted, crls,
214                       show_chain, sm2_id, sm2_idlen) != 1)
215                 ret = -1;
216     }
217
218  end:
219     X509_VERIFY_PARAM_free(vpm);
220     X509_STORE_free(store);
221     sk_X509_pop_free(untrusted, X509_free);
222     sk_X509_pop_free(trusted, X509_free);
223     sk_X509_CRL_pop_free(crls, X509_CRL_free);
224     release_engine(e);
225     return (ret < 0 ? 2 : ret);
226 }
227
228 static int check(X509_STORE *ctx, const char *file,
229                  STACK_OF(X509) *uchain, STACK_OF(X509) *tchain,
230                  STACK_OF(X509_CRL) *crls, int show_chain,
231                  unsigned char *sm2id, size_t sm2idlen)
232 {
233     X509 *x = NULL;
234     int i = 0, ret = 0;
235     X509_STORE_CTX *csc;
236     STACK_OF(X509) *chain = NULL;
237     int num_untrusted;
238
239     x = load_cert(file, FORMAT_PEM, "certificate file");
240     if (x == NULL)
241         goto end;
242
243     if (sm2id != NULL) {
244 #ifndef OPENSSL_NO_SM2
245         ASN1_OCTET_STRING v;
246
247         v.data = sm2id;
248         v.length = sm2idlen;
249
250         X509_set_sm2_id(x, &v);
251 #endif
252     }
253
254     csc = X509_STORE_CTX_new();
255     if (csc == NULL) {
256         printf("error %s: X.509 store context allocation failed\n",
257                (file == NULL) ? "stdin" : file);
258         goto end;
259     }
260
261     X509_STORE_set_flags(ctx, vflags);
262     if (!X509_STORE_CTX_init(csc, ctx, x, uchain)) {
263         X509_STORE_CTX_free(csc);
264         printf("error %s: X.509 store context initialization failed\n",
265                (file == NULL) ? "stdin" : file);
266         goto end;
267     }
268     if (tchain != NULL)
269         X509_STORE_CTX_set0_trusted_stack(csc, tchain);
270     if (crls != NULL)
271         X509_STORE_CTX_set0_crls(csc, crls);
272     i = X509_verify_cert(csc);
273     if (i > 0 && X509_STORE_CTX_get_error(csc) == X509_V_OK) {
274         printf("%s: OK\n", (file == NULL) ? "stdin" : file);
275         ret = 1;
276         if (show_chain) {
277             int j;
278
279             chain = X509_STORE_CTX_get1_chain(csc);
280             num_untrusted = X509_STORE_CTX_get_num_untrusted(csc);
281             printf("Chain:\n");
282             for (j = 0; j < sk_X509_num(chain); j++) {
283                 X509 *cert = sk_X509_value(chain, j);
284                 printf("depth=%d: ", j);
285                 X509_NAME_print_ex_fp(stdout,
286                                       X509_get_subject_name(cert),
287                                       0, get_nameopt());
288                 if (j < num_untrusted)
289                     printf(" (untrusted)");
290                 printf("\n");
291             }
292             sk_X509_pop_free(chain, X509_free);
293         }
294     } else {
295         printf("error %s: verification failed\n", (file == NULL) ? "stdin" : file);
296     }
297     X509_STORE_CTX_free(csc);
298
299  end:
300     if (i <= 0)
301         ERR_print_errors(bio_err);
302     X509_free(x);
303
304     return ret;
305 }
306
307 static int cb(int ok, X509_STORE_CTX *ctx)
308 {
309     int cert_error = X509_STORE_CTX_get_error(ctx);
310     X509 *current_cert = X509_STORE_CTX_get_current_cert(ctx);
311
312     if (!ok) {
313         if (current_cert != NULL) {
314             X509_NAME_print_ex(bio_err,
315                             X509_get_subject_name(current_cert),
316                             0, get_nameopt());
317             BIO_printf(bio_err, "\n");
318         }
319         BIO_printf(bio_err, "%serror %d at %d depth lookup: %s\n",
320                X509_STORE_CTX_get0_parent_ctx(ctx) ? "[CRL path] " : "",
321                cert_error,
322                X509_STORE_CTX_get_error_depth(ctx),
323                X509_verify_cert_error_string(cert_error));
324
325         /*
326          * Pretend that some errors are ok, so they don't stop further
327          * processing of the certificate chain.  Setting ok = 1 does this.
328          * After X509_verify_cert() is done, we verify that there were
329          * no actual errors, even if the returned value was positive.
330          */
331         switch (cert_error) {
332         case X509_V_ERR_NO_EXPLICIT_POLICY:
333             policies_print(ctx);
334             /* fall thru */
335         case X509_V_ERR_CERT_HAS_EXPIRED:
336             /* Continue even if the leaf is a self signed cert */
337         case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
338             /* Continue after extension errors too */
339         case X509_V_ERR_INVALID_CA:
340         case X509_V_ERR_INVALID_NON_CA:
341         case X509_V_ERR_PATH_LENGTH_EXCEEDED:
342         case X509_V_ERR_INVALID_PURPOSE:
343         case X509_V_ERR_CRL_HAS_EXPIRED:
344         case X509_V_ERR_CRL_NOT_YET_VALID:
345         case X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION:
346             ok = 1;
347         }
348
349         return ok;
350
351     }
352     if (cert_error == X509_V_OK && ok == 2)
353         policies_print(ctx);
354     if (!v_verbose)
355         ERR_clear_error();
356     return ok;
357 }