KyberSwap’s $47M Reentrancy Attack: A Deep Dive into the Exploit
Let’s take a closer look inside a $47M reentrancy attack on KyberSwap.
🇺🇦 Hacken stands with Ukraine!Learn more
How we would like to start this topic, perhaps with the fact that this is the most critical vulnerability and what it will cost for a webapp, business, brand. In the professional cybersecurity world, this vulnerability is considered the most critical according to OWASP Top10.
Nowadays, more and more people worry about their personal data and how the companies use this data when asked to enter their personal data in registration forms. In this regard, a large number of organizations and rules for the use of personal data have appeared. We mean GDPR and CCPA, which control how companies protect users’ data.
For example, companies that violate the GDPR will have to pay 4% of the annual turnover. Having carried out a small mathematical calculation on financial losses, we will receive such data:
A company with an annual turnover of $10M will have to pay a fine of $400K, but nothing beats more than the loss of trust on the part of users who entrusted their data to this company.
152 million EUROS was lost by top 5 global companies in 2019, and these are only the loudest fines that were brought to the public. As for companies that did not have high ratings or were narrow-profile, such fines bankrupted their business. In this article, we will reveal the secret of how hackers gain access to customer databases and bring this information to the public. Therefore, the authorities controlling violations in this area easily find such companies and bring them to administrative responsibility. Both hackers and the state have their own interest in disclosing information or infringement. Everything except the business, which will suffer losses.
The conclusion is to make a regular Pentest, to participate in Bug Bounty programs, which always causes a positive result for business owners and clients, and that it is 10 times cheaper than paying a fine and getting a hit on your reputation that will be difficult to return.
According to Wikipedia, Structured Query Language is a domain-specific language used in programming and designed for managing data held in a relational database management system (RDBMS), or for stream processing in a relational data stream management system (RDSMS). It is particularly useful in handling structured data, i.e. data incorporating relations among entities and variables.
SQL offers two main advantages over older read-write APIs such as ISAM or VSAM. Firstly, it introduced the concept of accessing many records with one single command. Secondly, it eliminates the need to specify how to reach a record, e.g. with or without an index.
Some common SQL injection examples include: Retrieving hidden data, where you can modify an SQL query to return additional results. Subverting application logic, where you can change a query to interfere with the application’s logic. UNION attacks, where you can retrieve data from different database tables.
Besides above, what is meant by SQL injection (SQLi)? It is a type of security exploit in which the attacker adds Structured Query Language code to a Web form input box in order to gain access to unauthorized resources or make changes to sensitive data. An SQL query is a request for some action to be performed on a database.
SQL queries work by interacting with data in the database through the use of statements. The SELECT statement is used to retrieve data, so a login query would be:
SELECT username, password FROM users WHERE username='myname' AND password='mypassword';
Let’s look at the classic SQL injection command ‘ or 1=1–. Here is what the SQL statement is when entered into the login field:
SELECT username, password FROM users WHERE username='' or 1=1-- AND password='';
The single quote effectively turns the first part into a blank string, and 1=1 always evaluates to true, so the username query will now run as “blank” or “true”. The double dashes comment out the rest of the query so the password field is ignored. Since “blank” or “true” is always true, and the password field is ignored, the database will return account data.
What can attackers do? Here are some examples:
Dynamic SQL gives us the ability to insert variables into SQL at runtime, which allows us to perform tasks that would otherwise be time consuming or inefficient. This type of attack makes it a valuable tool, but its users should make sure that each of these variables is properly cleared before use.
Such an attack makes it possible to obtain a list of usernames, tables, passwords, credit card data, addresses, phone numbers, in general, everything that this database can store. Usernames can be used to log in, steal client funds, gain full access to a client’s account, and block users.
URL Strings Modification
Most websites are protected against this these days, and URL cracking is one of the most popular ways to get access to data. This way is difficult to detect, doesn’t require big knowledge, and the determination of success or failure occurs almost immediately.
Consider an example where a URL contains search strings, security descriptors, or other sensitive components, the application must validate the contents of the URL before processing them. The app must hide any content in the URL that could be used to retrieve unwanted information about the app.
Keeping and monitoring web logs can be challenging but can give essential understanding of areas in which hackers are attempting to maliciously gain access to a given site. Data from these logs can provide us with advance notice of possible attacks and itemized information on how they are performed.
Web and Application Forms
Special attention should be paid to any place where the user enters web form data. This is the source of most of the SQL injection attacks. Hackers enter every odd combination of characters, or data lengths in an attempt to trigger an error or unexpected behavior.
It is difficult for us to accept the fact that an internal employee can be a potential attacker. A login with limited access to the server can use SQL injection to get extra access that is usually not allowed.
SQL injection protection eliminates the possibility of attacks and protects the organization from the inside.
In a modern world, where attacks like social engineering, phishing, and others have a place that can go beyond the simplicity of a single malicious employee. A hacker controlling access to applications or a database for an internal resource can gain quite a lot of authority that the employee did not even know about. We are trying to convey to all our clients so that this access is minimized to the limit, and many of the security methods that we perform to confront SQL injection are very helpful in solving this problem!
When you use an app and see an error like this, what do you think?
Most people will go ahead and ignore this error, but to a hacker, it is a signal that displaying this error message does two things:
Error messages should always be caught, whether they are SQL errors, application errors, or web errors.
Writing secure code is perhaps the most important thing in developing a web application, but over time and technology changes, what was secure 2 years ago is further not appropriate.
With each stage of development of our project, we make a new code and build new functions, we also need to revise the old code and functions to make sure that old things also do not become obsolete. Unused or unnecessary code should also be excluded as it most likely will not be paid attention in the future. This balance provides confidence that all code remains safe and up to date when it is encountered the test of time.
Outdated and Unpatched Applications
Companies that use unsupported or outdated software or features lead to security holes; these vulnerabilities cannot be fixed or discovered as fastly as with recent software.
Using patched and up-to-date software versions is critical to preventing security vulnerabilities, including SQL injection. Unceasingly monitoring and responding as needed is a significant move to preventing new vulnerabilities in your system.
Thinking about the security of your applications, due to the isolation of different groups of applications or environments, is inherently deceiving itself. Even if the application’s web forms are protected from injection by default, no one is immune to mistakes when developing stored procedures or other database objects.
Everyone should apply optimal security whenever possible and never think that high security elsewhere will take care of us. Applications are transforming, and what was safe 2 months ago is no longer safe at all in the present time. Such mistakes and thoughts ultimately lead to failures in compliance and security auditing.
The best way to protect your organization’ data is to keep it secure. You must configure and own a secure database server accessed by the secure application server. Each of these devices must be connected to secure network devices and monitored by services that warn in the event of a threat. The end result is a system that requires substantial effort to access the data. Such efforts will be enough to trigger a warning that an attack is taking place on their servers.
Build servers securely to the limit, and do not suppose that other components of your application will protect you from intruders.
To understand who the potential victims are and what their number is, you need to look “under the hood.”
According to shodan.io data, we see the number of 1,709,501 “mysql” servers and 721,540 “postgresql” servers.
To get a broader picture, we’ve collected data from different sources. If you look at the ZoomEye.org website, you can see 27,739,742 mysql servers. This is a huge amount of potentially vulnerable servers.
Let’s look at a more advanced way that hackers use; and for this, they use the most popular search engine, Google which helps with its Google Dorks. Hackers write automatic scanners that scan Google for days and nights with a huge list of Google Dorks, then they find potentially vulnerable resources, and then the database is hacked. Below you will see the potential number of resources that may contain errors in the SQL configurations. We have used four of the most popular Google Dorks as an example.
Google Dork are advanced queries to search engines that help open access to the public but hidden from prying eyes.
Among all Google’s advanced search operators, we are mainly interested in four:
Also, when composing a request, you need to remember several operators, which are specified by special characters.
| – vertical slash, it is the OR operator (logical or). Indicates to display results that contain at least one of the words listed in the query.
“” quotes. Indicates an exact match.
– – minus. It is used to clean up search results and exclude from it the results with the words specified after the minus.
* – an asterisk. Used as a mask and means “whatever”.
SQL injection usually has this structure in the url “file.php?id=[vulnerable]“, to search for pages vulnerable to SQLi we can use the “inurl:” operator, which only shows the results with the X string in the url, a hyphen in front of a word to prevent the word from appearing in the search.
In the first example we use dork: “inurl:index.php?=” and find about 3,600,000,000 results. Not all will be vulnerable but if only 1% of that result will be this is 36,000,000 in potentially hacked databases.
Let’s check the second example; for this, we use dork:”inurl:index.php?page=” and find about 386,000,000 results. Let’s use the same math method as in the previous example: if we have 1% of vulnerable sites, we`ll have about 3,860,000 in potentially hacked databases.
In the third example we use shopping dork:”inurl:products.php?cat=” and find about 1,970,000 results. What does this mean — “shopping dorks”? It means that hackers can get not only emails and passwords from databases, but also they can get credit cards details.
In the fourth example we also use shopping dork: “inurl:product.php?pid=” and find about 895,000 results.
57% of websites are potentially vulnerable to SQL injection. And this applies to most companies in the world – be it a small business or an international corporation. This applies to everyone! Companies should always prioritize the safety of their resources, as well as the privacy of their customers. The opinions of small business owners that, due to their average sales figures or narrow territorial coverage, they are in a safe position and of no interest to hackers are completely and completely wrong! Hackers put such vulnerabilities on automatic search, and Google, by indexing pages in its search, only helps with this.
10 billion user data is potentially at risk if companies tend to make the security of their applications a secondary concern. Companies invest in marketing to increase their profits, while forgetting about security – the lack of which can destroy them. Most companies believe that securing their assets is more of an expense than a forward-looking investment. If a company, in the pursuit of profit, forgets about the protection of its users and customers, then the user / client must himself decide not to trust his personal data to this company!
Prepared statements provide that a hacker can not transform the intention of a query, even an attacker includes SQL commands. In the safe example below, if an attacker needed to input the userID of ben’ or ‘1’=’1, the parameterized query would not be vulnerable and would instead search for a username that textually matched the entire string ben’ or ‘1’=’1.
Developers like the Prepared Statement method because all the SQL code stays in the app. It provides comparative independence of your application from database.
Stored procedures are sometimes not protected from SQL injection. But specific standard stored procedure programming constructions affect the same way as using parameterized queries when performed securely which is the rule for the majority of stored procedure languages.
Stored procedures demand the developer to just design SQL statements with arguments that are automatically parameterized if only the developer is doing something substantially out of the rule. The distinction from prepared statements is that the SQL code for a stored procedure is defined and stored in the database itself, and then is requested from the app. These mechanisms have the equal efficiency in averting SQL injection so your institution can select which mechanism you need.
Different parts of SQL queries aren’t legal places for the using bind variables, such as the names of tables or columns, and the sort order indicator (ASC or DESC). In such cases, input validation or query redesign is the most suitable protection. For the names of tables or columns, primely, those values come from the code, and not from user parameters.
If user parameter values are used for targeting various names of table and column, the parameter values need to be charted to the legal/expected table or column names to assure unvalidated user input does not end in the query. Please pay attention, it is a sign of low development and a complete overwork needs to be reviewed if it is enough time.
Any time user input can be transformed to a non-String, like a date, numeric, boolean, enumerated type, etc., before its adding to a query, or used to choose a value to add to the query, this assures to be secure.
Input validation is also advised as well as a subordinate protection in ALL situations, even when using bind variables as is described below in the paper. More mechanisms of performing severe whitelist input validation are reported in the Input Validation Cheat Sheet(you can find it on OWASP website).
This mechanism is solely used as a latter treatment when others described are not executable. Input validation is likely a better option as this methodology is weakly compared to other protections, and we can’t assure it will preclude all SQL Injection in all cases.
This mechanism is to avoid user input before you put it in a query. Its implementation is very database particular. It’s commonly just advised to modify legacy code when realizating input validation is economically ineffective. Apps designed from scratch, or apps demanding low risk toleration should be designed or overworked with parameterized queries, stored procedures, or some Object Relational Mapper (ORM) that designs queries for you.
At the end of this research, we would like to draw conclusions about such a dangerous and critical vulnerability, which hits not only the companies’ database, but also the customers themselves who eventually become victims of phishing attacks, as well as revealing their passwords, which are usually used on other services.
Therefore, in order to always keep your finger on the pulse of the security of your web applications, you need to regularly do a Web Risk Assessment Scan, specially developed by Hacken experts who will indicate the existence of a problem.