vSRX + K2 SaaS

Instructions for deploying vSRX with K2 SaaS Platform.

Goal

Deploy vSRX in a VPC and K2 Agents on EC2 Instances in that VPC via cloudformation template.

Prerequisites

Steps

Part 1: vSRX installation (This is a sample and you should use your own vSRX installation CFT)

  • STEP 1: vSRX Configuration :

    • Update the following parameters in the sample yml below

      • General Parameters

        • KeyName : Name of an existing EC2 KeyPair to enable SSH access to the instance.

        • AllowedSshIpAddress : Source IP address (CIDR notation) from which SSH to vSRXs is allowed.

        • AllowedAddress : Source IP address (CIDR notation) from which any access to vSRXs is allowed.

        • TerminationProtection: Enable termination protection on the VSRX EC2 instances to avoid accidential VSRX termination?.

      • vSRX Parameters

        • VpcCidr : CIDR block for vSRX VPC.

        • PubSubnet1 : Address range for vSRX VPC management subnet.

        • PubSubnet2 : Address range for vSRX VPC data subnet to be created in AZ1.

        • PriSubnet1 : Address range for vSRX VPC private subnet to be created in AZ1.

        • VSRXType : Virtual machine size required for VSRX instances.

      • AMIID Mappings

        • Mappings : Update the mappings and specify the AMI Id for vSRX.

          • The AMI-ID should be updated for the region in which you wish to deploy the vSRX controller.

    • Copy the sample yml below and update the parameters and use them in final yml

      •   KeyName:
            Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
            Default: cft #Configurable Section1
            Type: AWS::EC2::KeyPair::KeyName
            ConstraintDescription: must be the name of an existing EC2 KeyPair.
          AllowedSshIpAddress:
            Description: Source IP address (CIDR notation) from which SSH to vSRXs is allowed
            Type: String
            Default: 0.0.0.0/0
          AllowedAddress:
            Description: Source IP address (CIDR notation) from which any access to vSRXs is allowed
            Type: String
            Default: 0.0.0.0/0
        ############################ Juniper Configuration #1 Starts Here  ############################
          TerminationProtection:
            Description: >-
              Enable termination protection on the VSRX EC2 instances to avoid
              accidential VSRX termination?
            Type: String
            Default: 'No'
            AllowedValues:
              - 'Yes'
              - 'No'
          VpcCidr:
            Description: CIDR block for vSRX VPC.
            Type: String
            Default: 200.0.0.0/16
          PubSubnet1:
            Description: Address range for vSRX VPC management subnet.
            Type: String
            Default: 200.0.254.0/24
          PubSubnet2:
            Description: Address range for vSRX VPC data subnet to be created in AZ1.
            Type: String
            Default: 200.0.1.0/24
          PriSubnet1:
            Description: Address range for vSRX VPC private subnet to be created in AZ1.
            Type: String
            Default: 200.0.2.0/24
          VSRXType:
            Description: Virtual machine size required for VSRX instances.
            Type: String
            Default: C4.Xlarge
            AllowedValues:
              - C4.Xlarge
        Mappings:
          JunipervSRXAMI: #Configurable Section7
            us-east-1:
              byol: ami-40058d3a
            us-east-2:
              byol: ami-e6a18983
            us-west-2:
              byol: ami-cddd71b5
            us-west-1:
              byol: ami-04283cf0a2bf7c17c
            ca-central-1:
              byol: ami-ab04bbcf
            eu-west-1:
              byol: ami-2117ff58
            eu-west-2:
              byol: ami-d76f7eb3
            eu-central-1:
              byol: ami-f8fd7f97
            ap-south-1:
              byol: ami-26f68e49
            ap-southeast-1:
              byol: ami-c5a331a6
            ap-southeast-2:
              byol: ami-14c1de77
            ap-northeast-1:
              byol: ami-02729164
            ap-northeast-2:
              byol: ami-2bbe6745
            sa-east-1:
              byol: ami-0656216a
          vSRXInstance:
            C4.Xlarge:
              Type: c4.xlarge
              Bandwidth: '500000'
  • Step 2: Installation of vSRX :

    • Following CFT yml will include :

      • vSRX Network Infrastructure Provisioning

      • vSRX EC2 Instance Provisioning

    • Conditions:
        EnableTerm: !Equals
          - !Ref TerminationProtection
          - 'Yes'
      Metadata:
        'AWS::CloudFormation::Interface':
          ParameterGroups:
            - Label:
                default: Juniper VSRX Configuration
              Parameters:
                - VSRXType
                - KeyName
                - TerminationProtection
            - Label:
                default: Network Configuration
              Parameters:
                - VpcCidr
                - AllowedSshIpAddress
                - PubSubnet1
                - PubSubnet2
                - PriSubnet1
          ParameterLabels:
            AllowedSshIpAddress:
              default: Allowed IP Address to SSH from
            VpcCidr:
              default: vSRX VPC CIDR Block
            PubSubnet1:
              default: vSRX1- Management Subnet Network
            PubSubnet2:
              default: vSRX1- Data Subnet Network
            PriSubnet1:
              default: vSRX1- Private Subnet
            VSRXType:
              default: vSRX Instance Size
            KeyName:
              default: SSH Key to access VSRX
            TerminationProtection:
              default: Enable Termination Protection
      Resources:
        vSRXVPC:
          Type: 'AWS::EC2::VPC'
          Properties:
            CidrBlock: !Ref VpcCidr
            Tags:
              - Key: Name
                Value: vSRX VPC
        VPCPubSub11:
          Type: 'AWS::EC2::Subnet'
          Properties:
            VpcId: !Ref vSRXVPC
            CidrBlock: !Ref PubSubnet1
            MapPublicIpOnLaunch: false #Can be removed not Necessary
            AvailabilityZone: !Select
              - '0'
              - !GetAZs ''
            Tags:
              - Key: Network
                Value: Public
              - Key: Name
                Value: vSRX VPC Management Subnet 1
        VPCPubSub12:
          Type: 'AWS::EC2::Subnet'
          Properties:
            VpcId: !Ref vSRXVPC
            CidrBlock: !Ref PubSubnet2
            AvailabilityZone: !Select
              - '0'
              - !GetAZs ''
            Tags:
              - Key: Network
                Value: Public
              - Key: Name
                Value: vSRX VPC Data Subnet 1
        VPCPriSub11:
          Type: 'AWS::EC2::Subnet'
          Properties:
            VpcId: !Ref vSRXVPC
            CidrBlock: !Ref PriSubnet1
            AvailabilityZone: !Select
              - '0'
              - !GetAZs ''
            Tags:
              - Key: Network
                Value: Private
              - Key: Name
                Value: vSRX VPC Private Subnet 1
        IGW:
          Type: 'AWS::EC2::InternetGateway'
          Properties:
            Tags:
              - Key: Name
                Value: vSRX VPC IGW
        IGWToInternet:
          Type: 'AWS::EC2::VPCGatewayAttachment'
          Properties:
            VpcId: !Ref vSRXVPC
            InternetGatewayId: !Ref IGW
        VPCPublicRouteTable:
          Type: 'AWS::EC2::RouteTable'
          Properties:
            VpcId: !Ref vSRXVPC
            Tags:
              - Key: Network
                Value: Public
              - Key: Name
                Value: vSRX VPC
        VPCPublicRoute:
          Type: 'AWS::EC2::Route'
          Properties:
            RouteTableId: !Ref VPCPublicRouteTable
            DestinationCidrBlock: 0.0.0.0/0
            GatewayId: !Ref IGW
        VPCPrivateRouteTable:
          Type: 'AWS::EC2::RouteTable'
          Properties:
            VpcId: !Ref vSRXVPC
            Tags:
              - Key: Network
                Value: Private
              - Key: Name
                Value: vSRX VPCPrivateRouteTable
        S3Endpoint:
          Type: 'AWS::EC2::VPCEndpoint'
          Properties:
            PolicyDocument:
              Version: 2012-10-17
              Statement:
                - Effect: Allow
                  Principal: '*'
                  Action:
                    - 's3:*'
                  Resource:
                    - '*'
            RouteTableIds:
              - !Ref VPCPublicRouteTable
              - !Ref VPCPrivateRouteTable
            ServiceName: !Join
              - ''
              - - com.amazonaws.
                - !Ref 'AWS::Region'
                - .s3
            VpcId: !Ref vSRXVPC
        VPCPubSubnetRouteTableAssociation1:
          Type: 'AWS::EC2::SubnetRouteTableAssociation'
          Properties:
            SubnetId: !Ref VPCPubSub11
            RouteTableId: !Ref VPCPublicRouteTable
        VPCPubSubnetRouteTableAssociation2:
          Type: 'AWS::EC2::SubnetRouteTableAssociation'
          Properties:
            SubnetId: !Ref VPCPubSub12
            RouteTableId: !Ref VPCPublicRouteTable
        vSRXInterface11:
          Type: 'AWS::EC2::NetworkInterface'
          Properties:
            Description: vSRXManagementInterface1
            PrivateIpAddress: 200.0.254.154
            SourceDestCheck: false
            GroupSet:
              - !Ref VSRXSecurityGroup
            SubnetId: !Ref VPCPubSub11
        vSRXInterface12:
          Type: 'AWS::EC2::NetworkInterface'
          Properties:
            Description: vSRXRevenueInterface1
            PrivateIpAddress: 200.0.1.11
            SourceDestCheck: false
            GroupSet:
              - !Ref VSRXSecurityGroup
            SubnetId: !Ref VPCPubSub12
        vSRXInterface13:
          Type: 'AWS::EC2::NetworkInterface'
          Properties:
            Description: vSRXPrivateInterface1
            PrivateIpAddress: 200.0.2.22
            SourceDestCheck: false
            GroupSet:
              - !Ref VSRXSecurityGroup
            SubnetId: !Ref VPCPriSub11
        vSRXEip11:
          Type: 'AWS::EC2::EIP'
          Properties:
            Domain: vpc
            Tags:
              - Key: Name
                Value: ManagementElasticIP
        vSRXEip12:
          Type: 'AWS::EC2::EIP'
          Properties:
            Domain: vpc
            Tags:
              - Key: Name
                Value: RevenueDataElasticIP
        AssociateEIP11:
          Type: 'AWS::EC2::EIPAssociation'
          Properties:
            AllocationId: !GetAtt
              - vSRXEip11
              - AllocationId
            NetworkInterfaceId: !Ref vSRXInterface11
        AssociateEIP12:
          Type: 'AWS::EC2::EIPAssociation'
          Properties:
            AllocationId: !GetAtt
              - vSRXEip12
              - AllocationId
            NetworkInterfaceId: !Ref vSRXInterface12
        VpcvSRXEC2Instance1:
          Type: 'AWS::EC2::Instance'
          Metadata:
            Comment1: Launch Juniper VSRX1
          Properties:
            InstanceType: !FindInMap
              - vSRXInstance
              - !Ref VSRXType
              - Type
            KeyName: !Ref KeyName
            DisableApiTermination: !If
              - EnableTerm
              - true
              - false
            ImageId: !FindInMap
              - JunipervSRXAMI
              - !Ref 'AWS::Region'
              - byol
      #https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html
            NetworkInterfaces:
              - NetworkInterfaceId: !Ref vSRXInterface11
                DeviceIndex: '0'
              - NetworkInterfaceId: !Ref vSRXInterface12
                DeviceIndex: '1'
              - NetworkInterfaceId: !Ref vSRXInterface13
                DeviceIndex: '2'
            Tags:
              - Key: Name
                Value: Juniper VSRX Instance
          DependsOn: IGW
        VPCPrivateRoute:
          Type: 'AWS::EC2::Route'
          Properties:
            RouteTableId: !Ref VPCPrivateRouteTable
            DestinationCidrBlock: 0.0.0.0/0
            NetworkInterfaceId: !Ref vSRXInterface13
        VPCPriSubnetRouteTableAssociation1:
          Type: 'AWS::EC2::SubnetRouteTableAssociation'
          Properties:
            SubnetId: !Ref VPCPriSub11
            RouteTableId: !Ref VPCPrivateRouteTable
        VSRXSecurityGroup:
          Type: 'AWS::EC2::SecurityGroup'
          Properties:
            GroupDescription: VSRX Security Group Rules
            VpcId: !Ref vSRXVPC
            SecurityGroupIngress:
              - IpProtocol: tcp
                FromPort: 22
                ToPort: 22
                CidrIp: !Ref AllowedSshIpAddress
              - IpProtocol: icmp
                FromPort: 8
                ToPort: -1
                CidrIp: !Ref AllowedSshIpAddress
              - IpProtocol: tcp
                FromPort: 80
                ToPort: 80
                CidrIp: !Ref AllowedAddress
              - IpProtocol: tcp
                FromPort: 8080
                ToPort: 8080
                CidrIp: !Ref AllowedAddress
              - IpProtocol: tcp
                FromPort: 443
                ToPort: 443
                CidrIp: !Ref AllowedAddress
            SecurityGroupEgress:
              - IpProtocol: '-1'
                FromPort: 0
                ToPort: 65535
                CidrIp: 0.0.0.0/0
      Outputs:
        VSRXInstanceId:
          Description: The name of the VSRX Instance created
          Value: !Ref VpcvSRXEC2Instance1
        VPCId:
          Description: The name of the VPCID of VPC created
          Value: !Ref vSRXVPC
          Export:
            Name: !Join [ ':', [ !Ref 'AWS::StackName', 'vSRXVPC' ] ]
        PublicSubnetId11:
          Description: The name of the SubnetId of VPC created
          Value: !Ref VPCPubSub11
          Export:
            Name: !Join [ ':', [ !Ref 'AWS::StackName', 'VPCPubSub11' ] ]
        PublicSubnetId12:
          Description: The name of the SubnetId of VPC created
          Value: !Ref VPCPubSub12
          Export:
            Name: !Join [ ':', [ !Ref 'AWS::StackName', 'VPCPubSub12' ] ]
        PrivateSubnetId11:
          Description: The name of the SubnetId of VPC created
          Value: !Ref VPCPriSub11
          Export:
            Name: !Join [ ':', [ !Ref 'AWS::StackName', 'VPCPriSub11' ] ]
        VSRXSecurityGroup:
          Description: The name of the SubnetId of VPC created
          Value: !Ref VSRXSecurityGroup
          Export:
            Name: !Join [ ':', [ !Ref 'AWS::StackName', 'VSRXSecurityGroup' ] ]
        VSRXIPAddress:
          Description: Management IP Address for VSRX
          Value: !GetAtt
            - VpcvSRXEC2Instance1
            - PublicIp
        ManagementIP:
          Description: The name of the VPCID of VPC created
          Value: !Ref vSRXEip11
          Export:
            Name: !Join [ ':', [ !Ref 'AWS::StackName', 'ManagementElasticIP' ] ]
        RevenueIP:
          Description: The name of the VPCID of VPC created
          Value: !Ref vSRXEip12
          Export:
            Name: !Join [ ':', [ !Ref 'AWS::StackName', 'RevenueDataElasticIP' ] ]
  • Step 3: Once your template is ready and valid, Run it via EC2 console or AWS CLI

    • Commands to run

      • Using AWS Console

      • Using AWS Cli For e.g.

        • aws cloudformation create-stack --region ${REGION_NAME} --stack-name ${PROVIDE_STACKNAME_HERE} --template-body file://${PROVIDE_TEMPLATE_NAME}
        • Example Command is below

        • aws cloudformation create-stack --region us-west-1 --stack-name k2-vSRX --template-body file
  • Step 4: Create policy shell script as per your use case and apply them on vSRX instance, for more details checkout the Complete Example.

  • Step 5: (As per the current vSRX configuration support) Enable password based SSH on the vSRX instance using the following commands.

    • SSH to vSRX instance.

      ssh -i <pem-file> ec2-user@<ManagementElasticIP>
    • Enter the configure mode.

      configure
    • Delete existing no-passwords rule.

      delete groups aws-default system services ssh no-passwords
    • Enable ssh using password.

      set groups aws-default system services ssh
    • Set plain-text-password for the SSH login user and set its class to super-user .

      set system login user ec2-user class super-user authentication plain-text-password
    • Commit the changes.

      commit
    • Exit from the vSRX controller instance.

      exit

