Skip to content

Commit

Permalink
Includes original fix expanded for not taking into consideration quot…
Browse files Browse the repository at this point in the history
…ed parenthesis

Revert "Revert "Fix go-gorm#2517 : Check for incomplete parentheses to prevent SQL injection." (go-gorm#2674)"
  • Loading branch information
Federico Laitano committed Feb 5, 2020
1 parent bcc1898 commit 87d8239
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
12 changes: 12 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ func TestStringPrimaryKeyForNumericValueStartingWithZero(t *testing.T) {
t.Errorf("Fetch a record from with a string primary key for a numeric value starting with zero should work, but failed, zip code is %v", address.ZipCode)
}
}

func TestStringAgainstIncompleteParentheses(t *testing.T) {
type AddressByZipCode struct {
ZipCode string `gorm:"primary_key"`
Expand All @@ -151,6 +152,17 @@ func TestStringAgainstIncompleteParentheses(t *testing.T) {

}

func TestStringAgainstIncompleteParenthesesQuoted(t *testing.T) {
DB.Save(&User{Name: "name-)-surname"})

var user User
res := DB.Raw("select * from users WHERE name = 'name-)-surname'").First(&user)

if res.Error != nil {
t.Errorf("Can't execute valid query because error : %s", res.Error.Error())
}
}

func TestFindAsSliceOfPointers(t *testing.T) {
DB.Save(&User{Name: "user"})

Expand Down
19 changes: 13 additions & 6 deletions scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,16 +280,23 @@ func (scope *Scope) AddToVars(value interface{}) string {
// IsCompleteParentheses check if the string has complete parentheses to prevent SQL injection
func (scope *Scope) IsCompleteParentheses(value string) bool {
count := 0
for i, _ := range value {
if value[i] == 40 { // (
count++
} else if value[i] == 41 { // )
count--
unquoted := true
for _, ch := range value {
switch ch {
case '(':
if unquoted {
count++
}
case ')':
if unquoted {
count--
}
case '\'':
unquoted = unquoted != true
}
if count < 0 {
break
}
i++
}
return count == 0
}
Expand Down

0 comments on commit 87d8239

Please sign in to comment.