Improve tls certificate verification

This commit is contained in:
2025-10-02 11:14:59 +03:30
parent 4de23d2cc9
commit 6acdcb7429

View File

@@ -4,6 +4,8 @@ import (
"MQTTLogger/config"
"crypto/tls"
"crypto/x509"
"fmt"
"net/url"
"os"
"go.uber.org/zap"
@@ -25,10 +27,24 @@ func NewTLSConfig(logger *zap.Logger, config *config.Config) *tls.Config {
return &tls.Config{
RootCAs: certpool,
// We use the provided cert not the one server sends.
ClientAuth: tls.NoClientCert,
ClientCAs: nil,
InsecureSkipVerify: true, // I know
InsecureSkipVerify: true,
Certificates: nil,
VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
cert, err := x509.ParseCertificate(rawCerts[0])
if err != nil {
return fmt.Errorf("failed to parse certificate: %w", err)
}
opts := x509.VerifyOptions{Roots: certpool}
if _, err := cert.Verify(opts); err != nil {
return fmt.Errorf("failed to verify chain: %w", err)
}
expectedCN, _ := url.Parse(config.URI)
if cert.Subject.CommonName != expectedCN.Hostname() {
return fmt.Errorf("unexpected CN, expected %s but got %s", expectedCN.Host, cert.Subject.CommonName)
}
return nil
},
}
}