简体   繁体   English

获取访问密钥年龄 AWS Boto3

[英]Getting access key age AWS Boto3

I am trying to figure out a way to get a users access key age through an aws lambda function using Python 3.6 and Boto 3. My issue is that I can't seem to find the right api call to use if any exists for this purpose.我正在尝试找出一种使用 Python 3.6 和 Boto 3 通过 aws lambda 函数让用户访问密钥年龄的方法。我的问题是我似乎无法找到合适的 api 调用来使用(如果有的话) . The two closest that I can seem to find are list_access_keys which I can use to find the creation date of the key.我能找到的最接近的两个是list_access_keys ,我可以用它来查找密钥的创建日期。 And get_access_key_last_used which can give me the day the key was last used. get_access_key_last_used可以告诉我上次使用密钥的日期。 However neither or others I can seem to find give simply the access key age like is shown in the AWS IAM console users view.但是,我似乎找不到的其他人都没有像 AWS IAM 控制台用户视图中显示的那样简单地提供访问密钥年龄。 Does a way exist to get simply the Access key age?是否存在简单获取访问密钥年龄的方法?

This simple code do the same stuff without converting a lot of time etc:这个简单的代码做同样的事情而不需要转换很多时间等:

import boto3
from datetime import date

client = boto3.client('iam')
username = "<YOUR-USERNAME>"
res = client.list_access_keys(UserName=username)
accesskeydate = res['AccessKeyMetadata'][0]['CreateDate'].date()
currentdate = date.today()
active_days = currentdate - accesskeydate
print (active_days.days)

There is no direct way.没有直接的方法。 You can use the following code snippet to achieve what you are trying:您可以使用以下代码片段来实现您正在尝试的目标:

import boto3, json, time, datetime, sys

client = boto3.client('iam')
username = "<YOUR-USERNAME>"
res = client.list_access_keys(UserName=username)
accesskeydate = res['AccessKeyMetadata'][0]['CreateDate'] ### Use for loop if you are going to run this on production. I just wrote it real quick
accesskeydate = accesskeydate.strftime("%Y-%m-%d %H:%M:%S")
currentdate = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

accesskeyd = time.mktime(datetime.datetime.strptime(accesskeydate, "%Y-%m-%d %H:%M:%S").timetuple())
currentd = time.mktime(datetime.datetime.strptime(currentdate, "%Y-%m-%d %H:%M:%S").timetuple())

active_days = (currentd - accesskeyd)/60/60/24 ### We get the data in seconds. converting it to days
print (int(round(active_days)))

Let me know if this works as expected.让我知道这是否按预期工作。

Upon further testing, I've come up with the following which runs in Lambda.经过进一步测试,我想出了以下在 Lambda 中运行的内容。 This function in python3.6 will email users if their IAM keys are 90 days or older.如果用户的 IAM 密钥超过 90 天或更早,python3.6 中的此函数将向用户发送电子邮件。

Pre-requisites先决条件

all IAM users have an email tag with a proper email address as the value.所有 IAM 用户都有一个电子邮件标签,其中包含正确的电子邮件地址作为值。

Example;例子;

  • IAM user tag key: email IAM 用户标签键:电子邮件
  • IAM user tag value: someone@gmail.com IAM 用户标签值: someone@gmail.com

every email used, needs to be confirmed in SES使用的每个电子邮件都需要在 SES 中确认

    import boto3, os, time, datetime, sys, json
    from datetime import date
    from botocore.exceptions import ClientError

    iam = boto3.client('iam')
    email_list = []
    def lambda_handler(event, context):
        print("All IAM user emails that have AccessKeys 90 days or older")
        for userlist in iam.list_users()['Users']:
                userKeys = iam.list_access_keys(UserName=userlist['UserName'])
                for keyValue in userKeys['AccessKeyMetadata']:
                        if keyValue['Status'] == 'Active':
                                currentdate = date.today()
                                active_days = currentdate - \
                                    keyValue['CreateDate'].date()
                                if active_days >= datetime.timedelta(days=90):
                                    userTags = iam.list_user_tags(
                                        UserName=keyValue['UserName'])
                                    email_tag = list(filter(lambda tag: tag['Key'] == 'email', userTags['Tags']))
                                    if(len(email_tag) == 1):
                                        email = email_tag[0]['Value']
                                        email_list.append(email)
                                        print(email)

        email_unique = list(set(email_list))
        print(email_unique)
        RECIPIENTS = email_unique
        SENDER = "AWS SECURITY "
        AWS_REGION = os.environ['region']
        SUBJECT = "IAM Access Key Rotation"
        BODY_TEXT = ("Your IAM Access Key need to be rotated in AWS Account: 123456789 as it is 3 months or older.\r\n"
                    "Log into AWS and go to your IAM user to fix: https://console.aws.amazon.com/iam/home?#security_credential"
                    )
        BODY_HTML = """
        AWS Security: IAM Access Key Rotation: Your IAM Access Key need to be rotated in AWS Account: 123456789 as it is 3 months or older. Log into AWS and go to your https://console.aws.amazon.com/iam/home?#security_credential to create a new set of keys. Ensure to disable / remove your previous key pair.
                    """            
        CHARSET = "UTF-8"
        client = boto3.client('ses',region_name=AWS_REGION)
        try:
            response = client.send_email(
                Destination={
                    'ToAddresses': RECIPIENTS,
                },
                Message={
                    'Body': {
                        'Html': {
                            'Charset': CHARSET,
                            'Data': BODY_HTML,
                        },
                        'Text': {
                            'Charset': CHARSET,
                            'Data': BODY_TEXT,
                        },
                    },
                    'Subject': {
                        'Charset': CHARSET,
                        'Data': SUBJECT,
                    },
                },
                Source=SENDER,
            )
        except ClientError as e:
            print(e.response['Error']['Message'])
        else:
            print("Email sent! Message ID:"),
            print(response['MessageId'])

Using the above methods you will only get the age of the access keys.使用上述方法,您将只能获得访问密钥的年龄。 But as a best practice or a security approach, you need to check the rotation period, when the keys are last rotated.但作为最佳实践或安全方法,您需要检查轮换周期,即上次轮换密钥的时间。 If the keys rotation age is more than 90 days you could alert your team.如果密钥轮换期限超过 90 天,您可以提醒您的团队。

The only way to get the rotation age of the access keys is by using the credentials report from IAM.获取访问密钥轮换年龄的唯一方法是使用来自 IAM 的凭证报告 Download it, parse it, and calculate the age.下载它,解析它,并计算年龄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM