PowerShell, AWS, Jenkins and continuously enforced security groups

I recently did a series on how to spin up EC2 instances using Powershell, Jenkins and cloudflare. One of the things I really liked about the series was how you could limit the security groups presented to the user when generating the instance. If you have a passing experience with the AWS console you are probably aware it is easy to create a new security group when spinning up an EC2 instance. Since it takes a little bit of extra work to recreate the instance with the correct security group you often end up with a sea of generic security groups. The groups themselves are not a problem, but if your team is leaving RDP and SSH open to the world it can raise additional security concerns.

The script I wrote integrates with Jenkins and allows you to enforce IP rules for these security groups.
In order for the script to work you will need to have completed the “Getting started with AWS powershell plugin
I also recommend you check out  Matthew Hodgkins’ 2 part blog series on getting started with Jenkins and Powershell
There are no additional Jenkins plugins needed.

You can get the script I will be talking about from my github here. I wrote 2 versions, I’ll mostly be focused on the dynamic IP version and that will be what most of the code snippets and Jenkins build will be about in the post. I’ll make notes on the differences for the other Jenkins build later down since that is the major difference in each version.

 

The work flow:

First we’ll focus on the Jenkins build.

The script takes a couple of environment variables from jenkins to launch. We’ll need the “AWSprofile” parameter with the names that were pre-saved in the powershell plugin. Since these are windows profile dependent it is recommended to set them up as the service account running Jenkins.

The other variable the script needs is the ports we want to limit to our current external IP. I wrote this script with the idea of limiting management ports so it will mindlessly lock down all ports listed. So if you enter port 80 in the list then only you will be able to reach port 80 from all your EC2 instances.

 

In the end the build will appear like this:

Note: The script reads the build parameters and uses a ‘;’ colon delimiter.

The code that loads the parameters:

import-module awspowershell
#AWS stored Credential names
$profile_list = $ENV:AWSProfiles -split ";"
#Path for log file
$path_log = $ENV:Path_log
#Uses Value "From Port in AWS" SSH is 22, RDP is 3389. This script expects a standard port 22 maps to port 22 design
$Search_ports = $ENV:Ports_list -split ";"

Next we load the Get-ExternalIP function. This function reaches out to the ipify.org API and parses the Json response and returns the CDR formatted response for the AWS firewall.

function Get-externalCDR() {
try {
$ip = $(invoke-restmethod 'https://api.ipify.org?format=json' | select -expandproperty IP) + "/32"
return $ip
} catch {
return $false
}
}
#Allowed IP Ranges.
$Allowed_IP_Ranges = Get-ExternalCDR

Load the profile names and then start iterating through all the AWS regions:

