Sunday, May 4, 2014

Smart Configuration of AWS Security Group Using PowerShell

Securing the infrastructure is critical for any company’s success. Absolute security does not exist and hence it is important to follow security best practices and implementing redundant layers of security aka defense in depth. Likewise security is never complete, one has to continuously monitor and enhance security infrastructure. Keep up with security trends!

Firewalls is an effective mechanism to mitigate security threats. Firewalls limit access to specific type of network traffic and allow traffic from valid sources only. It is important to restrict traffic only from valid source IP addresses, this will substantially prune security attack surface. You should restrict internal traffic just like external (e.g.) Allow DB connections only from middle tier and bastion hosts. This will prevent lateral movement if one of the server is compromised. Firewalls can come in layers. The last layer of defense is the OS firewall layer running inside the instance. AWS offers two additional firewall layers (i.e.) Security Groups and Network ACLs.

Security Group Overview

A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. When you launch an instance in a VPC, you can assign the instance to up to five security groups. Security groups act at the instance level, not the subnet level. Therefore, each instance in a subnet in your VPC could be assigned to a different set of security groups. If you don't specify a particular group at launch time, the instance is automatically assigned to the default security group for the VPC.

For each security group, you add rules that control the inbound traffic to instances, and a separate set of rules that control the outbound traffic. This section describes the basics things you need to know about security groups for your VPC and their rules. Learn more here.

Network ACLs

A network access control list (ACL) is an optional layer of security that acts as a firewall for controlling traffic in and out of a subnet. Network ACLs are collection of stateless rules, processed in order, supports both allow and deny rules. Learn more here.

Security Groups and Network ACLs

·         Security groups—Act as a firewall for associated Amazon EC2 instances, controlling both inbound and outbound traffic at the instance level

·         Network access control lists (ACLs)—Act as a firewall for associated subnets, controlling both inbound and outbound traffic at the subnet level


The following table summarizes the basic differences between security groups and network ACLs.

Security Group
Network ACL
Operates at the instance level (first layer of defense)
Operates at the subnet level (second layer of defense)
Supports allow rules only
Supports allow rules and deny rules
Is stateful: Return traffic is automatically allowed, regardless of any rules
Is stateless: Return traffic must be explicitly allowed by rules
All rules are processed before deciding whether to allow traffic
Rules are processed in number order when deciding whether to allow traffic

 

PowerShell Automation of Security Groups

As discussed before Security Groups are a powerful mechanism to specify what traffic to allow and from what IP addresses. The source IP addresses range is defined in the CIDR notation. Security Groups are flexible in that they can have one or more rules and each rule can specify one or more IP address ranges.

One Nifty trick to only allow traffic from your computer is to use the service http://checkip.amazonaws.com. This endpoint returns your public IP address as seen by AWS. Configuring the Security Group only to allow traffic from this source is the most security it can get. This will likely work for the test scenarios but for production you might have to open up depending on the scenario. (e.g.)  Front end webserver has to be opened up globally with CIDR “0.0.0.0/0”

The following script can be used as a starting point for your customization, it illustrates the basic concepts. By default it enables PowerShell, HTTP, ICMP and RDP and restricts the source IP to checkup (i.e.) to your public IP address. This script is idempotent in the sense that it can be run any number of times. If the config is different it will be updated.


