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