└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # SQL-Injection-attacks 2 | SQL Injection attack is the most common website hacking technique. Most websites use Structured Query Language (SQL) to interact with databases. SQL allows the website to create, retrieve, update, and delete database records. It used for everything from logging a user into the website to storing details of an eCommerce transaction. An SQL injection attack places SQL into a web form in an attempt to get the application to run it. For example, instead of typing plain text into a username or password field, a hacker may type in ‘ OR 1=1. If the application appends this string directly to an SQL command that is designed to check if a user exists in the database, it will always return true. This can allow a hacker to gain access to a restricted section of a website. Other SQL injection attacks can be used to delete data from the database or insert new data. Hackers sometimes use automated tools to perform SQL injections on remote websites. They will scan thousands of websites, testing many types of injection attacks until they are successful. SQL injection attacks can be prevented by correctly filtering user input. Most programming languages have special functions to safely handle user input that is going to be used in an SQL query. 3 | 4 | 5 |
6 |
7 |

SQL (Structured query language) Injection

8 |
9 | 324.3k views 10 |
11 | 12 | App SecurityThreats 13 |
23 |
24 |
25 |
26 |

What is SQL injection

27 |

SQL injection, also known as SQLI, is a common attack vector that uses malicious SQL code for backend database manipulation to access information that was not intended to be displayed. This information may include any number of items, including sensitive company data, user lists or private customer details.

28 |

The impact SQL injection can have on a business is far-reaching. A successful attack may result in the unauthorized viewing of user lists, the deletion of entire tables and, in certain cases, the attacker gaining administrative rights to a database, all of which are highly detrimental to a business.

29 |

When calculating the potential cost of an SQLi, it’s important to consider the loss of customer trust should personal information such as phone numbers, addresses, and credit card details be stolen.

30 |

While this vector can be used to attack any SQL database, websites are the most frequent targets.

31 |

What are SQL queries

32 |

SQL is a standardized language used to access and manipulate databases to build customizable data views for each user. SQL queries are used to execute commands, such as data retrieval, updates, and record removal. Different SQL elements implement these tasks, e.g., queries using the SELECT statement to retrieve data, based on user-provided parameters.

33 |

A typical eStore’s SQL database query may look like the following:

34 |
SELECT ItemName, ItemDescription
 35 | FROM Item
 36 | WHERE ItemNumber = ItemNumber
37 |

From this, the web application builds a string query that is sent to the database as a single SQL statement:

38 |
sql_query= "
 39 | SELECT ItemName, ItemDescription
 40 | FROM Item
 41 | WHERE ItemNumber = " & Request.QueryString("ItemID")
42 |

A user-provided input http://www.estore.com/items/items.asp?itemid=999 can then generates the following SQL query:

43 |
SELECT ItemName, ItemDescription
 44 | FROM Item
 45 | WHERE ItemNumber = 999
46 |

As you can gather from the syntax, this query provides the name and description for item number 999.

47 |

Types of SQL Injections

48 |

SQL injections typically fall under three categories: In-band SQLi (Classic), Inferential SQLi (Blind) and Out-of-band SQLi. You can classify SQL injections types based on the methods they use to access backend data and their damage potential.

49 |

In-band SQLi

50 |

The attacker uses the same channel of communication to launch their attacks and to gather their results. In-band SQLi’s simplicity and efficiency make it one of the most common types of SQLi attack. There are two sub-variations of this method:

51 | 55 |

Inferential (Blind) SQLi

56 |

The attacker sends data payloads to the server and observes the response and behavior of the server to learn more about its structure. This method is called blind SQLi because the data is not transferred from the website database to the attacker, thus the attacker cannot see information about the attack in-band.

57 |

Blind SQL injections rely on the response and behavioral patterns of the server so they are typically slower to execute but may be just as harmful. Blind SQL injections can be classified as follows:

58 | 62 |

Out-of-band SQLi

63 |

The attacker can only carry out this form of attack when certain features are enabled on the database server used by the web application. This form of attack is primarily used as an alternative to the in-band and inferential SQLi techniques.

64 |

Out-of-band SQLi is performed when the attacker can’t use the same channel to launch the attack and gather information, or when a server is too slow or unstable for these actions to be performed. These techniques count on the capacity of the server to create DNS or HTTP requests to transfer data to an attacker.

65 |

SQL injection example

66 |

An attacker wishing to execute SQL injection manipulates a standard SQL query to exploit non-validated input vulnerabilities in a database. There are many ways that this attack vector can be executed, several of which will be shown here to provide you with a general idea about how SQLI works.

67 |

For example, the above-mentioned input, which pulls information for a specific product, can be altered to read http://www.estore.com/items/items.asp?itemid=999 or 1=1.

68 |

As a result, the corresponding SQL query looks like this:

69 |
SELECT ItemName, ItemDescription
 70 | FROM Items
 71 | WHERE ItemNumber = 999 OR 1=1
72 |

And since the statement 1 = 1 is always true, the query returns all of the product names and descriptions in the database, even those that you may not be eligible to access.

73 |

Attackers are also able to take advantage of incorrectly filtered characters to alter SQL commands, including using a semicolon to separate two fields.

74 |

For example, this input http://www.estore.com/items/iteams.asp?itemid=999; DROP TABLE Users would generate the following SQL query:

75 |
SELECT ItemName, ItemDescription
 76 | FROM Items
 77 | WHERE ItemNumber = 999; DROP TABLE USERS
78 |

As a result, the entire user database could be deleted.

79 |

Another way SQL queries can be manipulated is with a UNION SELECT statement. This combines two unrelated SELECT queries to retrieve data from different database tables.

80 |

For example, the input http://www.estore.com/items/items.asp?itemid=999 UNION SELECT user-name, password FROM USERS produces the following SQL query:

81 |
SELECT ItemName, ItemDescription
 82 | FROM Items
 83 | WHERE ItemID = '999' UNION SELECT Username, Password FROM Users;
84 |

Using the UNION SELECT statement, this query combines the request for item 999’s name and description with another that pulls names and passwords for every user in the database.

85 |

SQL injection combined with OS Command Execution: The Accellion Attack

86 |

Accellion, maker of File Transfer Appliance (FTA), a network device widely deployed in organizations around the world, and used to move large, sensitive files. The product is over 20 years old and is now at end of life.

87 |

FTA was the subject of a unique, highly sophisticated attack combining SQL injection with operating system command execution. Experts speculate the Accellion attack was carried out by hackers with connections to the financial crimes group FIN11, and ransomware group Clop.

88 |

The attack demonstrates that SQL injection is not just an attack that affects web applications or web services, but can also be used to compromise back-end systems and exfiltrate data.

89 |

Who was affected by the attack?

90 |

The Accellion exploit is a supply chain attack, affecting numerous organizations that had deployed the FTA device. These included the Reserve Bank of New Zealand, the State of Washington, the Australian Securities and Investments Commission, telecommunication giant Singtel, and security software maker Qualys, as well as numerous others.

91 |

Accelion Attack flow

92 |

According to a report commissioned by Accellion, the combination SQLi and command execution attack worked as follows:

93 |
    94 |
  1. Attackers performed SQL Injection to gain access to document_root.html, and retrieved encryption keys from the Accellion FTA database.
  2. 95 |
  3. Attackers used the keys to generate valid tokens, and used these tokens to gain access to additional files
  4. 96 |
  5. Attackers exploited an operating system command execution flaw in the sftp_account_edit.php file, allowing them to execute their own commands
  6. 97 |
  7. Attackers created a web shell in the server path /home/seos/courier/oauth.api
  8. 98 |
  9. Using this web shell, they uploaded a custom, full-featured web shell to disk, which included highly customized tooling for exfiltration of data from the Accellion system. The researchers named this shell DEWMODE.
  10. 99 |
  11. Using DEWMODE, the attackers extracted a list of available files from a MySQL database on the Accellion FTA system, and listed files and their metadata on an HTML page
  12. 100 |
  13. The attackers performed file download requests, which contained requests to the DEWMODE component, with encrypted and encoded URL parameters.
  14. 101 |
  15. DEWMODE is able to accept these requests and then delete the download requests from the FTA web logs.
  16. 102 |
103 |

This raises the profile of SQL injection attacks, showing how they can be used as a gateway for a much more damaging attack on critical corporate infrastructure.

104 |

SQLI prevention and mitigation

105 |

There are several effective ways to prevent SQLI attacks from taking place, as well as protecting against them, should they occur.

106 |

The first step is input validation (a.k.a. sanitization), which is the practice of writing code that can identify illegitimate user inputs.

107 |

While input validation should always be considered best practice, it is rarely a foolproof solution. The reality is that, in most cases, it is simply not feasible to map out all legal and illegal inputs—at least not without causing a large number of false positives, which interfere with user experience and an application’s functionality.

108 |

For this reason, a web application firewall (WAF) is commonly employed to filter out SQLI, as well as other online threats. To do so, a WAF typically relies on a large, and constantly updated, list of meticulously crafted signatures that allow it to surgically weed out malicious SQL queries. Usually, such a list holds signatures to address specific attack vectors and is regularly patched to introduce blocking rules for newly discovered vulnerabilities.

109 |

Modern web application firewalls are also often integrated with other security solutions. From these, a WAF can receive additional information that further augments its security capabilities.

110 |

For example, a web application firewall that encounters a suspicious, but not outright malicious input may cross-verify it with IP data before deciding to block the request. It only blocks the input if the IP itself has a bad reputational history.

111 |

Imperva cloud-based WAF uses signature recognition, IP reputation, and other security methodologies to identify and block SQL injections, with a minimal amount of false positives. The WAF’s capabilities are augmented by IncapRules—a custom security rule engine that enables granular customization of default security settings and the creation of additional case-specific security policies.

112 |

Our WAF also employs crowdsourcing techniques that ensure that new threats targeting any user are immediately propagated across the entire user-base. This enables rapid response to newly disclosed vulnerability and zero-day threats.

113 |

Adding Data-Centric Protection for Defense in Depth

118 |

The optimal defense is a layered approach that includes data-centric strategies that focus on protecting the data itself, as well as the network and applications around it. Imperva Database Security continuously discovers and classifies sensitive data to identify how much sensitive data there is, where it is stored, and whether it’s protected.

119 |

In addition, Imperva Database Security actively monitors data access activity to identify any data access behavior that is a risk or violates policy, regardless of whether it originates with a network SQL query, a compromised user account, or a malicious insider. Receive automatic notification of a security event so you can respond quickly with security analytics that provides a clear explanation of the threat and enables immediate initiation of the response process, all from a single platform.

120 |

Database security is a critical last line of defense to preventing hacks like SQLi. Imperva’s unique approach to protecting data encompasses a complete view of both the web application and data layer.

121 |
122 |
123 | 124 |
125 | 126 |

SQL injection

127 | 128 | 129 |

130 | In this section, we'll explain what SQL injection (SQLi) is, describe some common examples, explain how to find and exploit various kinds of SQL injection vulnerabilities, and summarize how to prevent SQL injection. 131 |

132 | SQL injection 133 | 140 |

What is SQL injection (SQLi)?

141 |
142 |
143 |

144 | SQL injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. It generally allows an attacker to view data that they are not normally able to retrieve. This might include data belonging to other users, or any other data that the application itself is able to access. In many cases, an attacker can modify or delete this data, causing persistent changes to the application's content or behavior. 145 |

146 |

147 | In some situations, an attacker can escalate an SQL injection attack to compromise the underlying server or other back-end infrastructure, or perform a denial-of-service attack. 148 |

149 |
150 |
151 |
152 |

What is the impact of a successful SQL injection attack?

153 |

154 | A successful SQL injection attack can result in unauthorized access to sensitive data, such as passwords, credit card details, or personal user information. Many high-profile data breaches in recent years have been the result of SQL injection attacks, leading to reputational damage and regulatory fines. In some cases, an attacker can obtain a persistent backdoor into an organization's systems, leading to a long-term compromise that can go unnoticed for an extended period. 155 |

