Last active
June 5, 2025 12:15
-
-
Save andreyev/1376d61ff14a3eee5eb4a308526c7e3e to your computer and use it in GitHub Desktop.
aws-policy-inspector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Before run you need to cache policies files running: | |
# $ mkdir policies | |
# $ i=0 aws iam list-policies | jq -r '.Policies[]|"\(.PolicyName) \(.Arn) \(.DefaultVersionId)"' | while read name arn version; do echo $((i++)); aws iam get-policy-version --policy-arn $arn --version-id $version > policies/${name}.json; done | |
# And map policy name and ARN | |
# $ aws iam list-policies | jq -r '.Policies[]|"\(.PolicyName) \(.Arn)"' > policies-arn | |
# To do: handle inline policies | |
# usage example to get all users who have s3 action on my-bucket: `$ bash policy-inspector.sh 's3:' "arn:aws:s3:::my-bucket" policies/*` | |
ACTION=$1 | |
shift | |
RESOURCE=$1 | |
shift | |
for FILE in $*; do | |
jq --arg RESOURCE "$RESOURCE" -re '.PolicyVersion.Document.Statement[]|select(.Resource != null)|.Resource|if type=="array" then .[] else . end|select(.|startswith($RESOURCE))' $FILE &> /dev/null &&\ | |
( | |
grep -E "^$(echo $FILE | perl -pe 's@(policies/|.json)@@g') " policies-arn| cut -d ' ' -f2| while read ARN; do | |
USERS_=$(aws iam list-entities-for-policy --policy-arn $ARN | jq -r '.PolicyUsers[].UserName'| tr '\n' ',') | |
USERS_FROM_GROUPS=$(aws iam list-entities-for-policy --policy-arn $ARN | jq -r '.PolicyGroups[].GroupName' | while read i; do aws iam get-group --group-name $i | jq -r '.Users[].UserName'; done | sort -u | tr '\n' ',') | |
[[ $USERS_ || $USERS_FROM_GROUPS ]] || exit | |
PERM=$(jq -r --arg RESOURCE "$RESOURCE" --arg ACTION "$ACTION" '.PolicyVersion.Document.Statement[]|select(.Action != null and .Effect == "Allow" and .Resource != null)| if (.Resource|type=="array") then (select(.Resource[]|startswith($RESOURCE))|if (.Action|type=="array") then ((select(.Action[]|startswith($ACTION)))|.Action[]) else ((select(.Action|startswith($ACTION)))|.Action) end) else (select(.Resource|startswith($RESOURCE))|if (.Action|type=="array") then ((select(.Action[]|startswith($ACTION)))|.Action[]) else ((select(.Action|startswith($ACTION)))|.Action) end) end' $FILE | grep -E '^'$ACTION | sort -u | tr '\n' ',') | |
[[ $PERM ]] || exit | |
echo -ne "$ARN;${USERS_},${USERS_FROM_GROUPS};${PERM}\n" | |
done | |
) | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment