Parameters:
  KeyName:
    Description: Name of an existing EC2 KeyPair to enable SSH access to the instances. Linked to AWS Parameter
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: must be the name of an existing EC2 KeyPair.
  LatestAmiId:
    Description: (DO NOT CHANGE)
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'
    AllowedValues:
      - /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2

Resources:
# IAM Role & Instance Profile
  IAMLabInstanceRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: IAMLabInstanceRole
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          -
            Effect: Allow
            Principal:
              Service:
                - ec2.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

  IAMRoleForInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      InstanceProfileName: IAMLabRoleForInstances
      Path: /
      Roles:
        - !Ref IAMLabInstanceRole

# VPC
  MyVPC:
    Type: AWS::EC2::VPC
    Properties:
     CidrBlock: 10.0.0.0/16
     EnableDnsHostnames: true
     EnableDnsSupport: true
     Tags:
        - Key: Name
          Value: My-VPC

  MyIGW:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: My-IGW

  MyIGWAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref MyIGW
      VpcId: !Ref MyVPC

  MyPublicRT:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC
      Tags:
        - Key: Name
          Value: My-Public-RT

  DefaultPublicRoute:
    Type: AWS::EC2::Route
    DependsOn: MyIGWAttachment
    Properties:
      RouteTableId: !Ref MyPublicRT
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref MyIGW

  MyPublicSN:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC
      AvailabilityZone: !Select [ 0, !GetAZs '' ]
      CidrBlock: 10.0.0.0/24
      Tags:
        - Key: Name
          Value: My-Public-SN

  MyPublicSN2:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC
      AvailabilityZone: !Select [ 2, !GetAZs '' ]
      CidrBlock: 10.0.1.0/24
      Tags:
        - Key: Name
          Value: My-Public-SN-2

  MyPublicSNRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref MyPublicRT
      SubnetId: !Ref MyPublicSN

  MyPublicSNRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref MyPublicRT
      SubnetId: !Ref MyPublicSN2

  ALBSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: ELB Security Group
      VpcId: !Ref MyVPC
      Tags:
        - Key: Name
          Value: ELB-SG
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: '80'
        ToPort: '80'
        CidrIp: 0.0.0.0/0
      - IpProtocol: tcp
        FromPort: '443'
        ToPort: '443'
        CidrIp: 0.0.0.0/0

  ALBTG:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Name: ALBTG
      Port: 80
      Protocol: HTTP
      HealthCheckPath: '/login.php'
      VpcId: !Ref MyVPC
      Targets:
        - Id: !Ref MYEC2
          Port: 80
      TargetGroupAttributes:
      - Key: stickiness.enabled
        Value: 'true'
      - Key: stickiness.type
        Value: lb_cookie
      - Key: stickiness.lb_cookie.duration_seconds
        Value: '180'

  MyALB:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Scheme: internet-facing
      Name: My-ALB
      SecurityGroups:
        - !Ref ALBSG
      Subnets:
        - !Ref MyPublicSN
        - !Ref MyPublicSN2

  ALBListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref ALBTG
      LoadBalancerArn: !Ref MyALB
      Port: 80
      Protocol: HTTP

  MySG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: WEB Security Group
      VpcId: !Ref MyVPC
      Tags:
        - Key: Name
          Value: My-SG
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: '22'
        ToPort: '22'
        CidrIp: 0.0.0.0/0
      - IpProtocol: tcp
        FromPort: '80'
        ToPort: '80'
        CidrIp: 10.0.0.20/32
      - IpProtocol: tcp
        FromPort: '80'
        ToPort: '80'
        SourceSecurityGroupId : !GetAtt ALBSG.GroupId

  MySG2:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: WEB Security Group
      VpcId: !Ref MyVPC
      Tags:
        - Key: Name
          Value: My-SG2
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: '22'
        ToPort: '22'  
        CidrIp: 0.0.0.0/0
      # - IpProtocol: tcp
      #   FromPort: '80'
      #   ToPort: '80'
      #   CidrIp: 0.0.0.0/0
      - IpProtocol: tcp
        FromPort: '4280'
        ToPort: '4280'
        CidrIp: 0.0.0.0/0

  MYEC2:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t2.micro
      ImageId: !Ref LatestAmiId
      IamInstanceProfile: IAMLabRoleForInstances
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: DVWA
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref MyPublicSN
          GroupSet:
          - !Ref MySG
          AssociatePublicIpAddress: true
          PrivateIpAddress: 10.0.0.10
      BlockDeviceMappings:
        - DeviceName: /dev/xvda
          Ebs:
            VolumeType: gp3
            VolumeSize: 30
            DeleteOnTermination: true
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            hostnamectl --static set-hostname DVWA
            echo "sudo su -" >> /home/ec2-user/.bashrc

            # Change Timezone
            sed -i "s/UTC/Asia\/Seoul/g" /etc/sysconfig/clock
            ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

            # Install Packages
            amazon-linux-extras install epel -y
            yum update -y
            yum install -y tree git htop jq httpd mariadb-server mariadb php php-mysql php-gd
            systemctl start mariadb httpd && systemctl enable httpd mariadb
            amazon-linux-extras install php8.2 -y

            # Configure mariadb
            echo -e "\n\nqwe123\nqwe123\ny\nn\ny\ny\n" | /usr/bin/mysql_secure_installation
            mysql -uroot -pqwe123 -e "create database dvwa; GRANT ALL PRIVILEGES ON dvwa.* TO 'dvwa'@'localhost' IDENTIFIED BY 'qwe123'; flush privileges;"

            # Install DVWA
            git clone https://github.com/digininja/DVWA.git
            mv DVWA/* /var/www/html/
            cp /var/www/html/config/config.inc.php.dist /var/www/html/config/config.inc.php
            sed -i "s/p@ssw0rd/qwe123/g" /var/www/html/config/config.inc.php
            sed -i 's/allow_url_include = Off/allow_url_include = on/g' /etc/php.ini
            sed -i 's/display_errors = Off/display_errors = on/g' /etc/php.ini
            sed -i 's/display_startup_errors = Off/display_startup_errors = on/g' /etc/php.ini
            chmod 777 /var/www/html/hackable/uploads
            chmod 777 /var/www/html/config
            systemctl restart httpd

  MYEC22:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t2.micro
      ImageId: !Ref LatestAmiId
      KeyName: !Ref KeyName
      Tags:
        - Key: Name
          Value: Attacker
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref MyPublicSN
          GroupSet:
          - !Ref MySG2
          AssociatePublicIpAddress: true
          PrivateIpAddress: 10.0.0.20
      BlockDeviceMappings:
        - DeviceName: /dev/xvda
          Ebs:
            VolumeType: gp3
            VolumeSize: 30
            DeleteOnTermination: true
      UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            hostnamectl --static set-hostname Attacker
            echo "sudo su -" >> /home/ec2-user/.bashrc

            # Change Timezone
            sed -i "s/UTC/Asia\/Seoul/g" /etc/sysconfig/clock
            ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

            # Install Packages
            amazon-linux-extras install epel -y
            yum update -y
            yum install -y tree git htop jq nc lynx hydra httpd

            # Install aws cli v2
            curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
            unzip awscliv2.zip >/dev/null 2>&1
            sudo ./aws/install
            complete -C '/usr/local/bin/aws_completer' aws
            echo 'export AWS_PAGER=""' >>/etc/profile
            export AWS_DEFAULT_REGION=${AWS::Region}
            echo "export AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION" >> /etc/profile

            # Install Docker
            cat <<EOF | sudo tee /etc/sysctl.d/docker.conf
            net.bridge.bridge-nf-call-ip6tables = 1
            net.bridge.bridge-nf-call-iptables = 1
            EOF
            amazon-linux-extras install docker -y
            systemctl start docker && systemctl enable docker
            curl -SL https://github.com/docker/compose/releases/download/v2.20.3/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose
            chmod +x /usr/local/bin/docker-compose

Outputs:
  WebServerIP:
    Value: !GetAtt MYEC2.PublicIp
  AttackerIP:
    Value: !GetAtt MYEC22.PublicIp
