1656645311
An implementation of Amazon's Simple Queue Service (SQS). This project aims to imitate live SQS as close as possible.
Localstack was an inspiration for this project. We used Localstack for our SQS needs before this project was started. We chose to create this implementation for the following reasons:
$ sqslite --help
Usage: sqslite [options]
A SQS http server
Options:
--help Display this help message and exit
--port <port> The port to listen on (default: 4567)
Report bugs at github.com/jennyEckstein/sqslite/issues
To start the SQSLite server:
$ sqslite --port=3001
As a prerequisite to interacting with SQSLite through the command line, first install AWS CLI.
In order to create a queue, run the command shown below. Make sure to provide the same endpoint url where SQSLite server is running.
$ aws sqs create-queue --queue-name=test-queue-1 --region=us-east-1 --endpoint=http://localhost:3001
Or programmatically:
const sqslite = require('sqslite');
sqslite({}).listen(3001, (err, address) => {
if (err) throw err;
console.log(`server listening on ${address}`);
});
Once running, here's how to use AWS SDK to connect:
const AWS = require('aws-sdk');
const sqs = new AWS.SQS({ endpoint: 'http://localhost:3001' });
await sqs.listQueues().promise();
With npm do:
npm install -g sqslite
Or to install for development/testing in your project:
npm install -D sqslite
Download Details:
Author: jennyEckstein
Source Code: https://github.com/jennyEckstein/sqslite
License: Apache-2.0 license
#sql #database sqslite
1656496041
A comment is simply a text that is ignored by the database engine. Comments can be used to provide a quick hint about the SQL statement.
SQL support single-line as well as multi-line comments. To write a single-line comment start the line with two consecutive hyphens (--
). For example:
-- Select all the employees
SELECT * FROM employees;
However to write multi-line comments, start the comment with a slash followed by an asterisk (/*
) and end the comment with an asterisk followed by a slash (*/
), like this:
/* Select all the employees whose
salary is greater than 5000 */
SELECT * FROM employees
WHERE salary > 5000;
1656495781
Consider another SQL statement that retrieves the records from employees table:
SELECT emp_name, hire_date, salary FROM employees;
The same statement can also be written, as follow:
select emp_name, hire_date, salary from employees;
SQL keywords are case-insensitive that means SELECT
is same as select
. But, the database and table names may case-sensitive depending on the operating system. In general, Unix or Linux platforms are case-sensitive, whereas Windows platforms aren't.
Tip: It is recommended to write the SQL keywords in uppercase, to differentiate it from other text inside a SQL statement for a better understanding.
1656494968
SQL statements are very simple and straightforward like plain English but with specific syntax.
An SQL statement is composed of a sequence of keywords, identifiers, etc. terminated by a semicolon (;
). Here is an example of a valid SQL statement.
SELECT emp_name, hire_date, salary FROM employees WHERE salary > 5000;
For better readability you can also write the same statement, as follow:
SELECT emp_name, hire_date, salary
FROM employees
WHERE salary > 5000;
Use semicolon at the end of an SQL statement — it terminates the statement or submits the statement to the database server. Some database management system has, however, no such requirement, but it is considered as a best practice to use it.
We'll discuss each part of these statements in detail in upcoming chapters.
Note: Any number of line breaks may occur within a SQL statement, provided that any line break does not break off keywords, values, expression, etc.
1656318537
How to write a sql query to fetch data from a database. Part of a music player sql app tutorial. Learn to create and use a database application.
In this tutorial, we’ve collected all the essential information about writing SQL queries into one ultimate guide to help you gain and practice this knowledge more effectively.
Structured Query Language (SQL) is a programming language specific to a domain, designed to help maintain structured data held in a database. Basically, this language is what helps us communicate with a database, update it, and retrieve data from it.
From this definition, we can conclude that you can use SQL to perform a variety of tasks, like:
To better understand how this language functions, you also need to have a basic knowledge of its main components or dialects.
Some experts also single out the Transaction Control Language dialect that is used to manage and control transactions in order to maintain data integrity (the assurance of accuracy and consistency) in the SQL statement.
To write an SQL query, you will first need to create a relational database.
In SQL, we call a database relational because it is divided into tables that are related to each other. These tables break down the data into smaller and more manageable units, which allows better maintenance and overall performance.
To do it, you need to have a Database Management System (DBMS) installed. A DBMS is a software that helps you create and manage the database. If you don’t have one installed on your system already, here are a few most popular options:
Regardless of the DBMS you choose, all of them provide security and protection for all the databases you create. It also helps maintain consistency if there are several users working on the DBMS at once.
Now, let’s take a closer look at what you need to know to write an SQL query as well as some common mistakes to avoid.
Before you start writing an SQL query, you need to understand how it works, when performing commands.
When you enter a query, it is immediately parsed into a tree. A parser, which is a computer program that translates SQL statements into a parse tree, helps identify whether the query fits the syntactical as well as semantic requirements, i.e., that it is recognizable.
Then, if everything is correct, the parser creates an internal query, which is then passed to the rewrite engine.
After that, the task optimizer, which analyzes how many execution plans a query has, finds the optimal execution plan for your given query. This plan represents the algorithm, which will be used to perform the command.
If the query is written correctly, you will get the results you expect.
Now, let’s take a look at what it takes to write a proper SQL query.
So, as we already mentioned, to write an SQL query, you need to create an environment for it by launching a database.
If you already have your DBMS software installed, you can proceed right to creating a database by using a ‘CREATE DATABASE’ statement. The basic syntax of this command will look like this:
CREATE DATABASE database_name;
For instance, if you want to create a database for client reviews, the result will look like this:
CREATE DATABASE client_reviews;
To move on to using your database, you need to continue your SQL query with the ‘USE’ statement:
USE client_reviews;
This will make this database a target for all your future commands.
Keep in mind: if the database with this name already exists, you will get an error message. However, to avoid this, you can use the ‘IF NOT EXISTS’ statement. Here’s how it looks like in MySQL:
mysql> CREATE DATABASE IF NO EXISTS client_reviews;
If your query is correct, you will get an OK message.
If the database is ready, you can now proceed to creating a table. As we already mentioned, tables help you structure your queries and make the data more manageable.
To create a table, you need to input the ‘CREATE TABLE’ statement. The syntax for this statement will look similar to this:
CREATE TABLE table_name (
column1_name_constraint,
…
)
It is clear what we should insert in the table name and column name, but let’s take a closer look at the types of constraints.
A constraint is a declaration of data type, which indicates what kind of data the column will include. There are several kinds of constraints that you can include in a column:
If we create a table for each of the people who have given their customer reviews, the final result will look like this:
CREATE TABLE customer profiles (
id INT NOT NULL AUTO_INCREMENT
name VARCHAR NOT NULL
birth_date DATE
review TEXT
) ;
When creating a table, you can encounter the same problem as with a database if the table does not exist. To avoid it, to the ‘CREATE TABLE’ statement, you should also add the ‘IF NOT EXISTS’ statement.
When the table is ready and operational, you can now continue writing SQL queries by inserting data inside the table.
Here are all basic statements to input and manage the data inside the table:
This statement is used to include new rows into a table. Here’s how the syntax will look like in this case:
INSERT INTO table_name (column1, column2, column 3);
You can also include values – the data that you want to include in each column.
Here’s how the final query would look like for our customer reviews table after inserting data into it:
INSERT INTO customer profiles (name, birth_date, review)
VALUES (‘Jennifer Dickinson’, ‘1987-07-07’, ‘good service’)
The final result will give you a numbered list of the names, birth dates, and reviews in the form of a table.
This clause is used to select and extract data from one or different tables. The syntax for this clause will follow this pattern:
SELECT column1_name, column2_name FROM table_name
-_name
The combination of the ‘SELECT’ and ‘FROM’ clauses allows you to fetch information from one or several columns within one or different tables. If you want to select all columns in one table, you can simply use the combination of ‘SELECT’, ‘FROM’ clauses, and the name of the table.
By inserting this clause in a table, you can select data based on a certain condition. It is helpful if you want to select for an update or entirely delete one of the records in a row or a column based on a condition like a name, birth date, etc. Here’s the basic syntax using this clause:
SELECT column1_name FROM table_name WHERE condition
-_name
As you can see, the WHERE clause is used together with the ‘SELECT’ and ‘FROM’ clauses to help you fetch the right data from the right column or row.
You can also use the ‘WHERE’ clause to filter different records based on a certain condition.
To make sure that you select the right data, this clause allows you to use several basic comparison operators:
To make these operators work, include them right after the ‘WHERE’ clause.
To write a basic SQL query and effectively select the data from a certain column in a table, you also need to use ‘AND’ and ‘OR’ operators used together with the ‘WHERE’ clause.
The AND operator is used to combine two different conditions and gives you the results only if there is data that matches both these conditions. Here’s how the syntax with the ‘AND’ operator looks like:
SELECT column1_name, column2_name…FROM table_name
WHERE condition1 AND condition2
Respectively, the OR operator combines two different conditions and gives you the results if there is data that matches one of these conditions. The syntax, in this case, looks like this:
SELECT column1_name, column2_name…FROM table_name
WHERE condition1 OR condition2
To write a more complex SQL query, you can also combine the ‘AND’ and ‘OR’ operators, which will allow you to retrieve data that matches many different conditions.
These operators help you select an exclusive variety of values based on certain conditions.
The IN operator allows you to select all the data that falls under a certain criterion. The syntax of the query, including the ‘IN’ operator, should look like this:
SELECT column1_name…FROM table_name
WHERE condition1 IN (value1, value2, value3…)
For instance, you can retrieve information about customers coming from the same country using this operator. Similarly, you can add ‘NOT’ to the ‘IN’ operator, if you want to exclude some results.
If you want to get results within a certain range of values, you can use the BETWEEN operator. In this case, the syntax will look as follows:
SELECT column1_name…FROM table_name
WHERE condition1 BETWEEN value1 AND value 2
As you can see, the ‘AND’ operator is also used to compare the values and fetch the results.
This clause is used when you want to put the fetched results in a certain order. The ORDER BY clause tells the server how to organize the data, and the syntax looks like this:
SELECT column_list…FROM table_name ORDER BY column_name
preferred order of the fetched data.
If you want to limit the number of results, you can include the ‘LIMIT’ clause in MySQL or Top clause in SQL Server. The basic syntax using this clause looks like this:
SELECT column_list…FROM table_name ORDER BY value LIMIT number
As you can see, the ‘ORDER BY’ clause is also used in this case, because it helps identify the values to be limited.
Once you’ve inserted and selected data, you can now proceed to writing an SQL query to update this data. To do it, you will need to use the UPDATE statement, for which the syntax looks similar to this:
UPDATE table_name
SET column1_name = value 1…
WHERE condition1, condition2…
The ‘SET’ clause allows you to identify a specific column or row that needs to be updated. You can also use all the above-mentioned operators, like ‘AND’ and ‘OR’ to update the table.
This statement allows you to remove one or several rows. The syntax for this query is simple and looks like this:
DELETE FROM table_name WHERE condition
The ‘WHERE’ clause specifies the record that should be deleted according to the condition assigned to it. Don’t omit it, otherwise, you will delete all the records from the table.
However, if you do want to remove all the rows at once, the TRUNCATE TABLE statement will help you do it quicker than a ‘DELETE’ statement. The syntax for this query looks like this:
TRUNCATE TABLE table_name
While removing the rows from the table, this statement doesn’t actually delete the structure of the table. You can use this statement if you want to rework the entire table.
If you’ve finished writing an SQL query and it still doesn’t work, you might have made a mistake along the way.
So, watch out for these most common SQL query mistakes and make sure you proofread your query to avoid them:
To make your SQL queries work, you need to write them while keeping in mind where performance problems might appear within your query. Then, if you get an error message, you might already have an understanding, where to look for an issue and how to solve it.
An SQL Query is used to retrieve the required data from the database. However, there may be multiple SQL queries that yield the same results but with different levels of efficiency. An inefficient query can drain the database resources, reduce the database speed or result in a loss of service for other users. So it is very important to optimize the query to obtain the best database performance.
Let us consider some sample tables to understand these different methods to optimize a query.
Customers : Table Customers contains the details of the prospective customers for a shop.
CustomerID | LastName | FirstName | Address | Age |
---|---|---|---|---|
73001 | Smith | John | 45 Jump Street | 21 |
73002 | Parker | Anna | 83 Wild Avenue | 45 |
73003 | James | Josie | 99 Chestnut Avenue | 25 |
73004 | White | Anna | 55 Paper Street | 72 |
73005 | Sparks | Harry | 11 Wisteria Lane | 23 |
73006 | Parker | Jane | 12 Quentin Road | 50 |
Products : Table Products contains the details of the products available in the shop.
ProductID | ProductName | ProductPrice |
---|---|---|
1001 | Shampoo | 100 |
1002 | Tooth paste | 20 |
1003 | Soap | 15 |
1004 | Hand Sanitizer | 50 |
1005 | Deodorant | 100 |
Orders : Table Orders contains the details of the products ordered by the customers from the shop.
CustomerID | ProductID | ProductQuantity |
---|---|---|
73001 | 1003 | 5 |
73001 | 1001 | 1 |
73003 | 1002 | 1 |
73004 | 1003 | 2 |
73004 | 1005 | 1 |
Now that we have analyzed the tables Customers, Products and Orders, the different ways to optimize a query are given below with query examples from these tables:
It is very important to provide the correct formatting while writing a query. This enhances the readability of the query and also makes reviewing and troubleshooting it easier. Some of the rules for formatting a query are given below:
Example: This is a query that displays the CustomerID and LastName of the customers that have currently ordered products and are younger than 50 years.
Select distinct Customers.CustomerID, Customers.LastName from Customers INNER join Orders on Customers.CustomerID = Orders.CustomerID where Customers.Age < 50;
The above query looks unreadable as all the statements are in one line and the keywords are in lower case. So an optimized version is given below using the rules for formatting specified earlier.
SELECT DISTINCT Customers.CustomerID, Customers.LastName
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
WHERE Customers.Age < 50;
SELECT * is used to obtain all the data from a table. So it should not be used unless all of the data is actually required for a given condition as it is highly inefficient and slows the execution time of the query. It is much better to use SELECT along with the specific fields required to optimize the query.
Example: This is a query that displays all the data in the table Customers when only the CustomerID and LastName was required.
SELECT *
FROM Customers;
It is better to use the select statement with the fields CustomerID and LastName to obtain the desired result.
SELECT CustomerID, LastName
FROM Customers;
A correlated subquery is a nested query that depends on the outer query for its values. If there are millions of users in the database, the correlated subquery is inefficient and takes a lot of time as it will need to run millions of times. In that case, an inner join is more efficient.
Example: This is a query that displays the CustomerID of the customers that have currently ordered products using a correlated subquery.
SELECT CustomerID
FROM Customers
WHERE EXISTS (SELECT * FROM Orders
WHERE Customers.CustomerID = Orders.CustomerID);
It is better to use the inner join in this case to obtain the same result.
SELECT DISTINCT Customers.CustomerID
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;
Note: It is best to avoid a correlated subquery if almost all of the rows are needed from the database. However, in some cases, they are inevitable and have to be used.
In case only limited results are required, it is better to use the LIMIT statement. This statement limits the records and only displays the number of records specified. For Example: If there is a large database of a million records and only the first ten are required, it is better to use the LIMIT statement as this will ensure that only the relevant records are obtained without overtaxing the system.
Example: This is a query that displays the customer details with limit 3:
SELECT *
FROM Customers
LIMIT 3;
The DISTINCT clause is used to obtain distinct results from a query by eliminating the duplicates. However, this increases the execution time of the query as all the duplicate fields are grouped together. So, it is better to avoid the DISTINCT clause as much as possible. As an alternative, the GROUP BY clause can be used to obtain distinct results.
Example: This is a query that displays the distinct LastName of all the customers using the DISTINCT clause.
select distinct LastName
from Customers;
The distinct LastName of the customers can also be obtained using the GROUP BY clause which is demonstrated by the next example:
SELECT LastName
FROM CUSTOMERS
GROUP BY LastName;
Functions in SQL are used to perform specific actions. However, they are quite inefficient as they do not allow the usage of indexes which in turn slows the execution time of the query. So it is better to avoid functions in a query as much as possible to ensure its optimization.
Example: This is a query that displays the details of the products whose name starts with 'Sha'.
SELECT *
FROM Products
WHERE SUBSTR(ProductName, 1, 3) = 'Sha';
It is better to avoid the function and use the LIKE clause instead to obtain the same result.
SELECT *
FROM Products
WHERE ProductName LIKE 'Sha%';
It is highly likely that indexes are not in use when OR, AND, NOT operators are used. In the case of large databases, it is better to find replacements for these to speed up the execution time of the query.
Examples of this for OR and AND operators are given below:
Example 1: This is a query that displays the details of the customers with CustomerID 73001, 73004 and 73005 using the OR operator.
SELECT *
FROM Customers
WHERE CustomerID = 73001
OR CustomerID = 73004
OR CustomerID = 73005;
It is better to use the IN operator in this case to obtain the same result.
SELECT *
FROM Customers
WHERE CustomerID IN (73001, 73004, 73005);
Example 2: This is a query that displays the details of the customers with age between 25 and 50 using the AND operator.
SELECT *
FROM Customers
WHERE age >= 25 AND age <= 50;
It is better to use the BETWEEN operator in this case to obtain the same result.
SELECT *
FROM Customers
WHERE age BETWEEN 25 AND 50;
The HAVING clause is used with the GROUP BY clause to enforce conditions as the WHERE clause cannot be used with aggregate functions. However, the HAVING clause does not allow the usage of indexes which slows the execution time of the query. So it is better to use the WHERE clause instead of the HAVING clause whenever possible.
Example: This is a query that displays the Customer FirstNames with the count of customers who have them for the customers aged more than 25. This is done using the HAVING clause.
SELECT FirstName, COUNT(*)
FROM Customers
GROUP BY FirstName
HAVING Age > 25;
It is better to use the WHERE clause in this case as it applies the condition to individual rows rather than the HAVING clause that applies the condition to the result from the GROUP BY clause.
SELECT FirstName, COUNT(*)
FROM Customers
where Age > 25
GROUP BY FirstName;
Using the WHERE clause for creating joins results in a Cartesian Product where the number of rows is the product of the number of rows of the two tables. This is obviously problematic for large databases as more database resources are required. So it is much better to use INNER JOIN as that only combines the rows from both tables which satisfy the required condition.
Example: This is a query that displays the CustomerID of the customers that have currently ordered products using the WHERE clause.
SELECT DISTINCT Customers.CustomerID
FROM Customers, Orders
WHERE Customers.CustomerID = Orders.CustomerID;
It is better to use the Inner join in this case to obtain the same result.
SELECT DISTINCT Customers.CustomerID
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;
Wildcard characters such as % and _ are used to filter out the results of a LIKE clause. However, they should not be used at the beginning of the pattern as this disables the database from using the index. In that case, a full table scan is required to match the pattern which consumes more database resources. So it is better to avoid the wildcard characters at the beginning of the pattern and only use them at the end if possible.
Example:
SELECT * FROM Customers
WHERE FirstName LIKE '%A%'
The above query is inefficient as it uses the wildcard character % at the beginning of the pattern. A much more efficient version of the query that avoids this is given below:
SELECT * FROM Customers
WHERE FirstName LIKE 'A%'
#sql #database
1656252000
In this video, we learn about Basic Hospital management system project using C# windows form application step by step with SQL Server Database.
1656156720
Los desarrolladores que trabajan con aplicaciones web ven muchas cosas que amenazan con dañar las cosas que construyen. Algunas de estas cosas incluyen ataques dirigidos a personas (por ejemplo, ingeniería social), algunos de estos ataques (ataques DoS o DDoS, secuencias de comandos entre sitios, falsificación de solicitudes entre sitios, autenticación rota, exposición de datos confidenciales, control de acceso roto, inseguridad). deserialización, etc.) partes de destino de las aplicaciones web. Sin embargo, algunos ataques se dirigen principalmente a su base de datos y los datos almacenados allí; uno de esos ataques es la inyección de SQL (SQLi para abreviar). En esta publicación de blog, veremos los impactos que podría tener un ataque de este tipo.
La inyección SQL es un ataque frecuentemente dirigido a aplicaciones web. Con frecuencia, el propósito de un ataque de este tipo es extraer datos confidenciales de la base de datos y utilizarlos para el beneficio personal del atacante. Tal ataque es tan frecuente y peligroso precisamente porque muchos desarrolladores pasan por alto la importancia de la seguridad al crear soluciones públicas orientadas a la web. Cuando se pasan por alto las brechas de seguridad, las partes maliciosas a menudo las encuentran y las explotan. Estos actores nefastos explotan tales vulnerabilidades porque pueden beneficiarse de la venta de datos robados durante la violación.
Los impactos de tal ataque dependen de su aplicación web. Supongamos que su aplicación no almacena información confidencial, en cuyo caso, es probable que el ataque no tenga consecuencias de largo alcance. Sin embargo, si ese no es el caso, es posible que tenga un problema grave en sus manos: los datos confidenciales podrían ser robados y vendidos para obtener ganancias, causando problemas para su negocio y problemas innecesarios para sus clientes debido al estrés de restablecer contraseñas y cambiar información en otro lugar.
El concepto de inyección SQL es bastante simple: un ataque de este tipo funciona porque algunos desarrolladores ponen todo lo que el usuario escribe en un campo de entrada determinado en una consulta y lo pasan a una base de datos. Un fragmento básico de código vulnerable se vería así (también puede usar $_GET en lugar de $_POST, la premisa es la misma):
$Input = $_POST['input'];
SELECT * FROM demo_table WHERE column [= | < | > | <= | >= | LIKE ...] '$Input';
Como puede ver, en algunos de los casos, el código vulnerable es bastante simple (también puede volverse complejo, veremos diferentes escenarios más adelante): los atacantes explotan dicho código vulnerable con frecuencia usando el carácter de comilla (') para inducir errores. Una vez que induce errores, los atacantes saben que el código es vulnerable y pueden atacar nuestras aplicaciones.
Hay un par de categorías en las que se incluyen los ataques de inyección SQL:
Los atacantes usan cada uno de los tipos descritos anteriormente para lograr diferentes objetivos: la inyección SQL clásica es útil si el atacante tiene algún conocimiento implícito sobre el funcionamiento interno del sistema, la inyección SQL basada en unión puede ser útil si el atacante combina los resultados de un par de SELECT
declaraciones en un solo conjunto de resultados, la inyección SQL basada en errores se usa cuando la aplicación es "silenciosa" (lo que significa que no devuelve ninguna respuesta, por lo que el atacante busca cambios en la funcionalidad al emitir ciertos tipos de consultas)
En este punto, debe comprender bastante bien qué es la inyección de SQL y cuáles son sus tipos, pero ¿cómo protege sus aplicaciones de tal ataque? Afortunadamente, hay un par de formas conocidas de reducir el riesgo de que se explote una vulnerabilidad de este tipo ahora o en el futuro:
/* Prepare MySQL statement */
if (!($statement = $mysqli->prepare(
"SELECT customerID
FROM orders
WHERE item = ?"
))) {
echo "Failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/*
Bind variables to statement as parameters using bind_param().
The type (first) parameter can take integers (i), doubles (d),
strings(s), and blobs (b).
*/
$purchasedItem = 'ice cream';
if (!$statement->bind_param("s", $purchasedItem)) {
echo "Failed: (" . $statement->errno . ") " . $statement->error;
}
/* Execute prepared MySQL statement */
if (!$statement->execute()) {
echo "Failed: (" . $statement->errno . ") " . $statement->error;
}
Tener estos puntos en mente debería ayudar a que su aplicación funcione bien.
El uso de declaraciones preparadas, el uso de complementos centrados en la seguridad proporcionados por MySQL, evitar otorgar privilegios administrativos innecesarios y tener en cuenta otras precauciones mencionadas anteriormente debería ponerlo a usted y a su base de datos en un buen camino. Sin embargo, si desea profundizar en MySQL y comprender por qué las consultas SQL funcionan de la manera en que lo hacen y por qué el uso de, por ejemplo, un firewall de aplicaciones web (WAF) podría protegerlo contra muchos tipos de ataques, incluida la inyección de SQL, considere esto:
SHOW PROFILE FOR QUERY [query id here];
Si se usa correctamente, en la mayoría de los casos, la salida le proporcionará lo que hizo la consulta y la duración de la tarea. También podrá observar un montón de cosas interesantes, incluida la obtención de respuestas a preguntas como:
Algunas de las respuestas a estas preguntas pueden ayudarlo a comprender por qué la inyección de SQL funciona de la manera en que lo hace. Por ejemplo, emita una SHOW PROFILE FOR QUERY
consulta nuevamente y verá lo siguiente:
Una parte del resultado de la consulta.SHOW PROFILE FOR QUERY
La fila marcada indica que inmediatamente después de comenzar a ejecutar la consulta, MySQL verifica los permisos. ¿Recuerdas lo que discutimos antes? Debe evitar otorgar privilegios innecesarios precisamente por este motivo: si la cuenta de MySQL a la que se dirige un atacante no tiene suficientes permisos, la consulta fallará. Dado que la funcionalidad de las SHOW PROFILE FOR QUERY
consultas no está dentro del alcance de esta publicación de blog, no vamos a entrar en demasiados detalles aquí, pero puede ver cómo y por qué es importante seguir los consejos anteriores.
La mayoría de los consejos descritos anteriormente también se aplican en el espacio de la base de datos:
Tenga en cuenta los consejos anteriores y debería estar bien encaminado para mitigar los problemas de inyección SQL que podrían afectar a su base de datos ahora o en el futuro.
Como puede ver, la mayoría de los consejos que lo ayudan a proteger sus aplicaciones y bases de datos de la inyección de SQL son bastante generales y directos. Sin embargo, proteger sus bases de datos de la inyección de SQL tampoco es ciencia espacial: tenga en cuenta las pautas que se han descrito anteriormente, ¡y debería estar listo para comenzar!
1656082200
数据库领域的主要问题之一是 SQL 注入——它的普遍程度甚至连OWASP 都将其列为针对 Web 应用程序的第一大威胁。SQL 注入可以有多种类型,其中一种是盲 SQL 注入——在这篇博文中,我们将了解这种攻击的危害有多大。
什么是 SQL 注入?它的类别是什么?
正如我们在之前的一些博客文章中已经告诉您的那样,SQL 注入是针对数据库的主要攻击——当用户提供的输入未经清理和正确地直接转发到数据库时,应用程序很容易受到 SQL 注入的攻击处理。
由于以下几个关键原因,SQL 注入的类别非常重要:
SQL注入有几个类别:
如您所见,SQL 注入的类别并不多——然而,虽然经典 SQL 注入使用最频繁,但当经典 SQL 注入攻击不起作用时,攻击者通常会转向 SQL 的盲区——他们尝试使用盲 SQL 注入攻击应用程序。
SQL盲注王国
将您的应用程序想象成一座城堡。我们知道,这可能看起来至少有点奇怪,但请耐心等待。现在,将您的 Web 应用程序想象成一座城堡。完毕?好吧,想象一下一群拿着长矛的盲人士兵正在攻击它,他们的长矛经常错过城堡的防御工事。你怎么看——拿着长矛的盲人士兵有多少时间来完成你城堡的防御工作?这需要一段时间,但士兵们最终会度过难关。这是真的——一旦士兵通过,你存储在城堡中的宝藏(你的网络应用程序中的数据)就是仙人掌——他们会偷走一切。
士兵装备精良,即使他们是盲人,他们最终也会为你提供防御——哦,不!这就是盲注 SQL 注入在现实世界中的工作方式,让我们再举一个例子:
您可能已经注意到,盲 SQL 注入就是这样一种攻击,它以查询的形式向数据库询问“问题”,并尝试根据 Web 应用程序上的响应来确定它们是真还是假。通过运行如下查询最常检测到 SQL 盲注:
如果 Web 应用程序返回“肯定”响应(意味着它返回网页上的可见差异),则 Web 应用程序容易受到这种攻击,而如果应用程序无动于衷,则可能不会。在第一种情况下,攻击者会知道您的数据库有问题,并试图进一步渗透您的防御。于是游戏开始了——攻击者试图注意到你的 Web 应用程序愿意返回什么样的响应。一个查询返回一个带有结果的页面——好的,他进一步探索,一个查询返回一个空白页面——嗯……他改变了查询并再次尝试。因此,游戏将继续进行,直到从您的数据库中提取了邪恶方感兴趣的所有数据。是的,这样的查询会需要很长时间(这也是盲目 SQL 注入最广为人知的原因之一),但请记住,尽管时间可能很可悲,但可能不会阻止旨在破坏您的系统的攻击者尽可能多地窃取您的所有数据。
一些 Web 应用程序甚至可能过滤 GET 或 POST 参数中的部分,这意味着它们可能“捕获”正在使用的单引号或双引号,但这只是难题的一部分。这样的功能通常是 Web 应用程序防火墙类型功能的一部分——我们已经在我们的另一篇文章中讨论了 WAF(Web 应用程序防火墙的缩写) ,所以我们不会详细介绍,但请记住Web 应用程序防火墙可以抵御从拒绝服务到 SQL 注入等各种攻击。您可以通过访问世界上最大和最快的数据泄露搜索引擎之一 - BreachDirectory 的网站找到 Web 应用程序防火墙的实时示例,但现在,让我们回到主题。
SQL 盲注的类型
有两种类型的盲 SQL 注入——基于布尔值和基于时间。基于布尔的 SQL 盲注依赖于向数据库发送某个 SQL 查询,通过查看应用程序的响应来确定查询是否返回TRUE
结果FALSE
,而基于时间的 SQL 注入依赖于时间——一个查询用于基于盲时间的 SQL 注入的 Web 应用程序将强制数据库在返回响应之前等待几秒钟,如果在指定的确切秒数过去后返回响应,攻击者将能够确定应用程序容易受到盲目的、基于时间的 SQL 注入的影响。以下是这两种类型之间的一些主要区别和相似之处:
防止 SQL 盲注
与普遍的看法相反,防止盲目的 SQL 注入并不需要太多的技巧或努力——可以使用基本的安全措施来防止它。是的,就是这么简单!我们可以通过在 PHP 中使用准备好的数据对象 (PDO) 来实现这一点(它们将用户提供的输入和查询的其余部分分开,因此任何类型的 SQL 注入都是不可能的),通过使用自动测试解决方案来告知我们是否或者我们的应用程序是否容易受到 SQLi 的影响,或者,当然,使用白名单安全控制——作为开发人员,我们应该养成过滤和清理以某种方式与我们的数据交互的每一种参数的习惯。通过这样做,我们可以通过防止各种 SQL 注入攻击和其他类型的安全问题,将我们的 Web 应用程序置于下一个安全级别。
一旦我们将 Web 应用程序置于下一个安全级别,我们也必须注意自己账户的安全——我们可以通过BreachDirectory进行搜索,看看我们的任何账户是否存在风险,并根据给出的建议采取行动给我们。一旦我们这样做了,我们的帐户也应该是安全的。赢——赢!
概括
盲 SQL 注入是一种 SQL 注入,攻击者无法弄清楚我们的 Web 应用程序是如何“思考”的,因此他们必须依赖 Web 应用程序给我们的输出或依赖时间,具体取决于哪种方法(基于布尔值或基于时间)正在使用中。当依赖基于布尔的 SQL 注入时,攻击者依赖于 Web 应用程序可能看起来与平常不同的事实,而在使用基于时间的 SQL 注入时,攻击者严重依赖时间。
无论攻击者选择使用哪种类型的 SQL 注入,都没有一种类型可以为攻击者提供快速获取数据的方法——攻击者实际上可能会花费数小时、数天甚至数月来获取他感兴趣的数据,但一旦攻击成功完成后,通常会在暗网上以数千美元的价格卖给其他不法分子,循环往复。
为了防止盲目的 SQL 注入,请确保采用安全的编码实践,不要将用户输入直接转发到数据库中,并优化 Web 应用程序中错误的返回方式。
此外,请确保通过已知的数据泄露搜索引擎(例如BreachDirectory )运行搜索,以确保您的数据在白天和晚上以及直到下一次都是安全的。下一篇博客见!
来源:https ://betterprogramming.pub/blind-sql-injection-threat-or-childs-play-6080d955a933
1656081660
Một trong những vấn đề chính trong thế giới cơ sở dữ liệu là SQL injection - nó phổ biến đến mức thậm chí OWASP liên tục liệt kê nó là mối đe dọa số 1 nhắm vào các ứng dụng web . SQL injection có thể có nhiều loại và một trong những loại này là mù SQL injection - trong bài đăng trên blog này, chúng ta sẽ xem xét mức độ nguy hại của một cuộc tấn công như vậy.
SQL Injection là gì? Danh mục của nó là gì?
Như chúng tôi đã nói với bạn trong một số bài đăng trước đây của chúng tôi , SQL injection, là cuộc tấn công chính nhắm vào cơ sở dữ liệu - một ứng dụng dễ bị tấn công SQL injection khi một đầu vào do người dùng cung cấp được chuyển tiếp thẳng vào cơ sở dữ liệu mà không được làm sạch và đúng cách xử lý.
Các danh mục của SQL injection rất quan trọng cần hiểu vì một số lý do chính:
SQL injection có một số loại:
Như bạn có thể thấy, không có nhiều danh mục SQL injection thuộc - tuy nhiên, trong khi SQL injection cổ điển đang được sử dụng thường xuyên nhất, khi các cuộc tấn công SQL injection cổ điển không hoạt động, những kẻ tấn công thường chuyển sang mặt mù của SQL - họ cố gắng tấn công các ứng dụng với SQL injection.
Vương quốc mù SQL Injection
Hãy coi ứng dụng của bạn như một lâu đài. Chúng tôi biết, điều này có vẻ hơi kỳ cục một chút, nhưng hãy chịu khó với chúng tôi. Bây giờ, hãy tưởng tượng ứng dụng web của bạn như một lâu đài. Xong? Được rồi, hãy tưởng tượng rằng một đám lính mù với giáo đang tấn công nó và giáo của họ thường xuyên bắn trượt các tuyến phòng thủ kiên cố của lâu đài. Bạn nghĩ sao - những người lính mù cầm giáo có bao nhiêu thời gian để hoàn thành việc phòng thủ lâu đài của bạn? Sẽ mất một lúc, nhưng những người lính cuối cùng sẽ vượt qua được. Đó là sự thật - và một khi những người lính vượt qua, kho báu bạn lưu trữ trong lâu đài của mình (dữ liệu bên trong các ứng dụng web của bạn) là cây xương rồng - chúng sẽ đánh cắp mọi thứ.
Những người lính được trang bị tốt, và mặc dù họ bị mù, nhưng cuối cùng họ vẫn sẽ duy trì được khả năng phòng thủ của bạn - oh, noes! Đó là khá nhiều cách hoạt động của SQL injection trong thế giới thực, vì vậy hãy để chúng tôi cung cấp cho bạn một ví dụ khác:
Như bạn có thể đã nhận thấy, một cuộc tấn công mù mịt SQL là một cuộc tấn công yêu cầu cơ sở dữ liệu "câu hỏi" dưới dạng truy vấn và cố gắng xác định xem chúng đúng hay sai dựa trên phản hồi trên ứng dụng web. Chèn SQL mù thường được phát hiện bằng cách chạy các truy vấn như sau:
Nếu một ứng dụng web trả về phản hồi “tích cực” (có nghĩa là nó trả về sự khác biệt có thể nhìn thấy trên một trang web), ứng dụng web đó dễ bị tấn công như vậy, trong khi nếu một ứng dụng thờ ơ, thì có lẽ là không. Trong trường hợp đầu tiên, kẻ tấn công sẽ biết được điều gì đó xảy ra với cơ sở dữ liệu của bạn và cố gắng thâm nhập sâu hơn vào hệ thống phòng thủ của bạn. Và thế là trò chơi bắt đầu - kẻ tấn công đang cố gắng để ý xem ứng dụng web của bạn sẵn sàng trả lại loại phản hồi nào. Một truy vấn trả về một trang có kết quả - OK, anh ta thăm dò thêm, một truy vấn trả về một trang trống - hmmm… anh ta thay đổi truy vấn và thử lại. Và vì vậy trò chơi tiếp tục cho đến khi tất cả dữ liệu mà một bên bất chính quan tâm được trích xuất từ cơ sở dữ liệu của bạn. Có, kiểu truy vấn như vậy sẽmất nhiều thời gian (và đó là một trong những điều mà người mù SQL injection hầu hết được biết đến), nhưng hãy nhớ rằng thời gian, thật đáng buồn, có lẽ sẽ không ngăn được kẻ tấn công có mục đích làm hại hệ thống của bạn như càng nhiều càng tốt hoặc ăn cắp tất cả dữ liệu của bạn.
Một số ứng dụng web thậm chí có thể lọc các phần trong tham số GET hoặc POST, nghĩa là chúng có thể "bắt" được các dấu ngoặc kép hoặc đơn đang được sử dụng, nhưng đó chỉ là một phần của câu đố. Một chức năng như vậy thường là một phần của loại chức năng của tường lửa ứng dụng web - chúng ta đã thảo luận về WAFs (viết tắt của Web Application Firewalls) trong một bài viết khác của chúng tôi , vì vậy chúng tôi sẽ không đi quá chi tiết, nhưng hãy nhớ rằng tường lửa ứng dụng web ngăn chặn tất cả các loại tấn công từ Từ chối dịch vụ đến, bạn đoán nó, SQL injection. Bạn có thể tìm thấy một ví dụ trực tiếp về tường lửa ứng dụng web bằng cách truy cập trang web của một trong những công cụ tìm kiếm vi phạm dữ liệu lớn nhất và nhanh nhất trên thế giới - BreachDirectory - nhưng bây giờ, hãy quay lại chủ đề.
Các kiểu tiêm SQL mù
Có hai kiểu tiêm SQL mù - dựa trên boolean và dựa trên thời gian. Việc đưa vào SQL mù dựa trên Boolean phụ thuộc vào việc gửi một truy vấn SQL nhất định đến cơ sở dữ liệu để xác định xem truy vấn trả về một TRUE
hoặc FALSE
kết quả bằng cách xem phản hồi của ứng dụng, trong khi SQL injection dựa trên thời gian phụ thuộc vào thời gian - một truy vấn thăm dò ứng dụng web cho việc đưa vào SQL dựa trên thời gian mù sẽ buộc cơ sở dữ liệu đợi vài giây trước khi trả lại phản hồi và nếu phản hồi được trả lại sau khi lượng giây chính xác đã trôi qua, kẻ tấn công sẽ có thể xác định rằng ứng dụng dễ bị tiêm SQL mù, dựa trên thời gian. Dưới đây là một số điểm khác biệt và tương đồng chính giữa hai loại:
Bảo vệ chống lại việc tiêm SQL mù
Bảo vệ khỏi kiểu tiêm SQL mù quáng, trái với suy nghĩ thông thường, không tốn nhiều kỹ năng hoặc nỗ lực - nó có thể được ngăn chặn bằng cách sử dụng các biện pháp bảo mật cơ bản. Vâng, nó đơn giản như vậy! Chúng tôi có thể thực hiện điều đó bằng cách sử dụng Đối tượng dữ liệu chuẩn bị (PDO) trong PHP (chúng chia nhỏ đầu vào do người dùng cung cấp và phần còn lại của truy vấn, do đó bất kỳ loại chèn SQL nào đều không thể thực hiện được), bằng cách sử dụng các giải pháp kiểm tra tự động cho chúng tôi biết liệu hoặc ứng dụng của chúng ta có dễ bị SQLi hay không, hoặc tất nhiên, sử dụng các biện pháp kiểm soát bảo mật trong danh sách trắng - chúng ta, với tư cách là nhà phát triển, nên có thói quen lọc và khử trùng mọi loại tham số bằng cách nào đó tương tác với dữ liệu của chúng ta. Bằng cách đó, chúng tôi có thể đặt các ứng dụng web của mình ở cấp độ bảo mật tiếp theo bằng cách bảo vệ chống lại tất cả các loại tấn công SQL injection và các loại vấn đề bảo mật khác.
Khi chúng tôi đặt các ứng dụng web của mình ở cấp độ bảo mật tiếp theo, chúng tôi cũng phải quan tâm đến tính bảo mật của tài khoản của chính mình - chúng tôi có thể chạy tìm kiếm thông qua BreachDirectory để xem có bất kỳ tài khoản nào của chúng tôi gặp rủi ro hay không và hành động theo lời khuyên được đưa ra cho chúng tôi. Khi chúng tôi làm điều đó, tài khoản của chúng tôi cũng sẽ được bảo mật. Chiến thắng - chiến thắng!
Bản tóm tắt
Blind SQL injection là một loại SQL injection mà kẻ tấn công không thể tìm ra cách các ứng dụng web của chúng ta "suy nghĩ", vì vậy thay vào đó chúng phải dựa vào kết quả mà ứng dụng web cung cấp cho chúng ta hoặc dựa vào thời gian, tùy thuộc vào phương pháp nào (dựa trên boolean hoặc dựa trên thời gian) đang được sử dụng. Khi dựa vào SQL injection dựa trên boolean, kẻ tấn công dựa vào thực tế là ứng dụng web có thể trông khác bình thường, trong khi khi sử dụng SQL injection dựa trên thời gian, kẻ tấn công chủ yếu dựa vào thời gian.
Dù kẻ tấn công chọn loại SQL injection nào, thì không có kiểu nào cung cấp cho kẻ tấn công một cách nhanh chóng để lấy được dữ liệu - kẻ tấn công có thể dành hàng giờ, hàng ngày hoặc thậm chí hàng tháng để thu thập dữ liệu mà anh ta quan tâm, nhưng một khi cuộc tấn công được thực hiện thành công, nó thường sẽ được bán trên dark web với giá hàng nghìn đô la cho các bên bất chính khác và chu kỳ này sẽ tiếp tục.
Để bảo vệ khỏi việc chèn SQL mù, hãy đảm bảo áp dụng các phương pháp mã hóa an toàn, không chuyển tiếp đầu vào của người dùng thẳng vào cơ sở dữ liệu và tinh chỉnh cách trả về lỗi trong các ứng dụng web của bạn.
Ngoài ra, hãy đảm bảo thực hiện tìm kiếm thông qua các công cụ tìm kiếm vi phạm dữ liệu đã biết, chẳng hạn như BreachDirectory để đảm bảo rằng dữ liệu của bạn được an toàn vào ban ngày lẫn ban đêm và cho đến thời gian tiếp theo. Hẹn gặp lại các bạn trong blog tiếp theo!
Nguồn: https://betterprogramming.pub/blind-sql-injection-threat-or-childs-play-6080d955a933
1656081125
Uno de los principales problemas en el mundo de las bases de datos es la inyección de SQL: prevalece hasta tal punto que incluso OWASP la enumera continuamente como la amenaza número 1 dirigida a las aplicaciones web . La inyección de SQL puede tener muchos tipos y uno de estos tipos es la inyección de SQL ciega: en esta publicación de blog, veremos cuán dañino puede ser un ataque de este tipo.
¿Qué es la inyección SQL? ¿Cuáles son sus Categorías?
Como ya le dijimos en algunas de nuestras publicaciones de blog anteriores , la inyección de SQL es el principal ataque dirigido a las bases de datos: una aplicación es vulnerable a la inyección de SQL cuando una entrada proporcionada por un usuario se envía directamente a una base de datos sin ser desinfectada y correctamente tratado.
Es muy importante entender las categorías de inyección SQL por un par de razones clave:
La inyección SQL tiene un par de categorías:
Como puede ver, no hay muchas categorías en las que caiga la inyección de SQL; sin embargo, mientras que la inyección de SQL clásica se usa con más frecuencia, cuando los ataques de inyección de SQL clásicos no funcionan, los atacantes generalmente recurren al lado ciego de SQL: intentan atacando aplicaciones con inyección ciega de SQL.
El Reino de la Inyección SQL Ciega
Think of your application as a castle. We know, this might seem at least a little bit odd, but bear with us. Now, imagine your web application as a castle. Done? Okay, imagine that a bunch of blind soldiers with spears are attacking it and their spears frequently miss the fortified defenses of the castle. What do you think — how much time the blind soldiers with spears have to spare to be done with your castle’s defenses? It will take a while, but the soldiers will eventually get through. That’s true — and once the soldiers get through, the treasures you store in your castle (the data inside of your web applications) are cactus — they will steal everything.
Soldiers are well-equipped, and even though they are blind, they will eventually perpetrate your defenses — oh, noes! That’s pretty much how blind SQL injection works in the real world, so let us give you another example:
As you might already notice, a blind SQL injection is such an attack that asks the database “questions” in a form of queries and tries to determine whether they are true or false based on the response on the web application. Blind SQL injection is most frequently detected by running queries like so:
If a web application returns a “positive” response (meaning that it returns a visible difference on a web page), the web application is susceptible to such an attack, while if an application is indifferent, it is probably not. In the first scenario, the attacker will know something’s up with your database and try to penetrate your defenses even further. And so the game begins — the attacker is trying to notice what kind of responses your web application is willing to return. A query returns a page with results — OK, he probes further, a query returns a blank page — hmmm… he changes the query and tries again. And so the game continues until all data that interests a nefarious party is extracted from your database. Yes, such kind of querying willtomar mucho tiempo (y esa es una de las cosas por las que la inyección ciega de SQL es más conocida), pero tenga en cuenta que el tiempo, por triste que sea, probablemente no detendrá a un atacante que tiene como objetivo dañar sus sistemas como tanto como sea posible o robar todos sus datos.
Some web applications might even filter the parts in GET or POST parameters meaning that they might “catch” single or double quotes being used, but that’s only one piece of the puzzle. Such a function is frequently a part of a web application firewall type of functionality — we have already discussed WAFs (short for Web Application Firewalls) in another article of ours, so we won’t go too much into detail, but keep in mind that web application firewalls deflect all kinds of attacks ranging from Denial of Service to, you guessed it, SQL injection. You can find a live example of a web application firewall by visiting the website of one of the biggest & fastest data breach search engines in the world — BreachDirectory — but for now, let’s get back to the topic.
Types of Blind SQL Injection
Hay dos tipos de inyección SQL ciega: basada en booleanos y basada en el tiempo. La inyección SQL ciega basada en booleanos depende del envío de una determinada consulta SQL a la base de datos para determinar si la consulta devuelve un resultado TRUE
o FALSE
al observar la respuesta de la aplicación, mientras que la inyección SQL basada en el tiempo depende del tiempo: una consulta que prueba un aplicación web para la inyección de SQL basada en tiempo ciego obligará a la base de datos a esperar un par de segundos antes de devolver una respuesta, y si la respuesta se devuelve después de que hayan pasado la cantidad exacta de segundos especificados, el atacante podrá determinar que la aplicación es susceptible a la inyección SQL ciega basada en el tiempo. Aquí hay un par de diferencias y similitudes clave entre los dos tipos:
Protección contra la inyección ciega de SQL
Protecting from a blind type of SQL injection, contrary to popular belief, does not take much skill or effort — it can be prevented using basic security measures. Yes, it’s as simple as that! We can accomplish that by using Prepared Data Objects (PDO) in PHP (they split the input provided by the user and the rest of the query, thus any kind of SQL injection is not possible), by using automated testing solutions that inform us whether or not our application is susceptible to SQLi, or, of course, using whitelist security controls — we, as developers, should have a habit of filtering and sanitizing every kind of parameter that somehow interacts with our data. By doing that we can put our web applications at the next security level both by protecting against all kinds of SQL injection attacks and other types of security issues.
Once we put our web applications at the next level of security, we must take care of the security of our own accounts too — we can run a search through BreachDirectory to see if any of our accounts are at risk and act according to the advice given to us. Once we do that, our accounts should be secure as well. Win — win!
Summary
Blind SQL injection is a type of SQL injection where an attacker cannot figure out how our web applications “think”, so instead they have to rely on the output a web application gives us or rely on time, depending on which method (boolean-based or time-based) is in use. When relying on boolean-based SQL injection, an attacker counts on the fact that the web application might look different than usual, while when using time-based SQL injection, the attacker heavily relies on time.
No matter what type of SQL injection is elected to use by the attacker, no type provides the attacker with a quick way to gain data — an attacker may literally spend hours, days, or even months gaining data of interest to him, but once the attack is successfully accomplished, it will usually be sold on the dark web for thousands of dollars to other nefarious parties, and the cycle will continue.
To protect against blind SQL injection, make sure to employ secure coding practices, do not forward user input straight into a database, and refine how errors are returned in your web applications.
Additionally, make sure to run a search through known data breach search engines such as BreachDirectory to ensure that your data is safe both during the day and the night and until the next time. See you in the next blog!
Fuente: https://betterprogramming.pub/blind-sql-injection-threat-or-childs-play-6080d955a933
1656080949
L'injection SQL est l'un des principaux problèmes dans le monde des bases de données. Elle est si répandue que même l'OWASP la classe en permanence comme la menace n°1 ciblant les applications Web . L'injection SQL peut avoir plusieurs types et l'un de ces types est l'injection SQL aveugle - dans cet article de blog, nous verrons à quel point une telle attaque peut être nocive.
Qu'est-ce que l'Injection SQL ? Quelles sont ses catégories ?
Comme nous vous l'avons déjà dit dans certains de nos articles de blog précédents , l'injection SQL est la principale attaque dirigée contre les bases de données - une application est vulnérable à l'injection SQL lorsqu'une entrée fournie par un utilisateur est transmise directement dans une base de données sans être nettoyée et correctement traité.
Les catégories d'injection SQL sont très importantes à comprendre pour deux raisons principales :
L'injection SQL a deux catégories :
Comme vous pouvez le voir, il n'y a pas beaucoup de catégories dans lesquelles l'injection SQL tombe - cependant, alors que l'injection SQL classique est utilisée le plus fréquemment, lorsque les attaques par injection SQL classiques ne fonctionnent pas, les attaquants se tournent généralement vers le côté aveugle de SQL - ils essaient attaquer les applications avec une injection SQL aveugle.
Le royaume de l'injection SQL aveugle
Considérez votre application comme un château. Nous savons que cela peut sembler au moins un peu étrange, mais soyez patient. Maintenant, imaginez votre application Web comme un château. Fait? D'accord, imaginez qu'un groupe de soldats aveugles avec des lances l'attaquent et que leurs lances manquent fréquemment les défenses fortifiées du château. Que pensez-vous - combien de temps les soldats aveugles avec des lances doivent-ils consacrer pour en finir avec les défenses de votre château ? Cela prendra du temps, mais les soldats finiront par passer. C'est vrai - et une fois que les soldats sont passés, les trésors que vous stockez dans votre château (les données à l'intérieur de vos applications Web) sont des cactus - ils voleront tout.
Les soldats sont bien équipés, et même s'ils sont aveugles, ils finiront par perpétrer vos défenses - oh, non ! C'est à peu près comme ça que l'injection SQL aveugle fonctionne dans le monde réel, alors laissez-nous vous donner un autre exemple :
Comme vous l'avez peut-être déjà remarqué, une injection SQL aveugle est une telle attaque qui pose des « questions » à la base de données sous forme de requêtes et tente de déterminer si elles sont vraies ou fausses en fonction de la réponse sur l'application Web. L'injection SQL aveugle est le plus souvent détectée en exécutant des requêtes telles que :
Si une application Web renvoie une réponse "positive" (ce qui signifie qu'elle renvoie une différence visible sur une page Web), l'application Web est susceptible d'une telle attaque, alors que si une application est indifférente, elle ne l'est probablement pas. Dans le premier scénario, l'attaquant saura que quelque chose ne va pas avec votre base de données et tentera de pénétrer encore plus loin vos défenses. Et ainsi le jeu commence - l'attaquant essaie de remarquer quel type de réponses votre application Web est prête à renvoyer. Une requête renvoie une page avec des résultats - OK, il sonde plus loin, une requête renvoie une page vierge - hmmm… il modifie la requête et essaie à nouveau. Et ainsi le jeu continue jusqu'à ce que toutes les données qui intéressent une partie infâme soient extraites de votre base de données. Oui, ce type de requête seraprendre beaucoup de temps (et c'est l'une des choses pour lesquelles l'injection SQL aveugle est surtout connue), mais gardez à l'esprit que le temps, aussi triste que cela puisse être, n'arrêtera probablement pas un attaquant qui a pour objectif de nuire à vos systèmes comme autant que possible ou voler toutes vos données.
Certaines applications Web peuvent même filtrer les parties des paramètres GET ou POST, ce qui signifie qu'elles peuvent "attraper" les guillemets simples ou doubles utilisés, mais ce n'est qu'une pièce du puzzle. Une telle fonction fait souvent partie d'une fonctionnalité de type pare-feu d'application Web - nous avons déjà discuté des WAF (abréviation de Web Application Firewalls) dans un autre de nos articles , nous n'entrerons donc pas trop dans les détails, mais gardez à l'esprit que Les pare-feu d'applications Web dévient toutes sortes d'attaques allant du déni de service à, vous l'aurez deviné, l'injection SQL. Vous pouvez trouver un exemple concret de pare-feu d'application Web en visitant le site Web de l'un des moteurs de recherche de violation de données les plus importants et les plus rapides au monde - BreachDirectory - mais pour l'instant, revenons au sujet.
Types d'injection SQL aveugle
Il existe deux types d'injection SQL aveugle - basée sur les booléens et basée sur le temps. L'injection SQL aveugle basée sur les booléens dépend de l'envoi d'une certaine requête SQL à la base de données pour déterminer si la requête renvoie un résultat TRUE
ou FALSE
en examinant la réponse de l'application, tandis que l'injection SQL basée sur le temps dépend du temps - une requête sondant un l'application Web pour l'injection SQL basée sur le temps aveugle forcera la base de données à attendre quelques secondes avant de renvoyer une réponse, et si la réponse est renvoyée après le nombre exact de secondes spécifiées, l'attaquant pourra déterminer que l'application est sensible à l'injection SQL aveugle basée sur le temps. Voici quelques différences et similitudes clés entre les deux types :
Protection contre l'injection SQL aveugle
La protection contre un type aveugle d'injection SQL, contrairement à la croyance populaire, ne demande pas beaucoup de compétences ou d'efforts - elle peut être évitée en utilisant des mesures de sécurité de base. Oui, c'est aussi simple que ça ! Nous pouvons accomplir cela en utilisant des objets de données préparés (PDO) en PHP (ils divisent l'entrée fournie par l'utilisateur et le reste de la requête, donc tout type d'injection SQL n'est pas possible), en utilisant des solutions de test automatisées qui nous informent si ou non, notre application est sensible à SQLi, ou, bien sûr, en utilisant des contrôles de sécurité de liste blanche - nous, en tant que développeurs, devrions avoir l'habitude de filtrer et de nettoyer tous les types de paramètres qui interagissent d'une manière ou d'une autre avec nos données. Ce faisant, nous pouvons placer nos applications Web au niveau de sécurité supérieur, à la fois en les protégeant contre toutes sortes d'attaques par injection SQL et d'autres types de problèmes de sécurité.
Une fois que nous avons mis nos applications Web au niveau de sécurité supérieur, nous devons également prendre soin de la sécurité de nos propres comptes - nous pouvons lancer une recherche via BreachDirectory pour voir si l'un de nos comptes est à risque et agir selon les conseils donnés à nous. Une fois que nous aurons fait cela, nos comptes devraient également être sécurisés. Gagner - gagner !
Sommaire
L'injection SQL aveugle est un type d'injection SQL où un attaquant ne peut pas comprendre comment nos applications Web "pensent", donc à la place, ils doivent s'appuyer sur la sortie qu'une application Web nous donne ou compter sur le temps, selon la méthode (booléenne ou basé sur le temps) est en cours d'utilisation. Lorsqu'il s'appuie sur l'injection SQL basée sur les booléens, un attaquant compte sur le fait que l'application Web peut sembler différente de la normale, tandis qu'en utilisant l'injection SQL basée sur le temps, l'attaquant s'appuie fortement sur le temps.
Quel que soit le type d'injection SQL choisi par l'attaquant, aucun type ne fournit à l'attaquant un moyen rapide d'obtenir des données - un attaquant peut littéralement passer des heures, des jours, voire des mois à obtenir des données qui l'intéressent, mais une fois que le l'attaque est accomplie avec succès, elle sera généralement vendue sur le dark web pour des milliers de dollars à d'autres parties infâmes, et le cycle se poursuivra.
Pour vous protéger contre l'injection SQL aveugle, veillez à utiliser des pratiques de codage sécurisées, à ne pas transférer les entrées utilisateur directement dans une base de données et à affiner la manière dont les erreurs sont renvoyées dans vos applications Web.
De plus, assurez-vous d'effectuer une recherche dans les moteurs de recherche de violation de données connus tels que BreachDirectory pour vous assurer que vos données sont en sécurité de jour comme de nuit et jusqu'à la prochaine fois. A bientôt dans le prochain blog !
Source : https://betterprogramming.pub/blind-sql-injection-threat-or-childs-play-6080d955a933
1656080820
データベースの世界における主要な問題の1つは、SQLインジェクションです。これは、OWASPでさえ、Webアプリケーションを標的とする最大の脅威として継続的にリストされているほどに蔓延しています。SQLインジェクションには多くの種類があり、そのうちの1つがブラインドSQLインジェクションです。このブログ投稿では、このような攻撃がどれほど有害であるかについて説明します。
SQLインジェクションとは何ですか?そのカテゴリーは何ですか?
以前のブログ投稿のいくつかですでに説明したように、SQLインジェクションはデータベースに向けられた主な攻撃です。ユーザーから提供された入力がサニタイズされて適切にデータベースに転送されない場合、アプリケーションはSQLインジェクションに対して脆弱です。対処しました。
SQLインジェクションのカテゴリは、いくつかの重要な理由から理解することが非常に重要です。
SQLインジェクションには、次の2つのカテゴリがあります。
ご覧のとおり、SQLインジェクションに該当するカテゴリはそれほど多くありませんが、従来のSQLインジェクションが最も頻繁に使用されていますが、従来のSQLインジェクション攻撃が機能しない場合、攻撃者は通常SQLのブラインドサイドに目を向けます。ブラインドSQLインジェクションでアプリケーションを攻撃します。
ブラインドSQLインジェクションの王国
アプリケーションを城と考えてください。これは少なくとも少し奇妙に思えるかもしれませんが、我慢してください。ここで、Webアプリケーションを城として想像してください。終わり?さて、槍を持った盲目の兵士の束がそれを攻撃していて、彼らの槍が城の要塞化された防御をしばしば逃していると想像してください。あなたはどう思いますか—槍を持った盲目の兵士があなたの城の防御を行うためにどれくらいの時間を割く必要がありますか?しばらく時間がかかりますが、兵士たちはやがて通り抜けます。それは本当です—そして兵士が通り抜けると、あなたがあなたの城に保存する宝物(あなたのウェブアプリケーション内のデータ)はサボテンです—彼らはすべてを盗みます。
兵士は設備が整っており、盲目であっても、最終的には防御を実行します—ああ、いや!これは、現実の世界でブラインドSQLインジェクションがどのように機能するかとほぼ同じなので、別の例を挙げましょう。
すでにお気づきかもしれませんが、ブラインドSQLインジェクションは、データベースにクエリの形式で「質問」を求め、Webアプリケーションの応答に基づいてそれらが真か偽かを判断しようとする攻撃です。ブラインドSQLインジェクションは、次のようなクエリを実行することで最も頻繁に検出されます。
Webアプリケーションが「肯定的な」応答を返す場合(つまり、Webページで目に見える違いを返す場合)、Webアプリケーションはそのような攻撃を受けやすくなりますが、アプリケーションが無関心である場合は、おそらくそうではありません。最初のシナリオでは、攻撃者はデータベースに問題があることを認識し、防御をさらに突破しようとします。そして、ゲームが始まります—攻撃者は、Webアプリケーションがどのような応答を返すかを認識しようとしています。クエリは結果のあるページを返します— OK、彼はさらに調査し、クエリは空白のページを返します—うーん…彼はクエリを変更して再試行します。そのため、悪意のある当事者が関心を持つすべてのデータがデータベースから抽出されるまで、ゲームは続行されます。はい、そのような種類のクエリは長い時間がかかります(これは、ブラインドSQLインジェクションが最もよく知られていることの1つです)が、悲しいことに、システムに危害を加えることを目的とした攻撃者を阻止することはできないことを覚えておいてください。可能な限り、またはすべてのデータを盗みます。
一部のWebアプリケーションは、GETまたはPOSTパラメーターでパーツをフィルター処理する場合もあります。これは、使用されている一重引用符または二重引用符を「キャッチ」する可能性があることを意味しますが、これはパズルの1つのピースにすぎません。このような機能は、多くの場合、Webアプリケーションファイアウォールタイプの機能の一部です。WAF(Webアプリケーションファイアウォールの略)については、別の記事ですでに説明しているので、あまり詳しくは説明しませんが、次の点に注意してください。 Webアプリケーションファイアウォールは、サービス拒否からSQLインジェクションに至るまで、あらゆる種類の攻撃を阻止します。世界で最大かつ最速のデータ侵害検索エンジンの1つであるBreachDirectoryのWebサイトにアクセスすると、Webアプリケーションファイアウォールの実例を見つけることができますが、今のところ、トピックに戻りましょう。
ブラインドSQLインジェクションの種類
ブラインドSQLインジェクションには、ブールベースと時間ベースの2種類があります。ブールベースのブラインドSQLインジェクションは、特定のSQLクエリをデータベースに送信して、クエリがアプリケーションの応答を調べて結果を返すかどうかを判断することに依存していTRUE
ますFALSE
。一方、時間ベースのSQLインジェクションは、時間に依存しています。ブラインドタイムベースのSQLインジェクション用のWebアプリケーションは、応答を返す前にデータベースを数秒待機させます。指定された正確な秒数が経過した後に応答が返された場合、攻撃者はアプリケーションがアプリケーションであると判断できます。ブラインドの時間ベースのSQLインジェクションの影響を受けやすい。2つのタイプの主な違いと類似点は次のとおりです。
ブラインドSQLインジェクションからの保護
ブラインドタイプのSQLインジェクションからの保護は、一般的な信念に反して、多くのスキルや労力を必要としません。基本的なセキュリティ対策を使用して防ぐことができます。はい、それはそれと同じくらい簡単です!PHPでPreparedDataObjects(PDO)を使用することで(ユーザーから提供された入力とクエリの残りの部分を分割するため、どのような種類のSQLインジェクションも不可能です)、自動テストソリューションを使用してそれを実現できます。アプリケーションがSQLiの影響を受けやすいかどうか、またはもちろん、ホワイトリストセキュリティコントロールを使用します。開発者として、データと何らかの形で相互作用するあらゆる種類のパラメータをフィルタリングおよびサニタイズする習慣が必要です。そうすることで、あらゆる種類のSQLインジェクション攻撃やその他の種類のセキュリティ問題から保護することで、Webアプリケーションを次のセキュリティレベルに置くことができます。
Webアプリケーションを次のレベルのセキュリティに設定したら、自分のアカウントのセキュリティにも注意を払う必要があります。BreachDirectoryを検索して、アカウントが危険にさらされているかどうかを確認し、与えられたアドバイスに従って行動することができます。私たちに。そうすれば、アカウントも安全になります。勝つ—勝つ!
概要
ブラインドSQLインジェクションはSQLインジェクションの一種であり、攻撃者はWebアプリケーションがどのように「考える」かを理解できないため、代わりに、Webアプリケーションが提供する出力に依存するか、どちらの方法に応じて時間に依存する必要があります(ブールベースまたは時間ベース)が使用されています。ブールベースのSQLインジェクションに依存する場合、攻撃者はWebアプリケーションが通常とは異なって見える可能性があるという事実を信頼しますが、時間ベースのSQLインジェクションを使用する場合、攻撃者は時間に大きく依存します。
攻撃者が使用するSQLインジェクションのタイプに関係なく、データを取得するための迅速な方法を攻撃者に提供するタイプはありません。攻撃者は、文字通り数時間、数日、さらには数か月かけて関心のあるデータを取得する可能性があります。攻撃は成功裏に達成され、通常はダークウェブで数千ドルで他の悪意のある当事者に販売され、このサイクルが続きます。
ブラインドSQLインジェクションから保護するために、安全なコーディング手法を採用し、ユーザー入力をデータベースに直接転送しないようにし、Webアプリケーションでエラーが返される方法を改善してください。
さらに、 BreachDirectoryなどの既知のデータ侵害検索エンジンを介して検索を実行し、昼夜を問わず、次回までデータが安全であることを確認してください。次のブログでお会いしましょう!
ソース:https ://betterprogramming.pub/blind-sql-injection-threat-or-childs-play-6080d955a933
1656080667
Um dos principais problemas no mundo do banco de dados é a injeção de SQL — ela é tão prevalente que até mesmo o OWASP a lista continuamente como a ameaça nº 1 direcionada a aplicativos da web . A injeção de SQL pode ter muitos tipos e um desses tipos é a injeção de SQL cega – nesta postagem do blog, veremos o quão prejudicial esse ataque pode ser.
O que é injeção de SQL? Quais são suas categorias?
Como já dissemos em alguns de nossos posts anteriores , a injeção de SQL é o principal ataque direcionado a bancos de dados — um aplicativo é vulnerável à injeção de SQL quando uma entrada fornecida por um usuário é encaminhada diretamente para um banco de dados sem ser higienizada e adequadamente tratado.
As categorias de injeção de SQL são muito importantes para entender por causa de alguns motivos principais:
A injeção de SQL tem algumas categorias:
As you can see, there are not that many categories SQL injection falls under — however, while classic SQL injection is being used the most frequently, when classic SQL injection attacks do not work, attackers usually turn to the blind side of SQL — they try attacking applications with blind SQL injection.
The Kingdom of Blind SQL Injection
Think of your application as a castle. We know, this might seem at least a little bit odd, but bear with us. Now, imagine your web application as a castle. Done? Okay, imagine that a bunch of blind soldiers with spears are attacking it and their spears frequently miss the fortified defenses of the castle. What do you think — how much time the blind soldiers with spears have to spare to be done with your castle’s defenses? It will take a while, but the soldiers will eventually get through. That’s true — and once the soldiers get through, the treasures you store in your castle (the data inside of your web applications) are cactus — they will steal everything.
Soldiers are well-equipped, and even though they are blind, they will eventually perpetrate your defenses — oh, noes! That’s pretty much how blind SQL injection works in the real world, so let us give you another example:
As you might already notice, a blind SQL injection is such an attack that asks the database “questions” in a form of queries and tries to determine whether they are true or false based on the response on the web application. Blind SQL injection is most frequently detected by running queries like so:
If a web application returns a “positive” response (meaning that it returns a visible difference on a web page), the web application is susceptible to such an attack, while if an application is indifferent, it is probably not. In the first scenario, the attacker will know something’s up with your database and try to penetrate your defenses even further. And so the game begins — the attacker is trying to notice what kind of responses your web application is willing to return. A query returns a page with results — OK, he probes further, a query returns a blank page — hmmm… he changes the query and tries again. And so the game continues until all data that interests a nefarious party is extracted from your database. Yes, such kind of querying will take a long time (and that’s one of the things blind SQL injection is mostly known for), but keep in mind that time, as sad as it might be, probably won’t stop an attacker that has an aim to harm your systems as much as possible or steal all of your data.
Some web applications might even filter the parts in GET or POST parameters meaning that they might “catch” single or double quotes being used, but that’s only one piece of the puzzle. Such a function is frequently a part of a web application firewall type of functionality — we have already discussed WAFs (short for Web Application Firewalls) in another article of ours, so we won’t go too much into detail, but keep in mind that web application firewalls deflect all kinds of attacks ranging from Denial of Service to, you guessed it, SQL injection. You can find a live example of a web application firewall by visiting the website of one of the biggest & fastest data breach search engines in the world — BreachDirectory — but for now, let’s get back to the topic.
Types of Blind SQL Injection
There are two types of blind SQL injection — boolean-based and time-based. Boolean-based blind SQL injection is reliant on sending a certain SQL query to the database to determine whether the query returns a TRUE
or FALSE
result by looking at the response of the application, while time-based SQL injection is reliant on time – a query probing a web application for blind time-based SQL injection will force the database to wait a couple of seconds before returning a response, and if the response is returned after the exact amount of specified seconds have passed, the attacker will be able to determine that the application is susceptible to blind, time-based SQL injection. Here are a couple of key differences and similarities between the two types:
Protecting Against Blind SQL Injection
Protecting from a blind type of SQL injection, contrary to popular belief, does not take much skill or effort — it can be prevented using basic security measures. Yes, it’s as simple as that! We can accomplish that by using Prepared Data Objects (PDO) in PHP (they split the input provided by the user and the rest of the query, thus any kind of SQL injection is not possible), by using automated testing solutions that inform us whether or not our application is susceptible to SQLi, or, of course, using whitelist security controls — we, as developers, should have a habit of filtering and sanitizing every kind of parameter that somehow interacts with our data. By doing that we can put our web applications at the next security level both by protecting against all kinds of SQL injection attacks and other types of security issues.
Once we put our web applications at the next level of security, we must take care of the security of our own accounts too — we can run a search through BreachDirectory to see if any of our accounts are at risk and act according to the advice given to us. Once we do that, our accounts should be secure as well. Win — win!
Summary
Blind SQL injection is a type of SQL injection where an attacker cannot figure out how our web applications “think”, so instead they have to rely on the output a web application gives us or rely on time, depending on which method (boolean-based or time-based) is in use. When relying on boolean-based SQL injection, an attacker counts on the fact that the web application might look different than usual, while when using time-based SQL injection, the attacker heavily relies on time.
No matter what type of SQL injection is elected to use by the attacker, no type provides the attacker with a quick way to gain data — an attacker may literally spend hours, days, or even months gaining data of interest to him, but once the attack is successfully accomplished, it will usually be sold on the dark web for thousands of dollars to other nefarious parties, and the cycle will continue.
To protect against blind SQL injection, make sure to employ secure coding practices, do not forward user input straight into a database, and refine how errors are returned in your web applications.
Additionally, make sure to run a search through known data breach search engines such as BreachDirectory to ensure that your data is safe both during the day and the night and until the next time. See you in the next blog!
Fonte: https://betterprogramming.pub/blind-sql-injection-threat-or-childs-play-6080d955a933
#sql
1656071340
处理 Web 应用程序的开发人员看到了许多威胁到他们构建的东西的东西。其中一些包括针对人的攻击(例如,社会工程),其中一些攻击(DoS 或 DDoS 攻击、跨站点脚本、跨站点请求伪造、身份验证损坏、敏感数据暴露、访问控制损坏、不安全反序列化等)针对 Web 应用程序的部分。但是,一些攻击主要针对您的数据库和存储在其中的数据——其中一种攻击是 SQL 注入(简称 SQLi)。在这篇博文中,我们将研究这种攻击可能产生的影响。
SQL 注入是一种经常针对 Web 应用程序的攻击。这种攻击的目的经常是从数据库中窃取敏感数据并将其用于攻击者的个人利益。这种攻击如此普遍和危险,正是因为许多开发人员在创建面向 Web 的公共解决方案时忽略了安全性的重要性。当安全漏洞被忽视时,恶意方通常会发现并利用它们。这些邪恶的行为者利用这些漏洞,因为他们可以通过出售在违规期间被盗的数据获利。
这种攻击的影响取决于您的 Web 应用程序。假设您的应用程序不存储敏感信息,在这种情况下,攻击可能不会产生任何深远的后果。但是,如果不是这种情况,您的手上可能会遇到严重问题——敏感数据可能会被盗并出售以获取利润,由于重设密码和在其他地方更改信息的压力,会给您的业务和客户带来不必要的问题。
SQL 注入的概念非常简单:这种攻击之所以有效,是因为一些开发人员将用户在给定输入字段中写入的所有内容放入查询中并将其传递给数据库。易受攻击的基本代码片段如下所示(您也可以使用 $_GET 代替 $_POST,前提是相同的):
$Input = $_POST['input'];
SELECT * FROM demo_table WHERE column [= | < | > | <= | >= | LIKE ...] '$Input';
如您所见,在某些情况下,易受攻击的代码非常简单(它也可能变得复杂,我们稍后会进入不同的场景)——然后攻击者经常使用引号字符 (') 来利用这些易受攻击的代码诱发错误。一旦它引发错误,攻击者就知道代码易受攻击,他们可以攻击我们的应用程序。
SQL 注入攻击分为几类:
攻击者使用上面列出的每种类型来实现不同的目标——如果攻击者对系统的内部工作有一些隐含的了解,经典的 SQL 注入很有用,如果攻击者结合了几个结果,则基于联合的 SQL 注入可能很有用将SELECT
语句放入单个结果集中,当应用程序“静默”时使用基于错误的 SQL 注入(这意味着它不返回任何响应,因此攻击者在发出某些类型的查询时会寻找功能更改)
至此,您应该对什么是 SQL 注入以及它的类型有一个很好的了解,但是如何保护您的应用程序免受此类攻击呢?值得庆幸的是,有几种众所周知的方法可以降低现在或将来利用此类漏洞的风险:
/* Prepare MySQL statement */if (!($statement = $mysqli->prepare( "SELECT customerID FROM orders WHERE item = ?" ))) { echo "Failed: (" . $mysqli->errno . ") " . $mysqli->error;}/* Bind variables to statement as parameters using bind_param().The type (first) parameter can take integers (i), doubles (d), strings(s), and blobs (b).*/$purchasedItem = 'ice cream';if (!$statement->bind_param("s", $purchasedItem)) { echo "Failed: (" . $statement->errno . ") " . $statement->error;}/* Execute prepared MySQL statement */if (!$statement->execute()) { echo "Failed: (" . $statement->errno . ") " . $statement->error;}
牢记这些要点应该有助于让您的应用程序顺利运行。
使用准备好的语句,使用 MySQL 提供的以安全为中心的插件,避免授予不必要的管理权限,并考虑其他上述预防措施,应该让您和您的数据库走上一条良好的道路。但是,如果您想更深入地研究 MySQL 并了解 SQL 查询的工作方式以及为什么使用例如 Web 应用程序防火墙 (WAF) 可以保护您免受包括 SQL 注入在内的多种攻击,请考虑以下几点:
SHOW PROFILE FOR QUERY [query id here];
如果使用得当,在大多数情况下,输出将为您提供查询所做的事情和任务的持续时间。您还将能够观察到许多有趣的事情,包括获得以下问题的答案:
这些问题的一些答案可能会帮助您理解为什么 SQL 注入会以这种方式工作。例如,SHOW PROFILE FOR QUERY
再次发出查询,您将看到以下内容:
查询输出的一部分SHOW PROFILE FOR QUERY
标记的行表示在开始运行查询后,MySQL 会立即检查权限。还记得我们之前讨论过的吗?正是出于这个原因,您应该避免授予不必要的权限——如果攻击者所针对的 MySQL 帐户没有足够的权限,则查询将失败。由于SHOW PROFILE FOR QUERY
查询的功能不在本博文的范围内,因此我们不会在此详细介绍,但您可以了解遵循上述建议的方式和原因很重要。
上面列出的大多数建议也适用于数据库空间:
考虑到上面的建议,您应该可以很好地缓解现在或将来可能会影响您的数据库的 SQL 注入问题。
正如您可能会说的,大多数帮助您保护应用程序和数据库免受 SQL 注入攻击的建议都非常笼统和直接。但是,保护您的数据库免受 SQL 注入也不是火箭科学——请牢记上面概述的指导方针,您应该一切顺利!
1656070508
Các nhà phát triển xử lý các ứng dụng web thấy rất nhiều thứ đe dọa làm tổn hại đến những thứ họ xây dựng. Một số trong số những điều này bao gồm các cuộc tấn công nhắm mục tiêu vào mọi người (ví dụ: kỹ thuật xã hội), một số trong số các cuộc tấn công này (tấn công DoS hoặc DDoS, Tập lệnh chéo trang, Giả mạo yêu cầu chéo trang, Xác thực bị hỏng, Tiếp xúc dữ liệu nhạy cảm, Kiểm soát truy cập bị hỏng, Không an toàn Deserialization, v.v.) nhắm mục tiêu các phần của ứng dụng web. Tuy nhiên, một số cuộc tấn công chủ yếu nhắm vào cơ sở dữ liệu của bạn và dữ liệu được lưu trữ ở đó — một trong những cuộc tấn công như vậy là SQL injection (viết tắt là SQLi). Trong bài đăng trên blog này, chúng ta sẽ xem xét những tác động mà một cuộc tấn công như vậy có thể gây ra.
SQL injection là một cuộc tấn công thường nhắm vào các ứng dụng web. Mục đích của một cuộc tấn công như vậy thường xuyên là để lấy dữ liệu nhạy cảm khỏi cơ sở dữ liệu và sử dụng nó cho lợi ích cá nhân của kẻ tấn công. Một cuộc tấn công như vậy rất phổ biến và nguy hiểm bởi vì nhiều nhà phát triển bỏ qua tầm quan trọng của bảo mật khi tạo ra các giải pháp công khai trên web. Khi các lỗ hổng bảo mật bị bỏ qua, các bên độc hại thường tìm ra và khai thác chúng. Những kẻ bất chính này khai thác các lỗ hổng như vậy vì họ có thể kiếm lợi từ việc bán dữ liệu bị đánh cắp trong quá trình vi phạm.
Tác động của một cuộc tấn công như vậy phụ thuộc vào ứng dụng web của bạn. Giả sử ứng dụng của bạn không lưu trữ thông tin nhạy cảm, trong trường hợp đó, cuộc tấn công có thể sẽ không gây ra bất kỳ hậu quả sâu rộng nào. Tuy nhiên, nếu không phải vậy, bạn có thể gặp phải vấn đề nghiêm trọng — dữ liệu nhạy cảm có thể bị đánh cắp và bán ra để thu lợi, gây ra các vấn đề cho doanh nghiệp của bạn và các vấn đề không cần thiết cho khách hàng của bạn do quá căng thẳng khi đặt lại mật khẩu và thay đổi thông tin ở nơi khác.
Khái niệm về SQL injection khá đơn giản: một cuộc tấn công như vậy hoạt động bởi vì một số nhà phát triển đưa mọi thứ mà người dùng viết trong một trường đầu vào nhất định vào một truy vấn và chuyển nó vào cơ sở dữ liệu. Đoạn mã cơ bản của mã dễ bị tấn công sẽ trông giống như sau (bạn cũng có thể sử dụng $ _GET thay vì $ _POST, tiền đề giống nhau):
$Input = $_POST['input'];
SELECT * FROM demo_table WHERE column [= | < | > | <= | >= | LIKE ...] '$Input';
Như bạn có thể thấy, trong một số trường hợp, mã dễ bị tấn công khá đơn giản (nó cũng có thể trở nên phức tạp, chúng ta sẽ đi vào các tình huống khác nhau sau) - mã dễ bị tấn công sau đó bị những kẻ tấn công thường xuyên sử dụng ký tự trích dẫn (') để gây ra lỗi. Khi nó gây ra lỗi, những kẻ tấn công biết mã dễ bị tấn công và chúng có thể tấn công các ứng dụng của chúng tôi.
Có một số loại mà các cuộc tấn công SQL injection nằm trong:
Những kẻ tấn công sử dụng từng kiểu được nêu ở trên để thực hiện các mục tiêu khác nhau - SQL injection cổ điển rất hữu ích nếu kẻ tấn công có một số kiến thức ngụ ý về hoạt động bên trong của hệ thống, SQL injection dựa trên liên minh có thể hữu ích nếu kẻ tấn công kết hợp các kết quả của một vài của các SELECT
câu lệnh vào một tập kết quả duy nhất, việc chèn SQL dựa trên lỗi được sử dụng khi ứng dụng "im lặng" (có nghĩa là nó không trả về bất kỳ phản hồi nào, vì vậy kẻ tấn công tìm kiếm các thay đổi chức năng khi đưa ra một số loại truy vấn)
Tại thời điểm này, bạn đã hiểu khá rõ về SQL injection là gì và các kiểu của nó, nhưng làm cách nào để bạn bảo vệ các ứng dụng của mình khỏi một cuộc tấn công như vậy? Rất may, có một số cách nổi tiếng để giảm nguy cơ bị khai thác lỗ hổng bảo mật như vậy ở hiện tại hoặc trong tương lai:
/* Prepare MySQL statement */
if (!($statement = $mysqli->prepare(
"SELECT customerID
FROM orders
WHERE item = ?"
))) {
echo "Failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/*
Bind variables to statement as parameters using bind_param().
The type (first) parameter can take integers (i), doubles (d),
strings(s), and blobs (b).
*/
$purchasedItem = 'ice cream';
if (!$statement->bind_param("s", $purchasedItem)) {
echo "Failed: (" . $statement->errno . ") " . $statement->error;
}
/* Execute prepared MySQL statement */
if (!$statement->execute()) {
echo "Failed: (" . $statement->errno . ") " . $statement->error;
}
Hãy ghi nhớ những điểm này sẽ giúp ứng dụng của bạn luôn hoạt động tốt.
Sử dụng các câu lệnh đã chuẩn bị sẵn, sử dụng các plugin tập trung vào bảo mật do MySQL cung cấp, tránh cấp các đặc quyền quản trị không cần thiết và tính đến các biện pháp phòng ngừa đã đề cập ở trên sẽ giúp bạn và cơ sở dữ liệu của bạn có một con đường tốt. Tuy nhiên, nếu bạn muốn tìm hiểu sâu hơn về MySQL và hiểu tại sao các truy vấn SQL hoạt động theo cách chúng làm và tại sao việc sử dụng, ví dụ: tường lửa ứng dụng web (WAF) có thể bảo vệ bạn chống lại nhiều loại tấn công, bao gồm cả SQL injection, hãy xem xét điều này:
SHOW PROFILE FOR QUERY [query id here];
Nếu được sử dụng đúng cách, trong hầu hết các trường hợp, đầu ra sẽ cung cấp cho bạn những gì truy vấn đã làm và thời lượng của tác vụ. Bạn cũng sẽ có thể quan sát thấy nhiều điều thú vị, bao gồm cả việc nhận được câu trả lời cho những câu hỏi như:
Một số câu trả lời cho những câu hỏi này có thể giúp bạn hiểu tại sao SQL injection lại hoạt động theo cách mà nó hoạt động. Ví dụ: đưa ra một SHOW PROFILE FOR QUERY
truy vấn một lần nữa và bạn sẽ thấy như sau:
Một phần của đầu ra cho truy vấnSHOW PROFILE FOR QUERY
Hàng được đánh dấu cho biết rằng ngay sau khi bắt đầu chạy truy vấn, MySQL sẽ kiểm tra quyền. Nhớ những gì chúng ta đã thảo luận trước đó? Bạn nên tránh cấp các đặc quyền không cần thiết vì lý do này - nếu tài khoản MySQL mà kẻ tấn công đang nhắm mục tiêu không có đủ quyền, truy vấn sẽ không thành công. Vì chức năng của các SHOW PROFILE FOR QUERY
truy vấn không nằm trong phạm vi trong bài đăng blog này, chúng tôi sẽ không đi vào quá nhiều chi tiết ở đây, nhưng bạn có thể thấy cách thức và lý do tại sao việc làm theo lời khuyên ở trên là quan trọng.
Hầu hết các lời khuyên nêu trên cũng có thể áp dụng trong không gian cơ sở dữ liệu:
Hãy tính đến những lời khuyên ở trên và bạn sẽ đi đúng hướng để giảm thiểu các sự cố chèn SQL có thể tấn công cơ sở dữ liệu của bạn ngay bây giờ hoặc trong tương lai.
Như bạn có thể nói, hầu hết các lời khuyên giúp bạn bảo mật các ứng dụng và cơ sở dữ liệu của mình khỏi SQL injection là khá chung chung và đơn giản. Tuy nhiên, việc bảo vệ cơ sở dữ liệu của bạn khỏi SQL injection cũng không phải là khoa học tên lửa - hãy ghi nhớ các nguyên tắc đã nêu ở trên và bạn nên thực hiện!