天天看點

利用CloudFormation部署AWS GWLB內建Palo Alto防火牆

AWS VPC 流量集中檢測系列--(2)利用CloudFormation自動化部署AWS GWLB內建Palo Alto防火牆

B站首頁:​​https://space.bilibili.com/408773931?spm_id_from=333.1007.0.0​​

歡迎大家關注我的微信公衆号:自劉地

上一篇文章講過了AWS GWLB如何內建Palo Alto防火牆,來對流量做集中檢測。上一次實驗是通過AWS 控制台操作的,部署起來還是比較繁瑣的,這裡分享一下實驗環境的CloudFormation代碼,幫助大家快速部署一下實驗環境。

一、CloudFormation 代碼部署

這裡的CloudFormation代碼在Tokyo區域(ap-northeast-1)部署的,如果要在其他Region部署,請修改paloalto和windows的ami id。堆棧大概會在8分鐘建立完成。

AWSTemplateFormatVersion: "2010-09-09"

Mappings:
  RegionMap:
    ap-northeast-1:
      PaBundle1: ami-0bcddfc3678d5a897
      PaBundle2: ami-0c4d901d7a5370b78
    us-west-2:
      PaBundle1: ami-01d7ef8ff7ddaff25
      PaBundle2: ami-0d45d840ed2fe3eba
Parameters:
  EC2InstanceAmiId:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'

  MyKeyPair:
    Description: Amazon EC2 Key Pair
    Type: AWS::EC2::KeyPair::KeyName

  PaVmType:
    Description: Choice PA Firewall License Type
    Type: String
    Default: PaBundle2
    AllowedValues:
      - PaBundle1
      - PaBundle2

Resources:
#=========================================建立SSM Role========================================#

  BastionSsmRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - ec2.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /

  BastionSsmPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: ApplianceInstanceAccess
      PolicyDocument:
        Statement:
          - Effect: Allow
            Action:
              - ssm:DescribeAssociation
              - ssm:GetDeployablePatchSnapshotForInstance
              - ssm:GetDocument
              - ssm:DescribeDocument
              - ssm:GetManifest
              - ssm:GetParameter
              - ssm:GetParameters
              - ssm:ListAssociations
              - ssm:ListInstanceAssociations
              - ssm:PutInventory
              - ssm:PutComplianceItems
              - ssm:PutConfigurePackageResult
              - ssm:UpdateAssociationStatus
              - ssm:UpdateInstanceAssociationStatus
              - ssm:UpdateInstanceInformation
            Resource: "*"
          - Effect: Allow
            Action:
              - ssmmessages:CreateControlChannel
              - ssmmessages:CreateDataChannel
              - ssmmessages:OpenControlChannel
              - ssmmessages:OpenDataChannel
            Resource: "*"
          - Effect: Allow
            Action:
              - ec2messages:AcknowledgeMessage
              - ec2messages:DeleteMessage
              - ec2messages:FailMessage
              - ec2messages:GetEndpoint
              - ec2messages:GetMessages
              - ec2messages:SendReply
            Resource: "*"
      Roles:
        - !Ref BastionSsmRole

  BastionSsmProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: /
      Roles:
        - !Ref BastionSsmRole
#=========================================建立VPC、IGW========================================#
# 建立一SecVpc
  SecVpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.20.0.0/16
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
      Tags:
       - Key: Name
         Value: SecVpc

# 建立IGW并且關聯到VPC
  SecVpcIGW:
    Type: "AWS::EC2::InternetGateway"
    Properties:
      Tags:
        - Key: Name
          Value: SecVpcIGW

  SecVpcAttachIgw:
    Type: "AWS::EC2::VPCGatewayAttachment"
    Properties:
      VpcId: !Ref SecVpc
      InternetGatewayId: !Ref SecVpcIGW

#---------------------------SecVpc建立4個子網-------------------------------------#

# SecVpc AZ1内建立GWLB子網
  Az1GwlbSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref SecVpc
      CidrBlock: 10.20.10.0/24
      AvailabilityZone:
        Fn::Select:
          - 0
          - Fn::GetAZs: ""
      Tags:
      - Key: Name
        Value: SecVpc-GWLB1-Subnet

# SecVpc AZ2内建立GWLB子網
  Az2GwlbSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref SecVpc
      CidrBlock: 10.20.30.0/24
      AvailabilityZone:
        Fn::Select:
          - 1
          - Fn::GetAZs: ""
      Tags:
      - Key: Name
        Value: SecVpc-GWLB2-Subnet

# SecVpc AZ1内建立MGT子網
  Az1MgtSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref SecVpc
      CidrBlock: 10.20.20.0/24
      AvailabilityZone:
        Fn::Select:
          - 0
          - Fn::GetAZs: ""
      Tags:
      - Key: Name
        Value: SecVpc-MGT1-Subnet

# SecVpc AZ2内建立MGT子網
  Az2MgtSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref SecVpc
      CidrBlock: 10.20.40.0/24
      AvailabilityZone:
        Fn::Select:
          - 1
          - Fn::GetAZs: ""
      Tags:
      - Key: Name
        Value: SecVpc-MGT2-Subnet

#---------------------------SecVpc建立路由表-------------------------------------#

# SecVpc建立管理網段的路由表
  MgtRouteTable:
    Type: "AWS::EC2::RouteTable"
    Properties:
      VpcId: !Ref SecVpc
      Tags:
        - Key: Name
          Value: SecVpc-Mgt-route-table

# Mgt路由表關聯子網
  Az1MgtSubnetAssociation:
    Type: "AWS::EC2::SubnetRouteTableAssociation"
    Properties:
      RouteTableId: !Ref MgtRouteTable
      SubnetId: !Ref Az1MgtSubnet

  Az2MgtSubnetAssociation:
    Type: "AWS::EC2::SubnetRouteTableAssociation"
    Properties:
      RouteTableId: !Ref MgtRouteTable
      SubnetId: !Ref Az2MgtSubnet

# SecVpc建立Gwlb的路由表
  GwlbRouteTable:
    Type: "AWS::EC2::RouteTable"
    Properties:
      VpcId: !Ref SecVpc
      Tags:
        - Key: Name
          Value: SecVpc-Gwlb-route-table

# Gwlb路由表關聯子網
  Az1GwlbSubnetAssociation:
    Type: "AWS::EC2::SubnetRouteTableAssociation"
    Properties:
      RouteTableId: !Ref GwlbRouteTable
      SubnetId: !Ref Az1GwlbSubnet

  Az2GwlbSubnetAssociation:
    Type: "AWS::EC2::SubnetRouteTableAssociation"
    Properties:
      RouteTableId: !Ref GwlbRouteTable
      SubnetId: !Ref Az2GwlbSubnet


# 管理網段添加預設路由去往IGW
  MgtToInternetRoute:
    Type: "AWS::EC2::Route"
    DependsOn: SecVpcIGW
    Properties:
     RouteTableId: !Ref MgtRouteTable
     DestinationCidrBlock: 0.0.0.0/0
     GatewayId: !Ref SecVpcIGW

#---------------------------SecVpc建立安全組------------------------------------#

# 在SecVpc内建立一個安全組
  SecVpcSg:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: SG to test ping
      VpcId: !Ref SecVpc
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: 22
        ToPort: 22
        CidrIp: 0.0.0.0/0
      - IpProtocol: icmp
        FromPort: -1
        ToPort: -1
        CidrIp: 0.0.0.0/0
      - IpProtocol: tcp
        FromPort: 443
        ToPort: 443
        CidrIp: 0.0.0.0/0
      - IpProtocol: tcp
        FromPort: 8443
        ToPort: 8443
        CidrIp: 0.0.0.0/0
      - IpProtocol: -1
        FromPort: -1
        ToPort: -1
        CidrIp: 10.20.0.0/16
      - IpProtocol: -1
        FromPort: -1
        ToPort: -1
        CidrIp: 10.10.0.0/16
      - IpProtocol: tcp
        FromPort: 3389
        ToPort: 3389
        CidrIp: 0.0.0.0/0
      Tags:
        - Key: Name
          Value: SecVpcSg

#---------------------------SecVpc建立paloalto接口------------------------------------#

  Pa1MgmtEip:
    Type: "AWS::EC2::EIP"
    Properties:
      Tags:
        - Key: Name
          Value: SecVpc-pa1-mgmt-eip

  Pa1MgmtEni:  # 建立PA1管理接口
    Type: "AWS::EC2::NetworkInterface"
    Properties:
      GroupSet:
        - Ref: "SecVpcSg"
      SubnetId:
        Ref: "Az1MgtSubnet"
      Tags:
        - Key: Name
          Value: SecVpc-pa1-mgmt-eni

  Pa1MgmtEniAssociation:  # 關聯公網IP到Mgt彈性接口
    Type: AWS::EC2::EIPAssociation
    DependsOn: PA1
    Properties:
      AllocationId: !GetAtt Pa1MgmtEip.AllocationId # 這裡是EIP
      NetworkInterfaceId: !Ref Pa1MgmtEni

  Pa1DataEni:  # 建立PA1資料接口
    Type: "AWS::EC2::NetworkInterface"
    Properties:
      GroupSet:
        - Ref: "SecVpcSg"
      SubnetId:
        Ref: "Az1GwlbSubnet"
      Tags:
        - Key: Name
          Value: SecVpc-pa1-data-eni

  Pa2MgmtEip:
    Type: "AWS::EC2::EIP"
    Properties:
      Tags:
        - Key: Name
          Value: SecVpc-pa2-mgmt-eip

  Pa2MgmtEni:  # 建立PA2管理接口
    Type: "AWS::EC2::NetworkInterface"
    Properties:
      GroupSet:
        - Ref: "SecVpcSg"
      SubnetId:
        Ref: "Az2MgtSubnet"
      Tags:
        - Key: Name
          Value: SecVpc-pa2-mgmt-eni

  Pa2MgmtEniAssociation:  # 關聯公網IP到Mgt彈性接口
    Type: AWS::EC2::EIPAssociation
    DependsOn: PA2
    Properties:
      AllocationId: !GetAtt Pa2MgmtEip.AllocationId # 這裡是EIP
      NetworkInterfaceId: !Ref Pa2MgmtEni

  Pa2DataEni:  # 建立PA2資料接口
    Type: "AWS::EC2::NetworkInterface"
    Properties:
      GroupSet:
        - Ref: "SecVpcSg"
      SubnetId:
        Ref: "Az2GwlbSubnet"
      Tags:
        - Key: Name
          Value: SecVpc-pa2-data-eni

#---------------------------SecVpc建立PA執行個體------------------------------------#

# PA1
  PA1:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !FindInMap [RegionMap, !Ref "AWS::Region", !Ref PaVmType]
      KeyName: !Ref MyKeyPair
      InstanceType: m5.2xlarge
      NetworkInterfaces:
        -
          NetworkInterfaceId: !Ref Pa1DataEni
          DeviceIndex: 0
        -
          NetworkInterfaceId: !Ref Pa1MgmtEni
          DeviceIndex: 1
      UserData:
        Fn::Base64:
          !Sub |
          mgmt-interface-swap=enable
          plugin-op-commands=aws-gwlb-inspect:enable      Tags:
        - Key: Name
          Value: PA-FW1

# PA2
  PA2:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !FindInMap [RegionMap, !Ref "AWS::Region", !Ref PaVmType]
      KeyName: !Ref MyKeyPair
      InstanceType: m5.2xlarge
      NetworkInterfaces:
        -
          NetworkInterfaceId: !Ref Pa2DataEni
          DeviceIndex: 0
        -
          NetworkInterfaceId: !Ref Pa2MgmtEni
          DeviceIndex: 1
      UserData:
        Fn::Base64:
          !Sub |
          mgmt-interface-swap=enable
          plugin-op-commands=aws-gwlb-inspect:enable      Tags:
        - Key: Name
          Value: PA-FW2

#---------------------------建立GWLB------------------------------------#

  Gwlb:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      LoadBalancerAttributes:
        - Key: load_balancing.cross_zone.enabled
          Value: true
      Name: PA-GWLB
      Type: gateway
      Subnets:
        - !Ref Az1GwlbSubnet
        - !Ref Az2GwlbSubnet
      Tags:
      - Key: Name
        Value: SecVpc-pa-gwlb

  TargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      HealthCheckIntervalSeconds: 5
      Name: PA-Target
      Port: 6081
      Protocol: GENEVE
      TargetGroupAttributes:
      - Key: deregistration_delay.timeout_seconds
        Value: 20
      VpcId: !Ref SecVpc
      HealthCheckPort: 80
      HealthCheckProtocol: HTTP
      TargetType: instance
      Targets:
        - Id: !Ref PA1
        - Id: !Ref PA2
      Tags:
      - Key: Name
        Value: !Sub "${AWS::StackName}-gwlbtg"

  Listener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
      - Type: forward
        TargetGroupArn: !Ref TargetGroup
      LoadBalancerArn: !Ref Gwlb

