7

I'm trying to find a function similar to Python's ssl.get_server_certificate(), which takes a hostname-port pair and returns a PEM-encoded certificate, but I haven't had any luck.

I've done a fair bit of digging around, but the closest question I've found (Get remote ssl certificate in golang) did not help, nor did reading through the documentation for the package crypto/tls. I'm new to Go, so I may have not understood something in the documentation

2 Answers 2

11
import (
    "bytes"
    "crypto/tls"
    "encoding/pem"
)

func GetCertificatesPEM(address string) (string, error) {
    conn, err := tls.Dial("tcp", address, &tls.Config{
        InsecureSkipVerify: true,
    })
    if err != nil {
        return "", err
    }
    defer conn.Close()
    var b bytes.Buffer
    for _, cert := range conn.ConnectionState().PeerCertificates {
        err := pem.Encode(&b, &pem.Block{
            Type: "CERTIFICATE",
            Bytes: cert.Raw,
        })
        if err != nil {
            return "", err
        }
    }
    return b.String(), nil
}

Usage:

certs, err := GetCertificatesPEM("example.com:443")
Sign up to request clarification or add additional context in comments.

2 Comments

Any idea why this is not working for "bitbucket.org:443" or "api.bitbucket.org:443"?
Sorry it's my problem when printing the result. It works perfectly! Thanks.
0

That won’t work if the server checks the client certificate. If the client has no valid certificate, the server breaks TLS connection (the code above does not have a certificate at all.

  1. Server <---Client Hello------------- golang code
  2. Server ----Server Hello with cert--> golang code On this step you already have the server's certificate, but unable to get it in tls.Dial()(connection), because the connection is not established.
  3. Server <---Client cert(empty cert)----golang code.
  4. Server(if validation is enabled) breaks connection because client certificate is not valid.

Eventually, golang code returns with an error and you do not get a server's certificate, no matter that you already have it on step 2.

2 Comments

Please consider including some source code to make the answer more complete.
I wrote about code marked as "solution". That code won’t work if the server checks the client certificate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.