forked from matthew-harper/pyCloudTrailProcesser
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlambda.py
More file actions
Latest commit
164 lines (129 loc) · 5.11 KB
/
Copy pathlambda.py
File metadata and controls
164 lines (129 loc) · 5.11 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
155
156
157
158
159
160
161
162
163
164
importjson
importurllib.requestasurllib
importurllib.parse
importboto3
importio
importgzip
importre
importos
importrequests
fromdatetimeimportdatetime
importdateutil.tz
s3=boto3.client('s3')
sns=boto3.client('sns')
sns_arn=os.environ['SNS_TOPIC']
webhook_url=os.environ['SLACK_HOOK']
slack_channel=os.environ['SLACK_CHANNEL']
USER_AGENTS= {"console.amazonaws.com", "Coral/Jakarta", "Coral/Netty4"}
IGNORED_EVENTS= {"DownloadDBLogFilePortion", "TestScheduleExpression", "TestEventPattern", "LookupEvents",
"listDnssec", "Decrypt", "REST.GET.OBJECT_LOCK_CONFIGURATION", "ConsoleLogin"}
timezone=dateutil.tz.gettz('Asia/Jerusalem')
current_time=datetime.now(tz=timezone)
time=current_time.strftime("%I:%M %p, %m/%d/%Y")
defpost_to_sns(user, event) ->None:
message=f'Manual AWS Changed Detected: {user} --> {event}'
sns_publish(message)
defpost_to_sns_details(message) ->None:
message= {"Manual AWS Change Detected": message}
sns_publish(message)
defsns_publish(message) ->None:
sns.publish(
TargetArn=sns_arn,
Message=json.dumps({'default': json.dumps(message, indent=4, sort_keys=True, ensure_ascii=False, separators=(',', ': '))}),
MessageStructure='json'
)
###############
defpost_to_slack(user, event, time, sns) ->None:
pretext=f'<!channel>\n*Manual AWS Changed Detected*: \n `{user} --> {event}`'
text=f'Detailed output was sent as AWS Notifications email to subscribers of *"{sns}"* topic at `{time}`'
slack_publish(pretext, text)
defslack_publish(pretext, text) ->None:
message= {
"channel": slack_channel,
"pretext": pretext,
"text": text,
"mrkdwn_in": ["pretext", "text"]
}
try:
response=requests.post(webhook_url, data=json.dumps(message), headers={'Content-Type': 'application/json'})
print('Response: '+str(response.text) +"\n"+'Response code: '+str(response.status_code))
print('Message posted to channel "'+slack_channel+'"')
excepturllib.error.HTTPErrorase:
text=e.reason
status=e.code
message=f"""
Error sending message to Slack channel {slack_channel}
Reason: {text}
Status code: {status}
"""
print(message)
raisee
excepturllib.error.URLErrorase:
print('Server connection failed: '+str(e.reason))
defcheck_regex(expr, txt) ->bool:
match=re.search(expr, txt)
returnmatchisnotNone
defmatch_user_agent(txt) ->bool:
iftxtinUSER_AGENTS:
returnTrue
expressions= (
"signin.amazonaws.com(.*)",
"^S3Console",
"^\[S3Console",
"^Mozilla/",
"^console(.*)amazonaws.com(.*)",
"^aws-internal(.*)AWSLambdaConsole(.*)",
)
forexpresioninexpressions:
ifcheck_regex(expresion, txt):
returnTrue
returnFalse
defmatch_readonly_event_name(txt) ->bool:
# starts with
expressions= (
"^Get",
"^Describe",
"^List",
"^Head",
)
forexpressioninexpressions:
ifcheck_regex(expression, txt):
returnTrue
returnFalse
defmatch_ignored_events(event_name) ->bool:
returnevent_nameinIGNORED_EVENTS
deffilter_user_events(event) ->bool:
is_match=match_user_agent(event['userAgent'])
is_read_only=match_readonly_event_name(event['eventName'])
is_ignored_event=match_ignored_events(event['eventName'])
is_in_event='invokedBy'inevent['userIdentity'] andevent['userIdentity']['invokedBy'] =='AWS Internal'
status=is_matchandnotis_read_onlyandnotis_ignored_eventandnotis_in_event
returnstatus
defget_user_email(principal_id) ->str:
words=principal_id.split(':')
iflen(words) >1:
returnwords[1]
returnprincipal_id
deflambda_handler(event, context) ->None:
message=json.loads(event['Records'][0]['Sns']['Message'])
bucket=message['Records'][0]['s3']['bucket']['name']
key=message['Records'][0]['s3']['object']['key']
try:
response=s3.get_object(Bucket=bucket, Key=key)
content=response['Body'].read()
withgzip.GzipFile(fileobj=io.BytesIO(content), mode='rb') asfh:
event_json=json.load(fh)
output_dict= [recordforrecordinevent_json['Records'] iffilter_user_events(record)]
iflen(output_dict) >0:
post_to_sns_details(output_dict)
foriteminoutput_dict:
post_to_slack(item['userIdentity']['principalId'], item['eventName'], time, sns_arn)
returnresponse['ContentType']
exceptExceptionase:
print(e)
message=f"""
Error getting object {key} from bucket {bucket}.
Make sure they exist and your bucket is in the same region as this function.
"""
print(message)
raisee