Saturday, 13 November 2021

Lock the user AWS access keys if the access key is inactive for certain days

 About the problem: 


 I got a specific requirement from my client compliance team that they want to disable the AWS access keys automatically if the user key is inactive for certain days . By default AWS IAM didn't provide that option so we have to find another way to meet that compliance .

Solution :


AWS "AccessKeyLastUsed" api helps to check the users last time used the access key. By using that I have build the below script which will disable the user if its disable for 90 days .


Lambda Script:

import json

import boto3

import os

from datetime import datetime, timedelta


def lambda_handler(event, context):

    #Variable declaration section

    iamClient = boto3.client('iam')

    UserMetaDataList = []

    DictionaryOfFate = {}


############################################# Conditional User Keys Activate/Inactivate #########################################


    # To list and append user meta data

    response = iamClient.list_users(MaxItems=150)

    UserMetaDataList.extend(response['Users'])

    while response['IsTruncated'] :

        response = iamClient.list_users(MaxItems=150, Marker = response['Marker'])

        UserMetaDataList.extend(response['Users'])


   

    # Collecting the usernames and creation dates

    for userMeta in UserMetaDataList :

        DictionaryOfFate[userMeta['UserName']] = userMeta['CreateDate'].date()


   

    #DictionaryOfFate = {'testUser':2010}


    # User Modification


    for UserNameAskey in DictionaryOfFate.keys() :

        AccessKeyList = []

        lastActivityDateList = []

        LastActivity = None


        # Collect Access keys

        response = iamClient.list_access_keys(UserName=UserNameAskey,MaxItems=150)

        AccessKeyList.extend(response['AccessKeyMetadata'])

        while response['IsTruncated'] :

            response = iamClient.list_access_keys(UserName=UserNameAskey,MaxItems=150,Marker = response['Marker'])

            AccessKeyList.extend(response['AccessKeyMetadata'])

        #print(AccessKeyList)

   

        # Finding Last Activity Date

        if(len(AccessKeyList)!=0) :

            flagForUnusedUser = 0           # this flag is for user having access keys but never logged in

            for accessKey in AccessKeyList :

                try :

                    response = iamClient.get_access_key_last_used(AccessKeyId=accessKey['AccessKeyId'])

                    LastActivity = response['AccessKeyLastUsed']['LastUsedDate'].date()

                    if(LastActivity != datetime.now().date()) :

                        LastActivity = str(datetime.now().date() - LastActivity)

                        temp = LastActivity.find('day')

                        LastActivity = int(LastActivity[:(temp-1)])

                        # If the User remains inactive for more than 90 days, then initiate deletion

                        if( LastActivity > 90 ) :

                            print("Defaulter : " + UserNameAskey)

                            print("\n")

                            # Access keys

                            if(accessKey['Status']=='Active'):

                                response = iamClient.update_access_key(UserName=UserNameAskey,AccessKeyId=accessKey['AccessKeyId'],Status='Inactive')

                        # print(LastActivity)

                    else :

                        #print("Recently accessed : " + UserNameAskey + "\n")

                        LastActivity = 0


                except Exception as e :

                    #print("Access not Found")

                    continue

                

        else:

            pass


No comments:

Post a Comment