156 |

SQL injection examples

157 |

158 | There are a wide variety of SQL injection vulnerabilities, attacks, and techniques, which arise in different situations. Some common SQL injection examples include: 159 |

160 | 167 |

Retrieving hidden data

168 |

169 | Consider a shopping application that displays products in different categories. When the user clicks on the Gifts category, their browser requests the URL: 170 |

171 | https://insecure-website.com/products?category=Gifts 172 |

173 | This causes the application to make an SQL query to retrieve details of the relevant products from the database: 174 |

175 | SELECT * FROM products WHERE category = 'Gifts' AND released = 1 176 |

177 | This SQL query asks the database to return: 178 |

179 | 193 |

194 | The restriction released = 1 is being used to hide products that are not released. For unreleased products, presumably released = 0. 195 |

196 |

197 | The application doesn't implement any defenses against SQL injection attacks, so an attacker can construct an attack like: 198 |

199 | https://insecure-website.com/products?category=Gifts'-- 200 |

201 | This results in the SQL query: 202 |

203 | SELECT * FROM products WHERE category = 'Gifts'--' AND released = 1 204 |

205 | The key thing here is that the double-dash sequence -- is a comment indicator in SQL, and means that the rest of the query is interpreted as a comment. This effectively removes the remainder of the query, so it no longer includes AND released = 1. This means that all products are displayed, including unreleased products. 206 |

207 |

208 | Going further, an attacker can cause the application to display all the products in any category, including categories that they don't know about: 209 |

210 | https://insecure-website.com/products?category=Gifts'+OR+1=1-- 211 |

212 | This results in the SQL query: 213 |

214 | SELECT * FROM products WHERE category = 'Gifts' OR 1=1--' AND released = 1 215 |

216 | The modified query will return all items where either the category is Gifts, or 1 is equal to 1. Since 1=1 is always true, the query will return all items. 217 |

218 | 219 | 220 | 227 | 228 |

Subverting application logic

229 |

230 | Consider an application that lets users log in with a username and password. If a user submits the username wiener and the password bluecheese, the application checks the credentials by performing the following SQL query: 231 |

232 | SELECT * FROM users WHERE username = 'wiener' AND password = 'bluecheese' 233 |

234 | If the query returns the details of a user, then the login is successful. Otherwise, it is rejected. 235 |

236 |

237 | Here, an attacker can log in as any user without a password simply by using the SQL comment sequence -- to remove the password check from the WHERE clause of the query. For example, submitting the username administrator'-- and a blank password results in the following query: 238 |

239 | SELECT * FROM users WHERE username = 'administrator'--' AND password = '' 240 |

241 | This query returns the user whose username is administrator and successfully logs the attacker in as that user. 242 |

243 | 244 | 245 | 252 | 253 |

Retrieving data from other database tables

254 |

255 | In cases where the results of an SQL query are returned within the application's responses, an attacker can leverage an SQL injection vulnerability to retrieve data from other tables within the database. This is done using the UNION keyword, which lets you execute an additional SELECT query and append the results to the original query. 256 |

257 |

258 | For example, if an application executes the following query containing the user input "Gifts": 259 |

260 | SELECT name, description FROM products WHERE category = 'Gifts' 261 |

262 | then an attacker can submit the input: 263 |

264 | ' UNION SELECT username, password FROM users-- 265 |

266 | This will cause the application to return all usernames and passwords along with the names and descriptions of products. 267 |

268 | 272 |

Examining the database

273 |

274 | Following initial identification of an SQL injection vulnerability, it is generally useful to obtain some information about the database itself. This information can often pave the way for further exploitation. 275 |

276 |

277 | You can query the version details for the database. The way that this is done depends on the database type, so you can infer the database type from whichever technique works. For example, on Oracle you can execute: 278 |

279 | SELECT * FROM v$version 280 |

281 | You can also determine what database tables exist, and which columns they contain. For example, on most databases you can execute the following query to list the tables: 282 |

283 | SELECT * FROM information_schema.tables 284 | 288 |

Blind SQL injection vulnerabilities

