Skip to content

Instantly share code, notes, and snippets.

@cmcconnell1
Created June 22, 2017 20:01
Show Gist options
  • Save cmcconnell1/e7f4c40e92728b164d24c6d9549c1e8b to your computer and use it in GitHub Desktop.
Save cmcconnell1/e7f4c40e92728b164d24c6d9549c1e8b to your computer and use it in GitHub Desktop.
restrict (dynamically created kubernetes) AWS security groups ssh access (older kube-aws versions created SGs' with: 0.0.0.0/0 on 22)
#!/usr/bin/env bash
# Why: within a few minutes of deploying a kube cluster, hackers start brute forcing on ssh
# for some time, older kube-aws versions had the dynamic SG allow on 0.0.0.0/0 for 22/ssh
#
# This was used immediately after deploying fresh kube-aws clusters to restrict their ssh access to specified CIDR ranges.
# Usage:
# cd kube-aws-dir ; $path_to_script/secure-kube-ssh-access.sh
#
# Note disregard errors like the below due to either the rule we want to remove doesnt exist (deis security groups) or the rules have already been applied by this script or another process.
# An error occurred (InvalidPermission.NotFound) when calling the RevokeSecurityGroupIngress operation: The specified rule does not exist in this security group.
# An error occurred (InvalidPermission.Duplicate) when calling the AuthorizeSecurityGroupIngress operation: the specified rule "peer: 10.1.0.0/20, TCP, from port: 22, to port: 22, ALLOW" already exists
#
printf "\ngrep kube clusterName from cluster.yaml file setting in the current directory\n"
#kube_cluster=cmcc-kube-test1
kube_cluster=$(grep 'clusterName:' ./cluster.yaml | awk -F ": " '{print $2}')
# get our desired kube cluster nodes
# not reliable using text output if the group descriptions are modified, etc
# aws ec2 describe-security-groups --filters Name=vpc-id,Values=vpc-xxxxx Name=tag:KubernetesCluster,Values=aergo-dev --output text | grep SECURITYGROUPS | grep -v 'deis'
for kube_sg_id in $(aws ec2 describe-security-groups --filters Name=vpc-id,Values=vpc-xxxxxx | jq -r '.SecurityGroups[] | [.GroupId, .GroupName] | @csv' | grep -i "$kube_cluster" | awk -F ',' '{print $1}' | sed 's/"//g') ; do
printf "KUBE-SG-ID: $kube_sg_id\n"
# first we remove the world-access
aws ec2 revoke-security-group-ingress --group-id ${kube_sg_id} --protocol tcp --port 22 --cidr 0.0.0.0/0
# now we grant sane default SSH rules for EC2 and VPN admin access
aws ec2 authorize-security-group-ingress --group-id ${kube_sg_id} --protocol tcp --port 22 --cidr x.x.x.x/xx
aws ec2 authorize-security-group-ingress --group-id ${kube_sg_id} --protocol tcp --port 22 --cidr x.x.x.x/xx
printf "\nawless show kube_sg_id: ${kube_sg_id}\n"
awless show ${kube_sg_id}
done
printf "\nSecurity Group IDs for Kubernetes Cluster: $kube_cluster\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment