-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathday12.py
163 lines (152 loc) · 4.8 KB
/
day12.py
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
import json
import base64
import zlib
import socket
import urllib3
from time import sleep
# Pool Manager for urllib3 to (re)use
http = urllib3.PoolManager()
def lambda_handler(event, context):
# parse CWL event
log_parser(event.get('awslogs', {}).get('data'))
def log_parser(data):
# Empty list to contain finished payloads
payloads = []
# Base64 Decode, decompress with ZLIB, load into a dict with json.loads
records = json.loads(zlib.decompress(base64.b64decode(data), 16 + zlib.MAX_WBITS))
# Loop through the query log message
for ql in records['logEvents']:
# parse the nested "message" object and load this into JSON as well
message = json.loads(ql['message'])
try:
# If a log is not flagged by a firewall, it will not have the associated keys, any KeyError can be ignored
message['firewall_rule_action']
# Send the pertinent messages to be enriched & write final result to list
payloads.append(
log_enrichment_and_normalization(
message
)
)
except KeyError:
continue
payload_processor(payloads)
def log_enrichment_and_normalization(message):
# Parse out the query name
queryName = message['query_name']
# Try to find out the IP Address...
try:
ip = socket.gethostbyname(queryName)
except Exception as e:
print(e)
ip = None
if ip != None:
geoint = geo_intelligence(ip)
countryCode = geoint['CountryCode']
latitude = int(geoint['Latitude'])
longitude = int(geoint['Longitude'])
isp = geoint['Isp']
org = geoint['Org']
asn = geoint['Asn']
asnName = geoint['AsnName']
else:
countryCode = None
latitude = int(0)
longitude = int(0)
isp = None
org = None
asn = None
asnName = None
# Source ID may not be an instance in the future...
try:
srcId = message['srcids']['instance']
except KeyError:
srcId = None
payload = {
'AccountId': message['account_id'],
'Region': message['region'],
'VpcId': message['vpc_id'],
'QueryTimestamp': message['query_timestamp'],
'QueryName': queryName,
'QueryIpAddress': ip,
'QueryType': message['query_type'],
'QueryClass': message['query_class'],
'Rcode': message['rcode'],
'Answers': str(message['answers']),
'SrcAddr': message['srcaddr'],
'SrcPort': message['srcport'],
'Transport': message['transport'],
'SrcId': srcId,
'FirewallRuleAction': message['firewall_rule_action'],
'FirewallRuleGroupId': message['firewall_rule_group_id'],
'FirewallDomainListId': message['firewall_domain_list_id'],
'CountryCode': countryCode,
'Latitude': latitude,
'Longitude': longitude,
'Isp': isp,
'Org': org,
'Asn': asn,
'Latitude': latitude,
'AsnName': asnName
}
return payload
def geo_intelligence(ip):
# Generate request url for use
url = f'http://ip-api.com/json/{ip}?fields=status,message,countryCode,lat,lon,isp,org,as,asname'
# GET request
r = http.request(
'GET',
url
)
ttlHeader = int(r.headers['X-Ttl'])
requestsLeftHeader = int(r.headers['X-Rl'])
# handle throttling
if requestsLeftHeader == 0:
ttlHeader = int(r.headers['X-Ttl'])
waitTime = ttlHeader + 1
sleep(waitTime)
print('Request limit breached - retrying')
del r
# new request
r = http.request(
'GET',
url
)
ipJson = json.loads(r.data.decode('utf-8'))
countryCode = str(ipJson['countryCode'])
latitude = float(ipJson['lat'])
longitude = float(ipJson['lon'])
isp = str(ipJson['isp'])
org = str(ipJson['org'])
asn = str(ipJson['as'])
asnName = str(ipJson['asname'])
# If not fail
else:
ipJson = json.loads(r.data.decode('utf-8'))
countryCode = str(ipJson['countryCode'])
latitude = float(ipJson['lat'])
longitude = float(ipJson['lon'])
isp = str(ipJson['isp'])
org = str(ipJson['org'])
asn = str(ipJson['as'])
asnName = str(ipJson['asname'])
geoint = {
'CountryCode': countryCode,
'Latitude': latitude,
'Longitude': longitude,
'Isp': isp,
'Org': org,
'Asn': asn,
'Latitude': latitude,
'AsnName': asnName
}
return geoint
def payload_processor(payloads):
# Receive and send chunks of payloads to SQS
for payload in payloads:
print(
json.dumps(
payload,
indent=2,
default=str
)
)