Skip to content

Commit 7d17b37

Browse files
authored
Add files via upload
1 parent 24d30e3 commit 7d17b37

File tree

2 files changed

+131
-3
lines changed

2 files changed

+131
-3
lines changed

honeypots/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
clean_all,
88
get_free_port,
99
kill_servers,
10+
PostgresClass,
1011
server_arguments,
1112
set_local_vars,
1213
setup_logger,
@@ -74,6 +75,7 @@
7475
"clean_all",
7576
"get_free_port",
7677
"kill_servers",
78+
"PostgresClass",
7779
"server_arguments",
7880
"set_local_vars",
7981
"setup_logger",

honeypots/helper.py

Lines changed: 129 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
import psutil
2626
from OpenSSL import crypto
2727
from psutil import process_iter
28-
28+
from psycopg import connect as psycopg_connect, sql
2929

3030
def set_up_error_logging():
3131
_logger = logging.getLogger("honeypots.error")
@@ -139,7 +139,7 @@ def setup_logger(name: str, temp_name: str, config: str | None, drop: bool = Fal
139139

140140
ret_logs_obj = getLogger(temp_name)
141141
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:
143143
ret_logs_obj.addHandler(CustomHandler(temp_name, logs, custom_filter, config_data, drop))
144144
elif "terminal" in logs:
145145
ret_logs_obj.addHandler(CustomHandler(temp_name, logs, custom_filter))
@@ -248,6 +248,17 @@ def __init__( # noqa: PLR0913
248248
self.logs = logs
249249
self.uuid = uuid
250250
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+
)
251262
if config and "db_sqlite" in self.logs:
252263
self.db["db_sqlite"] = SqliteClass(
253264
file=config["sqlite_file"], drop=drop, uuid=self.uuid
@@ -256,7 +267,7 @@ def __init__( # noqa: PLR0913
256267

257268
def emit(self, record: LogRecord): # noqa: C901,PLR0912
258269
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"]:
260271
if isinstance(record.msg, list):
261272
if record.msg[0] in {"sniffer", "errors"}:
262273
self.db["db_postgres"].insert_into_data_safe(
@@ -291,6 +302,121 @@ def emit(self, record: LogRecord): # noqa: C901,PLR0912
291302
stdout.write(f"{json.dumps(log_entry, sort_keys=True, cls=ComplexEncoder)}\n")
292303
stdout.flush()
293304

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+
294420

295421
class SqliteClass:
296422
def __init__(self, file=None, drop=False, uuid=None):

0 commit comments

Comments
 (0)