Skip to content

Commit 16b9ca4

Browse files
authored
Merge pull request #1225 from thunderkatz/master
fix: put spaces before negative numbers following minus signs in format.go to resolve CVE-2024-34359
2 parents cb17679 + 8067a8f commit 16b9ca4

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

driver/pgdriver/format.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ func appendArg(b []byte, v interface{}) ([]byte, error) {
6666
case nil:
6767
return append(b, "NULL"...), nil
6868
case int64:
69+
// To avoid accidental comments which can lead to SQL injection, put a space before
70+
// negative numbers immediately following a minus sign.
71+
if v < 0 && len(b) > 0 && b[len(b)-1] == '-' {
72+
b = append(b, ' ')
73+
}
6974
return strconv.AppendInt(b, v, 10), nil
7075
case float64:
7176
switch {
@@ -76,6 +81,11 @@ func appendArg(b []byte, v interface{}) ([]byte, error) {
7681
case math.IsInf(v, -1):
7782
return append(b, "'-Infinity'"...), nil
7883
default:
84+
// To avoid accidental comments which can lead to SQL injection, put a space before
85+
// negative numbers immediately following a minus sign.
86+
if v < 0 && len(b) > 0 && b[len(b)-1] == '-' {
87+
b = append(b, ' ')
88+
}
7989
return strconv.AppendFloat(b, v, 'f', -1, 64), nil
8090
}
8191
case bool:

driver/pgdriver/format_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,29 @@ func TestFormatQuery(t *testing.T) {
3535
args: []interface{}{nil, "", []byte(nil), time.Time{}},
3636
wanted: "select NULL,'',NULL,NULL",
3737
},
38+
{
39+
query: "select 1-$1, 1.0-$2, 1.0-$3",
40+
args: []interface{}{int64(-1), float64(-1.5), math.Inf(-1)},
41+
wanted: "select 1- -1, 1.0- -1.5, 1.0-'-Infinity'",
42+
},
43+
{
44+
query: "select 1+$1, 1.0+$2",
45+
args: []interface{}{int64(-1), float64(-1.5)},
46+
wanted: "select 1+-1, 1.0+-1.5",
47+
},
48+
{
49+
query: "select 1-$1, $2",
50+
args: []interface{}{int64(-1), "foo\n;\nSELECT * FROM passwords;--"},
51+
// Without a space before the negative number, the first line ends in a comment
52+
wanted: `select 1- -1, 'foo
53+
;
54+
SELECT * FROM passwords;--'`,
55+
},
56+
{
57+
query: "$1",
58+
args: []interface{}{int64(-1)},
59+
wanted: "-1",
60+
},
3861
}
3962

4063
for _, test := range tests {

0 commit comments

Comments
 (0)