What is SQL injection?

The number of sites and pages on the Web is growing steadily. Everyone who can can take on development. And novice web programmers very often use unsafe and old code. And this creates a lot of loopholes for attackers and hackers. What they use. One of the most classic vulnerabilities is SQL injection.

Bit of theory

Many people know that most sites and services on the network use SQL databases to store. This is such a structured query language that allows you to manage and administer data warehouses. Many different versions of database management systems are known - Oracle, MySQL, Postgre. Regardless of the name and type, they use data queries the same way. This is where potential vulnerability lies. If the developer was unable to correctly and safely process the request, then the attacker can take advantage of this and use special tactics to gain access to the database, and from there to manage the entire site.

sql injection

To avoid such situations, you need to correctly optimize the code and carefully monitor which request is processed in what way.

SQL injection check

To establish the presence of vulnerabilities in the network, there are a lot of ready-made automated software systems. But you can carry out a simple check manually. To do this, go to one of the sites under study and in the address bar try to cause a database error. For example, a script on a site may not process requests or crop them.

For example, there is a certain_site / index.php? Id = 25

The easiest way is to put a quotation mark after 25 and send a request. If no error has occurred, then either all requests are filtered on the site and processed correctly, or their output is disabled in the settings. If the page reloads with problems, then there is a vulnerability for SQL injection.

After it is discovered, you can try to get rid of it.

To implement this vulnerability, you need to know a little about SQL query commands. One of them is UNION. It combines multiple query results into one. So you can calculate the number of fields in the table. An example of the first request looks like this:

  • some_site / index.php? id = 25 UNION SELECT 1.

In most cases, such a record should throw an error. This means that the number of fields is not equal to 1. Thus, choosing options from 1 or more, you can set their exact number:

  • some_site / index.php? id = 25 UNION SELECT 1,2,3,4,5,6.

That is, when the error ceases to appear, then the number of fields is guessed.

There is also an alternative solution to this problem. For example, when the number of fields is large - 30, 60 or 100. This is a GROUP BY command. It groups the results of the query according to some characteristic, for example id:

  • some_site / index.php? id = 25 GROUP BY 5.

If no errors were received, then there are more than 5 fields. Thus, substituting options from a rather wide range, we can calculate how many of them actually are.

This example of SQL injection is for beginners who want to try their hand at testing their site. It is important to remember that for unauthorized access to someone else there is an article of the Criminal Code.

The main types of injections

There are several options for implementing vulnerabilities through SQL injection. The following are the most popular techniques:

  • UNION query SQL injection. A simple example of this type has already been discussed above. It is implemented due to an error in checking incoming data, which are not filtered in any way.

  • Error-based SQL injection. As the name implies, this type also uses errors, sending expressions made syntactically incorrectly. Then the response headers are intercepted, analyzing which, you can subsequently conduct SQL injection.

  • Stacked queries SQL injection. This vulnerability is determined by serial requests. It is characterized by the addition at the end of the “;” sign. This approach is often implemented to access the implementation of reading and writing data, or to control the functions of the operating system, if privileges allow it.

Software packages for searching for SQL vulnerabilities

Available for SQL injection, programs usually have two components - scanning the site for possible vulnerabilities and using them to gain access to data. There are such utilities for almost all known platforms. Their functionality greatly facilitates checking the site for the possibility of hacking by SQL injection.

Sqlmap

A very powerful scanner that works with most well-known DBMSs. It supports various techniques for implementing SQL injection. It has the ability to automatically recognize the type of password hash and crack it in the dictionary. There is also a functionality for downloading and uploading files from the server.

sql injection

Installing in a Linux environment is done using the following commands:

  • git clone https://github.com/sqlmapproject/sqlmap.git sqlmap-dev,
  • cdsqlmap-dev /,
  • ./sqlmap.py --wizard.

check for sql injection

For Windows, there is both a command line option and a graphical user interface.

jSQL injection

jSQL Injection is a cross-platform tool for testing the use of SQL vulnerabilities. It is written in Java, so a JRE must be installed on the system. Able to handle GET, POST, header, cookie requests. It has a convenient graphical interface.

The installation of this software package is as follows:

wget https://github.com/`curl -s https: //github.com/ron190/jsql-injection/releases | grep-E -o '/ron190/jsql-injection/releases/download/v[0-9-03{1,2►.0-0-9{{1,2►/jsql-injection-v[0-9] {1,2}. [0-9] {1,2} .jar '| head-n 1`

sql injection hack

The launch is done using the java -jar ./jsql-injection-v*.jar command

In order to start checking the site for SQL vulnerability, you need to enter its address in the upper field. They are separate for GET and for POST. If the result is positive, a list of available tables will appear in the left window. You can view them and find out some confidential information.

To search for administrative panels, use the “Admin page” tab. Using special templates, it automatically searches for system records of privileged users. From them you can get just a password hash. But he is also in the toolkit of the program.

how to make sql injection

After finding all the vulnerabilities and injecting the necessary requests, the utility will allow you to upload your file to the server or, conversely, download it from there.

SQLi Dumper v.7

This program is an easy-to-use tool for finding and implementing vulnerabilities in SQL. UN produces this on the basis of the so-called dorks. Their lists can be found on the Internet. SQL injection paths are special search query patterns. With their help, you can find a potentially vulnerable site through any search engine.

Training tools

Itsecgames.com has a special toolkit that allows you to use an example to show how to do SQL injection and test it. In order to use it, you need to download and install it. The archive contains a set of files, which is the structure of the site. To install it, you will need the Apache, MySQL and PHP web server package available in the system.

protection against sql php injection

After unpacking the archive into the web server folder, you need to go to the address entered during the installation of this software product. The user registration page will open. Here you need to enter your data and click "Create". Transferring the user to a new window, the system will prompt you to select one of the test options. Among them there are both described injections, and many other test tasks.

It is worth considering an example of SQL injection like GET / Search. Here you need to select it and click "Hack". The user will see a search bar and an imitation of a certain site with movies. You can sort through movies for a long time. But there are only 10. For example, you can try to introduce Iron Man. A movie will be displayed, which means that the site is working and there are tables in it. Now we need to check whether the script filters special characters, in particular the quotation mark. To do this, add '”to the address bar. Moreover, this must be done after the name of the film. The site will throw an error Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%' 'at line 1, which states that characters are still not processed correctly. So, you can try to substitute your request. But you must first calculate the number of fields. To do this, use order by, which is entered after the quotation mark: http://testsites.com/sqli_1.php?title=Iron+Man 'order by 2 - & action = search.

This command simply displays information about the movie, that is, the number of fields is greater than 2. A double hyphen tells the server that the remaining requests need to be dropped. Now we need to sort through, substituting all the larger values ​​until an error is displayed. As a result, it turns out that there will be 7 fields.

sql injection example

Now it's time to get something useful from the database. You’ll have to modify the request in the address bar a bit, making it look like this: http://testsites.com/sqli_1.php?title=Iron+Man 'union select 1, database (), user (), 4, password, 6, 7 from users - & action = search. As a result of its execution, lines with password hashes will be displayed, which can be easily turned into understandable characters using one of the online services. And having conjured a little and picking up the name of the field with the login, you can get access to someone else's record, for example, the site admin.

There are many varieties of types of injections in the product that you can practice. It is worth remembering that the use of these skills on the network, on real sites, can be criminally punishable.

Injection and PHP

As a rule, it is the PHP code that is responsible for the necessary processing of requests coming from the user. Therefore, it is at this level that you need to build protection against SQL injection in PHP.

To begin with, it is worth giving a few simple recommendations on the basis of which you need to do this.

  • Data should always be processed before being placed in the database. This can be implemented either using existing expressions, or by organizing queries manually. It is also worth considering here that numerical values ​​are converted to the type that is needed;
  • Avoid the appearance of various control structures in the request.

Now a little about the rules for compiling queries in MySQL to protect against SQL injection.

When creating any query expressions, it is important to separate the data from the SQL keywords.

  • SELECT * FROM table WHERE name = Zerg.

