CyberKeeda In Social Media
Showing posts with label AWS Cloudformation. Show all posts
Showing posts with label AWS Cloudformation. Show all posts

AWS Managed Policy to Restrict IAM User to Access AWS Resource from Specific IP Address.

 




AWS Managed Policy

Within this blog post, we will cover 
How we can use IAM Managed Policy used to create an IAM User Boundary which will limit a user for the below operations.

  • AWS S3 Limited Access [Get, Put, List]
  • S3 Access with only single IP Address.
Syntax Template

AWSTemplateFormatVersion: 2010-09-09
DescriptionCFN to create ManagedPolicy 

Resources:
  IBDSReconUserBoundaryPolicy:
    TypeAWS::IAM::ManagedPolicy
    Properties
      DescriptionA ManagedPolicy meant to restrict user based upon ingress IP.
      ManagedPolicyNamemy_s3_user_boundary
      Path/
      Users:
      - my_s3_user
      PolicyDocument
            Version'2012-10-17'
            Statement:
            - EffectAllow
              Action:
              - s3:ListBucket
              - s3:GetBucketLocation
              Resourcearn:aws:s3:::my-randon-s3-bucket
            - EffectAllow
              Action:
              - s3:PutObject
              - s3:PutObjectAcl
              Resourcearn:aws:s3:::my-randon-s3-bucketa/bucketfiles/*
              Condition:
                IpAddressIfExists:
                  aws:SourceIp123.345.657.12

Read more ...

AWS WAF : Web Access Firewall to control access to CloudFront Public domain URL using IPset Rules.

 

AWS WAFv2

AWS Web Access Firewall is one the services that can be used to inspect, control and manage web request.
WAF uses one or many rules to allow, limit or block as per request statement provided within rule.
AWS WAF and it's corresponding rule can be attached to multiple AWS services. such as
Official AWS Link
  • Amazon CloudFront distribution, 
  • Amazon API Gateway REST API, 
  • Application Load Balancer,
  • AWS API Gateway
In this blog post,, we will cover, how to restrict our AWS cloudfront distribution URL for limited IP Addresses only.

Lab Setup : So we have a Cloudfront distribution with both http and https access mapped to respective AWS S3 buckets, as we know once we have created a Cloudfront distribution, AWS provide us a publicly accessible Cloudfront domain URL, using which we can access our S3 content, thus url, which looks somehow similar to http://d3ocffr25e-somerandom.cloudfront.ne

We will use AWS WAF to restrict/block access approaching to our Cloudfront domain to all random IP other than the one which we have whitelisted within our IP sets.

CloudFormation Template to create below resources.
  • IP Sets : AWS::WAFv2::IPSet
  • Web ACLv2 : AWS::WAFv2::WebACL
  • Custom Response Body : CustomResponseBodies
  • Rules : IPSetReferenceStatement
  • CloudWatch Metrics
  • Sample Request Dashboard.

Note : After creation of below resources, this has to be associated with cloudformation distribution from cloudfromation section.

Syntax Template

---
AWSTemplateFormatVersion'2010-09-09'
DescriptionThis template will create WAFv2 Ipset, WebAcl with Cloudfront Scope, Web ACLs rules, Cloudwatch metric
              Sample Request Dashbaord with last 3 hour data.

Parameters:
  env:
    DescriptionThe environment name being worked on
    TypeString
    AllowedValues:
      - prod
      - non-prod
  CloudFrontInfo:
    DescriptionCloudfront Name.
    TypeString
  IPSetname:
    DescriptionThe short name to identify ipsets.
    TypeString
  IPSetDescription:
    DescriptionShort description to identify ipsets.
    TypeString

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      -
        Label:
          defaultEnvironment
        Parameters:
          - env
      - 
        Label:
          defaultIP Set Details
        Parameters:
          - IPSetname
          - IPSetDescription

Resources:
  SampleIPSet:
      Type'AWS::WAFv2::IPSet'
      Properties:
        Description!Sub "${IPSetDescription}"
        Name!Sub "${IPSetname}"
        ScopeCLOUDFRONT
        IPAddressVersionIPV4
        Addresses:  
          - 111.11.11.11/32 # Random-Pub-IP-1
          - 122.12.12.1/32   #  Random-Pub-IP-2
          - 133.225.192.0/18  #  Random-Pub-IP-3

  CDNAccessIPRestrictionWebACL:
    TypeAWS::WAFv2::WebACL
    Properties:
      Name!Sub "myproject-${env}-cdn-${CloudFrontInfo}-WebACL"
      ScopeCLOUDFRONT
      DefaultAction:
        Block: {
      "CustomResponse": {
        "ResponseCode"401,
        "CustomResponseBodyKey""Unauthorized"
      }
    }
      Description!Sub "To limit access of Cloudfront ${CloudFrontInfo}  from known IP ranges only"
      Rules:
        - Name!Sub "myproject-${env}-cdn-${CloudFrontInfo}-WebACL-Rule1"
          Priority0
          Statement:
            IPSetReferenceStatement:
              Arn!GetAtt SampleIPSet.Arn
          Action:
            Allow: {}
          VisibilityConfig:
            SampledRequestsEnabledtrue
            CloudWatchMetricsEnabledtrue
            MetricName!Sub "myproject-${env}-cdn-${CloudFrontInfo}-IpLimitationRule"
      VisibilityConfig:
        SampledRequestsEnabledtrue
        CloudWatchMetricsEnabledtrue
        MetricName!Sub "myproject-${env}-cdn-${CloudFrontInfo}-WebACLMetric"
      Capacity1

      CustomResponseBodies:
        Unauthorized:
          ContentTypeTEXT_PLAIN
          ContentUnauthorized !

We will go through each sections of the CloudFormation template to understand the same.

MetaData and Interface MetaDataFollow the link to know more about it

Going further into the Resource Section, our WAF relevant stuffs are defined.


AWS::WAFv2::IPSet
This part of CFN resource us used to define our custom set of IP Address, which will be later used while defining our WAF rules, Let's know what are those properties.

SampleIPSet:
      Type'AWS::WAFv2::IPSet'
      Properties:
        Description!Sub "${IPSetDescription}"
        Name!Sub "${IPSetname}"
        ScopeCLOUDFRONT
        IPAddressVersionIPV4
        Addresses:  
          - 111.11.11.11/32 # Random-Pub-IP-1
          - 122.12.12.1/32   #  Random-Pub-IP-2
          - 133.225.192.0/18  #  Random-Pub-IP-3

Scope
Scope can be either REGIONAL or CLOUDFRONT
As Cloudfront (CDN) is Global service, it's being treated as a Seperate scope.
Note : Please note, this scope can be created only within us-east-1 region only.


Addresses
Used to define set of IP using the valid CIDR format.

Example :
          - 111.11.11.11/32 # Used to define single IP as /32 - 122.12.12.1/32 - 133.225.192.0/18 # Used to define entire subnet range as /18


Custom Response Body : CustomResponseBodies

This part of CFN resource us used to define our custom response that can support in any type as ( Plain TEXT, HTML, JSON ), here we have used a plain text.


      CustomResponseBodies:
        Unauthorized:
          ContentTypeTEXT_PLAIN
          ContentUnauthorized !



Rules

This part of WAF ACL CFN resource us used to custom rules (Allow, Deny )based upon statements.


  • In our example, we are allowing IP Sets with priority 0 ( Highest Priority ), and it's linked the the ARN of the same IP Set, we have created above.
  • In addition to that, we are creating Cloudwatch Metrics Dashboard for each Allowed Request.
  • And at last we are enabling the Sampled Request, which will show us the Realtime calls/request.

Rules:
        - Name!Sub "myproject-${env}-cdn-${CloudFrontInfo}-WebACL-Rule1"
          Priority0
          Statement:
            IPSetReferenceStatement:
              Arn!GetAtt SampleIPSet.Arn
          Action:
            Allow: {}
          VisibilityConfig:
            SampledRequestsEnabledtrue
            CloudWatchMetricsEnabledtrue
            MetricName!Sub "myproject-${env}-cdn-${CloudFrontInfo}-IpLimitationRule"


Web ACLv2 : AWS::WAFv2::WebACL
This part of CFN resource us used to define the WAFv2 ACl and it defines the below parts.
  • It has scope of CloudFront.
  • Default action is to Block everything and thus in response provide HTTP access code 401 and with the custom response body that we have created above part.
  • It will create a Cloudwatch metric dashboard for all blocked request.
  • It will also create a panel for all realtime blocked request/calls.

 CDNAccessIPRestrictionWebACL:
    TypeAWS::WAFv2::WebACL
    Properties:
      Name!Sub "myproject-${env}-cdn-${CloudFrontInfo}-WebACL"
      ScopeCLOUDFRONT
      DefaultAction:
        Block: {
      "CustomResponse": {
        "ResponseCode"401,
        "CustomResponseBodyKey""Unauthorized"
      }
    }
      Description!Sub "To limit access of Cloudfront ${CloudFrontInfo}  from known IP ranges only"
      Rules:
        - Name!Sub "myproject-${env}-cdn-${CloudFrontInfo}-WebACL-Rule1"
          Priority0
          Statement:
            IPSetReferenceStatement:
              Arn!GetAtt SampleIPSet.Arn
          Action:
            Allow: {}
          VisibilityConfig:
            SampledRequestsEnabledtrue
            CloudWatchMetricsEnabledtrue
            MetricName!Sub "myproject-${env}-cdn-${CloudFrontInfo}-IpLimitationRule"
      VisibilityConfig:
        SampledRequestsEnabledtrue
        CloudWatchMetricsEnabledtrue
        MetricName!Sub "myproject-${env}-cdn-${CloudFrontInfo}-WebACLMetric"
      Capacity1

  • This part creates the AWS WAFv2 w


Read more ...

AWS CloudFormation Interface Metadata



AWS CloudFormation Metadata
Metadata section define the details about the cloudformation template. 

Syntax Template

Metadata:
  Instances:
    Description"Instances details within dev environment"
  Applications:
    Description"Application details for dev environment"

There are three types of AWS Cloudformation specific Metadata keys.
  •   AWS::CloudFormation::Designer
It's auto generated during drag and drop of canvas within Cloudformation designer section.
  •   AWS::CloudFormation::Interface
It's used for parameter grouping and labeling as per requirement
  •   AWS::CloudFormation::Init
One of the most important section from Automation prospective, it's used for Application installation and configuration on our AWS EC2 instances.

So within this blog post, we will cover 
  • What is Interface Metadata.
  • Why and How it's used
  • How to customize orders of defined parameters.
  • How to group up parameters and mark them a identifying label.
  • How to define labels for the parameters.

AWS::CloudFormation::Interface

So during our stack creation, you might have noticed our defined parameters appears into an alphabetical order by their Logical ids, it has nothing to do with the way or order we define in our CFN template.

Interface Metadata Syntax
Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - ParameterGroup
    ParameterLabels:
      - ParameterLabel

For this post, in order to understand more about it we will use the below CFN template as an example.

CFN Template

AWSTemplateFormatVersion: 2010-09-09
Description|
  CFN Script to demonstrate Cloudformation Interface Metadata Usage
  Interface Metadata : AWS::CloudFormation::Interface
  Interface Metadata can be used to
           Group Parameters and it's order.
           Labels for Parameter for user friendly description input.

Parameters:
  EnvironmentName:
    DescriptionSelect the environment.
    TypeString
    Defaultdev
    AllowedValues:
      - dev
      - prd
  EC2KeyName:
    DescriptionSelect your Key name from List.
    TypeAWS::EC2::KeyPair::KeyName
  EC2SecurityGroup:
    DescriptionSelect your security group from List.
    TypeAWS::EC2::SecurityGroup::Id
  EC2Subnet:
    DescriptionSelect your Subnet from List.
    TypeAWS::EC2::Subnet::Id
  EC2InstanceType:
    TypeString
    Defaultt2.micro
    AllowedValues:
      - t2.micro
      - t2.small
  ApplicationType:
    TypeString
    Defaultweb
    AllowedValues:
      - web
      - app
  MonitoringStatus:
    TypeString
    Defaultenabled
    AllowedValues:
      - enabled
      - disabled

When we will import the above template to create or update stack the console will appear something like below.



From above we can witness that irrespective of the order of allignment parameters within CFN script, it re-orders it within console alphabetically by Parameter's logical ids.

What if we want to group parameters and label them as a separate identifier, Interface metadata can help us to accomplish the goal

What are we going to do with above template ?
    Well we have two sections one relates to the  EC2 Configuration data and the other one is more specific to Application configuration, so we will define our parameter groups and label according to that only.

CFN Interface Metadata with Custom Parameter Group

AWSTemplateFormatVersion: 2010-09-09
Description|
  CFN Script to demonstrate Cloudformation Interface Metadata Usage
  Interface Metadata : AWS::CloudFormation::Interface
  Interface Metadata can be used to
           Group Parameters and it's order.
           Labels for Parameter for user friendly description input.
Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default"EC2 Configuration"
        Parameters:
          - EC2InstanceType
          - EC2KeyName
          - EC2SecurityGroup
          - EC2Subnet
      - Label:
          default"Application Configuration"
        Parameters:
          - EnvironmentName
          - ApplicationType
          - MonitoringStatus

Once above file is imported, here is how the console screen looks likes.
We have two Parameter Groups and our parameters are ordered by the way we defined under these groups.
  • EC2 Configuration
  • Application Configuration.

Now, we will add some custom Labels to our Parameters to make it more user friendly and informative for user to avoid confusion.

Within our base template, we will intuit below Parameter Logical Ids with our own Label.
  • EnvironmentName
    • Be carefull while choosing your deployment environmnet
  • EC2KeyName
    • Ensure you have the keys before selecting
  • MonitoringStatus
    • It enables cloudwatch logs for application data

CFN Template to demonstrate Custom Labels for Parameters

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default"EC2 Configuration"
        Parameters:
          - EC2InstanceType
          - EC2KeyName
          - EC2SecurityGroup
          - EC2Subnet
      - Label:
          default"Application Configuration"
        Parameters:
          - EnvironmentName
          - ApplicationType
          - MonitoringStatus
    ParameterLabels:
      EnvironmentName
        default"Be carefull while choosing your deployment environmnet"
      EC2KeyName:
        default"Ensure you have the keys before selecting"
      MonitoringStatus:
        default"It enables cloudwatch logs for application data"

Once imported, this is the output in cloudformation console.



From above, we can state few things to note while using a parameter label configuration.

  • ParameterLabels will substitute your logical Id for your parameter with the one we have declared as default within our ParameterLabels section.
  • Only Logical Id gets substituted, description mentioned under individual parameter section persists.

AWS CFN best practice, we must use Interface metadata for large stack creation this makes things quite helpful for end user.

Feel free to comment.  

Read more ...

AWS CloudFormation - EC2 UserData



AWS CloudFormation EC2 UserData.


EC2 UserData is a way to define multiple actions within ec2 instnace once the system gets first time started, if you are from a Linux background you might be familiar with rc.local file where we used to write all the commands or script action that needs to be executed whenever a system gets booted up.
It's somehow similar to that but not the same at all.

Something more about EC2 UserData
  • We can use UserData in CFN template for EC2. 
  • We need to use an intrinsic function Fn::Base64 with UserData in CFN template, this function return the Base64 representation of string, it passes encoded data to EC2 instance.
  • Multiple Line values can be used under Base64 followed by YAML Pipe ( | )
  • UserData scripts/commands runs during the boot cycle when we first launch the instance.
  • To Update and reflect the changes under the value of UserData, reboot is required.
  • Can be used the same way normal parameters are used via !Ref as an argument.
Usage Example.

Below CFN template along with UserData section is used to install to perform three steps.
  • Update YUM
  • Download Logstash using Wget
  • Install downloaded RPM
AWSTemplateFormatVersion: 2010-09-09
Description: A Cloudformation Script to demonstrate EC2 UserData

Resources:
CreateEC2Instance:
Type: "AWS::EC2::Instance"
Properties:
ImageId: ami-01460aa81365561fe
InstanceType: t2.micro
KeyName: kunal_eks_test
SubnetId: subnet-0cdcc621
IamInstanceProfile: "IamInstanceProfile"
SecurityGroups:
- launch-wizard-1
UserData:
Fn::Base64: |
#!/bin/bash
sudo yum update -y
sudo wget https://artifacts.elastic.co/downloads/logstash/logstash-7.1.0.rpm
sudo rpm -Uvh logstash/logstash-7.1.0.rpm

Feel free to comment !

Read more ...

AWS CloudFormation Psuedo Parameters




AWS Cloud Formation Pseudo Parameters.


Parameters section within CloudFormation template is way to gather inputs from user, which can be used within other sections of entire cloudformation script.

Pseudo Parameter
  • Type of parameters that are predefined by AWS Cloudformation.
  • We don't need to declare it within our template section.
  • Can be used the same way normal parameters are used via !Ref as an argument.
Usage Examples.

"AWS::Region" is one of the widely used Pseudo parameters, so below is the way we can use it under our CFN template.


CFN Output Section
Outputs:
  MyStacksRegion:
    Value: !Ref "AWS::Region"


CFN Mappings Section
Resources:
  CreateEC2Instance:
    Type: "AWS::EC2::Instance"
    Properties:
      ImageId: !FindInMap
      - ImageIdMap
      - !Ref !Ref "AWS::Region"
      - defaultAMI

So in the same there are few more pseudo parameters enlisted below.

AWS::AccountId
  • Returns the account id from where the stack is being created.
AWS::NotificationARNs
  • Returns the list of notification Amazon Resource Names (ARNs) for the current stack
AWS::NoValue
  • Removes the corresponding resource property when specified as a return value in the Fn::If intrinsic function.
AWS::Partition
  • Returns the partition that the resource is in. For standard AWS regions, the partition is aws. For resources in other partitions, the partition is aws-partitionname
AWS::Region
  • Return where the stack is being created, example ap-south-1
AWS::StackId
  • Returns the ID of the stack as specified with the aws cloudformation create-stack command, such as arn:aws:cloudformation:ap-south-1:123456789987:stack/cyberkeedastack/90af3dc0-d9a7-01e4-972e-1234567se123.
AWS::StackName
  • Returns the name of the stack as specified with the aws cloudformation create-stack command, such as cyberkeedastack.
AWS::URLSuffix
  • Returns the suffix for a domain. The suffix is typically amazonaws.com, but might differ by region.

Read more ...
Designed By Jackuna