• DevOps
    Case Study

    How we built a resilient multi-account, multi-cloud solution for a Health Tech service provider!

    READ CASESTUDY
    icon

    24/7 DevOps as a Service

    Round-the-clock DevOps for uninterrupted efficiency.

    icon

    Infrastructure as a Code

    Crafting infrastructure with ingenious code.

    icon

    CI/CD Pipeline

    Automated CI/CD pipeline for seamless deployments.

    icon

    DevSecOps

    Integrated security in continuous DevOps practices.

    icon

    Hire DevOps Engineers

    Level up your team with DevOps visionaries.

    icon

    Consulting Services

    Navigate success with expert DevOps consulting.

  • TechOps
    Case Study

    How we built a scalable Odoo solution for a Travel Tech service provider!

    READ CASESTUDY

    WEB HOSTING SUPPORT

    icon

    HelpDesk Support

    Highly skilled 24/7 HelpDesk Support

    icon

    Product Support

    Boost your product support with our expertise.

    MANAGED SERVICES

    icon

    Server Management

    Don’t let server issues slow you down. Let us manage them for you.

    icon

    Server Monitoring

    Safeguard your server health with our comprehensive monitoring solutions.

    STAFF AUGMENTATION

    icon

    Hire an Admin

    Transform your business operations with our expert administrative support.

    icon

    Hire a Team

    Augment your workforce with highly skilled professionals from our diverse talent pool.

  • CloudOps
    Case Study

    How we helped a Private Deemed University in India, save US $3500/m on hosting charges!

    READ CASESTUDY
    icon

    AWS Well Architected Review

    Round-the-clock for uninterrupted efficiency

    icon

    Optimize

    Efficient CloudOps mastery for seamless cloud management

    icon

    Manage

    Automated CI/CD pipeline for seamless deployments

    icon

    Migrate

    Upgrade the journey, Migrate & Modernize seamlessly

    icon

    Modernize

    Simplify compliance complexities with our dedicated services

    icon

    FinOps as a Service

    FinOps as a Service

  • SecOps
    Case Study

    How we built a scalable Odoo solution for TravelTech service provider!

    READ CASESTUDY
    icon

    VAPT

    Vulnerability Assessment and Penetration Testing

    icon

    Source Code Review

    Ensuring source code security ans safe practices to reduce risks

    icon

    Security Consultation

    On demand services for improving server security

    icon

    System Hardening

    Reduced vulnerability and proactive protection

    icon

    Managed SoC

    Monitors and maintains system security. Quick response on incidents.

    icon

    Compliance as a Service

    Regulatory compliance, reduced risk

  • Insights
    Case Study

    How we helped a Private Deemed University in India, save US $3,500/m on hosting charges!

    READ CASESTUDY
    icon

    Blog

    Explore our latest articles and insights

    icon

    Case Studies

    Read about our client success stories

    icon

    Flipbook

    Explore our latest Flipbook

    icon

    Events

    Join us at upcoming events and conferences

    icon

    Webinars

    Watch our educational webinar series

  • Our Story
  • Contact Us

Interested to collaborate?

Get in touch with us!

Ready to elevate your business with certified cloud expertise? Contact us today to learn how our team can help you leverage cloud technology to drive growth, streamline operations, and enhance security.

  • AWSAWS
  • Azure CloudAzure Cloud
  • Google CloudGoogle Cloud
  • Akamai CloudAkamai Cloud
  • OVHOVH
  • Digital OceanDigital Ocean
  • HetznerHetzner
  • Kubernetes Consultancy Services
  • K8s & Cloud native Solutions
  • 24/7 Infrastructure Monitoring
  • DevOps as a Service
  • Cloud CI/CD Solutions
  • White Labeled MSP Support
  • Our story
  • Life@SupportSages
  • Insights
  • Careers
  • Events
  • Contact Us

Connect with us!


LinkedInFacebookXInstagramYouTube

aws partneraws advanced partner
SupportSages

Copyright © 2008 – 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy

Analyzing AWS IAM Users: Access Key and Password Age

Arya P B

  • 4 min read
Analyzing AWS IAM Users: Access Key and Password Age

Generating audio, please wait...

Introduction

Security is a top priority in cloud computing, and managing IAM (Identity and Access Management) users effectively is crucial. In this blog post, we’ll explore a Python script designed to generate a report on AWS IAM users, detailing information about their access keys and password age. This report can be invaluable for security audits, ensuring the timely rotation of credentials and identifying potential vulnerabilities.

Prerequisites

Before we delve into the script, make sure you have the following:

  • AWS account with appropriate IAM permissions
  • Python installed on your machine
  • Boto3 library installed (pip install boto3)

The Python Script

import boto3
from datetime import datetime, timedelta, timezone
import csv
from io import StringIO
import time

def strfdelta(tdelta, fmt):
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
return fmt.format(**d)

def get_access_key_age(access_key_last_rotated):
current_time = datetime.now(timezone.utc)
age = current_time - access_key_last_rotated
return strfdelta(age, "{days} days, {hours:02}:{minutes:02}:{seconds:02}")

def calculate_password_age(password_last_changed):
try:
# Convert the timestamp string to a datetime object (offset-aware)
last_changed_time = datetime.strptime(password_last_changed, "%Y-%m-%dT%H:%M:%S%z")

# Make current_time offset-aware using UTC timezone
current_time = datetime.utcnow().replace(tzinfo=timezone.utc)

# Calculate the password age in days
age_in_days = (current_time - last_changed_time).total_seconds() / (60 * 60 * 24)

return age_in_days
except ValueError as e:
# Handle the case where the timestamp format is unexpected
print(f"Error parsing timestamp: {e}")
return None

def get_password_last_used(password_last_used):
if password_last_used:
return f"Password Last Used: {password_last_used}"
else:
return "Password Last Used: Never"

def generate_iam_report():
# Create an IAM client
iam_client = boto3.client('iam')

# Get IAM users
response = iam_client.list_users()
users = response['Users']

# Generate IAM credentials report
response = iam_client.generate_credential_report()

# Sleep and retry until the report is generated (maximum 60 seconds)
max_retries = 6
for _ in range(max_retries):
try:
# Download IAM credentials report
report_response = iam_client.get_credential_report()
break
except iam_client.exceptions.ReportInProgressException:
time.sleep(10)
else:
return {
'statusCode': 500,
'body': 'Timed out waiting for credential report to be generated.'
}

# Loop through each IAM user
for user in users:
user_name = user['UserName']

# Get IAM access keys for the user
access_keys = iam_client.list_access_keys(UserName=user_name)['AccessKeyMetadata']

# Get information about the user's password
password_last_used = user.get('PasswordLastUsed', None)

# Print information about each access key and password
for access_key in access_keys:
access_key_id = access_key['AccessKeyId']
access_key_last_rotated = access_key['CreateDate']

# Calculate access key age
access_key_age = get_access_key_age(access_key_last_rotated)

# Parse the CSV report to get the password_last_changed field
password_last_changed = None
for row in csv.reader(StringIO(report_response['Content'].decode('utf-8'))):
if row[0] == user_name:
password_last_changed = row[5] if len(row) > 5 else None # Assuming the column index for 'password_last_changed'
break

if password_last_changed and password_last_changed != 'N/A':
password_age_days = calculate_password_age(password_last_changed)
print(f"IAM User: {user_name}")
print(f"Access Key ID: {access_key_id}")
print(f"Access Key Age: {access_key_age}")
print(f"Password Age (in days): {password_age_days}")
print(get_password_last_used(password_last_used))
print("")
else:
print(f"IAM User: {user_name}")
print(f"Access Key ID: {access_key_id}")
print(f"Access Key Age: {access_key_age}")
print("Password Age: N/A (Not Available)")
print(get_password_last_used(password_last_used))
print("")

if __name__ == "__main__":

How to Use the Script

  1. Save the script as a Python file (e.g., iam_access_report.py).
  2. Open a terminal and navigate to the directory where the script is saved.
  3. Run the script:
python3 iam-age-check.py

The script will generate a detailed report on IAM users, including information about access keys and password age.


1_Ch8IENF56yiUSwo47M0zeQ.webp

Conclusion

This Python script simplifies the process of generating an IAM report, providing insights into access key age and password information. Regularly running this script can help you maintain a secure AWS environment by ensuring that access keys are rotated promptly, and password policies are adhered to.

Bolster your AWS security with automated IAM user reporting! This script generates a comprehensive report on user access keys, revealing their age and pinpointing potential vulnerabilities. By integrating this script into your security practices, you can enforce timely access key rotation and ensure password adherence to policies. Proactively manage IAM user credentials and safeguard your cloud environment.

  • AWS
  • DevOps

Continue Your Journey With…

DevOps as a Service

DevOps as a Service

Let us do the heavy lifting for you

Looking for AWS Experts?

We provide top-of-the-line custom AWS setup services tailored to your needs.

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • AWS
  • DevOps
logo

Automatically Retrieve AWS Activated Regions Using AWS Lambda and Boto3

Automatically Retrieve AWS Activated Regions Using AWS Lambda and Boto3
  • DevOps
  • AWS
logo
Analyzing AWS IAM Users: Access Key and Password Age

Posts by Arya P B

Athena