In this design, the system might think that Zerg is the name of a field, so you need to enclose it in quotation marks.

  • SELECT * FROM table WHERE name = 'Zerg'.

However, there are situations where the value itself contains quotation marks.

  • SELECT * FROM table WHERE name = 'Cote d'Ivoire'.

Here only part of the cat is processed, and the rest can be perceived as a team, which, of course, does not exist. Therefore, an error will occur. So you need to screen this kind of data. To do this, use the backslash - \.

  • SELECT * FROM table WHERE name = 'cat d \' ivory '.

All of the above apply to strings. If an action occurs with a number, then it does not need any quotation marks or slashes. However, they must be forced to lead to the required data type.

There is a recommendation that a field name should be enclosed in a quotation mark. This symbol is located on the left side of the keyboard, along with the tilde “~”. This is necessary so that MySQL can accurately distinguish the name of the field from its keyword.

Dynamic data handling

Very often, queries generated dynamically are used to get any data from the database. For instance:

  • SELECT * FROM table WHERE number = '$ number'.

Here the $ number variable is passed as the definition of the field value. What will happen if a cat-d'ivoire gets into it? Error.

To avoid this trouble, of course, you can enable the "magic quotes" in the settings. But now the data will be shielded where necessary and not necessary. In addition, if the code is written manually, then you can spend a little more time creating a system resistant to hacking yourself.

You can use mysql_real_escape_string to add a slash yourself.

$ number = mysql_real_escape_string ($ number);

$ year = mysql_real_escape_string ($ year);

$ query = "INSERT INTO table (number, year, class) VALUES ('$ number', '$ year', 11)".

Although the code has grown in volume, still, potentially it will work much safer.

Placeholders

Placeholders are unique markers by which the system recognizes that a special function needs to be substituted in this place. For instance:

$ sate = $ mysqli-> prepare ("SELECT District FROM Number WHERE Name =?");

$ sate-> bind_param ("s", $ number);

$ sate-> execute ();

This section of code prepares the request template, then binds the variable number, and executes it. This approach allows us to separate request processing and its implementation. Thus, you can protect yourself from using malicious code injection in SQL queries.

What can an attacker do

System protection is a very important factor that should not be neglected. Of course, a simple business card site will be easier to recover. And if it is a large portal, service, forum? What consequences can be if you do not think about security?

Firstly, a hacker can violate both the integrity of the database and delete it entirely. And if the site administrator or hoster did not make a backup, then it will be hard. In addition, an attacker who breaks into one site can go to others hosted on the same server.

Next is the theft of personal data of visitors. How to use them - everything is limited only by the hacker's imagination. But in any case, the consequences will not be very pleasant. Especially if financial information was contained.

Also, an attacker can drain the base for himself, and then extort money for its return.

Misinformation of users on behalf of the site administrator, who is not a person, can also have negative consequences, as fraud is possible.

Conclusion

All information in this article is provided for informational purposes only. You need to use it only for testing your own projects when vulnerabilities are detected and resolved.

For a more in-depth study of the methodology of how to conduct SQL injection, you need to start by actually exploring the capabilities and features of the SQL language. How queries, keywords, data types, and the application of all this are compiled.

Also, one cannot do without understanding the operation of PHP functions and HTML elements. The main vulnerable points for using injections are the address bar, search, and various fields. Studying the functions of PHP, the way they are implemented and their capabilities will help you understand how errors can be avoided.

The presence of many ready-made software tools allows you to conduct a deep analysis of the site for known vulnerabilities. One of the most popular products is kali linux. This is an image of a Linux-based operating system, which contains a large number of utilities and programs that can conduct a comprehensive analysis of the site for durability.

Why do I need to know how to hack a site? Everything is very simple - this is necessary in order to have an idea of ​​the potential vulnerabilities of your project or site. Especially if it’s any online store with the ability to pay online, where the user's payment data can be compromised by an attacker.

For professional research, there are information security services that can check the site for different criteria and depth. From simple HTML injection to social engineering and phishing.

Source: https://habr.com/ru/post/K16163/


All Articles