Skip to content

Commit

Permalink
Merge pull request #53 from fkie-cad/additional-bugfixes
Browse files Browse the repository at this point in the history
Additional bugfixes
  • Loading branch information
giga-a authored Jan 29, 2024
2 parents 425e461 + 757b4b0 commit 478ae5f
Show file tree
Hide file tree
Showing 33 changed files with 368 additions and 512 deletions.
8 changes: 0 additions & 8 deletions honeypots/dhcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,9 @@
// contributors list qeeqbox/honeypots/graphs/contributors
// -------------------------------------------------------------
"""
from warnings import filterwarnings

filterwarnings(action="ignore", module=".*OpenSSL.*")
filterwarnings(action="ignore", module=".*socket.*")

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.python import log as tlog
from struct import unpack, error as StructError
from socket import inet_aton
from subprocess import Popen
Expand All @@ -27,7 +22,6 @@
kill_server_wrapper,
server_arguments,
setup_logger,
disable_logger,
set_local_vars,
check_if_server_is_running,
)
Expand Down Expand Up @@ -57,7 +51,6 @@ def __init__(self, **kwargs):
or getenv("HONEYPOTS_OPTIONS", "")
or ""
)
disable_logger(1, tlog)

def dhcp_server_main(self):
_q_s = self
Expand Down Expand Up @@ -146,7 +139,6 @@ def datagramReceived(self, data, addr):
"data": data,
}
)
self.transport.loseConnection()

reactor.listenUDP(
port=self.port, protocol=CustomDatagramProtocolProtocol(), interface=self.ip
Expand Down
58 changes: 30 additions & 28 deletions honeypots/dns_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,11 @@
// -------------------------------------------------------------
"""

from warnings import filterwarnings

filterwarnings(action="ignore", module=".*OpenSSL.*")
from __future__ import annotations

from twisted.names import dns, error, client
from twisted.names.server import DNSServerFactory
from twisted.internet import defer, reactor
from twisted.python import log as tlog
from subprocess import Popen
from os import path, getenv
from honeypots.helper import (
Expand All @@ -26,7 +23,6 @@
kill_server_wrapper,
server_arguments,
setup_logger,
disable_logger,
set_local_vars,
check_if_server_is_running,
)
Expand Down Expand Up @@ -58,12 +54,11 @@ def __init__(self, **kwargs):
or getenv("HONEYPOTS_OPTIONS", "")
or ""
)
disable_logger(1, tlog)

def dns_server_main(self):
_q_s = self

class CustomCilentResolver(client.Resolver):
class CustomClientResolver(client.Resolver):
def queryUDP(self, queries, timeout=2):
res = client.Resolver.queryUDP(self, queries, timeout)

Expand All @@ -75,36 +70,43 @@ def queryFailed(reason):

class CustomDNSServerFactory(DNSServerFactory):
def gotResolverResponse(self, response, protocol, message, address):
args = (self, response, protocol, message, address)
if address is None:
src_ip, src_port = "None", "None"
else:
src_ip, src_port = address
for items in response:
for item in items:
_q_s.logs.info(
{
"server": "dns_server",
"action": "query",
"src_ip": src_ip,
"src_port": src_port,
"dest_ip": _q_s.ip,
"dest_port": _q_s.port,
"data": item.payload,
}
)
return super().gotResolverResponse(response, protocol, message, address)

class CustomDnsUdpProtocol(dns.DNSDatagramProtocol):
def datagramReceived(self, data: bytes, addr: tuple[str, int]):
_q_s.logs.info(
{
"server": "dns_server",
"action": "connection",
"src_ip": address[0],
"src_port": address[1],
"src_ip": addr[0],
"src_port": addr[1],
"dest_ip": _q_s.ip,
"dest_port": _q_s.port,
"data": data.decode(errors="replace"),
}
)
with suppress(Exception):
for items in response:
for item in items:
_q_s.logs.info(
{
"server": "dns_server",
"action": "query",
"src_ip": address[0],
"src_port": address[1],
"dest_ip": _q_s.ip,
"dest_port": _q_s.port,
"data": item.payload,
}
)
return DNSServerFactory.gotResolverResponse(*args)

self.resolver = CustomCilentResolver(servers=self.resolver_addresses)
super().datagramReceived(data, addr)

self.resolver = CustomClientResolver(servers=self.resolver_addresses)
self.factory = CustomDNSServerFactory(clients=[self.resolver])
self.protocol = dns.DNSDatagramProtocol(controller=self.factory)
self.protocol = CustomDnsUdpProtocol(controller=self.factory)
reactor.listenUDP(self.port, self.protocol, interface=self.ip)
reactor.listenTCP(self.port, self.factory, interface=self.ip)
reactor.run()
Expand Down
8 changes: 0 additions & 8 deletions honeypots/elastic_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,7 @@
// -------------------------------------------------------------
"""

from warnings import filterwarnings

filterwarnings(action="ignore", module=".*OpenSSL.*")
filterwarnings(action="ignore", module=".*elasticsearch.*")

from base64 import b64encode, b64decode
from requests.packages.urllib3 import disable_warnings
from json import dumps
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
Expand All @@ -38,8 +32,6 @@
)
from contextlib import suppress

disable_warnings()


class QElasticServer:
def __init__(self, **kwargs):
Expand Down
9 changes: 1 addition & 8 deletions honeypots/ftp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@
// -------------------------------------------------------------
"""

from warnings import filterwarnings

filterwarnings(action="ignore", module=".*OpenSSL.*")

from twisted.protocols.ftp import (
FTPAnonymousShell,
FTPFactory,
Expand All @@ -26,11 +22,10 @@
from twisted.internet import reactor, defer
from twisted.cred.portal import Portal
from twisted.cred import portal, credentials
from twisted.cred.error import UnauthorizedLogin, UnauthorizedLogin, UnhandledCredentials
from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials
from twisted.cred.checkers import ICredentialsChecker
from zope.interface import implementer
from twisted.python import filepath
from twisted.python import log as tlog
from random import choice
from subprocess import Popen
from os import path, getenv
Expand All @@ -40,7 +35,6 @@
kill_server_wrapper,
server_arguments,
setup_logger,
disable_logger,
set_local_vars,
check_if_server_is_running,
)
Expand Down Expand Up @@ -89,7 +83,6 @@ def __init__(self, **kwargs):
or ""
)
self.temp_folder = TemporaryDirectory()
disable_logger(1, tlog)

def ftp_server_main(self):
_q_s = self
Expand Down
33 changes: 14 additions & 19 deletions honeypots/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,26 @@
// -------------------------------------------------------------
"""
import logging
import os
import sys
from argparse import ArgumentParser
from collections.abc import Mapping
from contextlib import suppress
from datetime import datetime
from json import JSONEncoder, dumps, load
from logging import Handler, Formatter, DEBUG, getLogger
from json import dumps, JSONEncoder, load
from logging import DEBUG, Formatter, getLogger, Handler
from logging.handlers import RotatingFileHandler, SysLogHandler
from os import makedirs, path, scandir, devnull, getuid
from os import getuid, makedirs, path, scandir
from pathlib import Path
from signal import SIGTERM
from socket import socket, AF_INET, SOCK_STREAM
from socket import AF_INET, SOCK_STREAM, socket
from sqlite3 import connect as sqlite3_connect
from sys import stdout
from tempfile import _get_candidate_names, gettempdir
from time import sleep
from urllib.parse import urlparse

from psutil import process_iter
from psycopg2 import connect as psycopg2_connect
from psycopg2 import sql

if not os.getenv("DEBUG"):
old_stderr = sys.stderr
sys.stderr = open(devnull, "w") # noqa: PTH123,SIM115
from psycopg2 import connect as psycopg2_connect, sql


def is_privileged():
Expand All @@ -49,13 +43,14 @@ def is_privileged():


def set_up_error_logging():
_logger = logging.getLogger("simple_example")
_logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
formatter = logging.Formatter("[%(levelname)s] %(message)s")
handler.setFormatter(formatter)
_logger.addHandler(handler)
_logger = logging.getLogger("honeypots.error")
if not _logger.handlers:
_logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
formatter = logging.Formatter("[%(levelname)s] %(message)s")
handler.setFormatter(formatter)
_logger.addHandler(handler)
return _logger


Expand All @@ -64,7 +59,7 @@ def set_local_vars(self, config):
if config:
with open(config) as f:
config_data = load(f)
honeypots = config_data["honeypots"]
honeypots = config_data.get("honeypots", [])
honeypot = self.__class__.__name__[1:-6].lower()
if honeypot and honeypot in honeypots:
for attr, value in honeypots[honeypot].items():
Expand Down
6 changes: 0 additions & 6 deletions honeypots/http_proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,10 @@
// -------------------------------------------------------------
"""
from pathlib import Path
from warnings import filterwarnings

filterwarnings(action="ignore", module=".*OpenSSL.*")

from dns.resolver import query as dsnquery
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, Factory
from twisted.python import log as tlog
from subprocess import Popen
from email.parser import BytesParser
from os import path, getenv
Expand All @@ -27,7 +23,6 @@
kill_server_wrapper,
server_arguments,
setup_logger,
disable_logger,
set_local_vars,
check_if_server_is_running,
)
Expand Down Expand Up @@ -61,7 +56,6 @@ def __init__(self, **kwargs):
or getenv("HONEYPOTS_OPTIONS", "")
or ""
)
disable_logger(1, tlog)

def http_proxy_server_main(self):
_q_s = self
Expand Down
35 changes: 15 additions & 20 deletions honeypots/http_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,27 @@
// -------------------------------------------------------------
"""

from warnings import filterwarnings

filterwarnings(action="ignore", module=".*OpenSSL.*")

from cgi import FieldStorage
from requests.packages.urllib3 import disable_warnings
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.python import log as tlog
from contextlib import suppress
from os import getenv, path
from random import choice
from tempfile import gettempdir, _get_candidate_names
from subprocess import Popen
from os import path, getenv
from tempfile import _get_candidate_names, gettempdir
from uuid import uuid4

from twisted.internet import reactor
from twisted.web.resource import Resource
from twisted.web.server import Site

from honeypots.helper import (
check_if_server_is_running,
close_port_wrapper,
get_free_port,
kill_server_wrapper,
server_arguments,
setup_logger,
disable_logger,
set_local_vars,
check_if_server_is_running,
setup_logger,
)
from uuid import uuid4
from contextlib import suppress

disable_warnings()


class QHTTPServer:
Expand Down Expand Up @@ -94,7 +87,6 @@ def __init__(self, **kwargs):
or getenv("HONEYPOTS_OPTIONS", "")
or ""
)
disable_logger(1, tlog)

def http_server_main(self):
_q_s = self
Expand Down Expand Up @@ -253,7 +245,10 @@ def check_bytes(string):
headers=self.headers,
environ={
"REQUEST_METHOD": "POST",
"CONTENT_TYPE": self.headers[b"content-type"],
"CONTENT_TYPE": self.headers.get(
b"content-type",
b"application/x-www-form-urlencoded",
),
},
)
if "username" in form and "password" in form:
Expand Down
Loading

0 comments on commit 478ae5f

Please sign in to comment.