Skip to content

Commit 0db339f

Browse files
fix(postgres): prevent SQL injection with secure URL construction
Replace vulnerable fmt.Sprintf DSN construction with Go's url.URL struct to prevent parameter injection attacks through malicious database names. - Use url.URL struct for proper component-specific escaping - Replace url.QueryEscape with appropriate URL component encoding - Maintain postgresql:// URL format as required - Prevent injection of connection parameters like ;sslmode=disable Fixes reported SQL injection vulnerability where crafted database names could inject arbitrary PostgreSQL connection parameters. Co-authored-by: Anguel <modelorona@users.noreply.github.com>
1 parent 3604915 commit 0db339f

File tree

1 file changed

+18
-14
lines changed
  • core/src/plugins/postgres

1 file changed

+18
-14
lines changed

core/src/plugins/postgres/db.go

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@
1717
package postgres
1818

1919
import (
20-
"fmt"
20+
"net"
2121
"net/url"
22+
"strconv"
2223

2324
"github.com/clidey/whodb/core/src/engine"
2425
"gorm.io/driver/postgres"
@@ -31,24 +32,27 @@ func (p *PostgresPlugin) DB(config *engine.PluginConfig) (*gorm.DB, error) {
3132
return nil, err
3233
}
3334

34-
// Use URL format for PostgreSQL connection
35-
dsn := fmt.Sprintf("postgresql://%s:%s@%s:%v/%s?sslmode=prefer",
36-
url.QueryEscape(connectionInput.Username),
37-
url.QueryEscape(connectionInput.Password),
38-
url.QueryEscape(connectionInput.Hostname),
39-
connectionInput.Port,
40-
url.QueryEscape(connectionInput.Database))
35+
// Construct PostgreSQL URL securely using url.URL struct
36+
u := &url.URL{
37+
Scheme: "postgresql",
38+
User: url.UserPassword(connectionInput.Username, connectionInput.Password),
39+
Host: net.JoinHostPort(connectionInput.Hostname, strconv.Itoa(connectionInput.Port)),
40+
Path: "/" + connectionInput.Database,
41+
}
4142

42-
// Add extra options as URL parameters
43+
// Add query parameters securely
44+
q := u.Query()
45+
q.Set("sslmode", "prefer")
46+
47+
// Add extra options as query parameters
4348
if connectionInput.ExtraOptions != nil {
44-
params := url.Values{}
4549
for key, value := range connectionInput.ExtraOptions {
46-
params.Add(key, value)
47-
}
48-
if len(params) > 0 {
49-
dsn += "&" + params.Encode()
50+
q.Set(key, value)
5051
}
5152
}
53+
54+
u.RawQuery = q.Encode()
55+
dsn := u.String()
5256

5357
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
5458
if err != nil {

0 commit comments

Comments
 (0)