SQL Injection

Back To Listing

What is SQL Injection & How Does it Happen?

One of the most serious application security problems, SQL injection is a commonly employed attacker technique designed to exploit databases through a SQL query security flaw. It is a form of web hacking whereby SQL statements, query strings, and user input are used in the fields of a web form to cause a poorly designed web application to dump database content to the attacker.

SQL injections can occur anytime a developer takes untrusted data (such user input in a URL or a web form) and concatenates it into a database SQL query. This allows an attacker to insert characters that take control of the SQL query, or insert malicious SQL statements into input fields for execution by the underlying SQL database. SQL statements control the database server behind a web application. SQL injections change the intended meaning, giving the attacker unauthorized access to valuable data such as username and password information, transaction files, or database tables with the ability to compromise an entire database server through command execution.

SQL injection errors occur when:

  • SQL statements are constructed with known SQL injection vulnerabilities.
  • Input enters a program from an untrusted source.
  • Data is used to dynamically construct a SQL query.
  • Entry fields made available for user input allow SQL statements to query the database directly.

By taking control of the way a SQL query is constructed and executes against a backend database server, the SQL injection attacker is able to considerable damage, gaining access to a “secure” database to steal sensitive data, corrupt a database, spoof identities, tamper with transactions, and more. SQL injection attacks have headlined the OWASP Top Ten for the last 14 years, along with ways to prevent them.

How Does SQL Injection Happen?

With an SQL injection, the grand prize is gaining access to the database server. As we’ve seen, SQL injection is a code injection technique used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (for example, to dump the database contents to an attacker). SQL injections must exploit a security vulnerability in an application's software; for example, when user input is either not properly checked, is incorrectly filtered for string literal escape characters embedded in SQL statements, or user input is not strongly typed and is unexpectedly executed. SQL injection is mostly known as an attack vector for websites and the web servers behind them but it can be used to attack any type of SQL database.

To take a deeper dive into the question, “What is SQL injection and how does it work,” let’s look at an example. We’ve seen that SQL injections occur when an attacker manipulates data to control the way a SQL statement is constructed and then executes that changed statement to retrieve data from the backend database. This kind of attack depends upon the attacker’s ability to embed control characters that turn a normal SQL query into a compromised one, in this example changing the SELECT * FROM statement:

Normal Input: user@example.com
Normal SQL Query: SELECT * FROM users WHERE email='user@example.com'
Normal Result: A record for the individual user

SQL Injection Input: user_example.com' OR 3>2
SQL Injected SQL Query: SELECT * FROM users WHERE email='user@example.com' OR 3>2
SQL Injected Result: All records, or a subset of the attacker’s choosing

In extreme cases, hackers can even manipulate the input and inject it in such a way that login is possible without a username or password (there are tutorials for this online).

How Often Do SQL Injections Happen?

Based upon research included in the latest Contrast Lab’s AppSec Intelligence Report, Contrast has short-listed vulnerabilities that pose the greatest risk to organizations. The list was created by combining the likelihood of a vulnerability and an attack with the likelihood of a successful exploit and an impact factor. Interestingly, SQL injection was at the top of that list:

“While SQL injection attacks rarely reached vulnerable code within applications, they were the most prevalent attack type in November, a common open vulnerability, and have the highest severity level. By exploiting a vulnerability in an app's SQL queries, an attacker can steal a username and password, access sensitive data, corrupt a database, spoof identities, tamper with transactions, disclose information, and even become administrator of the database server.”

The three most common attack types in November 2019 were the same as October; SQL injection, cross-site scripting (XSS), and path traversal, in that order. But Contrast Labs saw large increases in the number of applications targeted by attackers using these three attack types month-over-month:

Here are more details regarding SQL injections from this latest Contrast Labs report:

  • Carefully crafted inputs alter the SQL queries an application uses in order to steal from a database or execute code.
  • SQL injection represented 52% of all known attacks in November.
  • SQL injection targeted 76% of applications (up from 59%).
  • Java applications carry a 79% chance of SQL injection attack.
  • There is a 60% chance of SQL injection attack for .NET applications.

SQL injection has been well understood for over 20 years, yet attackers continue to use this hacking method to grab usernames, passwords, and more. SQL injections still represent a serious security threat for enterprises and government agencies, including election systems, regardless of size and geography.

Why Are SQL Injection Attacks So Dangerous?

A web server is software or hardware that uses HTTP and other protocols to respond to client requests made over the Internet. Web server software controls how a user accesses hosted files, and the user provides a username and password intended to ensure secure access. Because a web server typically holds valuable information, organizations simply can’t allow attackers to take control of their web servers.

A successful SQL injection attack can result in identities being stolen; websites being defaced; confidential data being deleted, lost, or stolen; unauthorized access granted to systems, databases, and accounts; and even the compromise of individual machines or entire networks.

The cost of SQL injection attacks can be high because they allow attackers to spoof identity, capture account credentials, tamper with existing data, cause repudiation issues such as voiding transactions or changing balances, allow the complete disclosure of all data on the system, destroy the data or make it otherwise unavailable, and assume admin privileges for the database server. These all have real-world consequences with varying degrees of severity.

So now that we’ve answered the question, “What is SQL injection,” let’s look at how organizations can protect themselves from malicious input as they work to protect their systems, servers, databases, and users.

How to Prevent SQL Injection Attacks

Although SQL injection was discovered over fifteen years ago, it’s a hacking technique that is still devastatingly effective, and it remains a top application security priority. It specifically targets SQL injection vulnerabilities and was successfully used in the run-up to the 2016 U.S. presidential election to compromise the database holding personal data of 200,000 Illinois voters, as well as in high-profile attacks against organizations such as Sony Pictures, PBS, Microsoft, Yahoo, Heartland Payment Systems, and even the CIA.

Here are 10 recommended actions you can take to prevent SQL injection and avoid becoming a victim of these kinds of attacks:

  1. Think like an attacker: Go out on the web and look at the sites giving very explicit instructions on how to perform SQL injection attacks. Study these so you can “think like a hacker” as you write your code, particularly in terms of SELECT/UNION SELECT … FROM … WHERE query strings dealing with database tables, usernames, and passwords.
  2. Always expect the worst: Assume that all user-submitted data is suspect, trust no one, and take appropriate actions to validate and sanitize all data.
  3. Don't use dynamic SQL and don't construct queries with user input: Data sanitization routines aren’t foolproof, so it’s important to use prepared statements, parameterized queries, and stored procedures whenever possible. This ensures that an attacker is unable to change the intent of a query, even if malicious SQL commands are inserted.
  4. Whitelist input validation: if user parameter values are used for targeting different table and column names, those parameter values should be mapped to the legal/expected table or column names to make sure unvalidated user input doesn’t end up in the SQL query.
  5. Update and patch: Application and database vulnerabilities are regularly discovered, so you should apply patches and updates as quickly as they are available to prevent attacks.
  6. Least privilege: To minimize the potential damage of a successful SQL injection attack, minimize the privileges assigned to every database account in your environment. Avoid connecting to your database using an account with admin-level privileges; using a limited access account is far safer, and can limit what a hacker is able to do.
  7. Firewall: Use a web application firewall (WAF) – either software or appliance-based – to help filter out malicious data. Most WAFs will come with a comprehensive set of default rules, and they make it easy to add new ones whenever necessary.
  8. Reduce your attack surface: Remove any database functionality that you don't need. This will reduce your attack surface and prevent hackers from gaining a foothold as they launch attacks.
  9. Apply encryption: Assume that your application is not secure and act accordingly by encrypting or hashing passwords and other confidential data, including connection strings.
  10. Continuously monitor SQL statements from database-connected applications: This will help identify rogue SQL statements and SQL injection vulnerabilities. Monitoring tools that use machine learning and/or behavioral analysis can be especially useful.

Eliminating SQL Injection the Contrast Way