#---------------------------建立Endpoint Service------------------------------------#

  VpcEndpointService:
    Type: AWS::EC2::VPCEndpointService
    Properties:
      GatewayLoadBalancerArns:
        - !Ref Gwlb
      AcceptanceRequired: false

# Create Lambda Custom Resource to retrieve VPC Endpoint Service Name:

  VpceServiceLambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      Policies:
        - PolicyName: root
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: arn:aws:logs:*:*:*
              - Effect: Allow
                Action:
                  - ec2:DescribeVpcEndpointServiceConfigurations
                  - ec2:DescribeVpcEndpointServicePermissions
                  - ec2:DescribeVpcEndpointServices
                Resource: "*"

  # Lambda creates CloudWatch Log Group.
  # Since CF stack didn't explicitly create the Log Group, Log Group doesn't get deleted when stack is deleted.
  # Hence creating Log Group though the stack for Lambda specific funciton.
  # Their are few things to consider. For more details refer to: https://github.com/aws/serverless-application-model/issues/1216
  VpceServiceLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
        LogGroupName: !Sub /aws/lambda/${AWS::StackName}-service
        RetentionInDays: 1

  VpceServiceName:
    Type: AWS::Lambda::Function
    DependsOn: VpceServiceLogGroup
    Properties:
      FunctionName: !Sub ${AWS::StackName}-service
      Handler: "index.handler"
      Role: !GetAtt VpceServiceLambdaExecutionRole.Arn
      Code:
        ZipFile: |
          import json
          import logging
          import time
          import boto3
          import cfnresponse
          from botocore.exceptions import ClientError

          try:
              ec2 = boto3.client('ec2')
          except ClientError as e:
              logger.error(f"ERROR: failed to connect to EC2 client: {e}")
              sys.exit(1)

          def handler(event, context):
              logger = logging.getLogger()
              logger.setLevel(logging.INFO)
              logger.info('Received event: {}'.format(json.dumps(event)))

              responseData = {}
              responseStatus = cfnresponse.FAILED

              try:
                  serviceid = event["ResourceProperties"]["VpceServiceId"]
              except Exception as e:
                  logger.info('Attribute retrival failure: {}'.format(e))

              try:
                  if event["RequestType"] == "Delete":
                      responseStatus = cfnresponse.SUCCESS
                      cfnresponse.send(event, context, responseStatus, responseData)
              except Exception:
                  logger.exception("Signaling failure to CloudFormation.")
                  cfnresponse.send(event, context, cfnresponse.FAILED, {})

              if event["RequestType"] == "Create":
                  logger.info("Retrieving VPC Endpoint Service Name:")
                  try:
                      response = ec2.describe_vpc_endpoint_service_configurations(
                          Filters=[
                              {
                                  'Name': 'service-id',
                                  'Values': [serviceid]
                              }
                          ]
                      )
                  except Exception as e:
                      logger.info('ec2.describe_vpc_endpoint_service_configurations failure: {}'.format(e))

                  service_name = response['ServiceConfigurations'][0]['ServiceName']

                  time.sleep(120)

                  responseData['ServiceName'] = service_name
                  responseStatus = cfnresponse.SUCCESS
                  cfnresponse.send(event, context, responseStatus, responseData)
      Runtime: python3.7
      Timeout: 150


  RetrieveVpceServiceName:
    Type: Custom::RetrieveAttributes
    Properties:
      ServiceToken: !GetAtt VpceServiceName.Arn
      VpceServiceId: !Ref VpcEndpointService

  App1Endpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref AppVpc
      ServiceName: !GetAtt RetrieveVpceServiceName.ServiceName
      VpcEndpointType: GatewayLoadBalancer
      SubnetIds:
        - !Ref Gwlbe1Subnet

  App2Endpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref AppVpc
      ServiceName: !GetAtt RetrieveVpceServiceName.ServiceName
      VpcEndpointType: GatewayLoadBalancer
      SubnetIds:
        - !Ref Gwlbe2Subnet
#==============================建立App VPC、IGW==============================#
# 建立一APP VPC
  AppVpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.10.0.0/16
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
      Tags:
       - Key: Name
         Value: AppVpc

# 建立IGW并且關聯到VPC
  AppVpcIGW:
    Type: "AWS::EC2::InternetGateway"
    Properties:
      Tags:
        - Key: Name
          Value: AppVpc-IGW

  AppVpcAttachIgw:
    Type: "AWS::EC2::VPCGatewayAttachment"
    Properties:
      VpcId: !Ref AppVpc
      InternetGatewayId: !Ref AppVpcIGW

#---------------------------AppVpc建立4個子網-------------------------------------#

# AppVpc建立GWLBe1子網
  Gwlbe1Subnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref AppVpc
      CidrBlock: 10.10.10.0/24
      AvailabilityZone:
        Fn::Select:
          - 0
          - Fn::GetAZs: ""
      Tags:
      - Key: Name
        Value: AppVpc-GWLBe1-Subnet


# AppVpc建立App1子網
  App1Subnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref AppVpc
      CidrBlock: 10.10.20.0/24
      AvailabilityZone:
        Fn::Select:
          - 0
          - Fn::GetAZs: ""
      Tags:
      - Key: Name
        Value: AppVpc-App1-Subnet

# AppVpc建立GWLBe1子網
  Gwlbe2Subnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref AppVpc
      CidrBlock: 10.10.30.0/24
      AvailabilityZone:
        Fn::Select:
          - 1
          - Fn::GetAZs: ""
      Tags:
      - Key: Name
        Value: AppVpc-GWLBe2-Subnet

# AppVpc建立App1子網
  App2Subnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref AppVpc
      CidrBlock: 10.10.40.0/24
      AvailabilityZone:
        Fn::Select:
          - 1
          - Fn::GetAZs: ""
      Tags:
      - Key: Name
        Value: AppVpc-App2-Subnet

#---------------------------AppVpc建立4個路由表-------------------------------------#

#---------------IGW路由---------------#

# AppVpc建立IGW的路由表
  IgwIngressRouteTable:
    Type: "AWS::EC2::RouteTable"
    Properties:
      VpcId: !Ref AppVpc
      Tags:
        - Key: Name
          Value: AppVpc-Igw-Ingress-route-table

# IgwIngress路由表關聯IGW
  IgwIngressAssociation:
    Type: "AWS::EC2::GatewayRouteTableAssociation"
    Properties:
      RouteTableId: !Ref IgwIngressRouteTable
      GatewayId: !Ref AppVpcIGW

# IgwIngress去往App網段的路由
  IgwIngressToApp1:
    Type: "AWS::EC2::Route"
    DependsOn: App1Endpoint
    Properties:
     RouteTableId: !Ref IgwIngressRouteTable
     DestinationCidrBlock: 10.10.20.0/24
     VpcEndpointId: !Ref App1Endpoint

  IgwIngressToApp2:
    Type: "AWS::EC2::Route"
    DependsOn: App2Endpoint
    Properties:
     RouteTableId: !Ref IgwIngressRouteTable
     DestinationCidrBlock: 10.10.40.0/24
     VpcEndpointId: !Ref App2Endpoint

#---------------GWLBe路由---------------#

# AppVpc建立Gwlbe的路由表
  GwlbeRouteTable:
    Type: "AWS::EC2::RouteTable"
    Properties:
      VpcId: !Ref AppVpc
      Tags:
        - Key: Name
          Value: AppVpc-Gwlbe-route-table

# Gwlbe路由表關聯子網
  GwlbeRouteTableAz1Association:
    Type: "AWS::EC2::SubnetRouteTableAssociation"
    Properties:
      RouteTableId: !Ref GwlbeRouteTable
      SubnetId: !Ref Gwlbe1Subnet

  GwlbeRouteTableAz2Association:
    Type: "AWS::EC2::SubnetRouteTableAssociation"
    Properties:
      RouteTableId: !Ref GwlbeRouteTable
      SubnetId: !Ref Gwlbe2Subnet

# 管理網段添加預設路由去往IGW
  GwlbeToInternetRoute:
    Type: "AWS::EC2::Route"
    DependsOn: AppVpcIGW
    Properties:
     RouteTableId: !Ref GwlbeRouteTable
     DestinationCidrBlock: 0.0.0.0/0
     GatewayId: !Ref AppVpcIGW

#---------------App路由---------------#

# AppVpc建立App1的路由表
  App1RouteTable:
    Type: "AWS::EC2::RouteTable"
    Properties:
      VpcId: !Ref AppVpc
      Tags:
        - Key: Name
          Value: AppVpc-App1-route-table

# App1路由表關聯子網
  App1RouteTableAssociation:
    Type: "AWS::EC2::SubnetRouteTableAssociation"
    Properties:
      RouteTableId: !Ref App1RouteTable
      SubnetId: !Ref App1Subnet

# App1網段添加預設路由去往Endpoint
  App1ToEndpoint:
    Type: "AWS::EC2::Route"
    DependsOn: App1Endpoint
    Properties:
     RouteTableId: !Ref App1RouteTable
     DestinationCidrBlock: 0.0.0.0/0
     VpcEndpointId: !Ref App1Endpoint

# AppVpc建立App2的路由表
  App2RouteTable:
    Type: "AWS::EC2::RouteTable"
    Properties:
      VpcId: !Ref AppVpc
      Tags:
        - Key: Name
          Value: AppVpc-App2-route-table

# App2路由表關聯子網
  App2RouteTableAssociation:
    Type: "AWS::EC2::SubnetRouteTableAssociation"
    Properties:
      RouteTableId: !Ref App2RouteTable
      SubnetId: !Ref App2Subnet

# App2網段添加預設路由去往Endpoint
  App2ToEndpoint:
    Type: "AWS::EC2::Route"
    DependsOn: App1Endpoint
    Properties:
     RouteTableId: !Ref App2RouteTable
     DestinationCidrBlock: 0.0.0.0/0
     VpcEndpointId: !Ref App2Endpoint

#---------------------------AppVpc建立安全組------------------------------------#

# 在SEC VPC内建立一個安全組
  AppVpcSg:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: SG to test ping
      VpcId: !Ref AppVpc
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: 22
        ToPort: 22
        CidrIp: 0.0.0.0/0
      - IpProtocol: icmp
        FromPort: -1
        ToPort: -1
        CidrIp: 0.0.0.0/0
      - IpProtocol: tcp
        FromPort: 8443
        ToPort: 8443
        CidrIp: 0.0.0.0/0
      - IpProtocol: tcp
        FromPort: 443
        ToPort: 443
        CidrIp: 0.0.0.0/0
      - IpProtocol: -1
        FromPort: -1
        ToPort: -1
        CidrIp: 10.20.0.0/16
      - IpProtocol: -1
        FromPort: -1
        ToPort: -1
        CidrIp: 10.10.0.0/16
      - IpProtocol: tcp
        FromPort: 3389
        ToPort: 3389
        CidrIp: 0.0.0.0/0
      Tags:
        - Key: Name
          Value: AppVpcSg

#---------------------------AppVpc建立EC2執行個體------------------------------------#

# App1
  App1:
    Type: AWS::EC2::Instance
    Properties:
      IamInstanceProfile: !Ref BastionSsmProfile
      ImageId: !Ref EC2InstanceAmiId
      KeyName: !Ref MyKeyPair
      InstanceType: t2.micro
      NetworkInterfaces:
        - AssociatePublicIpAddress: true
          DeviceIndex: 0
          GroupSet:
            - Ref: AppVpcSg
          SubnetId:  !Ref App1Subnet
      Tags:
        - Key: Name
          Value: App1-Linux

#  App2 Windows AMI
  App2:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-09e5001ad68a3ec91  #Tokyo ami-09e5001ad68a3ec91
      KeyName: !Ref MyKeyPair
      InstanceType: t2.xlarge
      NetworkInterfaces:
        - AssociatePublicIpAddress: true
          DeviceIndex: 0
          GroupSet:
            - Ref: AppVpcSg
          SubnetId:  !Ref App2Subnet
      Tags:
        - Key: Name
          Value: App2-Windows
      UserData:
        Fn::Base64:
          !Sub |
          <powershell>
          $PASSWORD= ConvertTo-SecureString –AsPlainText -Force -String LIYJMSgaliu1qiang2long3windemoZJ2vG5
          New-LocalUser -Name "labuser" -Description "rdp user" -Password $Password
          Add-LocalGroupMember -Group 'Administrators' -Member 'labuser'
          net localgroup "Remote Desktop Users" /add labuser
          $file = "C:\" + (Get-Date).ToString("MM-dd-yy-hh-mm")
          New-Item $file -ItemType file
          </powershell>      

二、指令行配置 paloalto

AWS上paloalto其實可以做成開機自動加載配置,關鍵詞是Bootstrap the VM-Series Firewall on AWS[參見連結1]。原理大緻是将相關的檔案到放在S3桶内,在paloalto EC2的User Data裡面指定S3的路徑來加載這些檔案。視訊示範可以[參見連結2]。

這裡使用CloudFormation做成全自動需要寫的代碼挺多,但是實際場景并不多,是以這裡我并不進一步往下研究了。

通過SSH登入paloalto修改admin密碼。

Welcome admin.
admin@PA-VM> configure
Entering configuration mode
[edit]
admin@PA-VM# set mgt-config users admin password
Enter password   :
Confirm password :

[edit]
admin@PA-VM# commit

Commit job 2 is in progress. Use Ctrl+C to return to command prompt
.........55%75%98%..............100%
Configuration committed successfully

[edit]
admin@PA-VM#      

将下面的指令刷到PA FW1和FW2上。

set network profiles interface-management-profile MgtProfile http yes
set network profiles interface-management-profile MgtProfile ssh yes
set network profiles interface-management-profile MgtProfile ping yes

set network interface ethernet ethernet1/1 layer3 ndp-proxy enabled no
set network interface ethernet ethernet1/1 layer3 sdwan-link-settings upstream-nat enable no
set network interface ethernet ethernet1/1 layer3 sdwan-link-settings upstream-nat static-ip
set network interface ethernet ethernet1/1 layer3 sdwan-link-settings enable no
set network interface ethernet ethernet1/1 layer3 interface-management-profile MgtProfile
set network interface ethernet ethernet1/1 layer3 lldp enable no
set network interface ethernet ethernet1/1 layer3 dhcp-client

set network virtual-router default interface ethernet1/1
set zone untrust network layer3 ethernet1/1

set rulebase default-security-rules rules intrazone-default action allow
set rulebase default-security-rules rules intrazone-default log-start yes
set rulebase default-security-rules rules intrazone-default log-end yes
set rulebase default-security-rules rules intrazone-default profile-setting profiles url-filtering default
set rulebase default-security-rules rules intrazone-default profile-setting profiles file-blocking "strict file blocking"
set rulebase default-security-rules rules intrazone-default profile-setting profiles virus default
set rulebase default-security-rules rules intrazone-default profile-setting profiles spyware strict
set rulebase default-security-rules rules intrazone-default profile-setting profiles vulnerability strict
set rulebase default-security-rules rules intrazone-default profile-setting profiles wildfire-analysis default

commit

Commit job 3 is in progress. Use Ctrl+C to return to command prompt
.........55%70%98%.............100%
Configuration committed successfully
Warning: No valid Antivirus content package exists
(Module: device)      

三、測試

​3.1 App1 HTTP通路測試

通過SSH連接配接到App1上,安裝HTTP服務,修改端口為8443。

yum install -y httpd
sed -i.bak 's/Listen 80/Listen 8443/g' /etc/httpd/conf/httpd.conf
echo "<h2>Hello World from $(hostname -f)</h2>" > /var/www/html/index.html
systemctl start httpd.service
systemctl enable httpd.service      

通路EC2的公網8443端口測試,在浏覽器界面可以使用​

​CTRL+F5​

​多強制重新整理幾次。

利用CloudFormation部署AWS GWLB內建Palo Alto防火牆

檢視PA-FW1上的日志。

利用CloudFormation部署AWS GWLB內建Palo Alto防火牆

檢視PA-FW2上的日志。

利用CloudFormation部署AWS GWLB內建Palo Alto防火牆

​3.2 App2 RDP連接配接測試

通過RDP連接配接到App2上,可以通過浏覽器通路一些網頁制造流量。

利用CloudFormation部署AWS GWLB內建Palo Alto防火牆

檢視PA-FW1上的日志。

四、參考連結

  • [1] Bootstrap the VM-Series Firewall on AWS:https://docs.paloaltonetworks.com/vm-series/9-1/vm-series-deployment/bootstrap-the-vm-series-firewall/bootstrap-the-vm-series-firewall-in-aws
  • [2] Bootstrapping the VM-Series on AWS:https://www.youtube.com/watch?v=v4HIvytbVU8

繼續閱讀