This repository has been archived by the owner on Dec 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
le_cloudwatch.py
80 lines (68 loc) · 2.26 KB
/
le_cloudwatch.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
import logging
import json
import gzip
import socket
import ssl
import certifi
from StringIO import StringIO
import os
from uuid import UUID
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.info('Loading function...')
REGION = os.environ.get('region')
ENDPOINT = '{}.data.logs.insight.rapid7.com'.format(REGION)
PORT = 20000
TOKEN = os.environ.get('token')
LINE = u'\u2028'.encode('utf-8')
def treat_message(message):
return message.replace('\n', LINE)
def lambda_handler(event, context):
sock = create_socket()
if not validate_uuid(TOKEN):
logger.critical('{} is not a valid token. Exiting.'.format(TOKEN))
raise SystemExit
else:
cw_data = str(event['awslogs']['data'])
cw_logs = gzip.GzipFile(fileobj=StringIO(cw_data.decode('base64', 'strict'))).read()
log_events = json.loads(cw_logs)
logger.info('Received log stream...')
for log_event in log_events['logEvents']:
# look for extracted fields, if not present, send plain message
try:
sock.sendall('{} {}\n'.format(TOKEN, json.dumps(log_event['extractedFields'])))
except KeyError:
sock.sendall('{} {}\n'.format(TOKEN, treat_message(log_event['message'])))
sock.close()
logger.info('Function execution finished.')
def create_socket():
logger.info('Creating SSL socket')
s_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = ssl.wrap_socket(
sock=s_,
keyfile=None,
certfile=None,
server_side=False,
cert_reqs=ssl.CERT_REQUIRED,
ssl_version=getattr(
ssl,
'PROTOCOL_TLSv1_2',
ssl.PROTOCOL_TLSv1
),
ca_certs=certifi.where(),
do_handshake_on_connect=True,
suppress_ragged_eofs=True,
)
try:
logger.info('Connecting to {}:{}'.format(ENDPOINT, PORT))
s.connect((ENDPOINT, PORT))
return s
except socket.error, exc:
logger.error('Exception socket.error : {}'.format(exc))
def validate_uuid(uuid_string):
try:
val = UUID(uuid_string)
except Exception as uuid_exc:
logger.error('Can not validate token: {}'.format(uuid_exc))
return False
return val.hex == uuid_string.replace('-', '')