In the past, application security tools either scanned the source code or dynamically scanned the web interface. These tools were designed for experts in application security, took days or weeks to use, and generated huge numbers of false alarms. Many organizations are stuck with large application portfolios that they can't secure because their expert-based approach is a frustrating bottleneck. Scanning and penetration testing can be used to detect SQL injection problems, but they're prone to error and are likely to miss many instances. Static analysis and code review can also be used, but they are difficult and time consuming to manage.

Contrast Security Works Differently

Contrast works by passively tracking untrusted data within your running applications. Unlike static and dynamic analysis, Contrast works inside the running application and has interactive access to the code, configuration, HTTP requests and responses, data flows, control flows, and backend database connections. Access to all this information allows Contrast to detect places where your code is susceptible to attack accurately and in real time.

As it searches for SQL vulnerabilities, the Contrast Engine watches all the methods in your application that might be involved in a SQL injection flaw. Then as your application runs, Contrast identifies any time untrusted data reaches a SQL query. It's like putting a tracing beacon on the untrusted data as it flows through your application.

In Java, there are only a few calls that can be used to communicate with a database:

  • Statement.execute
  • Statement.addBatch
  • Connection.prepare

Contrast monitors these looking for any untrusted data, and if any shows up, Contrast reports a full trace of these SQL injection vulnerabilities back to the Contrast TeamServer. The trace includes all the steps in the vulnerability – including the actual data, the exact lines of code for each step, and the full HTTP request for replay and testing.

This approach has several advantages. Installation is incredibly fast, and it doesn't require any AppSec expertise to set up and use. And, it's far more accurate than traditional techniques.

Contrast Identifies SQL Injection Problems that Other Tools Miss

SQL injection can happen in many different types of code. But we often find these SQL injection vulnerabilities in web pages that result in "state-changing" operations, such as:

  • Authentication pages (something that includes a username and password)
  • Search engines (queries that are placed in a search field)
  • Reporting engines (requesting data from a database)
  • Transactions (with details committed to a database)

Recently, Contrast identified dozens of new SQL injection vectors in an application with over 10 million lines of code that had been through static analysis, dynamic scans, and even manual penetration testing. The complex data flow and unconventional use of untrusted data to reference table names caused these problems to be missed by traditional tools, leaving the application open to attacks. But Contrast's amazing data flow engine handled this application easily.

  • The Contrast Engineis a 3 MB JAR file that you drop onto your web application server.
  • The Engine is a standard Java agent that uses the Java Instrumentation API (JSR 163) to passively monitor your running application and gather security-critical information.

Identifying the problem is nice, but Contrast goes one step further to help you with remediation because it tells you where you need to go to fix the code. With virtually no false positives, and direct line-of-code reporting of SQL injection vulnerabilities, Contrast can save hours of work in both the detection and remediation of code.

Because Contrast is a passive, drop-in tool, it doesn't require the use of experts. And because Contrast works inside your running applications, it has unprecedented access to security relevant information, making it exceptionally accurate. All this means that ordinary developers can find their own SQL vulnerabilities and fix them before they even check in their code – allowing teams avoid attacks by delivering secure code the first time around.

Contrast represents a completely new approach to finding and fixing vulnerabilities, identifying threats, and stopping attacks. It is proud to have been named the only Gartner Magic Quadrant AST “Visionary” in Gartner’s latest "Magic Quadrant Report for Application Security Testing.” Developers are continually adopting rapid DevOps processes in order to implement their organizations’ digital transformation more efficiently. Contrast’s commitment is to empower developers to weave security into their code, and help security teams so they can rapidly test, deploy, and run code efficiently and securely.

Contrast Community Edition

Release Secure Software Faster... No Security Expertise Needed!

Meet software delivery deadlines and security mandates. Contrast Community Edition for Java applications, .NET Core (and .Net Framework coming soon), and APIs delivers security-as-code that protects your software against the most common security flaws. With Contrast, you can remediate vulnerabilities early in the SDLC and monitor and defend against attacks on production applications.

Contact Security Expert