Invalid percent escape in a connection string may expose credentials in error messages
Description
Impact
When a connection string option value contains an invalid percent-encoding, such as a literal % that isn't followed by two hex digits (for example %zz), the Go Driver returns a parse error that quotes the entire raw value. If that option holds a secret, such as tlsCertificateKeyFilePassword or an AWS session token in authMechanismProperties, the secret appears in plain text in the error. Anyone who can read wherever the application logs or displays that error may learn the secret.
Applications are affected if they insert a secret containing a % character into a connection string without percent-encoding it, and the resulting parse error reaches logs or responses that others can read.
Workarounds
If the application builds the connection string from separate values, such as form fields, configuration or environment variables, build it with the standard library's net/url package. url.UserPassword and url.Values escape each value as needed, so a secret containing % (or any reserved characters) reaches the driver correctly encoded and parses without error:
q := url.Values{}
q.Set("authMechanism", "MONGODB-AWS")
q.Set("authMechanismProperties", "AWS_SESSION_TOKEN:"+token)
u := url.URL{
Scheme: "mongodb",
User: url.UserPassword("user", password),
Host: "localhost:27017",
Path: "/",
RawQuery: q.Encode(),
}
client, err := mongo.Connect(options.Client().ApplyURI(u.String()))For a unix domain socket, percent-encode the socket path before setting it as the host:
u := url.URL{
Scheme: "mongodb",
Host: url.PathEscape("/tmp/mongodb-27017.sock"),
Path: "/",
}Alternatively, supply credentials programmatically instead of embedding them in the URI, so that a parse failure has no credential to disclose:
opts := options.Client().
ApplyURI("mongodb://host:27017/?authSource=admin").
SetAuth(options.Credential{
Username: "user",
Password: password,
AuthSource: "admin",
})If the application is handed a complete connection string, check it with both url.Parse and url.ParseQuery before passing it to the driver:
u, err := url.Parse(uri)
if err != nil {
return errors.New("invalid MongoDB connection string")
}
if _, err := url.ParseQuery(u.RawQuery); err != nil {
return err
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))Proof of Concept
Before 2.10.1, without loss of generality, an application that inserts an auth mechanism containing %zz into a conneciton string without percenting-encoding it:
uri := "mongodb://user:pass@localhost:27017/?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:SECRET%zz-token"
err := options.Client().ApplyURI(uri).Validate()gets an error that quotes the token:
error parsing uri: invalid option value "AWS_SESSION_TOKEN:SECRET%zz-token": invalid URL escape "%zz"As of 2.10.1, the error is error parsing uri: invalid option and no longer includes any part of the connection string.