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