25
25
import psutil
26
26
from OpenSSL import crypto
27
27
from psutil import process_iter
28
-
28
+ from psycopg import connect as psycopg_connect , sql
29
29
30
30
def set_up_error_logging ():
31
31
_logger = logging .getLogger ("honeypots.error" )
@@ -139,7 +139,7 @@ def setup_logger(name: str, temp_name: str, config: str | None, drop: bool = Fal
139
139
140
140
ret_logs_obj = getLogger (temp_name )
141
141
ret_logs_obj .setLevel (DEBUG )
142
- if "db_postgres_removed " in logs or "db_sqlite" in logs :
142
+ if "db_postgres " in logs or "db_sqlite" in logs :
143
143
ret_logs_obj .addHandler (CustomHandler (temp_name , logs , custom_filter , config_data , drop ))
144
144
elif "terminal" in logs :
145
145
ret_logs_obj .addHandler (CustomHandler (temp_name , logs , custom_filter ))
@@ -248,6 +248,17 @@ def __init__( # noqa: PLR0913
248
248
self .logs = logs
249
249
self .uuid = uuid
250
250
self .custom_filter = custom_filter
251
+ if config and "db_postgres" in self .logs :
252
+ self .db ["db_postgres" ] = PostgresClass (
253
+ path = "postgresql://{}:{}@{}:{}" .format (config ["postgres" ]["username" ],config ["postgres" ]["password" ],config ["postgres" ]["hostname" ],config ["postgres" ]["port" ]),
254
+ host = config ["postgres" ]["hostname" ],
255
+ port = config ["postgres" ]["port" ],
256
+ username = config ["postgres" ]["username" ],
257
+ password = config ["postgres" ]["password" ],
258
+ db = config ["postgres" ]["db" ],
259
+ uuid = self .uuid ,
260
+ drop = drop ,
261
+ )
251
262
if config and "db_sqlite" in self .logs :
252
263
self .db ["db_sqlite" ] = SqliteClass (
253
264
file = config ["sqlite_file" ], drop = drop , uuid = self .uuid
@@ -256,7 +267,7 @@ def __init__( # noqa: PLR0913
256
267
257
268
def emit (self , record : LogRecord ): # noqa: C901,PLR0912
258
269
try :
259
- if "db_postgres_removed " in self .logs and self .db ["db_postgres" ]:
270
+ if "db_postgres " in self .logs and self .db ["db_postgres" ]:
260
271
if isinstance (record .msg , list ):
261
272
if record .msg [0 ] in {"sniffer" , "errors" }:
262
273
self .db ["db_postgres" ].insert_into_data_safe (
@@ -291,6 +302,121 @@ def emit(self, record: LogRecord): # noqa: C901,PLR0912
291
302
stdout .write (f"{ json .dumps (log_entry , sort_keys = True , cls = ComplexEncoder )} \n " )
292
303
stdout .flush ()
293
304
305
+ class PostgresClass :
306
+ def __init__ ( # noqa: PLR0913
307
+ self ,
308
+ path = None ,
309
+ host = None ,
310
+ port = None ,
311
+ username = None ,
312
+ password = None ,
313
+ db = None ,
314
+ drop = False ,
315
+ uuid = None ,
316
+ ):
317
+ self .path = path
318
+ self .host = host
319
+ self .port = port
320
+ self .username = username
321
+ self .password = password
322
+ self .db = db
323
+ self .uuid = uuid
324
+ self .mapped_tables = ["errors" , "servers" , "sniffer" , "system" ]
325
+ self .wait_until_up ()
326
+ if drop :
327
+ self .con = psycopg_connect (
328
+ conninfo = self .path ,
329
+ autocommit = True
330
+ )
331
+ self .cur = self .con .cursor ()
332
+ self .drop_db ()
333
+ self .drop_tables ()
334
+ self .create_db ()
335
+ self .con .close ()
336
+ else :
337
+ self .con = psycopg_connect (
338
+ conninfo = self .path ,
339
+ autocommit = True
340
+ )
341
+ self .cur = self .con .cursor ()
342
+ if not self .check_db_if_exists ():
343
+ self .create_db ()
344
+ self .con .close ()
345
+ self .con = psycopg_connect (
346
+ conninfo = self .path + "/" + self .db ,
347
+ autocommit = True
348
+ )
349
+ self .cur = self .con .cursor ()
350
+ self .create_tables ()
351
+
352
+ def wait_until_up (self ):
353
+ test = True
354
+ while test :
355
+ with suppress ():
356
+ logger .info (f"{ self .uuid } - Waiting on postgres connection" )
357
+ stdout .flush ()
358
+ conn = psycopg_connect (
359
+ conninfo = self .path + "?connect_timeout=1"
360
+ )
361
+ conn .close ()
362
+ test = False
363
+ sleep (1 )
364
+ logger .info (f"{ self .uuid } - postgres connection is good" )
365
+
366
+ def addattr (self , x , val ):
367
+ self .__dict__ [x ] = val
368
+
369
+ def check_db_if_exists (self ):
370
+ exists = False
371
+ with suppress (Exception ):
372
+ self .cur .execute (
373
+ "SELECT exists(SELECT 1 from pg_catalog.pg_database where datname = %s)" ,
374
+ (self .db ,),
375
+ )
376
+ if self .cur .fetchone ()[0 ]:
377
+ exists = True
378
+ return exists
379
+
380
+ def drop_db (self ):
381
+ with suppress (Exception ):
382
+ logger .warning (f"Dropping { self .db } db" )
383
+ if self .check_db_if_exists ():
384
+ self .cur .execute (
385
+ sql .SQL ("drop DATABASE IF EXISTS {}" ).format (sql .Identifier (self .db ))
386
+ )
387
+ sleep (2 )
388
+ self .cur .execute (sql .SQL ("CREATE DATABASE {}" ).format (sql .Identifier (self .db )))
389
+
390
+ def create_db (self ):
391
+ logger .info ("Creating PostgreSQL database" )
392
+ self .cur .execute (sql .SQL ("CREATE DATABASE {}" ).format (sql .Identifier (self .db )))
393
+
394
+ def drop_tables (
395
+ self ,
396
+ ):
397
+ for x in self .mapped_tables :
398
+ self .cur .execute (
399
+ sql .SQL ("drop TABLE IF EXISTS {}" ).format (sql .Identifier (x + "_table" ))
400
+ )
401
+
402
+ def create_tables (self ):
403
+ for table in self .mapped_tables :
404
+ self .cur .execute (
405
+ sql .SQL (
406
+ "CREATE TABLE IF NOT EXISTS {} "
407
+ "(id SERIAL NOT NULL,date timestamp with time zone DEFAULT now(),data json)"
408
+ ).format (sql .Identifier (table + "_table" ))
409
+ )
410
+
411
+ def insert_into_data_safe (self , table , obj ):
412
+ with suppress (Exception ):
413
+ self .cur .execute (
414
+ sql .SQL ("INSERT INTO {} (id,date, data) VALUES (DEFAULT ,now(), %s)" ).format (
415
+ sql .Identifier (table + "_table" )
416
+ ),
417
+ [obj ],
418
+ )
419
+
294
420
295
421
class SqliteClass :
296
422
def __init__ (self , file = None , drop = False , uuid = None ):
0 commit comments