Chapter 2.1: SQL Injection - code #4
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Chapter 2: SQL Injection
Requirement
Since we are creating a marketplace application, we first decide to allow the upload of Listings, just text. We will worry about users later, since we want to focus on getting the DB and Models setup without needed to worry about authentication and session management at this point.
Development
Since the application will need some more configuration we change the
marketplace/__init__.pyto make use of thecreate_appfactory function. We add the DB connection functions intomarketplace/db.pyand add the factory function. We also add the DB schema inschema.sqland add a flask command to init the DB, which we run with thepython -m flask init-dbcommand.Vulnerability
Since we are generating the SQL to insert the new listing in a very unsecure way, we can insert SQL commands that will be run in the DB. For example if we insert
'as title or description we will getpsycopg2.errors.SyntaxError: INSERT has more target columns than expressions LINE 1: INSERT INTO listings (title, description) VALUES (''', ''') ^instead of a success.We can for example get the postgresql version or any other SQL function result, to check that out, insert
injection', (select version()))-- -as the title. When we do so, the SQL that's going to be executed will be the following:As it can be seen, the inserted title will be
injectionand the description will be the result of theselect version()command, or any other command we wish to insert there, including dropping the DB.