Update copyright year
[openssl.git] / crypto / x509 / t_x509.c
1 /*
2  * Copyright 1995-2022 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 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     return ret;
226 }
227
228 int X509_ocspid_print(BIO *bp, X509 *x)
229 {
230     unsigned char *der = NULL;
231     unsigned char *dertmp;
232     int derlen;
233     int i;
234     unsigned char SHA1md[SHA_DIGEST_LENGTH];
235     ASN1_BIT_STRING *keybstr;
236     const X509_NAME *subj;
237     EVP_MD *md = NULL;
238
239     if (x == NULL || bp == NULL)
240         return 0;
241     /*
242      * display the hash of the subject as it would appear in OCSP requests
243      */
244     if (BIO_printf(bp, "        Subject OCSP hash: ") <= 0)
245         goto err;
246     subj = X509_get_subject_name(x);
247     derlen = i2d_X509_NAME(subj, NULL);
248     if (derlen <= 0)
249         goto err;
250     if ((der = dertmp = OPENSSL_malloc(derlen)) == NULL)
251         goto err;
252     i2d_X509_NAME(subj, &dertmp);
253
254     md = EVP_MD_fetch(x->libctx, SN_sha1, x->propq);
255     if (md == NULL)
256         goto err;
257     if (!EVP_Digest(der, derlen, SHA1md, NULL, md, NULL))
258         goto err;
259     for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
260         if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0)
261             goto err;
262     }
263     OPENSSL_free(der);
264     der = NULL;
265
266     /*
267      * display the hash of the public key as it would appear in OCSP requests
268      */
269     if (BIO_printf(bp, "\n        Public key OCSP hash: ") <= 0)
270         goto err;
271
272     keybstr = X509_get0_pubkey_bitstr(x);
273
274     if (keybstr == NULL)
275         goto err;
276
277     if (!EVP_Digest(ASN1_STRING_get0_data(keybstr),
278                     ASN1_STRING_length(keybstr), SHA1md, NULL, md, NULL))
279         goto err;
280     for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
281         if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0)
282             goto err;
283     }
284     BIO_printf(bp, "\n");
285     EVP_MD_free(md);
286
287     return 1;
288  err:
289     OPENSSL_free(der);
290     EVP_MD_free(md);
291     return 0;
292 }
293
294 int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent)
295 {
296     const unsigned char *s;
297     int i, n;
298
299     n = sig->length;
300     s = sig->data;
301     for (i = 0; i < n; i++) {
302         if ((i % 18) == 0) {
303             if (i > 0 && BIO_write(bp, "\n", 1) <= 0)
304                 return 0;
305             if (BIO_indent(bp, indent, indent) <= 0)
306                 return 0;
307         }
308         if (BIO_printf(bp, "%02x%s", s[i], ((i + 1) == n) ? "" : ":") <= 0)
309             return 0;
310     }
311     if (BIO_write(bp, "\n", 1) != 1)
312         return 0;
313
314     return 1;
315 }
316
317 int X509_signature_print(BIO *bp, const X509_ALGOR *sigalg,
318                          const ASN1_STRING *sig)
319 {
320     int sig_nid;
321     int indent = 4;
322     if (BIO_printf(bp, "%*sSignature Algorithm: ", indent, "") <= 0)
323         return 0;
324     if (i2a_ASN1_OBJECT(bp, sigalg->algorithm) <= 0)
325         return 0;
326
327     if (sig && BIO_printf(bp, "\n%*sSignature Value:", indent, "") <= 0)
328         return 0;
329     sig_nid = OBJ_obj2nid(sigalg->algorithm);
330     if (sig_nid != NID_undef) {
331         int pkey_nid, dig_nid;
332         const EVP_PKEY_ASN1_METHOD *ameth;
333         if (OBJ_find_sigid_algs(sig_nid, &dig_nid, &pkey_nid)) {
334             ameth = EVP_PKEY_asn1_find(NULL, pkey_nid);
335             if (ameth && ameth->sig_print)
336                 return ameth->sig_print(bp, sigalg, sig, indent + 4, 0);
337         }
338     }
339     if (BIO_write(bp, "\n", 1) != 1)
340         return 0;
341     if (sig)
342         return X509_signature_dump(bp, sig, indent + 4);
343     return 1;
344 }
345
346 int X509_aux_print(BIO *out, X509 *x, int indent)
347 {
348     char oidstr[80], first;
349     STACK_OF(ASN1_OBJECT) *trust, *reject;
350     const unsigned char *alias, *keyid;
351     int keyidlen;
352     int i;
353     if (X509_trusted(x) == 0)
354         return 1;
355     trust = X509_get0_trust_objects(x);
356     reject = X509_get0_reject_objects(x);
357     if (trust) {
358         first = 1;
359         BIO_printf(out, "%*sTrusted Uses:\n%*s", indent, "", indent + 2, "");
360         for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) {
361             if (!first)
362                 BIO_puts(out, ", ");
363             else
364                 first = 0;
365             OBJ_obj2txt(oidstr, sizeof(oidstr),
366                         sk_ASN1_OBJECT_value(trust, i), 0);
367             BIO_puts(out, oidstr);
368         }
369         BIO_puts(out, "\n");
370     } else
371         BIO_printf(out, "%*sNo Trusted Uses.\n", indent, "");
372     if (reject) {
373         first = 1;
374         BIO_printf(out, "%*sRejected Uses:\n%*s", indent, "", indent + 2, "");
375         for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) {
376             if (!first)
377                 BIO_puts(out, ", ");
378             else
379                 first = 0;
380             OBJ_obj2txt(oidstr, sizeof(oidstr),
381                         sk_ASN1_OBJECT_value(reject, i), 0);
382             BIO_puts(out, oidstr);
383         }
384         BIO_puts(out, "\n");
385     } else
386         BIO_printf(out, "%*sNo Rejected Uses.\n", indent, "");
387     alias = X509_alias_get0(x, &i);
388     if (alias)
389         BIO_printf(out, "%*sAlias: %.*s\n", indent, "", i, alias);
390     keyid = X509_keyid_get0(x, &keyidlen);
391     if (keyid) {
392         BIO_printf(out, "%*sKey Id: ", indent, "");
393         for (i = 0; i < keyidlen; i++)
394             BIO_printf(out, "%s%02X", i ? ":" : "", keyid[i]);
395         BIO_write(out, "\n", 1);
396     }
397     return 1;
398 }
399
400 /*
401  * Helper functions for improving certificate verification error diagnostics
402  */
403
404 int ossl_x509_print_ex_brief(BIO *bio, X509 *cert, unsigned long neg_cflags)
405 {
406     unsigned long flags = ASN1_STRFLGS_RFC2253 | ASN1_STRFLGS_ESC_QUOTE |
407         XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_FN_SN;
408
409     if (cert == NULL)
410         return BIO_printf(bio, "    (no certificate)\n") > 0;
411     if (BIO_printf(bio, "    certificate\n") <= 0
412             || !X509_print_ex(bio, cert, flags, ~X509_FLAG_NO_SUBJECT))
413         return 0;
414     if (X509_check_issued((X509 *)cert, cert) == X509_V_OK) {
415         if (BIO_printf(bio, "        self-issued\n") <= 0)
416             return 0;
417     } else {
418         if (BIO_printf(bio, " ") <= 0
419             || !X509_print_ex(bio, cert, flags, ~X509_FLAG_NO_ISSUER))
420             return 0;
421     }
422     if (!X509_print_ex(bio, cert, flags,
423                        ~(X509_FLAG_NO_SERIAL | X509_FLAG_NO_VALIDITY)))
424         return 0;
425     if (X509_cmp_current_time(X509_get0_notBefore(cert)) > 0)
426         if (BIO_printf(bio, "        not yet valid\n") <= 0)
427             return 0;
428     if (X509_cmp_current_time(X509_get0_notAfter(cert)) < 0)
429         if (BIO_printf(bio, "        no more valid\n") <= 0)
430             return 0;
431     return X509_print_ex(bio, cert, flags,
432                          ~neg_cflags & ~X509_FLAG_EXTENSIONS_ONLY_KID);
433 }
434
435 static int print_certs(BIO *bio, const STACK_OF(X509) *certs)
436 {
437     int i;
438
439     if (certs == NULL || sk_X509_num(certs) <= 0)
440         return BIO_printf(bio, "    (no certificates)\n") >= 0;
441
442     for (i = 0; i < sk_X509_num(certs); i++) {
443         X509 *cert = sk_X509_value(certs, i);
444
445         if (cert != NULL) {
446             if (!ossl_x509_print_ex_brief(bio, cert, 0))
447                 return 0;
448             if (!X509V3_extensions_print(bio, NULL,
449                                          X509_get0_extensions(cert),
450                                          X509_FLAG_EXTENSIONS_ONLY_KID, 8))
451                 return 0;
452             }
453     }
454     return 1;
455 }
456
457 static int print_store_certs(BIO *bio, X509_STORE *store)
458 {
459     if (store != NULL) {
460         STACK_OF(X509) *certs = X509_STORE_get1_all_certs(store);
461         int ret = print_certs(bio, certs);
462
463         OSSL_STACK_OF_X509_free(certs);
464         return ret;
465     } else {
466         return BIO_printf(bio, "    (no trusted store)\n") >= 0;
467     }
468 }
469
470 /* Extend the error queue with details on a failed cert verification */
471 int X509_STORE_CTX_print_verify_cb(int ok, X509_STORE_CTX *ctx)
472 {
473     if (ok == 0 && ctx != NULL) {
474         int cert_error = X509_STORE_CTX_get_error(ctx);
475         BIO *bio = BIO_new(BIO_s_mem()); /* may be NULL */
476
477         if (bio == NULL)
478             return 0;
479         BIO_printf(bio, "%s at depth = %d error = %d (%s)\n",
480                    X509_STORE_CTX_get0_parent_ctx(ctx) != NULL
481                    ? "CRL path validation"
482                    : "Certificate verification",
483                    X509_STORE_CTX_get_error_depth(ctx),
484                    cert_error, X509_verify_cert_error_string(cert_error));
485         {
486             X509_STORE *ts = X509_STORE_CTX_get0_store(ctx);
487             X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
488             char *str;
489             int idx = 0;
490
491             switch (cert_error) {
492             case X509_V_ERR_HOSTNAME_MISMATCH:
493                 BIO_printf(bio, "Expected hostname(s) = ");
494                 while ((str = X509_VERIFY_PARAM_get0_host(vpm, idx++)) != NULL)
495                     BIO_printf(bio, "%s%s", idx == 1 ? "" : ", ", str);
496                 BIO_printf(bio, "\n");
497                 break;
498             case X509_V_ERR_EMAIL_MISMATCH:
499                 str = X509_VERIFY_PARAM_get0_email(vpm);
500                 if (str != NULL)
501                     BIO_printf(bio, "Expected email address = %s\n", str);
502                 break;
503             case X509_V_ERR_IP_ADDRESS_MISMATCH:
504                 str = X509_VERIFY_PARAM_get1_ip_asc(vpm);
505                 if (str != NULL)
506                     BIO_printf(bio, "Expected IP address = %s\n", str);
507                 OPENSSL_free(str);
508                 break;
509             default:
510                 break;
511             }
512         }
513
514         BIO_printf(bio, "Failure for:\n");
515         ossl_x509_print_ex_brief(bio, X509_STORE_CTX_get_current_cert(ctx),
516                                  X509_FLAG_NO_EXTENSIONS);
517         if (cert_error == X509_V_ERR_CERT_UNTRUSTED
518                 || cert_error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
519                 || cert_error == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
520                 || cert_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
521                 || cert_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
522                 || cert_error == X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER
523                 || cert_error == X509_V_ERR_STORE_LOOKUP) {
524             BIO_printf(bio, "Non-trusted certs:\n");
525             print_certs(bio, X509_STORE_CTX_get0_untrusted(ctx));
526             BIO_printf(bio, "Certs in trust store:\n");
527             print_store_certs(bio, X509_STORE_CTX_get0_store(ctx));
528         }
529         ERR_raise(ERR_LIB_X509, X509_R_CERTIFICATE_VERIFICATION_FAILED);
530         ERR_add_error_mem_bio("\n", bio);
531         BIO_free(bio);
532     }
533
534     return ok;
535 }