xref: /openssl/crypto/x509/t_x509.c (revision c90451d8)
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 
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     i2d_X509_NAME(subj, &dertmp);
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 |
377         XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_FN_SN;
378 
379     if (cert == NULL)
380         return BIO_printf(bio, "    (no certificate)\n") > 0;
381     if (BIO_printf(bio, "    certificate\n") <= 0
382             || !X509_print_ex(bio, cert, flags, ~X509_FLAG_NO_SUBJECT))
383         return 0;
384     if (X509_check_issued((X509 *)cert, cert) == X509_V_OK) {
385         if (BIO_printf(bio, "        self-issued\n") <= 0)
386             return 0;
387     } else {
388         if (BIO_printf(bio, " ") <= 0
389             || !X509_print_ex(bio, cert, flags, ~X509_FLAG_NO_ISSUER))
390             return 0;
391     }
392     if (!X509_print_ex(bio, cert, flags,
393                        ~(X509_FLAG_NO_SERIAL | X509_FLAG_NO_VALIDITY)))
394         return 0;
395     if (X509_cmp_current_time(X509_get0_notBefore(cert)) > 0)
396         if (BIO_printf(bio, "        not yet valid\n") <= 0)
397             return 0;
398     if (X509_cmp_current_time(X509_get0_notAfter(cert)) < 0)
399         if (BIO_printf(bio, "        no more valid\n") <= 0)
400             return 0;
401     return X509_print_ex(bio, cert, flags,
402                          ~neg_cflags & ~X509_FLAG_EXTENSIONS_ONLY_KID);
403 }
404 
print_certs(BIO * bio,const STACK_OF (X509)* certs)405 static int print_certs(BIO *bio, const STACK_OF(X509) *certs)
406 {
407     int i;
408 
409     if (certs == NULL || sk_X509_num(certs) <= 0)
410         return BIO_printf(bio, "    (no certificates)\n") >= 0;
411 
412     for (i = 0; i < sk_X509_num(certs); i++) {
413         X509 *cert = sk_X509_value(certs, i);
414 
415         if (cert != NULL) {
416             if (!ossl_x509_print_ex_brief(bio, cert, 0))
417                 return 0;
418             if (!X509V3_extensions_print(bio, NULL,
419                                          X509_get0_extensions(cert),
420                                          X509_FLAG_EXTENSIONS_ONLY_KID, 8))
421                 return 0;
422             }
423     }
424     return 1;
425 }
426 
print_store_certs(BIO * bio,X509_STORE * store)427 static int print_store_certs(BIO *bio, X509_STORE *store)
428 {
429     if (store != NULL) {
430         STACK_OF(X509) *certs = X509_STORE_get1_all_certs(store);
431         int ret = print_certs(bio, certs);
432 
433         OSSL_STACK_OF_X509_free(certs);
434         return ret;
435     } else {
436         return BIO_printf(bio, "    (no trusted store)\n") >= 0;
437     }
438 }
439 
440 /* Extend the error queue with details on a failed cert verification */
X509_STORE_CTX_print_verify_cb(int ok,X509_STORE_CTX * ctx)441 int X509_STORE_CTX_print_verify_cb(int ok, X509_STORE_CTX *ctx)
442 {
443     if (ok == 0 && ctx != NULL) {
444         int cert_error = X509_STORE_CTX_get_error(ctx);
445         BIO *bio = BIO_new(BIO_s_mem()); /* may be NULL */
446 
447         if (bio == NULL)
448             return 0;
449         BIO_printf(bio, "%s at depth = %d error = %d (%s)\n",
450                    X509_STORE_CTX_get0_parent_ctx(ctx) != NULL
451                    ? "CRL path validation"
452                    : "Certificate verification",
453                    X509_STORE_CTX_get_error_depth(ctx),
454                    cert_error, X509_verify_cert_error_string(cert_error));
455         {
456             X509_STORE *ts = X509_STORE_CTX_get0_store(ctx);
457             X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
458             char *str;
459             int idx = 0;
460 
461             switch (cert_error) {
462             case X509_V_ERR_HOSTNAME_MISMATCH:
463                 BIO_printf(bio, "Expected hostname(s) = ");
464                 while ((str = X509_VERIFY_PARAM_get0_host(vpm, idx++)) != NULL)
465                     BIO_printf(bio, "%s%s", idx == 1 ? "" : ", ", str);
466                 BIO_printf(bio, "\n");
467                 break;
468             case X509_V_ERR_EMAIL_MISMATCH:
469                 str = X509_VERIFY_PARAM_get0_email(vpm);
470                 if (str != NULL)
471                     BIO_printf(bio, "Expected email address = %s\n", str);
472                 break;
473             case X509_V_ERR_IP_ADDRESS_MISMATCH:
474                 str = X509_VERIFY_PARAM_get1_ip_asc(vpm);
475                 if (str != NULL)
476                     BIO_printf(bio, "Expected IP address = %s\n", str);
477                 OPENSSL_free(str);
478                 break;
479             default:
480                 break;
481             }
482         }
483 
484         BIO_printf(bio, "Failure for:\n");
485         ossl_x509_print_ex_brief(bio, X509_STORE_CTX_get_current_cert(ctx),
486                                  X509_FLAG_NO_EXTENSIONS);
487         if (cert_error == X509_V_ERR_CERT_UNTRUSTED
488                 || cert_error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
489                 || cert_error == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
490                 || cert_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
491                 || cert_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
492                 || cert_error == X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER
493                 || cert_error == X509_V_ERR_STORE_LOOKUP) {
494             BIO_printf(bio, "Non-trusted certs:\n");
495             print_certs(bio, X509_STORE_CTX_get0_untrusted(ctx));
496             BIO_printf(bio, "Certs in trust store:\n");
497             print_store_certs(bio, X509_STORE_CTX_get0_store(ctx));
498         }
499         ERR_raise(ERR_LIB_X509, X509_R_CERTIFICATE_VERIFICATION_FAILED);
500         ERR_add_error_mem_bio("\n", bio);
501         BIO_free(bio);
502     }
503 
504     return ok;
505 }
506 
507 /*
508  * Prints serial numbers in decimal and hexadecimal. The indent argument is only
509  * used if the serial number is too large to fit in a long int.
510  */
ossl_serial_number_print(BIO * out,const ASN1_INTEGER * bs,int indent)511 int ossl_serial_number_print(BIO *out, const ASN1_INTEGER *bs, int indent)
512 {
513     int i;
514     long l;
515     unsigned long ul;
516     const char *neg;
517 
518     if (bs->length <= (int)sizeof(long)) {
519         ERR_set_mark();
520         l = ASN1_INTEGER_get(bs);
521         ERR_pop_to_mark();
522     } else {
523         l = -1;
524     }
525     if (l != -1) { /* Reading a long int succeeded: print decimal and hex. */
526         if (bs->type == V_ASN1_NEG_INTEGER) {
527             ul = 0 - (unsigned long)l;
528             neg = "-";
529         } else {
530             ul = l;
531             neg = "";
532         }
533         if (BIO_printf(out, " %s%lu (%s0x%lx)", neg, ul, neg, ul) <= 0)
534             return -1;
535     } else { /* Reading a long int failed: just print hex. */
536         neg = (bs->type == V_ASN1_NEG_INTEGER) ? " (Negative)" : "";
537         if (BIO_printf(out, "\n%*s%s", indent, "", neg) <= 0)
538             return -1;
539 
540         for (i = 0; i < bs->length - 1; i++) {
541             if (BIO_printf(out, "%02x%c", bs->data[i], ':') <= 0)
542                 return -1;
543         }
544         if (BIO_printf(out, "%02x", bs->data[i]) <= 0)
545             return -1;
546     }
547     return 0;
548 }
549