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