Web Security 101 | Understanding SQL Injection Completely

Ali Gündoğar
7 min readJan 5, 2024

--

What is SQL Injection?

SQL injection (SQLi) is a code injection attack that exploits vulnerabilities in input validation of web applications connected to back-end databases. The attacker injects malicious SQL code into entry fields, gaining access to and control of the database, allowing them to steal data, corrupt or delete information, execute admin commands, or in some cases even take over the server.

With billions of web applications powered by SQL databases, SQLi remains one of the most dangerous security risks today. That’s why it’s crucial for developers and security professionals to thoroughly understand what SQL injection is, how it works, and how to prevent attacks.

How SQL Injection Works

SQL injection takes advantage of improper sanitization of user-supplied data. For example, an application might include user input through URLs or forms that gets passed directly to a SQL query without validation or escaping special characters. By crafting malicious input strings, attackers can append custom query conditions to alter the developer’s intended logic.

Some common examples include:

  • OR 1=1 -- tricking the query into returning all records
  • '; DROP TABLE users; -- deleting tables
  • ' UNION SELECT credit_card FROM users WHERE id = -- extracting hidden data

Depending on the database’s permissions, this gives attackers potential access to read, write, delete, or modify critical application or server data.

Types of SQL Injection Attacks

There are several main techniques attackers use to conduct SQL injection:

  • In-band SQLi — Uses the same communication channel to both launch the attack and gather results. Easy to pull off but also easy to detect.
  • Inferential SQLi — Doesn’t directly return database contents but allows the attacker to ask true/false questions to reconstruct data. Harder to detect.
  • Out-of-band SQLi — Uses an external channel to extract data, via DNS or timing delays for example, avoiding database logs. More subtle.
  • Blind SQLi — Gathers info bit-by-bit by observing how conditional responses change based on injected strings rather than retrieving outputs directly.

Preventing SQL Injection Attacks

The most important ways to stop SQL injection include:

  1. Input Validation — Encode or sanitize all user-supplied input before using it in SQL statements. Validate type, length, format, and acceptable character sets.
  2. Parameterized Queries/Prepared Statements — Define SQL queries by parameters rather than string concatenation so inputs can’t modify SQL logic.
  3. Whitelist Input Validation — Define an acceptable set of characters instead of trying to blacklist all bad inputs. Reject data that doesn’t match expected formats or types.
  4. Limit Database Permissions — Follow the principle of least privilege. Don’t over provision permissions beyond what each database role strictly requires.

Detecting SQL Injection Attacks

To detect SQLi attempts, key things to monitor include:

  • HTTP input parameters not matching expected data types or string formats
  • Unusual spikes in web traffic or database query volume
  • HTTP 500 errors and empty SQL exception errors
  • Logs showing HTTP traffic not associated with regular pages
  • Comparisons between inbound HTTP requests and actual SQL queries

Quickly flagging these patterns allows taking fast measures to prevent exploitation.

Tools for Testing SQL Injection

Pen testing SQL injection commonly relies on tools like:

  • SQLMap — Actively injects payloads and dumps database contents. Effective for testing but gives defenders insight too.
  • Havij — User-friendly GUI SQLi scanner designed for rapid exploitation. Lacks subtlety.
  • Sqlninja — Favored for inference attacks and stealthier direct access attacks via out-of-band channels.
  • BBQSQL — SQL injection framework focused on blind attacks by observing conditional responses.

There are also many browser add-ons and Burp Suite modules to facilitate manual testing.

SQL Injection on Different Platforms

While SQL injection is most associated with web apps, database interfaces exist across platforms including:

  • Web Services/APIs — OpenAPI, SOAP etc allow SQLi if user input isn’t properly isolated from queries.
  • Mobile Apps — Particularly prevalent on hybrid or cross-platform apps that reuse server-side code vulnerable to SQLi.
  • Desktop Apps — Thick client and desktop apps also include SQL backends allowing injection vectors.
  • Database Tools — Client software like Toad also expose parameters that enable SQLi if not correctly handled.

No SQL interface exposed to users should be considered immune. Cross-platform protections must filter untrusted input everywhere across the stack.

Exploiting SQL Injection Vulnerabilities

In most cases, the first step after discovering SQLi through testing is to determine details like the database type and version along with the table structure. Fingerprinting reveals the database schema and functions available to leverage in exploitation.

This exploration also maps out what data exists and where it’s stored to target sensitive information like credentials, PII, intellectual property, or other assets. SQLMap and Havij automate much of this reconnaissance.

