- Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
- **Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/carlospolopm)**.**
*`master.dbo.fn_varbintohexstr(SUSER_SID('MEGACORP\Administrator'))`: If you know the name of the domain (_MEGACORP_ in this example) this function will return the **SID of the user Administrator** in hex format. This will look like `0x01050000000[...]0000f401`, note how the **last 4 bytes** are the number **500** in **big endian** format, which is the **common ID of the user administrator**. \
This function will allow you to **know the ID of the domain** (all the bytes except of the last 4).
*`SUSER_SNAME(0x01050000000[...]0000e803)` : This function will return the **username of the ID indicated** (if any), in this case **0000e803** in big endian == **1000** (usually this is the ID of the first regular user ID created). Then you can imagine that you can bruteforce user IDs from 1000 to 2000 and probably get all the usernames of the users of the domain. For example using a function like the following one:
**(From** [**here**](https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/)**)** Error-based SQL injections typically resemble constructions such as «+AND+1=@@version–» and variants based on the «OR» operator. Queries containing such expressions are usually blocked by WAFs. As a bypass, concatenate a string using the %2b character with the result of specific function calls that trigger a data type conversion error on sought-after data.
**Information taken from** [**https://ibreak.software/2020/06/using-sql-injection-to-perform-ssrf-xspa-attacks/#MSSQL**](https://ibreak.software/2020/06/using-sql-injection-to-perform-ssrf-xspa-attacks/#MSSQL)
[Microsoft SQL Server provides multiple extended stored procedures that allow you to interact with not only the network but also the file system and even the ](https://docs.oracle.com/javadb/10.10.1.2/ref/rrefclob.html)[Windows Registry](https://blog.waynesheffield.com/wayne/archive/2017/08/working-registry-sql-server/).
One technique that keeps coming up is the usage of the undocumented stored procedure `xp_dirtree` that allows you to list the directories in a folder. This stored procedure supports UNC paths, which can be abused to leak Windows credentials over the network or extract data using DNS requests.
If you are able to execute operating system commands, then you could invoke Powershell to make a curl (`Invoke-WebRequest`) request. You could do this via the hacker favorite `xp_cmdshell` as well.
The most common method to make a network call you will come across using MSSQL is the usage of the Stored Procedure `xp_dirtree`, which weirdly is undocumented by Microsoft, which caused it to be [documented by other folks on the Internet](https://www.baronsoftware.com/Blog/sql-stored-procedures-get-folder-files/). This method has been used in [multiple examples](https://www.notsosecure.com/oob-exploitation-cheatsheet/) of [Out of Band Data exfiltration](https://gracefulsecurity.com/sql-injection-out-of-band-exploitation/) posts on the Internet.
Much like MySQL’s `LOAD_FILE`, you can use `xp_dirtree` to make a network request to only TCP port 445. You cannot control the port number, but can read information from network shares. Addtionally, much like any UNC path access, [Windows hashes will be sent over to the network that can be captured and replayed for further exploitation](https://medium.com/@markmotig/how-to-capture-mssql-credentials-with-xp-dirtree-smbserver-py-5c29d852f478).
**PS:** This does not work on `Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64)` running on a `Windows Server 2016 Datacenter` in the default config.
There are other stored procedures [like `master..xp_fileexist` ](https://social.technet.microsoft.com/wiki/contents/articles/40107.xp-fileexist-and-its-alternate.aspx)etc. as well that can be used for similar results.
The extended stored procedure [`xp_cmdshell` spawns a Windows command shell and executes the string passed to it, returning any rows of text](https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/xp-cmdshell-transact-sql). This command is run as the SQL Server service account.
`xp_cmdshell` is disabled by default. You can enable it using the SQL Server Configuration Option. Here’s how
You could use something like [PowerCat](https://github.com/besimorhino/powercat), download the Windows port of netcat/ncat, [use raw TCP Client for arbitrary ports](https://livebook.manning.com/book/powershell-deep-dives/chapter-4/9), or simply invoke Powershell’s `Invoke-WebRequest` to make HTTP requests to perform Server Side queries.
You can additionally pass other headers and change the HTTP method as well to access data on services that need a POST or PUT instead of a GET like in the case of IMDSv2 for AWS or a special header like `Metadata: true` in the case of Azure or the `Metadata-Flavor: Google` for GCP.
It is fairly straightforward to write a CLR UDF (Common Language Runtime User Defined Function - code written with any of the .NET languages and compiled into a DLL) and load it within MSSQL for custom functions. This, however, requires `dbo` access so may not work unless the web application connection to the database as `sa` or an Administrator role.
[This Github repo has the Visual Studio project and the installation instructions](https://github.com/infiniteloopltd/SQLHttp) to load the binary into MSSQL as a CLR assembly and then invoke HTTP GET requests from within MSSQL.
The [`http.cs` code uses the `WebClient` class to make a GET request and fetch the content](https://ibreak.software/2020/06/using-sql-injection-to-perform-ssrf-xspa-attacks/) as specified
In the installation instructions, run the following before the `CREATE ASSEMBLY` query to add the SHA512 hash of the assembly to the list of trusted assemblies on the server (you can see the list using `select * from sys.trusted_assemblies;`)
**(From** [**here**](https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/)**)** There exist two simple ways to retrieve the entire contents of a table in one query — the use of the FOR XML or the FOR JSON clause. The FOR XML clause requires a specified mode such as «raw», so in terms of brevity FOR JSON outperforms it.
**(From** [**here**](https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/)**)** An example of retrieving a local file `C:\Windows\win.ini` using the function OpenRowset():
**(From** [**here**](https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/)**)** The current SQL query being executed can be retrieved from access `sys.dm_exec_requests` and `sys.dm_exec_sql_text`:
**Permissions:** If the user has VIEW SERVER STATE permission on the server, the user will see all executing sessions on the instance of SQL Server; otherwise, the user will see only the current session.
- Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
- **Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/carlospolopm)**.**