Part 2: Installation of K2 agents on EC2 instances

  • Step 1: K2-SaaS Setup on EC2 instance where Web application runs:

    • Update the following parameters from the sample yml below

      • General Parameters

        • ParentStackName : Name of the parent CloudFormation stack using which the vSRX controller is deployed.

        • KeyName : Name of an existing EC2 KeyPair to enable SSH access to the Ec2 instance.

        • InstanceType : WebServer EC2 instance type.

      • K2 Parameters

        • k2IsDocker : Set docker or non docker install of K2 agents, true for docker install and vice versa.

        • k2IsPrivileged : Set privileged mode installation of K2 agents, true for privileged mode and vice versa.

        • k2VersionNumber : Set the K2 agents version for download for e.g. 1.10.10

        • k2CustomerId : Set your K2 customer Id for e.g. 1101

        • k2TempToken : Set the temp token for K2 agents tarball download, You can get it from K2 Manager UI.

      • AMIID Mappings

        • Mappings : Update the mappings and specify the AMI Id for K2 Demo Instance.

          • The AMI-ID should be updated for the region in which you wish to deploy the K2 agent.

      • AWSTemplateFormatVersion: 2010-09-09
        Description: >-
          (K20001) - This template creates a Juniper vSRX instance along with Instance where
          Vulnerable application along with k2 agents is installed ***NOTE*** You must
          first subscribe to the appropriate Juniper VSRX marketplace AMI from the
          before you launch this template.
        Parameters:
          ParentStackName:
            Description: Name of Parent Stack which is vSRX Stack Name as this cloudformation template will reuse some resources from vsrx stack like vpc, subnets.
            Default: vsrx #Configurable Section1
            Type: String
          KeyName:
            Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
            Default: cft #Configurable Section2
            Type: AWS::EC2::KeyPair::KeyName
            ConstraintDescription: must be the name of an existing EC2 KeyPair.
         InstanceType:
            Description: WebServer EC2 instance type
            Type: String
            Default: t2.medium
            AllowedValues: [t2.nano, t2.micro, t2.small, t2.medium, t2.large, t2.xlarge, t2.2xlarge,
              t3.nano, t3.micro, t3.small, t3.medium, t3.large, t3.xlarge, t3.2xlarge,
              m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge,
              m5.large, m5.xlarge, m5.2xlarge, m5.4xlarge,
              c5.large, c5.xlarge, c5.2xlarge, c5.4xlarge, c5.9xlarge,
              g3.8xlarge,
              r5.large, r5.xlarge, r5.2xlarge, r5.4xlarge,
              i3.xlarge, i3.2xlarge, i3.4xlarge, i3.8xlarge,
              d2.xlarge, d2.2xlarge, d2.4xlarge, d2.8xlarge]
            ConstraintDescription: must be a valid EC2 instance type.
            
          ############################ K2 Configuration #1 Starts Here  ############################
          k2IsDocker:
            Type: String
            Default: "true" #Configurable Section2
            Description: If you want to install k2 agent in docker mode then set this parameter
                         to true otherwise if in non docker mode then set it to false.
            AllowedValues:
              ["true",
              "false"]
          k2CloudIP:
            Type: String
            Default: "k2io.net" #Configurable Section2 # Use In general "k2io.net"
            Description: Public IP of K2Cloud
          # k2IsPrivileged:
          #   Type: String
          #   Default: "false" #Configurable Section3
          #   Description: If you want to install k2 agent in privileged mode then set this parameter
          #                to true otherwise if in non privileged mode then set it to false.
          #   AllowedValues:
          #     ["true",
          #     "false"]
          k2VersionNumber:
            Type: String
            Default: "1.10.14" #Configurable Section4
            Description: Version of K2 agents
          k2CustomerId:
            Type: String
            Default: "910"
            Description: Provide your customer id as provided in k2 portal.
          k2TempToken:
            Type: String
            Default: "65470008664519211083609100231891391175" #Configurable Section5
            Description: Temp token to install k2 agents tarball.
        ############################ K2 Configuration #1 Ends Here ############################
        Mappings:
          EC2AMI: #Configurable Section6
            us-east-1:
              AMIId: ami-0dd3922502962f0ae
            us-east-2:
              AMIId: ami-0dd3922502962f0ae
            us-west-2:
              AMIId: ami-b55a51cc
            us-west-1:
              #AMIId: ami-05db5717b629827c2
              AMIId: ami-0c09e97d0e404cb51
            eu-west-1:
              AMIId: ami-f1978897
            eu-central-1:
              AMIId: ami-0e258161
            ap-northeast-1:
              AMIId: ami-5c9a933b
            ap-southeast-1:
              AMIId: ami-cb981aa8
            ap-southeast-2:
              AMIId: ami-9a3322f9
  • Step 2: Installation of K2 Agents on the EC2 instances

    • Following CFT yml will include :

      • CFN Helper Scripts provisioning

      • K2 Agents Installation

      • K2 Demo application installation (this should be replaced by installation of your own application)

      • 
        Resources:
          vSRXInterface14:
            Type: 'AWS::EC2::NetworkInterface'
            Properties:
              Description: vSRXPrivateInterface1
              PrivateIpAddress: 200.0.2.44
              SourceDestCheck: false
              GroupSet:
                - Fn::ImportValue:
                    !Join [':', [!Ref 'ParentStackName', 'VSRXSecurityGroup']]
              SubnetId:
                Fn::ImportValue:
                  !Join [':', [!Ref 'ParentStackName', 'VPCPriSub11']]
          DemoInstance:
            Type: AWS::EC2::Instance
            Metadata:
        ############################ K2 Configuration #2 Starts Here  ############################
              AWS::CloudFormation::Init:
                configSets:
                  ascending:
                    - cfn_init_configuration
                    - k2_install
                    - k2_demo_app
                cfn_init_configuration:
                  files:
                     '/etc/cfn/cfn-hup.conf':
                       content: !Sub |
                         [main]
                         stack=${AWS::StackId}
                         region=${AWS::Region}
                         interval=1
                       mode: '000400'
                       owner: root
                       group: root
                     '/lib/systemd/system/cfn-hup.service':
                        content: |
                          [Unit]
                          Description=cfn-hup daemon
                          [Service]
                          Type=simple
                          ExecStart=/opt/aws/bin/cfn-hup
                          Restart=always
                          [Install]
                          WantedBy=multi-user.target
                  commands:
                    01enable_cfn_hup:
                      command:
                        systemctl enable cfn-hup.service
                    02start_cfn_hup:
                      command:
                        systemctl start cfn-hup.service
                k2_install:
                  files:
                    /tmp/k2tmpinstall.sh:
                      content: !Sub |
                        #!/bin/bash
                        sudo wget -O vm-all.zip '${k2CloudIP}/centralmanager/api/v1/help/installers/${k2VersionNumber}/download/${k2CustomerId}/${k2TempToken}/vm-all.zip?isDocker=${k2IsDocker}&groupName=PRODUCTION&agentDeploymentEnvironment=PRODUCTION&pullPolicyRequired=false'
                        sudo unzip vm-all.zip
                        sudo chown -R root:root k2install
                        sudo chmod 755 k2install
                        cd k2install
                        sudo bash k2install.sh -i prevent-web
                      mode: "000777"
                      owner: "root"
                      group: "root"
                  commands:
                    k2command:
                      command: bash /tmp/k2tmpinstall.sh > /tmp/k2out.log 2>&1
                      cwd: /tmp/
                k2_demo_app:
                  commands:
                    demoapp:
                      command: docker run -v /opt/k2-ic:/opt/k2-ic -itd -p 8080:8080 -e JAVA_OPTS=" -javaagent:/opt/k2-ic/K2-JavaAgent-1.0.0-jar-with-dependencies.jar" --name k2-demo-application k2cyber/ic-test-application:single-container-application
                      cwd: /tmp/
            Properties:
              NetworkInterfaces:
                - NetworkInterfaceId: !Ref vSRXInterface14
                  DeviceIndex: '0'
              UserData:
                Fn::Base64: !Sub |
                  #!/bin/bash
                  distribution=`cat /etc/os-release | grep -w NAME | awk -F= '{print $2}' | tr -d '"'`
                  if [[ -z $distribution ]]; then
                    distribution=`cat /etc/*release | head -1 | awk -F' ' '{print $1}' | tr -d '"'`
                    version_id=`cat /etc/*release | head -1 | awk -F' ' '{print $3}' | tr -d '"'`
                  fi
                  if [[ ($distribution == "Ubuntu") ]]; then
                      apt-get update -y
                      apt-get install -y python-setuptools
                      apt-get install -y wget
                      apt-get install -y unzip
                  elif [[ (($distribution == "Fedora" ) || ($distribution == "CentOS Linux") || ( $distribution == "Red Hat Enterprise Linux Server") || ($distribution == "Red Hat Enterprise Linux") || ($distribution == "Amazon Linux") || ($distribution == "Amazon Linux AMI")) ]]; then
                      yum update -y
                      yum install -y python-setuptools
                      yum install -y wget
                      yum install -y unzip
                  else
                    echo "Didn't Update and not able to install prereqs"
                  fi
                  mkdir -p /opt/aws/bin
                  wget https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz
                  python -m easy_install --script-dir /opt/aws/bin aws-cfn-bootstrap-latest.tar.gz > /tmp/cfn-install.log 2>&1
                  /opt/aws/bin/cfn-init -vvv --stack ${AWS::StackName} --resource DemoInstance -c ascending --region ${AWS::Region} > /tmp/cfn-init.log 2>&1
                  /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource DemoInstance --region ${AWS::Region} > /tmp/cfn-signal.log 2>&1
        ############################ K2 Configuration #2 Ends Here  ############################
        # Below Parts will come from customer
              ImageId: !FindInMap
                - EC2AMI
                - !Ref 'AWS::Region'
                - AMIId
              InstanceType: !Ref 'InstanceType'
              KeyName: !Ref 'KeyName'
              BlockDeviceMappings:
              - DeviceName: "/dev/sda1"
                Ebs:
                  VolumeType: "gp2"
                  DeleteOnTermination: true
                  VolumeSize: 200
              Tags:
                - Key: Name
                  Value: K2Agent with Vulnerable Application
        
        Outputs:
          InstanceId:
            Description: InstanceId of the newly created EC2 instance
            Value: !Ref 'DemoInstance'
          AZ:
            Description: Availability Zone of the newly created EC2 instance
            Value: !GetAtt [DemoInstance, AvailabilityZone]
  • Step 3: Once your template is ready and valid, Run it via EC2 console or AWS CLI

    • Commands to run

      • Using AWS Console

      • Using AWS Cli For e.g.

        • aws cloudformation create-stack --region ${REGION_NAME} --stack-name ${PROVIDE_STACKNAME_HERE} --template-body file://${PROVIDE_TEMPLATE_NAME}
        • Example Command is below

        • aws cloudformation create-stack --region us-west-1 --stack-name k2-vSRX --template-body file
  • Step 4: Verification

    • Two EIPs will be attached to vSRX Instance

      • Revenue Data EIP : A Revenue port is used for traffic processing. You can access the vulnerable app through revenue data elastic ip of vsrx instance (http://${REVENUE_DATA_IP}:8080).

        • SSH to secondary instance behind vSRX instance using revenue data ip.

      • Management EIP : The management interface is preconfigured with the AWS Elastic IP and default route. You can login to vSRX instance using Management IP and verify all the vSRX policies are set fine.

        • Login to vSRX instance

        • Go to configuration mode

          • configure
        • Check all the security policies applied to vSRX instance

          • show security policies
  • Step 5: Attack Detection

    • On the Vulnerable Application, there is broad category of attacks availible, you can launch one of the attacks like File based, Remote code, SQL Injection etc.

    • Access K2 SaaS portal (https://k2io.net/centralmanager ) and sign in with your username and password.

    • Attack detected would be shown in the attacks tab of K2 SaaS portal.

Part 3 : Configure vSRX policies using K2Manager

Step 1 : Open Firewall Integration

Go to Settings tab and go to Firewall Integration in dropdown list of Settings.

​Firewall | K2 Portal

Step 2 : Add a new Firewall Configuration Rule

Add a new Firewall Configuration Rule

  • Click on + on right side of the Firewall Integration view to add new firewall configuration

  • Configure the following attributes:

    • Firewall IP : vSRX controller IP

    • Username: SSH user (Used to SSH to vSRX controller instance)

    • Password: SSH password (Used to SSH to vSRX controller instance)

    • Update Interval: Periodic interval at which the xSRX controller pulls the information from K2

    • SNAT Enabled: True (For static NAT)​

Step 3 : Add Blocking List Configurations

Step 4 : Add Allowed List Configurations​

Complete Template Example

Following steps will show how to deploy vSRX in a VPC and K2 Agents on EC2 Instances in that VPC via cloudformation template.

Cloudformation Template :

Setup and Configure parameters in below template as per you environment :

  • KeyName : Name of an existing EC2 KeyPair to enable SSH access to the instance.

  • AllowedSshIpAddress : Source IP address (CIDR notation) from which SSH to vSRXs is allowed.

  • AllowedAddress : Source IP address (CIDR notation) from which any access to vSRXs is allowed.

  • TerminationProtection: Enable termination protection on the VSRX EC2 instances to avoid accidential VSRX termination?.

  • VpcCidr : CIDR block for vSRX VPC.

  • PubSubnet1 : Address range for vSRX VPC management subnet.

  • PubSubnet2 : Address range for vSRX VPC data subnet to be created in AZ1.

  • PriSubnet1 : Address range for vSRX VPC private subnet to be created in AZ1.

  • VSRXType : Virtual machine size required for VSRX instances.

  • K2DemoInstanceType : WebServer EC2 instance type.

  • k2IsDocker : Set docker or non docker install of K2 agents, true for docker install and vice versa.

  • k2IsPrivileged : Set privileged mode installation of K2 agents, true for privileged mode and vice versa.

  • k2VersionNumber : Set the K2 agents version for download for e.g. 1.10.10

  • k2CustomerId : Set your K2 customer Id for e.g. 1101

  • k2TempToken : Set the temp token for K2 agents tarball download, You can get it from K2 Manager UI.

  • Mappings : Update the mappings and specify the AMI Id for vSRX and k2demo machine respectively

VSRX.yml


AWSTemplateFormatVersion: 2010-09-09
Description: >-
  (K20001) - This template creates a Juniper vSRX instance along with Instance where
  Vulnerable application along with k2 agents is installed ***NOTE*** You must
  first subscribe to the appropriate Juniper VSRX marketplace AMI from the
  before you launch this template.
Parameters:
  KeyName:
    Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
    Default: cft #Configurable Section1
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: must be the name of an existing EC2 KeyPair.
  AllowedSshIpAddress:
    Description: Source IP address (CIDR notation) from which SSH to vSRXs is allowed
    Type: String
    Default: 0.0.0.0/0
  AllowedAddress:
    Description: Source IP address (CIDR notation) from which any access to vSRXs is allowed
    Type: String
    Default: 0.0.0.0/0
############################ Juniper Configuration #1 Starts Here  ############################
  TerminationProtection:
    Description: >-
      Enable termination protection on the VSRX EC2 instances to avoid
      accidential VSRX termination?
    Type: String
    Default: 'No'
    AllowedValues:
      - 'Yes'
      - 'No'
  VpcCidr:
    Description: CIDR block for vSRX VPC.
    Type: String
    Default: 200.0.0.0/16
  PubSubnet1:
    Description: Address range for vSRX VPC management subnet.
    Type: String
    Default: 200.0.254.0/24
  PubSubnet2:
    Description: Address range for vSRX VPC data subnet to be created in AZ1.
    Type: String
    Default: 200.0.1.0/24
  PriSubnet1:
    Description: Address range for vSRX VPC private subnet to be created in AZ1.
    Type: String
    Default: 200.0.2.0/24
  VSRXType:
    Description: Virtual machine size required for VSRX instances.
    Type: String
    Default: C4.Xlarge
    AllowedValues:
      - C4.Xlarge
Conditions:
  EnableTerm: !Equals
    - !Ref TerminationProtection
    - 'Yes'
Metadata:
  'AWS::CloudFormation::Interface':
    ParameterGroups:
      - Label:
          default: Juniper VSRX Configuration
        Parameters:
          - VSRXType
          - KeyName
          - TerminationProtection
      - Label:
          default: Network Configuration
        Parameters:
          - VpcCidr
          - AllowedSshIpAddress
          - PubSubnet1
          - PubSubnet2
          - PriSubnet1
    ParameterLabels:
      AllowedSshIpAddress:
        default: Allowed IP Address to SSH from
      VpcCidr:
        default: vSRX VPC CIDR Block
      PubSubnet1:
        default: vSRX1- Management Subnet Network
      PubSubnet2:
        default: vSRX1- Data Subnet Network
      PriSubnet1:
        default: vSRX1- Private Subnet
      VSRXType:
        default: vSRX Instance Size
      KeyName:
        default: SSH Key to access VSRX
      TerminationProtection:
        default: Enable Termination Protection
Mappings:
  JunipervSRXAMI: #Configurable Section7
    us-east-1:
      byol: ami-40058d3a
    us-east-2:
      byol: ami-e6a18983
    us-west-2:
      byol: ami-cddd71b5
    us-west-1:
      byol: ami-04283cf0a2bf7c17c
    ca-central-1:
      byol: ami-ab04bbcf
    eu-west-1:
      byol: ami-2117ff58
    eu-west-2:
      byol: ami-d76f7eb3
    eu-central-1:
      byol: ami-f8fd7f97
    ap-south-1:
      byol: ami-26f68e49
    ap-southeast-1:
      byol: ami-c5a331a6
    ap-southeast-2:
      byol: ami-14c1de77
    ap-northeast-1:
      byol: ami-02729164
    ap-northeast-2:
      byol: ami-2bbe6745
    sa-east-1:
      byol: ami-0656216a
  vSRXInstance:
    C4.Xlarge:
      Type: c4.xlarge
      Bandwidth: '500000'
Resources:
  vSRXVPC:
    Type: 'AWS::EC2::VPC'
    Properties:
      CidrBlock: !Ref VpcCidr
      Tags:
        - Key: Name
          Value: vSRX VPC
  VPCPubSub11:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref vSRXVPC
      CidrBlock: !Ref PubSubnet1
      MapPublicIpOnLaunch: false #Can be removed not Necessary
      AvailabilityZone: !Select
        - '0'
        - !GetAZs ''
      Tags:
        - Key: Network
          Value: Public
        - Key: Name
          Value: vSRX VPC Management Subnet 1
  VPCPubSub12:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref vSRXVPC
      CidrBlock: !Ref PubSubnet2
      AvailabilityZone: !Select
        - '0'
        - !GetAZs ''
      Tags:
        - Key: Network
          Value: Public
        - Key: Name
          Value: vSRX VPC Data Subnet 1
  VPCPriSub11:
    Type: 'AWS::EC2::Subnet'
    Properties:
      VpcId: !Ref vSRXVPC
      CidrBlock: !Ref PriSubnet1
      AvailabilityZone: !Select
        - '0'
        - !GetAZs ''
      Tags:
        - Key: Network
          Value: Private
        - Key: Name
          Value: vSRX VPC Private Subnet 1
  IGW:
    Type: 'AWS::EC2::InternetGateway'
    Properties:
      Tags:
        - Key: Name
          Value: vSRX VPC IGW
  IGWToInternet:
    Type: 'AWS::EC2::VPCGatewayAttachment'
    Properties:
      VpcId: !Ref vSRXVPC
      InternetGatewayId: !Ref IGW
  VPCPublicRouteTable:
    Type: 'AWS::EC2::RouteTable'
    Properties:
      VpcId: !Ref vSRXVPC
      Tags:
        - Key: Network
          Value: Public
        - Key: Name
          Value: vSRX VPC
  VPCPublicRoute:
    Type: 'AWS::EC2::Route'
    Properties:
      RouteTableId: !Ref VPCPublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref IGW
  VPCPrivateRouteTable:
    Type: 'AWS::EC2::RouteTable'
    Properties:
      VpcId: !Ref vSRXVPC
      Tags:
        - Key: Network
          Value: Private
        - Key: Name
          Value: vSRX VPCPrivateRouteTable
  S3Endpoint:
    Type: 'AWS::EC2::VPCEndpoint'
    Properties:
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal: '*'
            Action:
              - 's3:*'
            Resource:
              - '*'
      RouteTableIds:
        - !Ref VPCPublicRouteTable
        - !Ref VPCPrivateRouteTable
      ServiceName: !Join
        - ''
        - - com.amazonaws.
          - !Ref 'AWS::Region'
          - .s3
      VpcId: !Ref vSRXVPC
  VPCPubSubnetRouteTableAssociation1:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref VPCPubSub11
      RouteTableId: !Ref VPCPublicRouteTable
  VPCPubSubnetRouteTableAssociation2:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref VPCPubSub12
      RouteTableId: !Ref VPCPublicRouteTable
  vSRXInterface11:
    Type: 'AWS::EC2::NetworkInterface'
    Properties:
      Description: vSRXManagementInterface1
      PrivateIpAddress: 200.0.254.154
      SourceDestCheck: false
      GroupSet:
        - !Ref VSRXSecurityGroup
      SubnetId: !Ref VPCPubSub11
  vSRXInterface12:
    Type: 'AWS::EC2::NetworkInterface'
    Properties:
      Description: vSRXRevenueInterface1
      PrivateIpAddress: 200.0.1.11
      SourceDestCheck: false
      GroupSet:
        - !Ref VSRXSecurityGroup
      SubnetId: !Ref VPCPubSub12
  vSRXInterface13:
    Type: 'AWS::EC2::NetworkInterface'
    Properties:
      Description: vSRXPrivateInterface1
      PrivateIpAddress: 200.0.2.22
      SourceDestCheck: false
      GroupSet:
        - !Ref VSRXSecurityGroup
      SubnetId: !Ref VPCPriSub11
  vSRXEip11:
    Type: 'AWS::EC2::EIP'
    Properties:
      Domain: vpc
      Tags:
        - Key: Name
          Value: ManagementElasticIP
  vSRXEip12:
    Type: 'AWS::EC2::EIP'
    Properties:
      Domain: vpc
      Tags:
        - Key: Name
          Value: RevenueDataElasticIP
  AssociateEIP11:
    Type: 'AWS::EC2::EIPAssociation'
    Properties:
      AllocationId: !GetAtt
        - vSRXEip11
        - AllocationId
      NetworkInterfaceId: !Ref vSRXInterface11
  AssociateEIP12:
    Type: 'AWS::EC2::EIPAssociation'
    Properties:
      AllocationId: !GetAtt
        - vSRXEip12
        - AllocationId
      NetworkInterfaceId: !Ref vSRXInterface12
  VpcvSRXEC2Instance1:
    Type: 'AWS::EC2::Instance'
    Metadata:
      Comment1: Launch Juniper VSRX1
    Properties:
      # UserData:
      #   Fn::Base64:
      #     #!/bin/bash
      #     sleep 180
      #     configure
      #     set interfaces ge-0/0/0 unit 0 family inet address 200.0.1.11/24
      #     set interfaces ge-0/0/1 unit 0 family inet address 200.0.2.22/24
      #     set security zones security-zone untrust host-inbound-traffic system-services https
      #     set security zones security-z0one untrust host-inbound-traffic system-services ssh
      #     set security zones security-zone untrust host-inbound-traffic system-services http
      #     set security zones security-zone untrust host-inbound-traffic system-services ping
      #     set security zones security-zone untrust interfaces ge-0/0/0.0
      #     set security zones security-zone trust host-inbound-traffic system-services https
      #     set security zones security-zone trust host-inbound-traffic system-services ssh
      #     set security zones security-zone trust host-inbound-traffic system-services ping
      #     set security zones security-zone trust host-inbound-traffic system-services http
      #     set security zones security-zone trust interfaces ge-0/0/1.0
      #     set security policies from-zone untrust to-zone trust policy access-from-internet-to-server match source-address any
      #     set security policies from-zone untrust to-zone trust policy access-from-internet-to-server match destination-address any
      #     set security policies from-zone untrust to-zone trust policy access-from-internet-to-server match application any
      #     set security policies from-zone untrust to-zone trust policy access-from-internet-to-server then permit
      #     set security policies from-zone trust to-zone untrust policy access-from-server-to-internet match source-address any
      #     set security policies from-zone trust to-zone untrust policy access-from-server-to-internet match destination-address any
      #     set security policies from-zone trust to-zone untrust policy access-from-server-to-internet match application any
      #     set security policies from-zone trust to-zone untrust policy access-from-server-to-internet then permit
      #     set security nat source rule-set UNTRUST_TO_TRUST_SOURCE_NAT from zone untrust
      #     set security nat source rule-set UNTRUST_TO_TRUST_SOURCE_NAT to zone trust
      #     set security nat source rule-set UNTRUST_TO_TRUST_SOURCE_NAT rule U_TO_T_SOURCE_NAT_IPV4 match source-address 0.0.0.0/0
      #     set security nat source rule-set UNTRUST_TO_TRUST_SOURCE_NAT rule U_TO_T_SOURCE_NAT_IPV4 match destination-address 0.0.0.0/0
      #     set security nat source rule-set UNTRUST_TO_TRUST_SOURCE_NAT rule U_TO_T_SOURCE_NAT_IPV4 then source-nat interface
      #     set security nat source rule-set TRUST_TO_UNTRUST_SOURCE_NAT from zone trust
      #     set security nat source rule-set TRUST_TO_UNTRUST_SOURCE_NAT to zone untrust
      #     set security nat source rule-set TRUST_TO_UNTRUST_SOURCE_NAT rule T_TO_U_SOURCE_NAT_IPV4 match source-address 0.0.0.0/0
      #     set security nat source rule-set TRUST_TO_UNTRUST_SOURCE_NAT rule T_TO_U_SOURCE_NAT_IPV4 match destination-address 0.0.0.0/0
      #     set security nat source rule-set TRUST_TO_UNTRUST_SOURCE_NAT rule T_TO_U_SOURCE_NAT_IPV4 then source-nat interface
      #     set security nat destination pool DEST_NAT_TARGET_10_0_253_46 address 200.0.2.44/32
      #     set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT from interface ge-0/0/0.0
      #     set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-address 200.0.1.11/32
      #     set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-port 80
      #     set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-port 22
      #     set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-port 443
      #     set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-port 8080
      #     set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-port 9090
      #     set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 then destination-nat pool DEST_NAT_TARGET_10_0_253_46
      #     set routing-instances fwdd_vr instance-type virtual-router
      #     set routing-instances fwdd_vr interface ge-0/0/0.0
      #     set routing-instances fwdd_vr interface ge-0/0/1.0
      #     set routing-instances fwdd_vr routing-options static route 0.0.0.0/0 next-hop 200.0.1.1
      #     commit
      InstanceType: !FindInMap
        - vSRXInstance
        - !Ref VSRXType
        - Type
      KeyName: !Ref KeyName
      DisableApiTermination: !If
        - EnableTerm
        - true
        - false
      ImageId: !FindInMap
        - JunipervSRXAMI
        - !Ref 'AWS::Region'
        - byol
#https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html
      NetworkInterfaces:
        - NetworkInterfaceId: !Ref vSRXInterface11
          DeviceIndex: '0'
        - NetworkInterfaceId: !Ref vSRXInterface12
          DeviceIndex: '1'
        - NetworkInterfaceId: !Ref vSRXInterface13
          DeviceIndex: '2'
      Tags:
        - Key: Name
          Value: Juniper VSRX Instance
    DependsOn: IGW
  VPCPrivateRoute:
    Type: 'AWS::EC2::Route'
    Properties:
      RouteTableId: !Ref VPCPrivateRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      NetworkInterfaceId: !Ref vSRXInterface13
  VPCPriSubnetRouteTableAssociation1:
    Type: 'AWS::EC2::SubnetRouteTableAssociation'
    Properties:
      SubnetId: !Ref VPCPriSub11
      RouteTableId: !Ref VPCPrivateRouteTable
  VSRXSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: VSRX Security Group Rules
      VpcId: !Ref vSRXVPC
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: !Ref AllowedSshIpAddress
        - IpProtocol: icmp
          FromPort: 8
          ToPort: -1
          CidrIp: !Ref AllowedSshIpAddress
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: !Ref AllowedAddress
        - IpProtocol: tcp
          FromPort: 8080
          ToPort: 8080
          CidrIp: !Ref AllowedAddress
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: !Ref AllowedAddress
      SecurityGroupEgress:
        - IpProtocol: '-1'
          FromPort: 0
          ToPort: 65535
          CidrIp: 0.0.0.0/0
Outputs:
  VSRXInstanceId:
    Description: The name of the VSRX Instance created
    Value: !Ref VpcvSRXEC2Instance1
  VPCId:
    Description: The name of the VPCID of VPC created
    Value: !Ref vSRXVPC
    Export:
      Name: !Join [ ':', [ !Ref 'AWS::StackName', 'vSRXVPC' ] ]
  PublicSubnetId11:
    Description: The name of the SubnetId of VPC created
    Value: !Ref VPCPubSub11
    Export:
      Name: !Join [ ':', [ !Ref 'AWS::StackName', 'VPCPubSub11' ] ]
  PublicSubnetId12:
    Description: The name of the SubnetId of VPC created
    Value: !Ref VPCPubSub12
    Export:
      Name: !Join [ ':', [ !Ref 'AWS::StackName', 'VPCPubSub12' ] ]
  PrivateSubnetId11:
    Description: The name of the SubnetId of VPC created
    Value: !Ref VPCPriSub11
    Export:
      Name: !Join [ ':', [ !Ref 'AWS::StackName', 'VPCPriSub11' ] ]
  VSRXSecurityGroup:
    Description: The name of the SubnetId of VPC created
    Value: !Ref VSRXSecurityGroup
    Export:
      Name: !Join [ ':', [ !Ref 'AWS::StackName', 'VSRXSecurityGroup' ] ]
  VSRXIPAddress:
    Description: Management IP Address for VSRX
    Value: !GetAtt
      - VpcvSRXEC2Instance1
      - PublicIp
  ManagementIP:
    Description: The name of the VPCID of VPC created
    Value: !Ref vSRXEip11
    Export:
      Name: !Join [ ':', [ !Ref 'AWS::StackName', 'ManagementElasticIP' ] ]
  RevenueIP:
    Description: The name of the VPCID of VPC created
    Value: !Ref vSRXEip12
    Export:
      Name: !Join [ ':', [ !Ref 'AWS::StackName', 'RevenueDataElasticIP' ] ]

vsrx-policies.sh

# ssh -i "/mnt/c/Users/dell/Downloads/cftwest1.pem" ec2-user@13.57.70.243 < /mnt/e/Projects/install/cloudformation/ec2/vsrx-policies.sh
configure
set interfaces ge-0/0/0 unit 0 family inet address 200.0.1.11/24
set interfaces ge-0/0/1 unit 0 family inet address 200.0.2.22/24
set security zones security-zone untrust host-inbound-traffic system-services https
set security zones security-zone untrust host-inbound-traffic system-services ssh
set security zones security-zone untrust host-inbound-traffic system-services http
set security zones security-zone untrust host-inbound-traffic system-services ping
set security zones security-zone untrust interfaces ge-0/0/0.0
set security zones security-zone trust host-inbound-traffic system-services https
set security zones security-zone trust host-inbound-traffic system-services ssh
set security zones security-zone trust host-inbound-traffic system-services ping
set security zones security-zone trust host-inbound-traffic system-services http
set security zones security-zone trust interfaces ge-0/0/1.0
set security policies from-zone untrust to-zone trust policy access-from-internet-to-server match source-address any
set security policies from-zone untrust to-zone trust policy access-from-internet-to-server match destination-address any
set security policies from-zone untrust to-zone trust policy access-from-internet-to-server match application any
set security policies from-zone untrust to-zone trust policy access-from-internet-to-server then permit
set security policies from-zone trust to-zone untrust policy access-from-server-to-internet match source-address any
set security policies from-zone trust to-zone untrust policy access-from-server-to-internet match destination-address any
set security policies from-zone trust to-zone untrust policy access-from-server-to-internet match application any
set security policies from-zone trust to-zone untrust policy access-from-server-to-internet then permit
set security nat source rule-set UNTRUST_TO_TRUST_SOURCE_NAT from zone untrust
set security nat source rule-set UNTRUST_TO_TRUST_SOURCE_NAT to zone trust
set security nat source rule-set UNTRUST_TO_TRUST_SOURCE_NAT rule U_TO_T_SOURCE_NAT_IPV4 match source-address 0.0.0.0/0
set security nat source rule-set UNTRUST_TO_TRUST_SOURCE_NAT rule U_TO_T_SOURCE_NAT_IPV4 match destination-address 0.0.0.0/0
set security nat source rule-set UNTRUST_TO_TRUST_SOURCE_NAT rule U_TO_T_SOURCE_NAT_IPV4 then source-nat interface
set security nat source rule-set TRUST_TO_UNTRUST_SOURCE_NAT from zone trust
set security nat source rule-set TRUST_TO_UNTRUST_SOURCE_NAT to zone untrust
set security nat source rule-set TRUST_TO_UNTRUST_SOURCE_NAT rule T_TO_U_SOURCE_NAT_IPV4 match source-address 0.0.0.0/0
set security nat source rule-set TRUST_TO_UNTRUST_SOURCE_NAT rule T_TO_U_SOURCE_NAT_IPV4 match destination-address 0.0.0.0/0
set security nat source rule-set TRUST_TO_UNTRUST_SOURCE_NAT rule T_TO_U_SOURCE_NAT_IPV4 then source-nat interface
set security nat destination pool DEST_NAT_TARGET_10_0_253_46 address 200.0.2.44/32
set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT from interface ge-0/0/0.0
set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-address 200.0.1.11/32
set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-port 80
set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-port 22
set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-port 443
set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-port 8080
set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 match destination-port 9090
set security nat destination rule-set INCOMING_ON_GE_0_DEST_NAT rule DEST_NAT_2_240 then destination-nat pool DEST_NAT_TARGET_10_0_253_46
set routing-instances fwdd_vr instance-type virtual-router
set routing-instances fwdd_vr interface ge-0/0/0.0
set routing-instances fwdd_vr interface ge-0/0/1.0
set routing-instances fwdd_vr routing-options static route 0.0.0.0/0 next-hop 200.0.1.1
commit

K2-SAAS.yml

AWSTemplateFormatVersion: 2010-09-09
Description: >-
  (K20001) - This template creates a Juniper vSRX instance along with Instance where
  Vulnerable application along with k2 agents is installed ***NOTE*** You must
  first subscribe to the appropriate Juniper VSRX marketplace AMI from the
  before you launch this template.
Parameters:
  ParentStackName:
    Description: Name of Parent Stack which is vSRX Stack Name as this cloudformation template will reuse some resources from vsrx stack like vpc, subnets.
    Default: vsrx #Configurable Section1
    Type: String
  KeyName:
    Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
    Default: cft #Configurable Section2
    Type: AWS::EC2::KeyPair::KeyName
    ConstraintDescription: must be the name of an existing EC2 KeyPair.
############################ K2 Configuration #1 Starts Here  ############################
  InstanceType:
    Description: WebServer EC2 instance type
    Type: String
    Default: t2.medium
    AllowedValues: [t2.nano, t2.micro, t2.small, t2.medium, t2.large, t2.xlarge, t2.2xlarge,
      t3.nano, t3.micro, t3.small, t3.medium, t3.large, t3.xlarge, t3.2xlarge,
      m4.large, m4.xlarge, m4.2xlarge, m4.4xlarge, m4.10xlarge,
      m5.large, m5.xlarge, m5.2xlarge, m5.4xlarge,
      c5.large, c5.xlarge, c5.2xlarge, c5.4xlarge, c5.9xlarge,
      g3.8xlarge,
      r5.large, r5.xlarge, r5.2xlarge, r5.4xlarge,
      i3.xlarge, i3.2xlarge, i3.4xlarge, i3.8xlarge,
      d2.xlarge, d2.2xlarge, d2.4xlarge, d2.8xlarge]
    ConstraintDescription: must be a valid EC2 instance type.
  k2IsDocker:
    Type: String
    Default: "true" #Configurable Section2
    Description: If you want to install k2 agent in docker mode then set this parameter
                 to true otherwise if in non docker mode then set it to false.
    AllowedValues:
      ["true",
      "false"]
  k2CloudIP:
    Type: String
    Default: "k2io.net" #Configurable Section2 # Use In general "k2io.net"
    Description: Public IP of K2Cloud
  # k2IsPrivileged:
  #   Type: String
  #   Default: "false" #Configurable Section3
  #   Description: If you want to install k2 agent in privileged mode then set this parameter
  #                to true otherwise if in non privileged mode then set it to false.
  #   AllowedValues:
  #     ["true",
  #     "false"]
  k2VersionNumber:
    Type: String
    Default: "1.10.14" #Configurable Section4
    Description: Version of K2 agents
  k2CustomerId:
    Type: String
    Default: "910"
    Description: Provide your customer id as provided in k2 portal.
  k2TempToken:
    Type: String
    Default: "65470008664519211083609100231891391175" #Configurable Section5
    Description: Temp token to install k2 agents tarball.
############################ K2 Configuration #1 Ends Here ############################
Mappings:
  EC2AMI: #Configurable Section6
    us-east-1:
      AMIId: ami-0dd3922502962f0ae
    us-east-2:
      AMIId: ami-0dd3922502962f0ae
    us-west-2:
      AMIId: ami-b55a51cc
    us-west-1:
      #AMIId: ami-05db5717b629827c2
      AMIId: ami-0c09e97d0e404cb51
    eu-west-1:
      AMIId: ami-f1978897
    eu-central-1:
      AMIId: ami-0e258161
    ap-northeast-1:
      AMIId: ami-5c9a933b
    ap-southeast-1:
      AMIId: ami-cb981aa8
    ap-southeast-2:
      AMIId: ami-9a3322f9

Resources:
  vSRXInterface14:
    Type: 'AWS::EC2::NetworkInterface'
    Properties:
      Description: vSRXPrivateInterface1
      PrivateIpAddress: 200.0.2.44
      SourceDestCheck: false
      GroupSet:
        - Fn::ImportValue:
            !Join [':', [!Ref 'ParentStackName', 'VSRXSecurityGroup']]
      SubnetId:
        Fn::ImportValue:
          !Join [':', [!Ref 'ParentStackName', 'VPCPriSub11']]
  DemoInstance:
    Type: AWS::EC2::Instance
    Metadata:
############################ K2 Configuration #2 Starts Here  ############################
      AWS::CloudFormation::Init:
        configSets:
          ascending:
            - cfn_init_configuration
            - k2_install
            - k2_demo_app
        cfn_init_configuration:
          files:
             '/etc/cfn/cfn-hup.conf':
               content: !Sub |
                 [main]
                 stack=${AWS::StackId}
                 region=${AWS::Region}
                 interval=1
               mode: '000400'
               owner: root
               group: root
             '/lib/systemd/system/cfn-hup.service':
                content: |
                  [Unit]
                  Description=cfn-hup daemon
                  [Service]
                  Type=simple
                  ExecStart=/opt/aws/bin/cfn-hup
                  Restart=always
                  [Install]
                  WantedBy=multi-user.target
          commands:
            01enable_cfn_hup:
              command:
                systemctl enable cfn-hup.service
            02start_cfn_hup:
              command:
                systemctl start cfn-hup.service
        k2_install:
          files:
            /tmp/k2tmpinstall.sh:
              content: !Sub |
                #!/bin/bash
                sudo wget -O vm-all.zip '${k2CloudIP}/centralmanager/api/v1/help/installers/${k2VersionNumber}/download/${k2CustomerId}/${k2TempToken}/vm-all.zip?isDocker=${k2IsDocker}&groupName=PRODUCTION&agentDeploymentEnvironment=PRODUCTION&pullPolicyRequired=false'
                sudo unzip vm-all.zip
                sudo chown -R root:root k2install
                sudo chmod 755 k2install
                cd k2install
                sudo bash k2install.sh -i prevent-web
              mode: "000777"
              owner: "root"
              group: "root"
          commands:
            k2command:
              command: bash /tmp/k2tmpinstall.sh > /tmp/k2out.log 2>&1
              cwd: /tmp/
        k2_demo_app:
          commands:
            demoapp:
              command: docker run -v /opt/k2-ic:/opt/k2-ic -itd -p 8080:8080 -e JAVA_OPTS=" -javaagent:/opt/k2-ic/K2-JavaAgent-1.0.0-jar-with-dependencies.jar" --name k2-demo-application k2cyber/ic-test-application:single-container-application
              cwd: /tmp/
    Properties:
      NetworkInterfaces:
        - NetworkInterfaceId: !Ref vSRXInterface14
          DeviceIndex: '0'
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          # count=70
          # while [[ $count -ne 0 ]] ; do
          #       ping -c 1 8.8.8.8
          #       rc=$?
          #       if [[ $rc -eq 0 ]] ; then
          #         ((count = 1))
          #       fi
          #       ((count = count - 1))
          #       sleep 10
          # done
          # if [[ $rc -eq 0 ]] ; then
          #  echo `say The internet is back up.` > /tmp/connected.out
          # else
          #  echo `say Timeout.` > /tmp/timeout.out
          # fi
          distribution=`cat /etc/os-release | grep -w NAME | awk -F= '{print $2}' | tr -d '"'`
          if [[ -z $distribution ]]; then
            distribution=`cat /etc/*release | head -1 | awk -F' ' '{print $1}' | tr -d '"'`
            version_id=`cat /etc/*release | head -1 | awk -F' ' '{print $3}' | tr -d '"'`
          fi
          if [[ ($distribution == "Ubuntu") ]]; then
              apt-get update -y
              apt-get install -y python-setuptools
              apt-get install -y wget
              apt-get install -y unzip
          elif [[ (($distribution == "Fedora" ) || ($distribution == "CentOS Linux") || ( $distribution == "Red Hat Enterprise Linux Server") || ($distribution == "Red Hat Enterprise Linux") || ($distribution == "Amazon Linux") || ($distribution == "Amazon Linux AMI")) ]]; then
              yum update -y
              yum install -y python-setuptools
              yum install -y wget
              yum install -y unzip
          else
            echo "Didn't Update and not able to install prereqs"
          fi
          mkdir -p /opt/aws/bin
          wget https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz
          python -m easy_install --script-dir /opt/aws/bin aws-cfn-bootstrap-latest.tar.gz > /tmp/cfn-install.log 2>&1
          /opt/aws/bin/cfn-init -vvv --stack ${AWS::StackName} --resource DemoInstance -c ascending --region ${AWS::Region} > /tmp/cfn-init.log 2>&1
          /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource DemoInstance --region ${AWS::Region} > /tmp/cfn-signal.log 2>&1
############################ K2 Configuration #2 Ends Here  ############################
# Below Parts will come from customer
      ImageId: !FindInMap
        - EC2AMI
        - !Ref 'AWS::Region'
        - AMIId
      InstanceType: !Ref 'InstanceType'
      KeyName: !Ref 'KeyName'
      BlockDeviceMappings:
      - DeviceName: "/dev/sda1"
        Ebs:
          VolumeType: "gp2"
          DeleteOnTermination: true
          VolumeSize: 200
      Tags:
        - Key: Name
          Value: K2Agent with Vulnerable Application

Outputs:
  InstanceId:
    Description: InstanceId of the newly created EC2 instance
    Value: !Ref 'DemoInstance'
  AZ:
    Description: Availability Zone of the newly created EC2 instance
    Value: !GetAtt [DemoInstance, AvailabilityZone]
  • Go through all the parameters and define their default values as per your setup or pass them in cloudformation command in VSRX.yml and K2-SAAS.yml

  • Provide AMIID in Mappings section as per region, you can only change one region also for your deployment.

  • Save the file as mentioned names.

  • Run them in below sequence

    • VSRX.yml

    • vsrx-policies.sh

    • K2-SAAS.yml

  • Commands to run

    • Using AWS Console

    • Using AWS Cli For e.g.

      • aws cloudformation create-stack --region ${REGION_NAME} --stack-name ${PROVIDE_STACKNAME_HERE} --template-body file://${PROVIDE_TEMPLATE_NAME}
      • Example Command is below

      • aws cloudformation create-stack --region us-west-1 --stack-name k2-vSRX --template-body file://k2-vSRX.yml
  • Access the Vulnerable app through revenue data elastic ip of vsrx instance

End to End Verification

Generate an attack from the Vulnerable Application.

K2 Vulnerable Applications UI

The attacker IP is detected and added to the blocked list, which can be viewed on K2 UI.

This IP list is regularly pulled by vSRX which enables the firewall to block any further requests to the application.

  1. Link: Settings → Firewall Integration → Blocked List (https://www.k2io.net/centralmanager/#!/app/settings/firewall )

  1. Visit the Vulnerable Application and it should not be accessible.

    1. Note: The IP will be removed from the blocked list after 2 hours and if you wish you can remove it yourself.

Last updated

Was this helpful?