Reputation: 438
I connect to some server via openssl:
openssl s_client -crlf -connect somehost.com:700 -cert key.pem
And it works. Connection is successful.
But when I tried to do same from Go code (example from documentation), it doesn't work for me:
import (
"crypto/tls"
"crypto/x509"
)
func main() {
// Connecting with a custom root-certificate set.
const rootPEM = `
-----BEGIN CERTIFICATE-----
my key text
-----END CERTIFICATE-----`
// First, create the set of root certificates. For this example we only
// have one. It's also possible to omit this in order to use the
// default root set of the current operating system.
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(rootPEM))
if !ok {
panic("failed to parse root certificate")
}
conn, err := tls.Dial("tcp", "somehost.com:700", &tls.Config{
RootCAs: roots,
})
if err != nil {
panic("failed to connect: " + err.Error())
}
conn.Close()
}
My text error is:
panic: failed to connect: x509: certificate is valid for otherhost.com, not somehost.com [recovered]
Question: what did I do wrong? And maybe I didn't add some tls.Config parameters?
Upvotes: 0
Views: 1261
Reputation: 438
I didn't need to check ssl certificate of server. It was demo server of some domain registry. So I need server to check my certificate.
const certPEM = `-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
`
const certKey = `-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----`
cert, err := tls.X509KeyPair([]byte(certPEM), []byte(certKey))
if err != nil {
t.Error("server: loadkeys: %s", err)
}
cfg := tls.Config{
InsecureSkipVerify: true,
ServerName: "somehost.com",
Certificates: []tls.Certificate{cert},
}
conn, err := tls.Dial("tcp", "somehost.com:700", &cfg)
if err != nil {
t.Error("failed to connect: " + err.Error())
}
defer conn.Close()
So this code works in my case.
Upvotes: 0
Reputation: 123320
openssl s_client
is just a test tool which connects but it does not care much if the certificate is valid for the connection. Go instead cares if the certificate could be validated, so you get the information that the certificate is invalid because the name does not match.
what did I do wrong?
Based on the error message you did access the host by the wrong hostname. Or you've configured your server badly so that it sends the wrong certificate.
Upvotes: 2