#!/bin/bash

echo "========================="
echo " AWS Security Audit Script "
echo "========================="

# Function to check for public S3 buckets
check_public_s3_buckets() {
    echo "Checking for public S3 buckets..."
    buckets=$(aws s3 ls | awk '{print $3}')
    for bucket in $buckets; do
        acl=$(aws s3api get-bucket-acl --bucket $bucket --query "Grants[*].Grantee.URI" --output text 2>/dev/null)
        policy=$(aws s3api get-bucket-policy-status --bucket $bucket --query "PolicyStatus.IsPublic" --output text 2>/dev/null)
        
        if [[ "$acl" == *"AllUsers"* ]] || [[ "$acl" == *"AuthenticatedUsers"* ]] || [[ $policy == "True" ]]; then
            echo "⚠️  Public S3 Bucket Found: $bucket"
        fi
    done
}

# Function to check for IAM users without MFA
check_iam_users_without_mfa() {
    echo "Checking IAM users without MFA..."
    users=$(aws iam list-users --query "Users[*].UserName" --output text)
    for user in $users; do
        mfa=$(aws iam list-mfa-devices --user-name $user --query "MFADevices" --output text)
        if [ -z "$mfa" ]; then
            echo "⚠️  User without MFA: $user"
        fi
    done
}

# Function to detect overly permissive IAM policies
check_overly_permissive_policies() {
    echo "Checking for overly permissive IAM policies..."
    policies=$(aws iam list-policies --scope Local --query "Policies[*].Arn" --output text)
    for policy in $policies; do
        doc=$(aws iam get-policy-version --policy-arn $policy --version-id v1 --query "PolicyVersion.Document" --output json 2>/dev/null)
        if [[ "$doc" == *"\"Effect\": \"Allow\""* ]] && [[ "$doc" == *"\"Action\": \"*\""* ]] && [[ "$doc" == *"\"Resource\": \"*\""* ]]; then
            echo "⚠️  Overly Permissive Policy: $policy"
        fi
    done
}

# Function to check for open security groups
check_open_security_groups() {
    echo "Checking for open security groups..."
    open_sgs=$(aws ec2 describe-security-groups --query "SecurityGroups[?IpPermissions[?contains(IpRanges[].CidrIp, '0.0.0.0/0') || contains(Ipv6Ranges[].CidrIpv6, '::/0')]].GroupId" --output text)
    if [ -n "$open_sgs" ]; then
        echo "⚠️  Security groups allowing unrestricted access: $open_sgs"
    else
        echo "✅  No open security groups found."
    fi
}

# Function to find inactive IAM users (Last 90 days)
check_inactive_iam_users() {
    echo "Checking for inactive IAM users..."
    aws iam generate-credential-report
    sleep 5
    inactive_users=$(aws iam get-credential-report --query "Content" --output text | base64 --decode | awk -F, '{if ($7 == "N/A" && $8 == "N/A" && $9 == "N/A" && NR>1) print $1}')
    if [ -n "$inactive_users" ]; then
        echo "⚠️  Inactive IAM Users: $inactive_users"
    else
        echo "✅  No inactive users found."
    fi
}

# Function to check CloudTrail logging status
check_cloudtrail_status() {
    echo "Checking CloudTrail logging status..."
    status=$(aws cloudtrail describe-trails --query "trailList[*].IsLogging" --output text)
    if [ "$status" != "True" ]; then
        echo "⚠️  CloudTrail is not enabled!"
    else
        echo "✅  CloudTrail is enabled."
    fi
}

# Function to check EC2 instances without IMDSv2
check_ec2_imds_v2() {
    echo "Checking EC2 instances without IMDSv2..."
    imds_v1_instances=$(aws ec2 describe-instances --query "Reservations[*].Instances[?MetadataOptions.HttpTokens=='optional'].InstanceId" --output text)
    if [ -n "$imds_v1_instances" ]; then
        echo "⚠️  EC2 instances without IMDSv2: $imds_v1_instances"
    else
        echo "✅  All EC2 instances use IMDSv2."
    fi
}

# Run all checks
check_public_s3_buckets
check_iam_users_without_mfa
check_overly_permissive_policies
check_open_security_groups
check_inactive_iam_users
check_cloudtrail_status
check_ec2_imds_v2

echo "========================="
echo " AWS Security Audit Completed "
echo "========================="

