Skip to content

Commit

Permalink
dbconn: add additional protection layer againt sql inject when passin…
Browse files Browse the repository at this point in the history
…g requestId
  • Loading branch information
Ivansete-status committed Oct 14, 2024
1 parent 54b53e3 commit c065116
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion waku/common/databases/db_postgres/dbconn.nim
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,42 @@ proc waitQueryToFinish(

pqclear(pqResult)

proc containsRiskyPatterns(input: string): bool =
let riskyPatterns =
@[
" OR ", " AND ", " UNION ", " SELECT ", "INSERT ", "DELETE ", "UPDATE ", "DROP ",
"EXEC ", "--", "/*", "*/",
]

for pattern in riskyPatterns:
if pattern.toLowerAscii() in input.toLowerAscii():
return true

return false

proc isSecureString(input: string): bool =
## Returns `false` if the string contains risky characters or patterns, `true` otherwise.
let riskyChars = {'\'', '\"', ';', '-', '#', '\\', '%', '_', '/', '*', '\0'}

for ch in input:
if ch in riskyChars:
return false

if containsRiskyPatterns(input):
return false

return true

proc dbConnQuery*(
dbConnWrapper: DbConnWrapper,
query: SqlQuery,
args: seq[string],
rowCallback: DataProc,
requestId: string,
): Future[Result[void, string]] {.async, gcsafe.} =
if not requestId.isSecureString():
return err("the passed request id is not secure: " & requestId)

dbConnWrapper.futBecomeFree = newFuture[void]("dbConnQuery")

let cleanedQuery = ($query).replace(" ", "").replace("\n", "")
Expand All @@ -224,7 +253,7 @@ proc dbConnQuery*(

var queryStartTime = getTime().toUnixFloat()

let reqIdAndQuery = fmt"/* requestId={requestId} */ " & $query
let reqIdAndQuery = "/* requestId=" & requestId & " */ " & $query
(await dbConnWrapper.sendQuery(SqlQuery(reqIdAndQuery), args)).isOkOr:
error "error in dbConnQuery", error = $error
dbConnWrapper.futBecomeFree.fail(newException(ValueError, $error))
Expand Down

0 comments on commit c065116

Please sign in to comment.