-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaws_check_keys.py
More file actions
154 lines (131 loc) · 4.89 KB
/
Copy pathaws_check_keys.py
File metadata and controls
154 lines (131 loc) · 4.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#!/usr/bin/python3
#description: check AWS keys and send an email if they are over the specifed limit days old.
#limitations: only works on Linux or BSD
#filename: aws_check_keys.py
#author: Theodore Knab
import re
import subprocess
import datetime
import boto3
import socket
limit=90 #90 day limit
emaildomain="example.net"
sent_from=(f"someone@{emaildomain}") #from _ddress
sent_to=(f"zeekus@{emaildomain}") #to _address
systemn=(socket.gethostname()) #system name
def get_aws_key():
# get: aws iam list-access-keys
process = subprocess.Popen(["aws","iam","list-access-keys"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = process.communicate()
stdout = stdout.decode('utf-8')
if stderr is None:
output=(stdout)
else:
stderr = stderr.decode('utf-8')
output=(stderr)
return output #return converted text
def find_how_many_days_past(limit,time_string):
parsed_time=re.sub("\+.*","" ,time_string)
date_time = datetime.datetime.strptime(parsed_time, "%Y-%m-%dT%H:%M:%S")
a_timedelta = datetime.datetime.now() - date_time
if datetime.timedelta(days=limit)< a_timedelta:
expired=a_timedelta-datetime.timedelta(days=limit)
print(f"aws key is old with an age of {a_timedelta}")
print(f"key is {expired} overdue")
return expired
else:
print("ok")
return "ok"
def return_strings_cleanedup(regex_array,string_data):
name=""
myid=""
status=""
mydate=""
for dataline in string_data.splitlines():
for reline in regex_array:
my_regex = re.escape(reline)
p = re.compile(my_regex)
if re.search(my_regex, dataline, re.IGNORECASE):
if reline=="UserName":
name=re.sub("[\"|,]", "", dataline.split(': ')[1])
elif reline=="AccessKeyId":
myid=re.sub("[\"|,]", "", dataline.split(': ')[1])
elif reline=="Status":
status=re.sub("[\"|,]", "", dataline.split(': ')[1])
elif reline=="CreateDate":
mydate=re.sub("[\"|,]", "", dataline.split(': ')[1])
else:
tmp=""
return name,myid,status,mydate
def send_email_with_bobo(sent_from,sent_to,subject,body):
# Replace sender@example.com with your "From" address.
# This address must be verified with Amazon SES.
#SENDER = "Sender Name <sender@example.com>"
SENDER = ("Generic System <%s>" % sent_from)
# Replace recipient@example.com with a "To" address. If your account
# is still in the sandbox, this address must be verified.
#RECIPIENT = "recipient@example.com"
RECIPIENT = sent_to
# If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
AWS_REGION = "us-east-1"
# The subject line for the email.
SUBJECT = subject
BODY_TEXT=body
# The character encoding for the email.
CHARSET = "UTF-8"
# Create a new SES resource and specify a region.
client = boto3.client('ses',region_name=AWS_REGION)
# Try to send the email.
try:
#Provide the contents of the email.
response = client.send_email(
Destination={
'ToAddresses': [
RECIPIENT,
],
},
Message={
'Body': {
'Text': {
'Charset': CHARSET,
'Data': BODY_TEXT,
},
},
'Subject': {
'Charset': CHARSET,
'Data': SUBJECT,
},
},
Source=SENDER,
# If you are not using a configuration set, comment or delete the
# following line
#ConfigurationSetName=CONFIGURATION_SET,
)
# Display an error if something goes wrong.
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message ID:"),
print(response['MessageId'])
def send_email_with_mutt(sent_from, sent_to, subject, body):
# Construct the email message
message = f"Subject: {subject}\n\n{body}"
# Use mutt to send the email
try:
subprocess.run(['mutt', '-s', subject, '-e', f'my_hdr From: {sent_from}', '--', sent_to], input=message.encode(), check=True)
print("Email sent successfully!")
except subprocess.CalledProcessError as e:
print(f"An error occurred: {e}")
output=get_aws_key()
name,myid,status,mydate=return_strings_cleanedup(["UserName","AccessKeyId","Status","CreateDate"],output)
print(f"UserName: {name}")
print(f"AccessKeyId: {myid}")
print(f"Status: {status}")
print(f"CreateDate: {mydate}")
result=find_how_many_days_past(limit,time_string=mydate)
if result=="ok":
print("ok, don't need to do anything")
ok=1
else:
print("send an email")
send_email_with_mutt(sent_from,sent_to,subject=(f"Warning: {systemn} old aws key: {result} over limit"),body=(f"Your aws key on {systemn} may be {result} over the {limit} day policy limit."))