#
#
# sgremediate.sh

# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Written By: Eric Pullen, AWS Professional Services
#
# Will scan the given vpcID for SG's and detect if they have any associated services
# Services scaned: EC2, ELB, RDS, RedShift, ElastiCache
# If EC2 is detected, it will build a ElasticSearch URL that has the VPC FlowLogs ingested
#
#!/bin/bash

#
# Variables
#
# AWS CLI profile name
#profileName="MYProfile"
profileName="default"

# VPC We are looking at
vpcID="vpc-exammpleId"

# ElasticSearch URL
ElasticsearchURL="<YOUR_ES_DOMAIN_ENDPOINT>.es.amazonaws.com"
ElasticsearchDashboard="FlowLogDash"

# ---------------------------------------------------
# Start of check, no other variables below this line
# ---------------------------------------------------

# Start the process by getting a list of all the SG's in the defined VPC

sgList=`aws ec2 describe-security-groups --profile "$profileName" --filters Name=vpc-id,Values=$vpcID |jq -r .SecurityGroups[].GroupId`
if [ -z "$sgList" ]
 then
  # echo "VPC-ID $vpcID is invalid or returning no security groups";
  exit 0
fi


echo "<!DOCTYPE html>"
echo "<html>"
echo "<body>"

for securityGroup in $sgList; do

#We need to get a list of ENI’s based on the security group in this loop
#eniList=(`aws configservice get-resource-config-history --profile "$profileName" --resource-type AWS::EC2::SecurityGroup --resource-id "$securityGroup" | jq -r .configurationItems[].relationships[].resourceId |grep eni`)
eniList=(`aws ec2 describe-instances --profile "$profileName" --filters "Name=instance.group-id,Values=$securityGroup" |jq -r .Reservations[].Instances[].NetworkInterfaces[].NetworkInterfaceId`)
#echo "ElasticSearch URL for $securityGroup"

if [ -z "$eniList" ]
 then
  echo -n "$securityGroup - "

  # Check to see if they are associated with any RDS instances
  rdsVpcList=(`aws rds --profile "$profileName" describe-db-instances |grep $securityGroup`)
  if [ -z "$rdsVpcList" ]
   then
     echo -n ""
   else
     echo -n "RDS instance is associated "
     other="yes"
   fi

 # Check to see if they are associated with any ELB instances
  elbList=(`aws elb --profile "$profileName" describe-load-balancers |grep $securityGroup`)
   if [ -z "$elbList" ]
    then
      echo -n ""
    else
     echo -n "ELB instance is associated "
      other="yes"
    fi


  # Check to see if they are associated with any Redshift instances
   rsList=(`aws redshift --profile "$profileName" describe-clusters |grep $securityGroup`)
    if [ -z "$rsList" ]
     then
       echo -n ""
     else
      echo -n "Redshift cluster is associated "
       other="yes"
     fi

 # Check to see if they are associated with any ElastiCache instances
  ecList=(`aws elasticache --profile "$profileName" describe-cache-clusters |grep $securityGroup`)
   if [ -z "$ecList" ]
    then
      echo -n ""
    else
     echo -n "ElastiCache cluster is associated "
      other="yes"
    fi


 if [ -z "$other" ]
  then
     echo "No services related to this SG <BR>"
  else
     echo "<BR>"
  fi

else

# Start the URL string to present back to the user
echo -n "<a href=\"https://$ElasticsearchURL/_plugin/kibana/#/dashboard/$ElasticsearchDashboard?_g=(refreshInterval:(display:Off,section:0,value:0),time:(from:now-7d,mode:quick,to:now))&_a=(filters:!(),panels:!((col:4,id:enipi-all,row:1,size_x:6,size_y:7,type:visualization),(col:1,id:Eni-list,row:1,size_x:3,size_y:3,type:visualization),(col:1,id:eni-serch,row:8,size_x:11,size_y:5,type:search),(col:1,id:ENIAction,row:4,size_x:3,size_y:2,type:visualization),(col:1,id:EniProtocal,row:6,size_x:3,size_y:2,type:visualization),(col:10,id:ENIdestports,row:1,size_x:2,size_y:7,type:visualization)),query:(query_string:(analyze_wildcard:!t,query:'(action:%20ACCEPT)%20AND%20("

# Interate over all of the ENI's to generate the URL properly
count=0
for eniName in "${eniList[@]}"
 do
  count=$((count + 1))

  # For each ENI, let's get its private IP address
  privateIPList=`aws ec2 describe-network-interfaces --profile "$profileName" --network-interface-ids $eniName |jq -r .NetworkInterfaces[].PrivateIpAddress`
  # This is the string we need to add to the search URL
  if [ "$count" -eq "${#eniList[@]}" ]; then
    # If we are on the last array item, don't add the OR at the end
    buildString="(interface_id: $eniName NOT srcaddr: $privateIPList)"
  else
    # If we are still in the loop, then add the OR at the end
    buildString="(interface_id: $eniName NOT srcaddr: $privateIPList) OR "
  fi

  # Finally we have to convert the spaces to %20
  buildString=${buildString// /%20}

  # echo out the string
  echo -n "$buildString"
done

# close out the string we built
echo ")')),title:$ElasticsearchDashboard)\">$securityGroup</a><br>"


fi

done
echo "</body>"
echo "</html>"
