From 894013440f72ab80b77020ee422ff07017ce4bb4 Mon Sep 17 00:00:00 2001 From: Nicolas Valcarcel Date: Sat, 6 Jul 2019 19:13:39 -0500 Subject: [PATCH 1/2] Use parametrized query instead --- README.md | 9 +++++++++ marketplace/listings.py | 7 ++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index a0a7fb3..9b23b9f 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,15 @@ 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. +### 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)) +``` + +Now both our unit test and bandit are happy! + ## Description Welcome to the Secure coding with python course. In this repository you will find a series of branches for each step of the development of a sample marketplace application. In such a development, we will be making security mistakes and introducing vulnerabilities, we will add tests for them and finally fixing them. diff --git a/marketplace/listings.py b/marketplace/listings.py index 65ce3ac..7e92417 100644 --- a/marketplace/listings.py +++ b/marketplace/listings.py @@ -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')) From 21f912bcf3f20d13ce8baf306c8f9708c8272d91 Mon Sep 17 00:00:00 2001 From: Nicolas Valcarcel Date: Wed, 10 Jul 2019 12:10:30 -0500 Subject: [PATCH 2/2] fix next section link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b23b9f..7f036d4 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ The branches will have the following naming scheme for easier navigation: {Chapt For this course we will be using Python3, Flask and PostgreSQL. -**Proceed to [next section](https://github.com/nxvl/secure-coding-with-python/tree/2.2-sql-injection/fix2)** +**Proceed to [next section](https://github.com/nxvl/secure-coding-with-python/tree/2.3-sql-injection/fix3)** ## Index ### 1. Vulnerable Components