Перейти к содержимому

Как избежать sql инъекции python

  • автор:

Безопасная разработка на Python

Язык программирования Python приобрел большую популярность среди разработчиков благодаря различным решениям, заложенным в его архитектуру. Такими решениями являются сильная динамическая типизация, то есть язык не допускает неявных приведений типов в неоднозначных ситуациях (например, сложение букв и цифр), при этом тип переменной определяется во время присваивания ей значения и может изменяться по ходу программы. Также полезной функцией языка Python автоматическое управление памятью и поддержка множества парадигм программирования, таких как структурное и функциональное программирование. И наконец, Python является полностью объектно-ориентированным языком с поддержкой интроспекции, то есть способности определять тип объекта во время выполнения.

Но, как всякий другой язык программирования, Python имеет ряд уязвимостей, о которых мы подробно поговорим в этой статье. Так как статья ориентирована прежде всего на разработчиков Python, то мы будем говорить об ошибках в коде, которые по тем или иным причинам могут допустить программисты в процессе разработки. И начнем мы с рассмотрения инъекций команд.

Такие разные инъекции

Прежде всего, начнем с определения. Инъекция команд — это вид атаки, целью которой является выполнение произвольных команд ОС сервера или произвольных SQL запросов в случае с СУБД.

Инъекция команд позволяет выполнить практически любую команду ОС с правами текущего пользователя. Так, командная строка shell, запущенная с помощью инъекции /bin/sh в приложение, работающее с правами root, будет работать также с правами привилегированного пользователя. Причина такого “странного” поведения кода кроется в некорректной обработке данных при динамической оценке интерпретатором выполняемого кода.

Еще более интересными вариантами инъекции команд является возможность предоставить удаленный доступ с правами пользователя, запустившего приложения. Таким образом, очевидно, что выполнение произвольных команд посредством инъекций в приложения, написанные на Python, являются достаточно опасной уязвимостью. Далее мы рассмотрим несколько примеров использования небезопасных команд языка Python.

Объект Popen

Команда popen , а также команды popen3 , popen4 выполняют переданную строку как команду, что создает возможность для инъекции произвольных команд. Рассмотрим небольшой пример:

Здесь мы в переменной user_input в качестве пользовательского ввода получаем путь к тому каталогу, содержимое которого нужно вывести на экран. Но если пользователь передает в качестве параметра не только каталог, но и другую команду, то popen выполняет обе команды. То есть в данном случае выводит содержимое файла /etc/passwd.

Еще одна проблемная команда — это subprocess . Команда subprocess позволяет создавать новые процессы, подключаться к их каналам ввода/вывода/ошибок и получать их коды возврата. Данная команда позволяет создавать новые процессы, а метод call выполняет переданную текстовую строку:

И еще одна аналогичная команда, выполняющая переданные пользователем данные без какой-либо проверки это os.system:

SQL инъекции

Инъекции команд SQL, наверное, можно назвать наиболее распространенным видом инъекций команд. SQL инъекции — это метод внедрения кода, который позволяет злоумышленнику вставить или изменить SQL-запрос в приложении. Для понимания проблемы приведем пример фрагмента кода:

Здесь, если в качестве запроса к веб-приложению передать следующую строку:

http://localhost:5000/users?rank=user’ UNION ALL SELECT * FROM SSN—

Тогда приложение вернет все записи из таблицы SSN. SQL-инъекции являются проблемой для большинства языков программирования, не только для Python.

Общие рекомендации по защите

Мы рассмотрели несколько примеров использования небезопасных команд и способов эксплуатации инъекций. Теперь самое время поговорить о том, как можно защититься от таких уязвимостей. Сразу хочу заметить, что инъекции команд — это не единственный вид уязвимостей, которые есть в Python, и в следующих статьях мы поговорим о других проблемах данного языка.

Итак, список рекомендаций для разработчиков можно начать с «прописной истины», а именно: Никогда не доверяйте данным, передаваемым пользователями! Да, концепция нулевого доверия существует уже много лет и все вроде бы хорошо знают, что нельзя доверять данным передаваемым пользователями, но уязвимости инъекции команд по прежнему можно встретить, особенно в веб-приложениях.

Лучше всего вообще запретить выполнение любых команд, вводимых пользователем. То есть, сделайте список или какой-то другой интерфейс, в котором пользователь может выбрать то действие, которое ему нужно. При этом, лучше всего максимально ограничить ввод произвольных параметров, которые пользователь может передать команде.

Приведем небольшой пример. Пусть у нас в приложении используется команда find . Мы можем «захардкодить» выполнение этой команды, но оставить ввод произвольных параметров. Вроде бы пользователь не может осуществить инъекцию в чистом виде, но у find есть ключик exec, позволяющий выполнить любую команду. И если наше исходное приложение будет запущено под sudo или с SUID bit, то после инъекции ключа exec с нужным значением злоумышленник получит права root.

Таким образом, необходимо контролировать не только сами команды, вводимые пользователем но и ключи к командам, которые они собираются использовать. В случае с командой find разработчик приложения должен жестко ограничить, какие именно ключи и с какими значениями могут использоваться. Пользователю должно быть доступно для ввода только значение маски искомого файла, все остальные параметры должны устанавливаться с помощью переключателей в интерфейсе приложения.

Кроме того, не стоит пренебрегать рекомендациями сообщества в части использования безопасных команд и параметров.

Безопасные команды

Рассмотрим безопасные варианты из приведенных выше примеров кода:

Значение shell=False не позволит выполнить команды:

И наконец, проверка переданных приложению аргументов на соответствие имени какого-либо существующего файла.

В случае если избежать пользовательского ввода по тем или иным причинам нельзя, можно воспользоваться специальными библиотеками для контроля вводимых команд. Посмотрим несколько примеров использования таких библиотек.

Модуль Re

Принцип работы модуля — это использование регулярных выражений для проверки вводимых пользователем строк на наличие потенциально опасных команд.

Модуль Yaml

Еще одно средство контроля пользовательского ввода — это модуль Yaml. С помощью этого модуля мы можем проверить является ли переданный пользователем файл потенциально опасным или это обычный безобидный файл.

В примере ниже мы сначала проверяем обычный текстовый файл, на который программа никак не реагирует, а затем передаем в качестве входной строки путь к файлу /bin/ls и получаем кучу различных сообщений об ошибках.

Заключение

В этой статье мы поговорили об уязвимостях языка Python, связанных с инъекциями команд, а также о том, с помощью каких средств можно бороться с данными уязвимостями. В следующей статье мы продолжим рассмотрение проблем небезопасной разработки в Python.

А сейчас рекомендую всем желающим посетить открытый урок «Основы ООП в Python», на котором мы познакомимся с наследованием и научимся работать с классами. В результате этого занятия вы:

Article background

Every few years, the Open Web Application Security Project ranks the most critical web application security risks. Since the first report, the risk of injection is high! Among all injection types, SQL injection is one of the most common attack methods, and it is the most dangerous. Since Python is one of the most popular programming languages ​​in the world, it is important for us to understand how to prevent Python SQL injection

So when writing this article, I also inquired a lot of information at home and abroad, and finally completed the summary with questions:

  • What is Python SQL injection and how to prevent it
  • How to use text and identifier as parameter combination query
  • How to safely execute queries in the database

The operation demonstrated in the article is applicable to all databases. The example here uses PG, but the effect and process can be reproduced in other databases (such as SQLite, MySQL, Oracle, etc.)

1. Understand Python SQL injection

SQL injection attacks are a common security hole. Generating and executing SQL queries in our daily work is also a common task. However, sometimes terrible mistakes are often made when writing SQL statements

When we use Python to execute these queries directly into the database, it is likely to damage the system. So how to successfully implement the functions that compose dynamic SQL queries without making the system vulnerable to Python SQL injection?

2. Setting up the database

First, create a new PostgreSQL database and populate it with data. In the article, I will use the database to directly witness the working methods and basic operations of Python SQL injection

2.1 Create a database

Open your shell tool and create a new PostgreSQL database owned by the user:

Here, the command line option -O is used to set the owner of the database to the user postgres. The name of the database psycopgtest is also specified

postgres is a special user that will usually be reserved for administrative tasks, but for this article, postgres can be used. However, in the actual system, a separate user should be created as the owner of the database

The new database is ready! Now we connect it:

Now, you can see that you are connected to the database postgres as the psycopgtest user. This user is also the owner of the database, so it will have read access to every table in the database

2.2 Constructing the data creation table

Here we need to create a table containing some user information, and add some data to it:

We have added two columns username and admin. The admin column indicates whether the user has administrative privileges. Our goal is to target the admin domain and try to abuse it

2.3 Setting up a Python virtual environment

Now that we have a database, it is time to set up the Python environment. Create a virtual environment in the new directory:

After running this command, venv will create a new directory named. This directory will store all packages installed in the virtual environment

2.4 Use Python to connect to the database

When you use Python to connect to the PostgreSQL database, you need to make sure that our environment has psycopg2 installed. If you don’t use pip to install psycopg2:

After installation, we write the code to create a connection to the database:

The psycopg2.connect() function is used to create a connection to the database and accepts the following parameters:

  • host is the IP address of the server where the database is located
  • database is the name of the database to be connected
  • user is a user with database permissions
  • password The password to connect to the database

After we set up the connection, configure the session with autocommit=True. Activating autocommit means that there is no need to manually manage rollbacks by issuing commit or. This is the default behavior in most ORMs. You can also use this behavior here so that you can focus on writing SQL queries instead of managing transactions

2.5 execute query

Now that we have connected to the database, we begin to execute our query:

Use the connection object to create a cursor. Just like file operations in Python, cursor is implemented as a context manager. When creating a context, a cursor is opened for use to send commands to the database. When the context exits, close the cursor and you can no longer use it

Friends who are interested in the implementation of the Python with statement can check it out by themselves

In the context, the cursor used to execute the query and get the result. In this case, issue a query to count the rows in the users table. To get the results from the query, execute cursor.fetchone() and receive a tuple. Since the query can only return one result, fetchone() is used. If the query returns more than one result, then we need to iterate the cursor

3. Use query parameters in SQL

Now we have created the database and established a connection with the database, and executed the query. But the query we use is static. In other words, it has no parameters. Now we will start using parameters in the query

First, a function to check whether the user is an administrator will be implemented. is_admin() accepts the username and returns the user’s administrator status:

This function executes a query to get the value of the column of the username given by admin. Once fetchone() returned a tuple with a single result. Then, unzip this tuple into the variable admin. To test the function, please check the username:

So far, everything is normal. The function returns the expected results of the two users. But what if we look at users who do not exist? See what happens:

When the user does not exist, an exception can be seen. This is because if the result is not found, .fetchone() returns None, causing a TypeError to be raised

To handle non-existent users, we can create a special case None:

Here, the special case of handling None is added. If username does not exist, the function should return False. Test the feature on some users again:

It can be found that this function can now handle non-existent user names

4. Use Python SQL injection to exploit query parameters

In the previous example, string interpolation was used to generate the query. Then, execute the query and send the resulting string directly to the database. However, some things may be overlooked in the process

Recall that the username passed to is_admin(). What does this variable represent? We might think that this username is just a string representing the actual username. However, as we will see, an intruder can easily take advantage of this supervision and cause damage by performing Python SQL injection

Try to check if the following users are administrators:

Wait. what happened?

Let’s look at the implementation again. Print out the actual query being executed in the database:

The result text contains three sentences. In order to understand exactly how Python SQL injection works, you need to examine each part individually. The first statement is as follows:

This is the query we want. The semicolon (;) terminates the query, so the result of the query does not matter. Next is the second statement:

This is constructed by the intruder. It is designed to always return True.

Finally, we will see this short code:

This code snippet can eliminate all subsequent content. The intruder added a comment symbol (–) to convert everything we might enter after the last placeholder into a comment

When the function is executed with this parameter, it will always return True. For example, if we use this feature in the login page, the intruder can log in with a username’; select true; — and will be granted access.

If we think this is uncomfortable, it may become even more uncomfortable! Intruders who understand the table structure can use Python SQL injection to cause permanent damage. For example, an intruder can inject an update statement to change the information in the database:

Let’s break it down again:

Just like the previous injection, this code snippet terminates the query. The next statement is as follows:

Update admin to true user lisi

Finally, there is the following code snippet:

As in the previous example, this fragment returns true and comment out everything after it.

If the intruder manages to perform a function using this input, the user lisi will become the administrator:

The intruder can log in to lisi using the username. (If the intruder really wants to destroy, you can use the DROP DATABASE command)

Now we restore the original state of lisi:

4.1 Making security query parameters

Learned how an intruder can use a well-designed string to exploit the system and gain administrator privileges. The problem is that we allow the value passed from the client to be executed directly to the database without performing any kind of checking or verification. SQL injection relies on this type of vulnerability

Whenever user input is used in a database query, SQL injection may be vulnerable. The key to preventing Python SQL injection is to ensure that the value is used as expected by our development. In the previous example, username was used as a string. In fact, it is used as the original SQL statement

To ensure that we use the value as expected, the value needs to be escaped. For example, to prevent an intruder from replacing the original SQL with string parameters, you can escape the quotes:

This is just an example. There are many special characters and scenarios to consider when trying to prevent Python SQL injection. Modern database adapters come with some built-in tools that can prevent Python SQL injection by using query parameters. Use these parameters instead of ordinary string interpolation to form a query with parameters

Now that we have a clear understanding of the vulnerability, we can use query parameters instead of string interpolation to rewrite the function:

  • We used a named parameter username to indicate where the username should go
  • Pass the value username as the second parameter to cursor.execute(). When the username executes a query in the database, the type and value that the connection will use

To test this feature, we first try some valid and invalid values ​​and some hidden strings:

The same as we imagined! The function returns the expected result for all values. And, the hidden string no longer works. To understand why, you can check the query generated by execute():

The connection treats the value username as a string, escapes all characters that may terminate the string, and introduces Python SQL injection

4.2 Pass safe query parameters

Database adapters usually provide several methods for passing query parameters. Named placeholders are usually the most readable, but some implementations may benefit from using other options

Let’s take a quick look at some right and wrong ways to use query parameters. The following code block shows the types of queries we need to avoid:

Each of these statements is passed the username directly from the client to the database without performing any kind of checking or verification. This type of code can already achieve Python SQL injection

Compared to the above, the following types of queries can be executed safely:

In these statements, username is passed as a named parameter. Now, the database will use the specified type and value of username when executing queries, thus providing protection against Python SQL injection

5. Use SQL combination

But what if we have a use case where we need to write a different query (the parameter is another parameter, such as a table or column name)?

Following the previous example, we implement a function that accepts the name of the table and returns the number of rows in the table:

Try to perform the function on the user table:

The command cannot generate SQL. The database adapter treats variables as strings or literals. However, the table name is not a pure string. This is where the SQL combination comes in

We already know that it is not safe to write SQL using string interpolation. psycopg provides a module named psycopg.sql that can help us write SQL queries safely. Let us rewrite the function using the following code psycopg.sql.SQL():

There are two differences in this implementation. sql.SQL() composes the query. sql.Identifier() annotates the parameter value table_name (the identifier is the name of the column or table)

Now, we try to execute the function on the users table:

Next, let’s see what happens when the table does not exist:

This function raises an UndefinedTable exception. This exception will be used to show that our function is safe from Python SQL injection attacks

To put everything together, add an option to count the rows in the table until a certain limit is reached. For very large tables, this feature is useful. To achieve this operation, LIMIT adds a clause to the query and the query parameter of the limit value:

In the above code, limit is annotated with sql.Literal(). As with the previous examples, psycopg binds all query parameters as text when using the simple method. However, when using sql.SQL(), you need to use sql.Identifier() or explicitly annotate each parameter sql.Literal()

Unfortunately, the Python API specification does not address the binding of identifiers, only text. Psycopg is the only popular adapter that adds the ability to safely combine SQL using text and identifiers. This fact makes special attention when binding identifiers

Execute this function to ensure that it works:

Now that we have seen that the function is running, check if it is safe:

The exception shows that psycopg escapes the value and the database treats it as a table name. Since there is no table with this name, UndefinedTable throws an exception so it is safe!

6 Conclusion

By implementing dynamic SQL, we can effectively avoid the threat of Python SQL injection to our system with you! The use of text and identifiers in the query process will not affect security

7. Acknowledgements

Okay, here is the time to say goodbye to everyone. I’m just a reptile jokesman, a wanderer who hopes that one day I can realize the freedom of wealth and return to my hometown soon. I hope my article can bring you knowledge, help you and bring you laughter! At the same time, thank you for taking the time to read. It is not easy to create. If you like it, please like it before you go. Your support is the motivation for my creation, and I hope to bring you more high-quality articles in the future