foreach($profile in $profile_list) {
#Incase of Security group overlap clear the id list for every profile
[array]$updated_group_id = $NULL
#Set the AWS profile to use
Set-AWSCredentials -ProfileName $profile
#Iterate through all possible regions
$region_list = Get-AWSRegion | select -expandproperty Region
foreach($region in $region_list) {

Next we iterate through each instance and grab the assigned security group ID and Name:

$Instance_list = Get-EC2Instance -region $region |select -expandproperty instances
$VPC_list = Get-EC2Vpc -Region $region
foreach ($VPC in $VPC_list) {
$Instance_list | Where-Object {$_.VpcId -eq $VPC.VpcId} | foreach-object {
$Instance_name = ($_.Tags | Where-Object {$_.Key -eq 'Name'}).Value
$SecurityGroups = $_.SecurityGroups.GroupName
$SecurityGroupID = $_.SecurityGroups.GroupID

Next we confirm that we haven’t already touched this particular group. This is just to save time in larger AWS environments. If we update Security Group A then every EC2 instance with Security Group A is already up to date.

if($updated_group_id -notcontains $SecurityGroupID) {

Now the good part. We take the Array of Ports we defined in the Jenkins build to check and make sure the security group we are checking has them present. IF it doesn’t we just skip the group. Then we check that the allowed IP is not in our Array of allowed options. Since this is the Dynamic script it is checking for our extremely limited /32 CDR it’ll remove the rule if it doesn’t match. I utilize the compare-object command in order to skip rules that are correct.

foreach($port in $Search_Ports) {
if($Found_IP_List = $(Get-EC2SecurityGroup $SecurityGroupID -Region $region ).IpPermissions | where { $_.FromPort -eq "$port" } | select -expandproperty IPRange) {
$Removable_IPs = Compare-Object -ReferenceObject $Allowed_IP_Ranges -DifferenceObject $Found_IP_List | where { $_.SideIndicator -eq "=>" } | select -expandproperty InputObject
foreach($IP_Current_Rule in $Removable_IPs) {
$Time = Get-date -format "s"
echo "$Time : Removing $IP_Current_Rule from $SecurityGroups ( $SecurityGroupID ) with $profile in $region found on $Instance_name"
echo "$Time : Removing $IP_Current_Rule from $SecurityGroups ( $SecurityGroupID ) with $profile in $region found on $Instance_name" >> $path_log
Try {
$Firewall_rule = @{ IpProtocol="tcp"; FromPort="$port"; ToPort="$port"; IpRanges= "$IP_Current_Rule" }
Revoke-EC2SecurityGroupIngress -GroupId $SecurityGroupID -IpPermissions $Firewall_rule -Region $region
} catch {
echo "$Time ERROR: REMOVING $port for $SecurityGroups ($SecurityGroupID)"
echo "$Time ERROR: REMOVING $port for $SecurityGroups ($SecurityGroupID)" >> $Path_log
$_
$_ >> $Path_log
exit 1
}
}

We are still in the Foreach loop of $port in $SearchPorts, we are also in the IF check where the $found_IP_list variable is defined. We next need apply allowed IPs to the Security group. We re-compare the ips and make sure that we don’t try to apply IPs twice. The goal in this to clean everything up:

$Allowed_IPs = Compare-Object -ReferenceObject $Allowed_IP_Ranges -DifferenceObject $Found_IP_List | where { $_.SideIndicator -eq "<=" } | select -expandproperty InputObject
foreach($IP in $Allowed_IPs) {
if($Found_IP_List -notcontains $IP) {
$Time = Get-date -format "s"
echo "$Time : Adding $IP from $SecurityGroups ( $SecurityGroupID ) with $profile in $region found on $Instance_name"
echo "$Time : Adding $IP from $SecurityGroups ( $SecurityGroupID ) with $profile in $region found on $Instance_name" >> $path_log
Try {
$Firewall_rule = @{ IpProtocol="tcp"; FromPort="$port"; ToPort="$port"; IpRanges= "$IP" }
Grant-EC2SecurityGroupIngress -GroupId $SecurityGroupID -IpPermission @( $Firewall_rule ) -Region $region
} catch {
echo "$Time ERROR: ADDING $port for $SecurityGroups ($SecurityGroupID)"
echo "$Time ERROR: ADDING $port for $SecurityGroups ($SecurityGroupID)" >> $Path_log
$_
$_ >> $Path_log
exit 1
}
}
}
}

We are now out of the If($Found_IP_List check. There is the final step off adding the group to the skip Variable $updated_group_id. This again is to save time in large environments.

$updated_group_id += $SecurityGroupID.Trim()
}
}
}
}
}

There are some risks associated with this script, but they are pretty minor. The major issue is if the connection to AWS via powershell is interrupted it is possible a Security Group will not have a management port re-added. If it isn’t re-added then re-running the script won’t fix it. You’ll need to go through Log file the script generates to find the old setting. That is the reason I log both to the Jenkins console AND to a file so you have the ability to find a history of old settings. This is a blunt tool that works well for standardizing an environment. You may need to modify it to fit your environment.

 

Bonus Array defined IPs

Earlier I said I had worked on two versions. The other version is almost identical to this version except it accepts an Array of IPs. You find that version in the same github I’d listed earlier.

The major difference is the Jenkins build needs a new parameter added:

And the variable:

$Allowed_IP_Ranges = $ENV:Allowed_IP_list -split ";"

 

Thanks for reading.

I_Script_Stuff

Sharing is caring!

Leave your comment

twelve − 10 =