289 |

290 | Many instances of SQL injection are blind vulnerabilities. This means that the application does not return the results of the SQL query or the details of any database errors within its responses. Blind vulnerabilities can still be exploited to access unauthorized data, but the techniques involved are generally more complicated and difficult to perform. 291 |

292 |

293 | Depending on the nature of the vulnerability and the database involved, the following techniques can be used to exploit blind SQL injection vulnerabilities: 294 |

295 | 306 | 310 |

How to detect SQL injection vulnerabilities

311 |

312 | The majority of SQL injection vulnerabilities can be found quickly and reliably using Burp Suite's web vulnerability scanner. 313 |

314 |

315 | SQL injection can be detected manually by using a systematic set of tests against every entry point in the application. This typically involves: 316 |

317 | 334 |

SQL injection in different parts of the query

335 |

336 | Most SQL injection vulnerabilities arise within the WHERE clause of a SELECT query. This type of SQL injection is generally well-understood by experienced testers. 337 |

338 |

339 | But SQL injection vulnerabilities can in principle occur at any location within the query, and within different query types. The most common other locations where SQL injection arises are: 340 |

341 | 355 |

Second-order SQL injection

356 |

357 | First-order SQL injection arises where the application takes user input from an HTTP request and, in the course of processing that request, incorporates the input into an SQL query in an unsafe way. 358 |

359 |

360 | In second-order SQL injection (also known as stored SQL injection), the application takes user input from an HTTP request and stores it for future use. This is usually done by placing the input into a database, but no vulnerability arises at the point where the data is stored. Later, when handling a different HTTP request, the application retrieves the stored data and incorporates it into an SQL query in an unsafe way. 361 |

362 | Second-order SQL injection 363 |

364 | Second-order SQL injection often arises in situations where developers are aware of SQL injection vulnerabilities, and so safely handle the initial placement of the input into the database. When the data is later processed, it is deemed to be safe, since it was previously placed into the database safely. At this point, the data is handled in an unsafe way, because the developer wrongly deems it to be trusted. 365 |

366 |

Database-specific factors

367 |

368 | Some core features of the SQL language are implemented in the same way across popular database platforms, and so many ways of detecting and exploiting SQL injection vulnerabilities work identically on different types of database. 369 |

370 |

371 | However, there are also many differences between common databases. These mean that some techniques for detecting and exploiting SQL injection work differently on different platforms. For example: 372 |

373 | 390 | 394 |

How to prevent SQL injection

395 |

396 | Most instances of SQL injection can be prevented by using parameterized queries (also known as prepared statements) instead of string concatenation within the query. 397 |

398 |

399 | The following code is vulnerable to SQL injection because the user input is concatenated directly into the query: 400 |

401 | String query = "SELECT * FROM products WHERE category = '"+ input + "'"; 402 | Statement statement = connection.createStatement(); 403 | ResultSet resultSet = statement.executeQuery(query); 404 |

405 | This code can be easily rewritten in a way that prevents the user input from interfering with the query structure: 406 |

407 | PreparedStatement statement = connection.prepareStatement("SELECT * FROM products WHERE category = ?"); 408 | statement.setString(1, input); 409 | ResultSet resultSet = statement.executeQuery(); 410 |

411 | Parameterized queries can be used for any situation where untrusted input appears as data within the query, including the WHERE clause and values in an INSERT or UPDATE statement. They can't be used to handle untrusted input in other parts of the query, such as table or column names, or the ORDER BY clause. Application functionality that places untrusted data into those parts of the query will need to take a different approach, such as white-listing permitted input values, or using different logic to deliver the required behavior. 412 |

413 |

414 | For a parameterized query to be effective in preventing SQL injection, the string that is used in the query must always be a hard-coded constant, and must never contain any variable data from any origin. Do not be tempted to decide case-by-case whether an item of data is trusted, and continue using string concatenation within the query for cases that are considered safe. It is all too easy to make mistakes about the possible origin of data, or for changes in other code to violate assumptions about what data is tainted. 415 |

416 | 420 |
421 | --------------------------------------------------------------------------------