Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions dialer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1222,6 +1222,67 @@ func TestDialerChecksSubjectAlternativeNameAndFails(t *testing.T) {
}
}

func TestDialerChecksSubjectAlternativeNameAndFallsBackToCN(t *testing.T) {

// Create an instance with custom SAN 'db.example.com'
inst := mock.NewFakeCSQLInstance(
"myProject", "myRegion", "myInstance",
mock.WithDNS("db.example.com"),
mock.WithMissingSAN("db.example.com"), // don't put db.example.com in the server cert.
)

// resolve db.example.com to the same instance
wantName, _ := instance.ParseConnNameWithDomainName("myProject:myRegion:myInstance", "db.example.com")

d := setupDialer(t, setupConfig{
testInstance: inst,
reqs: []*mock.Request{
mock.InstanceGetSuccess(inst, 1),
mock.CreateEphemeralSuccess(inst, 1),
},

dialerOptions: []Option{
WithTokenSource(mock.EmptyTokenSource{}),
WithResolver(&fakeResolver{
entries: map[string]instance.ConnName{
"db.example.com": wantName,
"myProject:myRegion:myInstance": wantName,
},
}),
},
})

tcs := []struct {
desc string
icn string
}{
{
desc: "Fallback from connect with Instance Connection Name",
icn: "myProject:myRegion:myInstance",
},
{
desc: "Fallback from connect with configured domain name",
icn: "db.example.com",
},
}
for _, tc := range tcs {
t.Run(tc.desc, func(t *testing.T) {

// Dial 'db2.example.com'. This succeed overall.
// First the Hostname check will fail because the certificate does not
// contain db2.example.com
// Then the CN field check will succeed, because the instance connection
// name matches.
_, err := d.Dial(
context.Background(), tc.icn,
)
if err != nil {
t.Fatal("Want no error. Got: ", err)
}
})
}
}

func TestDialerRefreshesAfterRotateCACerts(t *testing.T) {
tcs := []struct {
desc string
Expand Down
87 changes: 14 additions & 73 deletions internal/cloudsql/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,87 +242,28 @@
pool.AddCert(caCert)
}

// If the instance metadata does not contain a domain name, use the legacy
// validation checking the CN field for the instance connection name.
if c.DNSName == "" {
return &tls.Config{
ServerName: c.ConnectionName.String(),
Certificates: []tls.Certificate{c.ClientCertificate},
RootCAs: pool,
// We need to set InsecureSkipVerify to true due to
// https://github.com/GoogleCloudPlatform/cloudsql-proxy/issues/194
// https://tip.golang.org/doc/go1.11#crypto/x509
//
// Since we have a secure channel to the Cloud SQL API which we use to
// retrieve the certificates, we instead need to implement our own
// VerifyPeerCertificate function that will verify that the certificate
// is OK.
InsecureSkipVerify: true,
VerifyPeerCertificate: verifyPeerCertificateFunc(c.ConnectionName, pool),
MinVersion: tls.VersionTLS13,
}
}

// If the connector was configured with a domain name, use that domain name
// to validate the certificate. Otherwise, use the DNS name from the
// instance metadata retrieved from the ConnectSettings API endpoint.
serverName := c.ConnectionName.DomainName()
if serverName == "" {
var serverName string
if c.ConnectionName.HasDomainName() {
// If the connector was configured with a DNS name, use the DNS name from
// the configuration to validate the server certificate.
serverName = c.ConnectionName.DomainName()
} else {
// If the connector was configured with an Instance Connection Name,
// use the DNS name from the instance metadata.
serverName = c.DNSName
}

// By default, use Standard TLS hostname verification name to
// verify the server identity.
return &tls.Config{
ServerName: serverName,
Certificates: []tls.Certificate{c.ClientCertificate},
RootCAs: pool,
MinVersion: tls.VersionTLS13,
}

}

// verifyPeerCertificateFunc creates a VerifyPeerCertificate func that
// verifies that the peer certificate is in the cert pool. We need to define
// our own because CloudSQL instances use the instance name (e.g.,
// my-project:my-instance) instead of a valid domain name for the certificate's
// Common Name.
func verifyPeerCertificateFunc(
cn instance.ConnName, pool *x509.CertPool,
) func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
return func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
if len(rawCerts) == 0 {
return errtype.NewDialError(
"no certificate to verify", cn.String(), nil,
)
}

cert, err := x509.ParseCertificate(rawCerts[0])
if err != nil {
return errtype.NewDialError(
"failed to parse X.509 certificate", cn.String(), err,
)
}

opts := x509.VerifyOptions{Roots: pool}
if _, err = cert.Verify(opts); err != nil {
return errtype.NewDialError(
"failed to verify certificate", cn.String(), err,
)
}

certInstanceName := fmt.Sprintf("%s:%s", cn.Project(), cn.Name())
if cert.Subject.CommonName != certInstanceName {
return errtype.NewDialError(
fmt.Sprintf(
"certificate had CN %q, expected %q",
cert.Subject.CommonName, certInstanceName,
),
cn.String(),
nil,
)
}
return nil
// Replace entire default TLS verification with our custom TLS
// verification defined in verifyPeerCertificateFunc(). This allows the
// connector to gracefully and securely handle deviations from standard TLS
// hostname validation in some existing Cloud SQL certificates.
InsecureSkipVerify: true,
VerifyPeerCertificate: verifyPeerCertificateFunc(serverName, c.ConnectionName, pool),
}
}

Expand Down
14 changes: 3 additions & 11 deletions internal/cloudsql/instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,14 +165,6 @@ func TestConnectionInfoTLSConfig(t *testing.T) {
}

got := ci.TLSConfig()
wantServerName := cn.String()
if got.ServerName != wantServerName {
t.Fatalf(
"ConnectInfo return unexpected server name in TLS Config, "+
"want = %v, got = %v",
wantServerName, got.ServerName,
)
}

if got.MinVersion != tls.VersionTLS13 {
t.Fatalf(
Expand Down Expand Up @@ -403,7 +395,7 @@ func TestConnectionInfoTLSConfigForCAS(t *testing.T) {
wantRootCAs.AddCert(subCACert)
// Assemble a connection info with the raw and parsed client cert
// and the self-signed server certificate
wantServerName := "testing dns name"
wantServerName := "db.example.com"
ci := ConnectionInfo{
DNSName: wantServerName,
ClientCertificate: tls.Certificate{
Expand Down Expand Up @@ -434,8 +426,8 @@ func TestConnectionInfoTLSConfigForCAS(t *testing.T) {
if got.Certificates[0].Leaf != ci.ClientCertificate.Leaf {
t.Fatal("leaf certificates do not match")
}
if got.InsecureSkipVerify {
t.Fatal("InsecureSkipVerify is true, expected false")
if !got.InsecureSkipVerify {
t.Fatal("InsecureSkipVerify is false, expected true")
}
if !got.RootCAs.Equal(wantRootCAs) {
t.Fatalf("unexpected root CAs, got %v, want %v", got.RootCAs, wantRootCAs)
Expand Down
157 changes: 157 additions & 0 deletions internal/cloudsql/tls_verify.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cloudsql

import (
"crypto/tls"
"crypto/x509"
"fmt"

"cloud.google.com/go/cloudsqlconn/errtype"
"cloud.google.com/go/cloudsqlconn/instance"
)

// verifyPeerCertificateFunc creates a VerifyPeerCertificate function with the
// custom TLS verification logic to gracefully and securely handle deviations
// from standard TLS hostname verification in existing Cloud SQL instance
// server certificates.
//
// This is the verification algorithm:
//
// 1. Verify the server cert CA, using the CA certs from the instance metadata.
// Reject the certificate if the CA is invalid.
//
// 2. Check that the server cert contains a SubjectAlternativeName matching the
// DNS name in the connector configuration OR the DNS Name from the instance
// metadata
//
// 3. If the SubjectAlternativeName does not match, and if the server cert
// Subject.CN field is not empty, check that the Subject.CN field contains
// the instance name.
//
// Reject the certificate if both the #2 SAN check and #3 CN checks fail.
//
// To summarize the deviations from standard TLS hostname verification:
//
// Historically, Cloud SQL creates server certificates with the instance name in
// the Subject.CN field in the format "my-project:my-instance". The connector is
// expected to check that the instance name that the connector was configured to
// dial matches the server certificate Subject.CN field. Thus, the Subject.CN
// field for most Cloud SQL instances does not contain a well-formed DNS Name.
//
// The default Go TLS hostname verification TLSConfig.serverName may be compared
// with the Subject.CN field if Subject.CN contains a well-formed DNS name.
// So the Cloud SQL server certs break the standard hostname verification in Go.
// See:
// - https://github.com/GoogleCloudPlatform/cloudsql-proxy/issues/194
// - https://tip.golang.org/doc/go1.11#crypto/x509
//
// Also, there are times when the instance metadata reports that an instance has
// a DNS name, but that DNS name does not yet appear in the SAN records of the
// server certificate. The client should fall back to validating the hostname
// using the instance name in the Subject.CN field.
func verifyPeerCertificateFunc(
serverName string, cn instance.ConnName, roots *x509.CertPool,
) func(certs [][]byte, chain [][]*x509.Certificate) error {
return func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
if len(rawCerts) == 0 {
return errtype.NewDialError(
"no certificate to verify", cn.String(), nil,
)
}
// Parse the raw certificates
certs := make([]*x509.Certificate, 0, len(rawCerts))
var err error
for _, certBytes := range rawCerts {
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return errtype.NewDialError(
"failed to parse X.509 certificate", cn.String(), err,
)
}
certs = append(certs, cert)
}
serverCert := certs[0]

// Verify the validity of the certificate chain
_, err = serverCert.Verify(x509.VerifyOptions{
Roots: roots,
})
if err != nil {
err = &tls.CertificateVerificationError{
UnverifiedCertificates: certs,
Err: err,
}
return errtype.NewDialError(
"failed to verify certificate", cn.String(), err,
)
}

var serverNameErr error

if serverName == "" {
// The instance has no DNS name.
// Verify only the CN
return verifyCn(cn, serverCert)
}

// The instance has a DNS name.
// First, verify the server hostname
serverNameErr = serverCert.VerifyHostname(serverName)
if serverNameErr != nil {
// If that failed, verify the CN field.
cnErr := verifyCn(cn, serverCert)
if cnErr != nil {
// If both failed, return the server hostname error.
serverNameErr = &tls.CertificateVerificationError{
UnverifiedCertificates: certs,
Err: serverNameErr,
}
return serverNameErr
}
}

// All checks passed
return nil
}
}

func verifyCn(cn instance.ConnName, cert *x509.Certificate) error {
// Reject CN check if the certificate CN field is empty
if cert.Subject.CommonName == "" {
return errtype.NewDialError(
fmt.Sprintf(
"certificate CN was empty, expected %q",
cert.Subject.CommonName,
),
cn.String(),
nil,
)
}

// Verify the CN field matches the instance name
certInstanceName := fmt.Sprintf("%s:%s", cn.Project(), cn.Name())
if cert.Subject.CommonName != certInstanceName {
return errtype.NewDialError(
fmt.Sprintf(
"certificate had CN %q, expected %q",
cert.Subject.CommonName, certInstanceName,
),
cn.String(),
nil,
)
}
return nil
}
Loading
Loading