This repository was archived by the owner on Dec 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathutils.py
More file actions
319 lines (266 loc) · 10.2 KB
/
utils.py
File metadata and controls
319 lines (266 loc) · 10.2 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# coding: utf-8
# vim: set ts=4 sw=4 et:
""" This file contains some utils for connecting to Logentries
as well as storing logs in a queue and sending them."""
VERSION = '2.0.7'
from logentries import helpers as le_helpers
import logging
import threading
import socket
import random
import time
import sys
import certifi
import requests
# Size of the internal event queue
QUEUE_SIZE = 32768
# Logentries API server address
LE_API_DEFAULT = "data.logentries.com"
# Port number for token logging to Logentries API server
LE_PORT_DEFAULT = 80
LE_TLS_PORT_DEFAULT = 443
# Minimal delay between attempts to reconnect in seconds
MIN_DELAY = 0.1
# Maximal delay between attempts to recconect in seconds
MAX_DELAY = 10
# Unicode Line separator character \u2028
LINE_SEP = le_helpers.to_unicode('\u2028')
# LE appender signature - used for debugging messages
LE = "LE: "
# Error message displayed when an incorrect Token has been detected
INVALID_TOKEN = ("\n\nIt appears the LOGENTRIES_TOKEN "
"parameter you entered is incorrect!\n\n")
def dbg(msg):
print(LE + msg)
class PlainTextSocketAppender(threading.Thread):
def __init__(self, verbose=True, le_api=LE_API_DEFAULT, le_port=LE_PORT_DEFAULT, le_tls_port=LE_TLS_PORT_DEFAULT):
threading.Thread.__init__(self)
# Logentries API server address
self.le_api = le_api
# Port number for token logging to Logentries API server
self.le_port = le_port
self.le_tls_port = le_tls_port
self.daemon = True
self.verbose = verbose
self._conn = None
self._queue = le_helpers.create_queue(QUEUE_SIZE)
def empty(self):
return self._queue.empty()
def open_connection(self):
self._conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._conn.connect((self.le_api, self.le_port))
def reopen_connection(self):
self.close_connection()
root_delay = MIN_DELAY
while True:
try:
self.open_connection()
return
except Exception:
if self.verbose:
dbg("Unable to connect to Logentries")
root_delay *= 2
if(root_delay > MAX_DELAY):
root_delay = MAX_DELAY
wait_for = root_delay + random.uniform(0, root_delay)
try:
time.sleep(wait_for)
except KeyboardInterrupt:
raise
def close_connection(self):
if self._conn is not None:
self._conn.close()
def run(self):
try:
# Open connection
self.reopen_connection()
# Send data in queue
while True:
# Take data from queue
data = self._queue.get(block=True)
# Replace newlines with Unicode line separator
# for multi-line events
if not le_helpers.is_unicode(data):
multiline = le_helpers.create_unicode(data).replace(
'\n', LINE_SEP)
else:
multiline = data.replace('\n', LINE_SEP)
multiline += "\n"
# Send data, reconnect if needed
while True:
try:
self._conn.send(multiline.encode('utf-8'))
except socket.error:
self.reopen_connection()
continue
break
except KeyboardInterrupt:
if self.verbose:
dbg("Logentries asynchronous socket client interrupted")
self.close_connection()
SocketAppender = PlainTextSocketAppender
try:
import ssl
ssl_enabled = True
except ImportError: # for systems without TLS support.
ssl_enabled = False
dbg("Unable to import ssl module. Will send over port 80.")
else:
class TLSSocketAppender(PlainTextSocketAppender):
def open_connection(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = ssl.wrap_socket(
sock=sock,
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,
)
sock.connect((self.le_api, self.le_tls_port))
self._conn = sock
class LogentriesHandler(logging.Handler):
def __init__(self, token, use_tls=True, verbose=True, format=None, le_api=LE_API_DEFAULT, le_port=LE_PORT_DEFAULT, le_tls_port=LE_TLS_PORT_DEFAULT):
logging.Handler.__init__(self)
self.token = token
self.good_config = True
self.verbose = verbose
# give the socket 10 seconds to flush,
# otherwise drop logs
self.timeout = 10
if not le_helpers.check_token(token):
if self.verbose:
dbg(INVALID_TOKEN)
self.good_config = False
if format is None:
format = logging.Formatter('%(asctime)s : %(levelname)s, %(message)s',
'%a %b %d %H:%M:%S %Z %Y')
self.setFormatter(format)
self.setLevel(logging.DEBUG)
if use_tls and ssl_enabled:
self._thread = TLSSocketAppender(verbose=verbose, le_api=le_api, le_port=le_port, le_tls_port=le_tls_port)
else:
self._thread = SocketAppender(verbose=verbose, le_api=le_api, le_port=le_port, le_tls_port=le_tls_port)
def flush(self):
# wait for all queued logs to be send
now = time.time()
while not self._thread.empty():
time.sleep(0.2)
if time.time() - now > self.timeout:
break
def emit(self, record):
if self.good_config and not self._thread.is_alive():
try:
self._thread.start()
if self.verbose:
dbg("Starting Logentries Asynchronous Socket Appender")
except RuntimeError: # It's already started.
pass
msg = self.format(record).rstrip('\n')
msg = self.token + msg
try:
self._thread._queue.put_nowait(msg)
except:
# Queue is full, try to remove the oldest message and put again
try:
self._thread._queue.get_nowait()
self._thread._queue.put_nowait(msg)
except:
# Race condition, no need for any action here
pass
def close(self):
logging.Handler.close(self)
LE_WH_API_DEFAULT = "http://eu.webhook.logs.insight.rapid7.com/v1/noformat/"
class LogentriesWHHandler(LogentriesHandler):
def __init__(self, token, verbose=True, format=None, le_url=LE_WH_API_DEFAULT):
logging.Handler.__init__(self)
self.token = token
self.good_config = True
self.verbose = verbose
# give the socket 10 seconds to flush,
# otherwise drop logs
self.timeout = 10
if not le_helpers.check_token(token):
if self.verbose:
dbg(INVALID_TOKEN)
self.good_config = False
if format is None:
format = logging.Formatter('%(asctime)s : %(levelname)s, %(message)s',
'%a %b %d %H:%M:%S %Z %Y')
self.setFormatter(format)
self.setLevel(logging.DEBUG)
self._thread = HTTPAppender(verbose=verbose, le_url=le_url+token, token=token)
def flush(self):
# wait for all queued logs to be send
now = time.time()
while not self._thread.empty():
time.sleep(0.2)
if time.time() - now > self.timeout:
break
def emit(self, record):
if self.good_config and not self._thread.is_alive():
try:
self._thread.start()
if self.verbose:
dbg("Starting Logentries Asynchronous HTTP Appender")
except RuntimeError: # It's already started.
pass
msg = self.format(record).rstrip('\n')
try:
self._thread._queue.put_nowait(msg)
except:
# Queue is full, try to remove the oldest message and put again
try:
self._thread._queue.get_nowait()
self._thread._queue.put_nowait(msg)
except:
# Race condition, no need for any action here
pass
def close(self):
logging.Handler.close(self)
import requests
class HTTPAppender(threading.Thread):
def __init__(self, verbose=True, le_url=LE_WH_API_DEFAULT, token=None):
threading.Thread.__init__(self)
self.daemon = True
self.verbose = verbose
self._queue = le_helpers.create_queue(QUEUE_SIZE)
self.le_url = le_url
self.token = token
def empty(self):
return self._queue.empty()
def run(self):
try:
# Send data in queue
while True:
# Take data from queue
data = self._queue.get(block=True)
# Replace newlines with Unicode line separator
# for multi-line events
if not le_helpers.is_unicode(data):
multiline = le_helpers.create_unicode(data).replace(
'\n', LINE_SEP)
else:
multiline = data.replace('\n', LINE_SEP)
multiline += "\n"
# Send data, reconnect if needed
while True:
try:
requests.post(self.le_url,data=multiline.encode('utf-8'))
except Exception:
try:
requests.post(self.le_url,data=multiline.encode('utf-8'))
except Exception as ex:
dbg("Failed to send log to logentries! {}".format(ex))
pass
break
except KeyboardInterrupt:
if self.verbose:
dbg("Logentries asynchronous HTTP client interrupted")