Skip to content

Instantly share code, notes, and snippets.

@kholisrag
Last active July 4, 2024 05:27
Show Gist options
  • Save kholisrag/c63bdfe7b89616d1ce6f9ca5cedc2e9c to your computer and use it in GitHub Desktop.
Save kholisrag/c63bdfe7b89616d1ce6f9ca5cedc2e9c to your computer and use it in GitHub Desktop.
gcloud script to check Allow SSH from Internet (`default-allow-ssh`) in your organization / projects that you have permission to access
#!/bin/bash
projects=$(gcloud projects list --format="value(projectId)")
for project in $projects; do
echo "Checking project: $project"
if ! gcloud services list --project "$project" --enabled | grep -q compute.googleapis.com; then
echo "Compute Engine API not enabled for $project. Skipping..."
echo "--------------------"
continue
fi
# Fetch and filter firewall rules (including network)
allowed_rules=$(\
gcloud compute firewall-rules list \
--project "$project" \
--format="value(name,network,disabled,allowed[].ports[],allowed[].IPProtocol[])" \
| \
while read -r name network disabled ports protocol; do
# Skip if the rule is disabled or not TCP protocol
if [[ "$disabled" == "True" ]] || [[ "$protocol" != "tcp" ]]; then
continue
fi
# Check if port 22 is in the list of allowed ports
if [[ "$ports" == *22* ]]; then
IFS=',' read -ra source_ranges <<< "$(gcloud compute firewall-rules describe "$name" --project "$project" --format="value(sourceRanges)")"
for source_range in "${source_ranges[@]}"; do
if [[ "$source_range" == "0.0.0.0/0" ]]; then
echo "$name (Network: $network)"
break
fi
done
fi
done
)
if [ -n "$allowed_rules" ]; then
echo "Project $project has the following firewall rules allowing SSH (port 22) from the Internet (0.0.0.0/0):"
echo "$allowed_rules"
else
echo "Project $project has no enabled firewall rules allowing SSH from the Internet."
fi
echo "--------------------"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment