Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[v9] Fix user mismatch in postgres backend #12553

Merged
merged 5 commits into from
May 12, 2022
Merged
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
26 changes: 26 additions & 0 deletions lib/backend/postgres/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ package postgres

import (
"context"
"crypto/tls"
"crypto/x509"
"database/sql"
"errors"
"fmt"
Expand Down Expand Up @@ -61,6 +63,17 @@ func (d *pgDriver) open(ctx context.Context, u *url.URL) (sqlbk.DB, error) {
}
connConfig.Logger = d.sqlLogger

// extract the user from the first client certificate in TLSConfig.
if connConfig.TLSConfig != nil {
connConfig.User, err = tlsConfigUser(connConfig.TLSConfig)
if err != nil {
return nil, trace.Wrap(err)
}
if connConfig.User == "" {
return nil, trace.BadParameter("storage backend certificate CommonName field is blank; database username is required")
}
}

// Attempt to create backend database if it does not exist.
err = d.maybeCreateDatabase(ctx, connConfig)
if err != nil {
Expand Down Expand Up @@ -228,6 +241,19 @@ func convertError(err error) error {
return trace.Wrap(err)
}

// tlsConfigUser returns the user defined in the CommonName field of the first
// client certificate in tlsConfig.
func tlsConfigUser(tlsConfig *tls.Config) (user string, err error) {
if tlsConfig == nil || len(tlsConfig.Certificates) == 0 || len(tlsConfig.Certificates[0].Certificate) == 0 {
return "", trace.BadParameter("unable to extract user from TLS Config")
}
cert, err := x509.ParseCertificate(tlsConfig.Certificates[0].Certificate[0])
if err != nil {
return "", trace.Wrap(err)
}
return cert.Subject.CommonName, nil
}

const (
// errCodeUniqueConstraint means a duplicate key value violated a unique constraint.
errCodeUniqueConstraint = "23505"
Expand Down