With mapping complete, the main goals involve extracting data, evading logs, maintaining access, and escalating privileges. Extracting data may mean simple record retrieval or more craft queries to exfiltrate via out-of-band channels. Evasion uses techniques like time delays, DNS tricks, or automation to avoid logging. Maintaining access could employ backdoors, shell prompts, or pivots through other flaws. Escalation seeks admin rights to own the database server itself.

Case Studies of SQL Injection Attacks

Some notorious SQL injection breaches include:

  • Sony Pictures (2014) — Attributed to North Korea over the movie The Interview, hackers used SQLi to steal 100TB of data including upcoming movie scripts, emails, and sensitive personnel records.
  • British Airways (2018) — Magecart group compromised BA’s payment pages via SQLi, injecting credit card skimming malware that stole 380,000 payment records in mere weeks.
  • Facebook (Multiple) — Facebook’s site has suffered SQLi vulnerabilities allowing access to accounts, in one case exposing 6 million records through mass automated attacks.
  • Equifax (Multiple) — Several SQLi vulnerabilities enabled stealing 143 million customers’ full identity, credit, and personal records from the credit reporting agency.

These examples showcase SQLi’s power to enable massive data breaches with widespread real-world consequences.

Best Practices for Securing Against SQLi

Engineering defenses to lock down SQLi risk should include:

  • Input Validation — Strong data validation, filtering, sanitization and type checking, plus eliminating unnecessary inputs.
  • Least Privilege — Restrict database permissions horizontally per role and vertically per query to minimize exploit impact.
  • WAF Rules — Craft Web Application Firewall rules targeting SQLi patterns including signatures with denial of service enabled.
  • Request Rate Limiting — Prevent high velocity automated attacks even if payloads pass filters by throttling requests.
  • Database Network Segmentation — Physically separate databases from public web segments and allow only authorized app servers to connect.
  • Prepared Statements — Enforce parameterized queries instead of inline variable string building.

OWASP Guidelines for Preventing SQLi

OWASP, the Open Web Application Security Project, provides comprehensive best practice guidance for locking down SQL injection written by security experts. Their top recommendations mirror the essentials already covered:

  • Validate and sanitize all input strings that will become part of SQL behavior.
  • Use parameterized queries and prepared statements rather than inline variable string building.
  • Apply the principle of least privilege to minimize the database permissions available externally.

Following OWASP advice serves as the front line against real-world SQL injection threats.

Keeping Up with SQL Injection Defense

With cyber threats continuously evolving, securing critical data and systems against SQLi requires ongoing diligence to stay on top of new:

  • Exploits and Techniques — From inference exfiltration channels to timing side channels, new methods emerge for evading defenses through novel exploits.
  • Prevention Measures — Stronger validation routines, improved intrusion detection, smarter parameterization, and other advancing protection schemes.
  • Programming Frameworks — Update to modern frameworks offering built-in protections against SQLi attacks.

By proactively monitoring security research, penetration testing results, and community advisories, SQL injection countermeasures can evolve as rapidly as the threats.

Conclusion

SQL injection remains one of the most widespread and devastating application security flaws threatening organizations today. However, by taking concrete steps to validate, sanitize, and isolate all application inputs plus restricting unnecessary access, companies can implement robust defenses to keep data safe. Driven by continuous testing and staying current with the latest protections as cybercriminal tools grow more advanced, enterprises can effectively shield their most valuable data assets from compromise through SQLi or related injection threats now and into the future.

FAQs

Q: What makes SQL injection such a prevalent web vulnerability compared to other flaws?

A: It’s deeply rooted in how web apps and backend databases communicate. All dynamic sites rely on taking user input and incorporating it into database queries. Without proper isolation and validation between untrusted inputs and queries, SQLi holes open up.

Q: What common flaws enable SQL injection vulnerabilities to emerge in code?

A: Failing to validate input data, concatenating strings into dynamic SQL queries, executing queries with unnecessary privileges, and failing to handle errors properly during SQL parsing can all lead to SQLi vulnerabilities.

Q: Is SQL injection only a web application problem?

A: SQL injection vulnerabilities occur anytime untrusted input gets passed unchecked into a SQL query. This includes APIs, microservices, thick client apps, databases tools, and other interfaces beyond just web apps.

Q: Are some types of databases more vulnerable to SQL injection than others?

A: It’s less about the database platform (MySQL, MSSQL, PostgreSQL etc) and more about the precautions taken in application code to prevent uncontrolled user input from manipulating SQL logic. All databases face SQLi threats.

Q: What is more dangerous — stealing data via SQLi extraction or using it to delete or corrupt data?

A: Deletion and corruption can be catastrophic but usually get detected faster during troubleshooting. Quietly extracting mass data via SQLi allows stealing data, intellectual property, and secrets that may go undiscovered for years with continued access. Hence, exfiltration is usually the higher risk.

--

--