bandit icon indicating copy to clipboard operation
bandit copied to clipboard

SQL Injection flagged when concatenating strings

Open Dreamsorcerer opened this issue 3 years ago • 6 comments

Describe the bug

It seems that when concatenating strings in a cur.execute() call, it flags up sql injection possibilities, even though all the string arguments are being passed into the execute() call. So, this looks safe to me.

Reproduction steps

See the # noqa: S608 lines in this file: https://github.com/aio-libs/aiohttp-session/blob/master/examples/postgres_storage.py#L68-L72

Expected behavior

No errors from concatenating string literals.

Bandit version

1.7.0 (Default)

Python version

3.7

Additional context

No response

Dreamsorcerer avatar Aug 07 '21 13:08 Dreamsorcerer

Please check this example: https://github.com/1n40/bandit/blob/master/examples/sql_statements-py36.py According to this example, concatenation is a bad practice and the query should not be concatenated.

1nf3rn0-H avatar Sep 29 '21 06:09 1nf3rn0-H

@1n40 Not sure what I'm looking for in that example. I don't see any that match what I've said or back up your claim that concatenation is bad practice...

Dreamsorcerer avatar Sep 29 '21 16:09 Dreamsorcerer

In the above mentioned example, at line number 21, under "Bad" formats, there is this line: cur.execute("SELECT * FROM foo WHERE id = '" + identifier + "'")

This might mean that string concatenation is considered a bad practice by the program. Your program https://github.com/aio-libs/aiohttp-session/blob/master/examples/postgres_storage.py#L68 shows similar type of string concatenation and hence, program raises a flag.

I know generally, string concatenation within query should not raise a flag but according to the program and documented example it is a possible vulnerability.

1nf3rn0-H avatar Sep 29 '21 17:09 1nf3rn0-H

No, the use of a variable in the string is a possible vulnerability.

Concatenating string literals is not a vulnerability.

If the program is checking purely for concatenation, then it is wrong, hence why this is a bug report.

Dreamsorcerer avatar Sep 29 '21 17:09 Dreamsorcerer

It might get a little more tricky on whether it can detect literals assigned to variables, with something like:

select = "SELECT ..."
where = "WHERE ..."
cur.execute(select + where)

Which should ideally still pass. But, at the very least it should allow literals to be concatenated:

cur.execute("SELECT ..."
            + "WHERE ...")

Dreamsorcerer avatar Sep 29 '21 17:09 Dreamsorcerer

Using the initial example provided by @Dreamsorcerer , it appears to have been introduced in the 1.6.3 release. The example passes in 1.6.2. Not quite sure what would have changed, since that mainly appears to have been a documentation release

lukegil avatar Oct 05 '21 22:10 lukegil