add OSSL_STACK_OF_X509_free() for commonly used pattern
[openssl.git] / crypto / x509 / t_x509.c
1 /*
2  * Copyright 1995-2021 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 "internal/cryptlib.h"
12 #include <openssl/buffer.h>
13 #include <openssl/bn.h>
14 #include <openssl/objects.h>
15 #include <openssl/x509.h>
16 #include <openssl/x509v3.h>
17 #include "crypto/asn1.h"
18 #include "crypto/x509.h"
19
20 void OSSL_STACK_OF_X509_free(STACK_OF(X509) *certs)
21 {
22     sk_X509_pop_free(certs, X509_free);
23 }
24
25 #ifndef OPENSSL_NO_STDIO
26 int X509_print_fp(FILE *fp, X509 *x)
27 {
28     return X509_print_ex_fp(fp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
29 }
30
31 int X509_print_ex_fp(FILE *fp, X509 *x, unsigned long nmflag,
32                      unsigned long cflag)
33 {
34     BIO *b;
35     int ret;
36
37     if ((b = BIO_new(BIO_s_file())) == NULL) {
38         ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
39         return 0;
40     }
41     BIO_set_fp(b, fp, BIO_NOCLOSE);
42     ret = X509_print_ex(b, x, nmflag, cflag);
43     BIO_free(b);
44     return ret;
45 }
46 #endif
47
48 int X509_print(BIO *bp, X509 *x)
49 {
50     return X509_print_ex(bp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
51 }
52
53 int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags,
54                   unsigned long cflag)
55 {
56     long l;
57     int ret = 0, i;
58     char *m = NULL, mlch = ' ';
59     int nmindent = 0, printok = 0;
60     EVP_PKEY *pkey = NULL;
61     const char *neg;
62
63     if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
64         mlch = '\n';
65         nmindent = 12;
66     }
67
68     if (nmflags == X509_FLAG_COMPAT) {
69         nmindent = 16;
70         printok = 1;
71     }
72
73     if (!(cflag & X509_FLAG_NO_HEADER)) {
74         if (BIO_write(bp, "Certificate:\n", 13) <= 0)
75             goto err;
76         if (BIO_write(bp, "    Data:\n", 10) <= 0)
77             goto err;
78     }
79     if (!(cflag & X509_FLAG_NO_VERSION)) {
80         l = X509_get_version(x);
81         if (l >= X509_VERSION_1 && l <= X509_VERSION_3) {
82             if (BIO_printf(bp, "%8sVersion: %ld (0x%lx)\n", "", l + 1, (unsigned long)l) <= 0)
83                 goto err;
84         } else {
85             if (BIO_printf(bp, "%8sVersion: Unknown (%ld)\n", "", l) <= 0)
86                 goto err;
87         }
88     }
89     if (!(cflag & X509_FLAG_NO_SERIAL)) {
90         const ASN1_INTEGER *bs = X509_get0_serialNumber(x);
91
92         if (BIO_write(bp, "        Serial Number:", 22) <= 0)
93             goto err;
94
95         if (bs->length <= (int)sizeof(long)) {
96                 ERR_set_mark();
97                 l = ASN1_INTEGER_get(bs);
98                 ERR_pop_to_mark();
99         } else {
100             l = -1;
101         }
102         if (l != -1) {
103             unsigned long ul;
104             if (bs->type == V_ASN1_NEG_INTEGER) {
105                 ul = 0 - (unsigned long)l;
106                 neg = "-";
107             } else {
108                 ul = l;
109                 neg = "";
110             }
111             if (BIO_printf(bp, " %s%lu (%s0x%lx)\n", neg, ul, neg, ul) <= 0)
112                 goto err;
113         } else {
114             neg = (bs->type == V_ASN1_NEG_INTEGER) ? " (Negative)" : "";
115             if (BIO_printf(bp, "\n%12s%s", "", neg) <= 0)
116                 goto err;
117
118             for (i = 0; i < bs->length; i++) {
119                 if (BIO_printf(bp, "%02x%c", bs->data[i],
120                                ((i + 1 == bs->length) ? '\n' : ':')) <= 0)
121                     goto err;
122             }
123         }
124
125     }
126
127     if (!(cflag & X509_FLAG_NO_SIGNAME)) {
128         const X509_ALGOR *tsig_alg = X509_get0_tbs_sigalg(x);
129
130         if (BIO_puts(bp, "    ") <= 0)
131             goto err;
132         if (X509_signature_print(bp, tsig_alg, NULL) <= 0)
133             goto err;
134     }
135
136     if (!(cflag & X509_FLAG_NO_ISSUER)) {
137         if (BIO_printf(bp, "        Issuer:%c", mlch) <= 0)
138             goto err;
139         if (X509_NAME_print_ex(bp, X509_get_issuer_name(x), nmindent, nmflags)
140             < printok)
141             goto err;
142         if (BIO_write(bp, "\n", 1) <= 0)
143             goto err;
144     }
145     if (!(cflag & X509_FLAG_NO_VALIDITY)) {
146         if (BIO_write(bp, "        Validity\n", 17) <= 0)
147             goto err;
148         if (BIO_write(bp, "            Not Before: ", 24) <= 0)
149             goto err;
150         if (ossl_asn1_time_print_ex(bp, X509_get0_notBefore(x), ASN1_DTFLGS_RFC822) == 0)
151             goto err;
152         if (BIO_write(bp, "\n            Not After : ", 25) <= 0)
153             goto err;
154         if (ossl_asn1_time_print_ex(bp, X509_get0_notAfter(x), ASN1_DTFLGS_RFC822) == 0)
155             goto err;
156         if (BIO_write(bp, "\n", 1) <= 0)
157             goto err;
158     }
159     if (!(cflag & X509_FLAG_NO_SUBJECT)) {
160         if (BIO_printf(bp, "        Subject:%c", mlch) <= 0)
161             goto err;
162         if (X509_NAME_print_ex
163             (bp, X509_get_subject_name(x), nmindent, nmflags) < printok)
164             goto err;
165         if (BIO_write(bp, "\n", 1) <= 0)
166             goto err;
167     }
168     if (!(cflag & X509_FLAG_NO_PUBKEY)) {
169         X509_PUBKEY *xpkey = X509_get_X509_PUBKEY(x);
170         ASN1_OBJECT *xpoid;
171         X509_PUBKEY_get0_param(&xpoid, NULL, NULL, NULL, xpkey);
172         if (BIO_write(bp, "        Subject Public Key Info:\n", 33) <= 0)
173             goto err;
174         if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0)
175             goto err;
176         if (i2a_ASN1_OBJECT(bp, xpoid) <= 0)
177             goto err;
178         if (BIO_puts(bp, "\n") <= 0)
179             goto err;
180
181         pkey = X509_get0_pubkey(x);
182         if (pkey == NULL) {
183             BIO_printf(bp, "%12sUnable to load Public Key\n", "");
184             ERR_print_errors(bp);
185         } else {
186             EVP_PKEY_print_public(bp, pkey, 16, NULL);
187         }
188     }
189
190     if (!(cflag & X509_FLAG_NO_IDS)) {
191         const ASN1_BIT_STRING *iuid, *suid;
192         X509_get0_uids(x, &iuid, &suid);
193         if (iuid != NULL) {
194             if (BIO_printf(bp, "%8sIssuer Unique ID: ", "") <= 0)
195                 goto err;
196             if (!X509_signature_dump(bp, iuid, 12))
197                 goto err;
198         }
199         if (suid != NULL) {
200             if (BIO_printf(bp, "%8sSubject Unique ID: ", "") <= 0)
201                 goto err;
202             if (!X509_signature_dump(bp, suid, 12))
203                 goto err;
204         }
205     }
206
207     if (!(cflag & X509_FLAG_NO_EXTENSIONS)
208         && !X509V3_extensions_print(bp, "X509v3 extensions",
209                                     X509_get0_extensions(x), cflag, 8))
210         goto err;
211
212     if (!(cflag & X509_FLAG_NO_SIGDUMP)) {
213         const X509_ALGOR *sig_alg;
214         const ASN1_BIT_STRING *sig;
215         X509_get0_signature(&sig, &sig_alg, x);
216         if (X509_signature_print(bp, sig_alg, sig) <= 0)
217             goto err;
218     }
219     if (!(cflag & X509_FLAG_NO_AUX)) {
220         if (!X509_aux_print(bp, x, 0))
221             goto err;
222     }
223     ret = 1;
224  err:
225     OPENSSL_free(m);
226     return ret;
227 }
228
229 int X509_ocspid_print(BIO *bp, X509 *x)
230 {
231     unsigned char *der = NULL;
232     unsigned char *dertmp;
233     int derlen;
234     int i;
235     unsigned char SHA1md[SHA_DIGEST_LENGTH];
236     ASN1_BIT_STRING *keybstr;
237     const X509_NAME *subj;
238     EVP_MD *md = NULL;
239
240     if (x == NULL || bp == NULL)
241         return 0;
242     /*
243      * display the hash of the subject as it would appear in OCSP requests
244      */
245     if (BIO_printf(bp, "        Subject OCSP hash: ") <= 0)
246         goto err;
247     subj = X509_get_subject_name(x);
248     derlen = i2d_X509_NAME(subj, NULL);
249     if (derlen <= 0)
250         goto err;
251     if ((der = dertmp = OPENSSL_malloc(derlen)) == NULL)
252         goto err;
253     i2d_X509_NAME(subj, &dertmp);
254
255     md = EVP_MD_fetch(x->libctx, SN_sha1, x->propq);
256     if (md == NULL)
257         goto err;
258     if (!EVP_Digest(der, derlen, SHA1md, NULL, md, NULL))
259         goto err;
260     for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
261         if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0)
262             goto err;
263     }
264     OPENSSL_free(der);
265     der = NULL;
266
267     /*
268      * display the hash of the public key as it would appear in OCSP requests
269      */
270     if (BIO_printf(bp, "\n        Public key OCSP hash: ") <= 0)
271         goto err;
272
273     keybstr = X509_get0_pubkey_bitstr(x);
274
275     if (keybstr == NULL)
276         goto err;
277
278     if (!EVP_Digest(ASN1_STRING_get0_data(keybstr),
279                     ASN1_STRING_length(keybstr), SHA1md, NULL, md, NULL))
280         goto err;
281     for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
282         if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0)
283             goto err;
284     }
285     BIO_printf(bp, "\n");
286     EVP_MD_free(md);
287
288     return 1;
289  err:
290     OPENSSL_free(der);
291     EVP_MD_free(md);
292     return 0;
293 }
294
295 int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent)
296 {
297     const unsigned char *s;
298     int i, n;
299
300     n = sig->length;
301     s = sig->data;
302     for (i = 0; i < n; i++) {
303         if ((i % 18) == 0) {
304             if (i > 0 && BIO_write(bp, "\n", 1) <= 0)
305                 return 0;
306             if (BIO_indent(bp, indent, indent) <= 0)
307                 return 0;
308         }
309         if (BIO_printf(bp, "%02x%s", s[i], ((i + 1) == n) ? "" : ":") <= 0)
310             return 0;
311     }
312     if (BIO_write(bp, "\n", 1) != 1)
313         return 0;
314
315     return 1;
316 }
317
318 int X509_signature_print(BIO *bp, const X509_ALGOR *sigalg,
319                          const ASN1_STRING *sig)
320 {
321     int sig_nid;
322     int indent = 4;
323     if (BIO_printf(bp, "%*sSignature Algorithm: ", indent, "") <= 0)
324         return 0;
325     if (i2a_ASN1_OBJECT(bp, sigalg->algorithm) <= 0)
326         return 0;
327
328     if (sig && BIO_printf(bp, "\n%*sSignature Value:", indent, "") <= 0)
329         return 0;
330     sig_nid = OBJ_obj2nid(sigalg->algorithm);
331     if (sig_nid != NID_undef) {
332         int pkey_nid, dig_nid;
333         const EVP_PKEY_ASN1_METHOD *ameth;
334         if (OBJ_find_sigid_algs(sig_nid, &dig_nid, &pkey_nid)) {
335             ameth = EVP_PKEY_asn1_find(NULL, pkey_nid);
336             if (ameth && ameth->sig_print)
337                 return ameth->sig_print(bp, sigalg, sig, indent + 4, 0);
338         }
339     }
340     if (BIO_write(bp, "\n", 1) != 1)
341         return 0;
342     if (sig)
343         return X509_signature_dump(bp, sig, indent + 4);
344     return 1;
345 }
346
347 int X509_aux_print(BIO *out, X509 *x, int indent)
348 {
349     char oidstr[80], first;
350     STACK_OF(ASN1_OBJECT) *trust, *reject;
351     const unsigned char *alias, *keyid;
352     int keyidlen;
353     int i;
354     if (X509_trusted(x) == 0)
355         return 1;
356     trust = X509_get0_trust_objects(x);
357     reject = X509_get0_reject_objects(x);
358     if (trust) {
359         first = 1;
360         BIO_printf(out, "%*sTrusted Uses:\n%*s", indent, "", indent + 2, "");
361         for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) {
362             if (!first)
363                 BIO_puts(out, ", ");
364             else
365                 first = 0;
366             OBJ_obj2txt(oidstr, sizeof(oidstr),
367                         sk_ASN1_OBJECT_value(trust, i), 0);
368             BIO_puts(out, oidstr);
369         }
370         BIO_puts(out, "\n");
371     } else
372         BIO_printf(out, "%*sNo Trusted Uses.\n", indent, "");
373     if (reject) {
374         first = 1;
375         BIO_printf(out, "%*sRejected Uses:\n%*s", indent, "", indent + 2, "");
376         for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) {
377             if (!first)
378                 BIO_puts(out, ", ");
379             else
380                 first = 0;
381             OBJ_obj2txt(oidstr, sizeof(oidstr),
382                         sk_ASN1_OBJECT_value(reject, i), 0);
383             BIO_puts(out, oidstr);
384         }
385         BIO_puts(out, "\n");
386     } else
387         BIO_printf(out, "%*sNo Rejected Uses.\n", indent, "");
388     alias = X509_alias_get0(x, &i);
389     if (alias)
390         BIO_printf(out, "%*sAlias: %.*s\n", indent, "", i, alias);
391     keyid = X509_keyid_get0(x, &keyidlen);
392     if (keyid) {
393         BIO_printf(out, "%*sKey Id: ", indent, "");
394         for (i = 0; i < keyidlen; i++)
395             BIO_printf(out, "%s%02X", i ? ":" : "", keyid[i]);
396         BIO_write(out, "\n", 1);
397     }
398     return 1;
399 }
400
401 /*
402  * Helper functions for improving certificate verification error diagnostics
403  */
404
405 int ossl_x509_print_ex_brief(BIO *bio, X509 *cert, unsigned long neg_cflags)
406 {
407     unsigned long flags = ASN1_STRFLGS_RFC2253 | ASN1_STRFLGS_ESC_QUOTE |
408         XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_FN_SN;
409
410     if (cert == NULL)
411         return BIO_printf(bio, "    (no certificate)\n") > 0;
412     if (BIO_printf(bio, "    certificate\n") <= 0
413             || !X509_print_ex(bio, cert, flags, ~X509_FLAG_NO_SUBJECT))
414         return 0;
415     if (X509_check_issued((X509 *)cert, cert) == X509_V_OK) {
416         if (BIO_printf(bio, "        self-issued\n") <= 0)
417             return 0;
418     } else {
419         if (BIO_printf(bio, " ") <= 0
420             || !X509_print_ex(bio, cert, flags, ~X509_FLAG_NO_ISSUER))
421             return 0;
422     }
423     if (!X509_print_ex(bio, cert, flags,
424                        ~(X509_FLAG_NO_SERIAL | X509_FLAG_NO_VALIDITY)))
425         return 0;
426     if (X509_cmp_current_time(X509_get0_notBefore(cert)) > 0)
427         if (BIO_printf(bio, "        not yet valid\n") <= 0)
428             return 0;
429     if (X509_cmp_current_time(X509_get0_notAfter(cert)) < 0)
430         if (BIO_printf(bio, "        no more valid\n") <= 0)
431             return 0;
432     return X509_print_ex(bio, cert, flags,
433                          ~neg_cflags & ~X509_FLAG_EXTENSIONS_ONLY_KID);
434 }
435
436 static int print_certs(BIO *bio, const STACK_OF(X509) *certs)
437 {
438     int i;
439
440     if (certs == NULL || sk_X509_num(certs) <= 0)
441         return BIO_printf(bio, "    (no certificates)\n") >= 0;
442
443     for (i = 0; i < sk_X509_num(certs); i++) {
444         X509 *cert = sk_X509_value(certs, i);
445
446         if (cert != NULL) {
447             if (!ossl_x509_print_ex_brief(bio, cert, 0))
448                 return 0;
449             if (!X509V3_extensions_print(bio, NULL,
450                                          X509_get0_extensions(cert),
451                                          X509_FLAG_EXTENSIONS_ONLY_KID, 8))
452                 return 0;
453             }
454     }
455     return 1;
456 }
457
458 static int print_store_certs(BIO *bio, X509_STORE *store)
459 {
460     if (store != NULL) {
461         STACK_OF(X509) *certs = X509_STORE_get1_all_certs(store);
462         int ret = print_certs(bio, certs);
463
464         OSSL_STACK_OF_X509_free(certs);
465         return ret;
466     } else {
467         return BIO_printf(bio, "    (no trusted store)\n") >= 0;
468     }
469 }
470
471 /* Extend the error queue with details on a failed cert verification */
472 int X509_STORE_CTX_print_verify_cb(int ok, X509_STORE_CTX *ctx)
473 {
474     if (ok == 0 && ctx != NULL) {
475         int cert_error = X509_STORE_CTX_get_error(ctx);
476         BIO *bio = BIO_new(BIO_s_mem()); /* may be NULL */
477
478         if (bio == NULL)
479             return 0;
480         BIO_printf(bio, "%s at depth = %d error = %d (%s)\n",
481                    X509_STORE_CTX_get0_parent_ctx(ctx) != NULL
482                    ? "CRL path validation"
483                    : "Certificate verification",
484                    X509_STORE_CTX_get_error_depth(ctx),
485                    cert_error, X509_verify_cert_error_string(cert_error));
486         {
487             X509_STORE *ts = X509_STORE_CTX_get0_store(ctx);
488             X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
489             char *str;
490             int idx = 0;
491
492             switch (cert_error) {
493             case X509_V_ERR_HOSTNAME_MISMATCH:
494                 BIO_printf(bio, "Expected hostname(s) = ");
495                 while ((str = X509_VERIFY_PARAM_get0_host(vpm, idx++)) != NULL)
496                     BIO_printf(bio, "%s%s", idx == 1 ? "" : ", ", str);
497                 BIO_printf(bio, "\n");
498                 break;
499             case X509_V_ERR_EMAIL_MISMATCH:
500                 str = X509_VERIFY_PARAM_get0_email(vpm);
501                 if (str != NULL)
502                     BIO_printf(bio, "Expected email address = %s\n", str);
503                 break;
504             case X509_V_ERR_IP_ADDRESS_MISMATCH:
505                 str = X509_VERIFY_PARAM_get1_ip_asc(vpm);
506                 if (str != NULL)
507                     BIO_printf(bio, "Expected IP address = %s\n", str);
508                 OPENSSL_free(str);
509                 break;
510             default:
511                 break;
512             }
513         }
514
515         BIO_printf(bio, "Failure for:\n");
516         ossl_x509_print_ex_brief(bio, X509_STORE_CTX_get_current_cert(ctx),
517                                  X509_FLAG_NO_EXTENSIONS);
518         if (cert_error == X509_V_ERR_CERT_UNTRUSTED
519                 || cert_error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
520                 || cert_error == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
521                 || cert_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
522                 || cert_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
523                 || cert_error == X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER
524                 || cert_error == X509_V_ERR_STORE_LOOKUP) {
525             BIO_printf(bio, "Non-trusted certs:\n");
526             print_certs(bio, X509_STORE_CTX_get0_untrusted(ctx));
527             BIO_printf(bio, "Certs in trust store:\n");
528             print_store_certs(bio, X509_STORE_CTX_get0_store(ctx));
529         }
530         ERR_raise(ERR_LIB_X509, X509_R_CERTIFICATE_VERIFICATION_FAILED);
531         ERR_add_error_mem_bio("\n", bio);
532         BIO_free(bio);
533     }
534
535     return ok;
536 }