How to Automate IAM Least Privilege Policies in AWS Using Access Analyzer: A Quick Guide

https://hackernoon.imgix.net/images/eQHzh6rz7ETBHLjs0KzCl1Dooqp2-r903bfk.jpeg

The Challenge: Replacing Wildcards with Granular Permissions

To implement least privilege, you must know exactly which API calls your application makes. Guessing leads to application downtime, while wildcards lead to security vulnerabilities.

The Solution: Automated Policy Generation via AWS CLI

AWS CloudTrail logs every API call. IAM Access Analyzer can digest these logs and output a perfectly tailored JSON IAM policy containing only the actions actually invoked by a role over a specific timeframe. Here is the automation script using the AWS CLI.

#!/bin/bashROLE_ARN="arn:aws:iam::123456789012:role/OverPermissiveAppRole"TRAIL_ARN="arn:aws:cloudtrail:us-east-1:123456789012:trail/management-events"START_TIME=$(date -u -d '7 days ago' +%Y-%m-%dT%H:%M:%SZ)END_TIME=$(date -u +%Y-%m-%dT%H:%M:%SZ)# Step 1: Initiate Policy GenerationJOB_ID=$(aws accessanalyzer start-policy-generation \ --policy-generation-details "principalArn=$ROLE_ARN" \ --cloud-trail-details "accessRole=arn:aws:iam::123456789012:role/AnalyzerRole,startTime=$START_TIME,endTime=$END_TIME,trails=[$TRAIL_ARN]" \ --query 'jobId' --output text)echo "Started job: $JOB_ID. Waiting for completion..."# Step 2: Poll for Completionwhile true; do STATUS=$(aws accessanalyzer get-generated-policy \ --job-id "$JOB_ID" \ --query 'jobDetails.status' --output text) if [ "$STATUS" == "SUCCEEDED" ]; then break; fi if [ "$STATUS" == "FAILED" ]; then...

Copyright of this story solely belongs to hackernoon.com. To see the full text click HERE

Read more