# Creates or updates the security group
# Default it enables RDP, PowerShell, HTTP and ICMP.
# Define appropriate switch to disable specific protocol
# If SourceIPRange is not defined, it configures based on http://checkip.amazonaws.com
function Update-WinEC2FireWallSource
{
    param (
        $SecurityGroupName = 'sg_rdp_ps_http_icmp',
        $Region=$defaultRegion,
        $SourceIPRange = $null,
        [switch] $NoRDP,
        [switch] $NoPS,
        [switch] $NoHTTP,
        [switch] $NoICMP
    )
    trap {break }
    $ErrorActionPreference = 'Stop'

    Set-DefaultAWSRegion $defaultRegion

    if ($SourceIPRange -eq $null)
    {
        $bytes = (Invoke-WebRequest 'http://checkip.amazonaws.com/').Content
        $SourceIPRange = @([System.Text.Encoding]::Ascii.GetString($bytes).Trim() + "/32")
    }
    else
    {
        $SourceIPRange = @($SourceIPRange) #Make it an array, if not already
    }

    $sg = Get-EC2SecurityGroup | ? { $_.GroupName -eq $SecurityGroupName}
    if ($sg -eq $null)
    {
        #Create the firewall security group
        $groupid = New-EC2SecurityGroup $SecurityGroupName  -Description "Enables rdp, ps, http and icmp"
    }
    else
    {
   
        foreach ($ipPermission in $sg.IpPermissions)
        {
            $delete = $true # will be set to false if we find exact match

            if ($ipPermission.IpProtocol -eq 'tcp' -and
                $ipPermission.FromPort -eq 3389 -and $ipPermission.ToPort -eq 3389)
            {
                if (-not $NoRDP)
                {
                    $delete = $false
                    $NoRDP = $true # Already defined don't have to create it again.
                }
            }
            if ($ipPermission.IpProtocol -eq 'tcp' -and
                $ipPermission.FromPort -eq 5985 -and $ipPermission.ToPort -eq 5985)
            {
                if (-not $NoPS)
                {
                    $delete = $false
                    $NoPS = $true # Already defined don't have to create it again.
                }
            }
            if ($ipPermission.IpProtocol -eq 'tcp' -and
                $ipPermission.FromPort -eq 80 -and $ipPermission.ToPort -eq 80)
            {
                if (-not $NoHTTP)
                {
                    $delete = $false
                    $NoHTTP = $true # Already defined don't have to create it again.
                }
            }
            if ($ipPermission.IpProtocol -eq 'icmp' -and
                $ipPermission.FromPort -eq -1 -and $ipPermission.ToPort -eq -1)
            {
                if (-not $NoICMP)
                {
                    $delete = $false
                    $NoICMP = $true # Already defined don't have to create it again.
                }
            }

            $update = $false
            if ($ipPermission.IpRanges.Count -ne $SourceIPRange.Count)
            {
                $update = $true
            }
            else
            {
                foreach ($sourceIP in $SourceIPRange)
                {
                    if (-not $ipPermission.IpRanges.Contains($sourceIP))
                    {
                        $update = $true
                        break
                    }
                }
            }

            if ($delete -or $update)
            {
                Revoke-EC2SecurityGroupIngress -GroupName $SecurityGroupName `
                    -IpPermissions $ipPermission
                if (-not $delete)
                {
                    $ipPermission.IpRanges = $SourceIPRange
                    Grant-EC2SecurityGroupIngress -GroupName $SecurityGroupName `
                        -IpPermissions $ipPermission
                }
            }
        }
    }

    if (-not $NoRDP)
    {
        Grant-EC2SecurityGroupIngress -GroupName $SecurityGroupName -IpPermissions `
          @{IpProtocol = 'tcp'; FromPort = 3389; ToPort = 3389; IpRanges = $SourceIPRange}
    }
    if (-not $NoPS)
    {
        Grant-EC2SecurityGroupIngress -GroupName $SecurityGroupName -IpPermissions `
          @{IpProtocol = 'tcp'; FromPort = 5985; ToPort = 5986; IpRanges = $SourceIPRange}
    }
    if (-not $NoHTTP)
    {
        Grant-EC2SecurityGroupIngress -GroupName $SecurityGroupName -IpPermissions `
          @{IpProtocol = 'tcp'; FromPort = 80; ToPort = 80; IpRanges = $SourceIPRange}
    }
    if (-not $NoICMP)
    {
        Grant-EC2SecurityGroupIngress -GroupName $SecurityGroupName -IpPermissions `
          @{IpProtocol = 'icmp'; FromPort = -1; ToPort = -1; IpRanges = $SourceIPRange}
    }

    Write-Host "Updated $SecurityGroupName IpRange to $SourceIPRange"
}


Sample usage of the script:

PS C:\temp> Update-WinEC2FireWallSource
Updated sg_rdp_ps_http_icmp IpRange to 174.21.164.151/32

PS C:\temp> Update-WinEC2FireWallSource -NoHTTP -NoICMP
Updated sg_rdp_ps_http_icmp IpRange to 174.21.164.151/32

PS C:\temp> Update-WinEC2FireWallSource -NoHTTP -NoICMP -SourceIPRange "10.0.0.0/8","172.31.0.0/16"
Updated sg_rdp_ps_http_icmp IpRange to 10.0.0.0/8 172.31.0.0/16


References

1.       Security Groups
2.       Network ACL

You can find the code under “AWS” folder at https://github.com/padisetty/Samples.


Explore & Enjoy!
/Siva

79 comments:

  1. These individuals are further prepared to work different obligations and undertakings that might be required whenever thus they are prepared with everything. https://how-to-remove.org/malware/ransomware-removal/fbi-virus/

    ReplyDelete
  2. Nice Information about Configuration of AWS Security Group Using PowerShell my sincere thanks for sharing this post please continue to share this kind of post
    AWS Training in Marathahalli

    ReplyDelete
  3. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it. Amazon Web Services Training in Chennai

    ReplyDelete
  4. Proactive reasons incorporate expanding your level of security: for diminishments in the cost of protection, particularly in regard of substance protection; in accordance with dangers, for example, an expansion in nearby wrongdoing including private premises; or following late interest in settled or moveable resources. Fast Guard Service

    ReplyDelete
  5. I feel really happy to have seen your webpage and look forward to so
    many more entertaining times reading here. Thanks once more for all
    the details.


    AWS Training in Chennai


    AWS Training in Bangalore


    AWS Training in Bangalore

    ReplyDelete
  6. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. Amazon Web Services Training in Chennai

    ReplyDelete
  7. Thank you so much for sharing this informative blog. Your technical information is really useful for me. Keep update your blog.
    Regards..
    Amazon Web Services Training in Chennai
    Amazon Web Services Training Institute in Chennai

    ReplyDelete
  8. I have been in the private security business for right around eleven years and I have possessed an organization for every last bit of it. I have chipped away at the roads as a watch and everything in the middle.timedoctor login

    ReplyDelete
  9. I‘d mention that most of us visitors are endowed to exist in a fabulous place with very many wonderful individuals with very helpful things... RPA Training in Chennai | Blue Prism Training in Chennai

    ReplyDelete
  10. AWS Training in Bangalore - Live Online & Classroom
    myTectra Amazon Web Services (AWS) certification training helps you to gain real time hands on experience on AWS. myTectra offers AWS training in Bangalore using classroom and AWS Online Training globally. AWS Training at myTectra delivered by the experienced professional who has atleast 4 years of relavent AWS experince and overall 8-15 years of IT experience. myTectra Offers AWS Training since 2013 and retained the positions of Top AWS Training Company in Bangalore and India.

    ReplyDelete
  11. IOT Training in Bangalore - Live Online & Classroom
    IOT Training course observes iot as the platform for networking of different devices on the internet and their inter related communication. Reading data through the sensors and processing it with applications sitting in the cloud and thereafter passing the processed data to generate different kind of output is the motive of the complete curricula. Students are made to understand the type of input devices and communications among the devices in a wireless media.

    ReplyDelete
  12. Nice blog..! I really loved reading through this article. Thanks for sharing such
    an amazing post with us and keep blogging... RPA Training in Chennai | Blue Prism Training in Chennai

    ReplyDelete
  13. In the beginning, I would like to thank you much about this great post. Its very useful and helpful for anyone looking for tips to help him learn and master in Angularjs. I like your writing style and I hope you will keep doing this good working.
    Angularjs Classes in Bangalore
    Angularjs Coaching in Bangalore
    Angularjs Institute in Bangalore
    Android Classes in Bangalore
    Android Development Training in Bangalore
    Android Development Course in Bangalore

    ReplyDelete
  14. Awwsome informative blog ,Very good information thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us. Aviation Courses in Chennai | Best Aviation Academy in Chennai | Aviation Academy in Chennai | Aviation Training in Chennai | Aviation Institute in Chennai

    ReplyDelete
  15. I wanted to thank you for this great blog! I really enjoying every little bit of it and I have you bookmarked to check out new stuff you post.
    Web Designing Course in chennai
    PHP Training in Chennai
    web designing training in chennai
    Web Development courses in Chennai
    PHP Training Chennai
    PHP Course Chennai

    ReplyDelete
  16. Nice Post. Looking for more updates from you. Thanks for sharing.

    Education
    Technology

    ReplyDelete
  17. Hi,
    I must appreciate you for providing such a valuable content for us. This is one amazing piece of article. Helped a lot in increasing my knowledge.
    Android Training Chennai
    Android Courses in Chennai
    Android Mobile apps Development Training in Chennai
    AWS Training in Chennai
    AWS Training
    AWS Course in Chennai

    ReplyDelete
  18. I have read your blog its very attractive and impressive. I like it your blog.
    Best AWS training in marathahalli bangalore

    ReplyDelete
  19. It is really a great work and the way in which u r sharing the knowledge is excellent. Thanks for helping me to understand basic concepts. Thanks for your informative article.
    Java Training in Chennai OMR
    Pega Training in Chennai OMR
    Python Training in Chennai OMR
    Blue prism Training in Chennai OMR
    RPA Training in Chennai OMR
    Aptitude Training in Chennai OMR

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. This comment has been removed by the author.

    ReplyDelete
  22. Consider sourcing out these cameras from Chinese wholesalers and outsource providers. The characteristics of Chinese items have risen significantly throughout the years and combined with their amazingly low costs would be extraordinary increments to any online store or item postings. here

    ReplyDelete
  23.  A portable fish finder is a good choice if you don't fish from the same ship all the time. Mens Watches

    ReplyDelete
  24. Resources like the one you mentioned here will be very useful to me ! I will post to this page on my blog. I am sure my visitors will find that very useful

    href="https://www.mytrainingbangalore.com/seo-training-in-bangalore/" rel="nofollow"SEO Training in Bangalore
    href="https://www.mytrainingbangalore.com/" rel="nofollow"Best Training in Bangalore

    ReplyDelete
  25. Hi! I know this is somewhat off topic, but I was wondering which blog platform are you using for this site? I'm getting tired of Wordpress because I've had issues with hackers and I'm looking at alternatives for another platform. I would be awesome if you could point me in the direction of a good platform. He said: Learn How To Lock Files From The Movies

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete
  27. very Nice. Thanks for the blog sir,

    If u are looking to build your carrier in AWS Please click the below links. we will help u

    AWS Training in Bangalore

    Best AWS Training Institute in Bangalore



    ReplyDelete
  28. A few mortgage holders even introduce minor remote home surveillance cameras inside and outside, where nobody can see, to screen suspicious movement.
    Best Security Place

    ReplyDelete
  29. You have all listed and very accurate with the details. Thanks!

    Click here Devops Training in Bangalore to learn trending courses in International market and we will provide u 100% job assistance even.

    ReplyDelete
  30. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information regarding Microsoft Azure which is latest and newest,

    Regards,
    Ramya

    Azure Training in Chennai
    Azure Training Center in Chennai
    Best Azure Training in Chennai
    Azure Devops Training in Chenna
    Azure Training Institute in Chennai
    Azure Training in Chennai OMR
    Azure Training in Chennai Velachery
    Azure Online Training
    Azure Training in Credo Systemz
    DevOps Training in Credo Systemz

    ReplyDelete
  31. A good blog for the people who really needs information about this. Good work keep it up.

    Guest posting sites
    Education

    ReplyDelete
  32. Appericated the efforts you put in the content of Data Science .The Content provided by you for Data Science is up to date and its explained in very detailed for Data Science like even beginers can able to catch.Requesting you to please keep updating the content on regular basis so the peoples who follwing this content for Data Science can easily gets the updated data.
    Thanks and regards,
    Data Science training in Chennai
    Data Science course in chennai with placement
    Data Science certification in chennai
    Data Science course in Omr

    ReplyDelete
  33. With the Internet, online business is quickly venturing into a quick moving, open worldwide market with a consistently expanding number of members. weneedprivacy

    ReplyDelete
  34. The principal thing you'll have to do, before you buy any hardware, is to ensure that the framework you pick accompanies a guidance manual.Cassy

    ReplyDelete
  35. Thank for sharing a great article. I wish I will find a more useful article from you
    AWS Training in Chennai
    Python Training in Chennai

    ReplyDelete
  36. Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though. Serious Alarm systems in Parramatta

    ReplyDelete
  37. Thank you so much for sharing this informative blog. Your technical information is really useful for me. Keep update your blog...
    IoT Training in Bangalore | Internet of Things Course | IoT Course in Bangalore - Tecmax - Tecmax offers the Best IoT Training in Bangalore, We offer Real-Time Job Oriented IoT Training with Live Projects,
    Our IoT (Internet of Things) Trainers are Working Professionals with 4+ years of Expertise in IoT, we also provide 100% Placement Assistance after IoT Course Completion.

    ReplyDelete