Skip to content
Open
53 changes: 7 additions & 46 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,55 +1,16 @@
# Secure Coding with Python.

## Chapter 2: SQL Injection
### Testing part 2
We could keep adding more cases to our fuzzer, or use external tools, like [sqlmap](http://sqlmap.org/), which are
going to be limited by the test cases we can pass to them, we could also use a Static Application Security Testing,
like [bandit](https://github.com/PyCQA/bandit/).

First we install bandit:
```bash
> pip install bandit
```
or
```bash
> pip install -r requirements.txt
### Fix part 2
In order to fix the SQL injetion once and for all, we should rely on prepared statements, and let the DB engine do the param sanitization, like this:
```python
sql = "INSERT INTO listings (title, description) VALUES (%s, %s)"
cur.execute(sql, (title, description))
```

Then we can go and check our code with it:
```text
> $ bandit marketplace/**/*.py
Test results:
>> Issue: [B608:hardcoded_sql_expressions] Possible SQL injection vector through string-based query construction.
Severity: Medium Confidence: Low
Location: marketplace/listings.py:27
More Info: https://bandit.readthedocs.io/en/latest/plugins/b608_hardcoded_sql_expressions.html
26
27 sql = "INSERT INTO listings (title, description) VALUES (E'%s', E'%s')" % (
28 title.replace("'", "\\'"), description.replace("'", "\\'")
29 )

--------------------------------------------------

Code scanned:
Total lines of code: 28
Total lines skipped (#nosec): 0

Run metrics:
Total issues (by severity):
Undefined: 0.0
Low: 0.0
Medium: 1.0
High: 0.0
Total issues (by confidence):
Undefined: 0.0
Low: 1.0
Medium: 0.0
High: 0.0
Files skipped (0):
```
As we can see, the tool doesn't like our sanitization strategies and flags our code as a possible source of SQL injection.
Now both our unit test and bandit are happy!

**Proceed to [next section](https://github.com/nxvl/secure-coding-with-python/tree/2.2-sql-injection/fix)**
**Proceed to [next section](https://github.com/nxvl/secure-coding-with-python/tree/2.3-sql-injection/fix)**

## Index
### 1. Vulnerable Components
Expand Down
7 changes: 2 additions & 5 deletions marketplace/listings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,8 @@ def register():
db = get_db()
cur = db.cursor()

sql = "INSERT INTO listings (title, description) VALUES (E'%s', E'%s')" % (
title.replace("'", "\\'"), description.replace("'", "\\'")
)
print(sql, file=sys.stdout)
cur.execute(sql)
sql = "INSERT INTO listings (title, description) VALUES (%s, %s)"
cur.execute(sql, (title, description))
db.commit()
return redirect(url_for('listings.index'))

Expand Down