Skip to content

Commit

Permalink
client/comms: check for non-standard compliant tls cert error
Browse files Browse the repository at this point in the history
  • Loading branch information
chappjc committed Feb 22, 2023
1 parent 465c2c6 commit 8c30008
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
22 changes: 18 additions & 4 deletions client/comms/wsconn.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"net"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"sync/atomic"
Expand Down Expand Up @@ -50,6 +51,20 @@ const (
InvalidCert
)

// invalidCertRegexp is a regexp that helps check for non-typed x509 errors
// caused by or related to an invalid cert.
var invalidCertRegexp = regexp.MustCompile(".*(unknown authority|not standards compliant|not trusted)")

// isErrorInvalidCert checks if the provided error is one of the different
// variant of an invalid cert error returned from the x509 package.
func isErrorInvalidCert(err error) bool {
var invalidCertErr x509.CertificateInvalidError
var unknownCertAuthErr x509.UnknownAuthorityError
var hostNameErr x509.HostnameError
return errors.As(err, &invalidCertErr) || errors.As(err, &hostNameErr) ||
errors.As(err, &unknownCertAuthErr) || invalidCertRegexp.MatchString(err.Error())
}

// ErrInvalidCert is the error returned when attempting to use an invalid cert
// to set up a ws connection.
var ErrInvalidCert = fmt.Errorf("invalid certificate")
Expand Down Expand Up @@ -197,13 +212,12 @@ func (conn *wsConn) connect(ctx context.Context) error {
}
ws, _, err := dialer.DialContext(ctx, conn.cfg.URL, nil)
if err != nil {
var e x509.UnknownAuthorityError
if errors.As(err, &e) {
if isErrorInvalidCert(err) {
conn.setConnectionStatus(InvalidCert)
if conn.tlsCfg == nil {
return ErrCertRequired
return dex.NewError(ErrCertRequired, err.Error())
}
return ErrInvalidCert
return dex.NewError(ErrInvalidCert, err.Error())
}
conn.setConnectionStatus(Disconnected)
return err
Expand Down
4 changes: 2 additions & 2 deletions client/comms/wsconn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,13 +263,13 @@ func TestWsConn(t *testing.T) {
err = noCertConnMaster.Connect(ctx)
noCertConnMaster.Disconnect()
if err == nil || !errors.Is(err, ErrCertRequired) {
t.Fatalf("failed to get ErrCertRequired for no cert connection")
t.Fatalf("failed to get ErrCertRequired for no cert connection, got %v", err)
}

// test invalid cert error
_, err = setupWsConn([]byte("invalid cert"))
if err == nil || !errors.Is(err, ErrInvalidCert) {
t.Fatalf("failed to get ErrInvalidCert for invalid cert connection")
t.Fatalf("failed to get ErrInvalidCert for invalid cert connection, got %v", err)
}

// connect with cert
Expand Down

0 comments on commit 8c30008

Please sign in to comment.