SQL Injection-how to avoid problem in Python DB API

Bartosz Skłodowski

We have few possibilities to manage the database with Python code. The recommended option is to use Object-Relational Mapping (ORM), that we can use in Python like the SQLAlchemy, but today I will write about the simplest database API, which is the Python DB API (specification available as PEP 249). This is a general purpose, low-level type interface to connect to a relational database, sending SQL queries and processing their results. Queries are created as strings by the programmer. The DB API does not see any differences between SQL dialects. You can use this API directly, but it is often rebuilt by other ORM libraries like SQLAlchemy.

When we use SQL queries in Python, we are dealing with metaprogramming. SQL code is a string from a programming language point of view. Python does not recognize SQL types, structures of tables and commands, so this is not a supporting thing for programmers. Hence, metaprogramming is sophisticated and it is easy to make errors. We should not use it for typical tasks like connecting to a database because it could lead to dangerous problems with application security.

What is SQL Injection?

As I wrote earlier, this solution can be tricky and full of ambiguities and today I will describe one of them: SQL Injection. This is one of the fairly frequent and, at the same time, dangerous web (and non-web) applications vulnerabilities. As the name suggests, the problem is the injection of an unauthorized SQL query. It is possible for one reason — the lack of proper checking (validation) of the parameter provided by the user. When dealing with SQL Injection, this parameter is often passed directly to the SQL query.

Depending on the situation, we can deal with:

  • unauthorized read or write access to the entire database,
  • the possibility of bypassing the authentication mechanism,
  • the ability to read selected files (operating system on which the database works),
  • the ability to create files in the operating system on which the database works,
  • the ability to execute the code in the operating system (user rights on which the database or web server works — in the case of web applications).

As you can see, SQL Injection can access various application components, so I only describe a very simple example. It shows how an attacker can use an SQL Injection vulnerability to go around application security and authenticate as the user.

The following script is pseudocode executed on a web server. It is a simple example of authenticating with a username and a password. The example database has a table named users with the following columns: username and password .

These input fields are vulnerable to SQL Injection. An attacker could use SQL commands in the input in a way that would alter the SQL statement executed by the database server. For example, they could use a trick involving a single quote and set the password = password' OR 1=1 input, as a result the database server runs the following SQL query:

Because of the OR 1=1 statement, the WHERE clause returns the first id from the users table no matter what the username and password are. The first user id in a database is very often the administrator. In this way, the attacker not only bypasses authentication but also gains administrator privileges. They can also comment out the rest of the SQL statement to control the execution of the SQL query further:

Example of SQL Injection problem using Python DB API

I have for you a short example of code, where I am using DB API. Purpose of this article is SQL Injection mistake, so I am not describe the details of using DB API. But you can see that I create AuthDatabase and then using SQL queries build table credentials and put into some data. Finally, the code simulates logging in and checking if the user has entered the correct password.

As you can see, if you put SQL Injection expression you will receive an access to database, what is more, result return all databases records.

Solution for this problem is allow to execute positional and keywords arguments in cursor method: cursor.execute(sql_string, *args, **kwargs) .Then you can relay login and password as a list to query method.

Now result of use SQL Injection expression is as we expect. We need to pass the correct password to get access to the database.

It was, of course, a very simple case of SQL Injection. I want show you that we must pay attention about security of apps we create.

Conclusion

As you can see, SQL Injection is a significant problem and we should protect our applications against it. There are many ways to do this, sometimes frameworks already have such protections, so we don’t have to worry about it. To put it briefly, you should always appropriately verify the variables passed from the user to the application.

Python

This builds a SQL string using Python’s string formatting, but it creates an unsafe string that is then passed through to the database and executed.

Instead, do this:

This sets up placeholders so that the database can fill in the data values properly and safely.

For cases involving a single variable do this:

Note that the placeholder syntax depends on the database you are using.

The values for the most common databases are:

So if you are using MySQL or PostgreSQL, use %s (even for numbers and other non-string values!) and if you are using SQLite use ? .

If you are using ODBC to connect to the DB, regardless of which DB it is, use ? .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *