Exemple #1
0
    def connect(self):
        #        print(g_dionaea.config()['modules']['python']['surfids'])
        self.dbh = pg_driver.connect(
            user=g_dionaea.config()['modules']['python']['surfids']
            ['username'],
            password=g_dionaea.config()['modules']['python']['surfids']
            ['password'],
            database=g_dionaea.config()['modules']['python']['surfids']
            ['dbname'],
            host=g_dionaea.config()['modules']['python']['surfids']['host'],
            port=g_dionaea.config()['modules']['python']['surfids']['port'])

        self.stmt_sensor_type = self.dbh.prepare(
            "SELECT surfids3_type_from_name('dionaea')")
        self.sensor_type = self.stmt_sensor_type()[0][0]
        logger.debug("surfids sensor type %i" % self.sensor_type)
        self.stmt_attack_add = self.dbh.prepare(
            "SELECT surfids3_attack_add($1, $2::text::inet, $3, $4::text::inet, $5, $6, $7)"
        )
        self.stmt_detail_add = self.dbh.prepare(
            "SELECT surfids3_detail_add($1, $2::text::inet, $3, $4)")
        self.stmt_detail_add_offer = self.dbh.prepare(
            "SELECT surfids3_detail_add_offer($1::text::inet, $2::text::inet, $3, $4)"
        )
        self.stmt_detail_add_download = self.dbh.prepare(
            "SELECT surfids3_detail_add_download($1::text::inet, $2::text::inet, $3, $4, $5)"
        )
        self.stmt_attack_update_severity = self.dbh.prepare(
            "SELECT surfids3_attack_update_severity($1, $2)")
Exemple #2
0
    def __init__(self, proto='tcp'):
        logger.debug("http test")
        connection.__init__(self,proto)
        self.state = 'HEADER'
        self.rwchunksize = 64*1024
        self._out.speed.limit = 16*1024
        self.env = None
        self.boundary = None
        self.fp_tmp = None
        self.cur_length = 0
        max_request_size = 32768

        try:
            if 'max-request-size' in g_dionaea.config()['modules']['python']['http']:
                # try to convert value to int
                max_request_size = int(
                    g_dionaea.config()['modules']['python']['http']['max-request-size'])
            else:
                logger.info(
                    "Value for 'max-request-size' not found, using default value.")
        except:
            logger.warning(
                "Error while converting 'max-request-size' to an integer value. Using default value.")

        self.max_request_size = max_request_size * 1024
Exemple #3
0
    def __init__(self, path):
        logger.debug("%s ready!" % (self.__class__.__name__))
        ihandler.__init__(self, path)
        self.apikey = g_dionaea.config(
        )['modules']['python']['virustotal']['apikey']
        self.cookies = {}
        self.loop = pyev.default_loop()

        self.backlog_timer = pyev.Timer(0, 20, self.loop,
                                        self.__handle_backlog_timeout)
        self.backlog_timer.start()
        p = g_dionaea.config()['modules']['python']['virustotal']['file']
        self.dbh = sqlite3.connect(p)
        self.cursor = self.dbh.cursor()
        self.cursor.execute("""
            CREATE TABLE IF NOT EXISTS backlogfiles (
                backlogfile INTEGER PRIMARY KEY,
                status TEXT NOT NULL, -- new, submit, query, comment
                md5_hash TEXT NOT NULL,
                path TEXT NOT NULL,
                timestamp INTEGER NOT NULL,
                scan_id TEXT,
                lastcheck_time INTEGER,
                submit_time INTEGER
            );""")
Exemple #4
0
def new():
    print("START")
    global g_slave, mode, addrs
    global addrs
    if mode == 'manual':
        addrs = g_dionaea.config()['listen']['addrs']
        g_slave = slave()
    elif mode == 'getifaddrs':
        g_slave = slave()
        ifaces = g_dionaea.getifaddrs()
        addrs = {}
        for iface in ifaces.keys():
            afs = ifaces[iface]
            for af in afs.keys():
                if af == 2 or af == 10:
                    configs = afs[af]
                    for config in configs:
                        if iface not in addrs:
                            addrs[iface] = []
                        addrs[iface].append(config['addr'])
        print(addrs)
    elif mode == 'nl':
        g_slave = nlslave()
        g_slave.ifaces = g_dionaea.config()['listen']['interfaces']

    load_submodules()
Exemple #5
0
    def connect(self):
        #        print(g_dionaea.config()['modules']['python']['surfids'])
        self.dbh = pg_driver.connect(user = g_dionaea.config()['modules']['python']['surfids']['username'],
                                     password = g_dionaea.config()['modules']['python'][
            'surfids']['password'],
            database = g_dionaea.config()['modules']['python'][
            'surfids']['dbname'],
            host = g_dionaea.config()['modules']['python'][
            'surfids']['host'],
            port = g_dionaea.config()['modules']['python']['surfids']['port'])


        self.stmt_sensor_type = self.dbh.prepare(
            "SELECT surfids3_type_from_name('dionaea')")
        self.sensor_type = self.stmt_sensor_type()[0][0]
        logger.debug("surfids sensor type %i" % self.sensor_type)
        self.stmt_attack_add = self.dbh.prepare(
            "SELECT surfids3_attack_add($1, $2::text::inet, $3, $4::text::inet, $5, $6, $7)")
        self.stmt_detail_add = self.dbh.prepare(
            "SELECT surfids3_detail_add($1, $2::text::inet, $3, $4)")
        self.stmt_detail_add_offer = self.dbh.prepare(
            "SELECT surfids3_detail_add_offer($1::text::inet, $2::text::inet, $3, $4)")
        self.stmt_detail_add_download = self.dbh.prepare(
            "SELECT surfids3_detail_add_download($1::text::inet, $2::text::inet, $3, $4, $5)")
        self.stmt_attack_update_severity = self.dbh.prepare(
            "SELECT surfids3_attack_update_severity($1, $2)")
Exemple #6
0
def new():
    print("START")
    global g_slave, mode, addrs
    global addrs
    if mode == 'manual':
        addrs = g_dionaea.config()['listen']['addrs']
        g_slave = slave()
    elif mode == 'getifaddrs':
        g_slave = slave()
        ifaces = g_dionaea.getifaddrs()
        addrs = {}
        for iface in ifaces.keys():
            afs = ifaces[iface]
            for af in afs.keys():
                if af == 2 or af == 10:
                    configs = afs[af]
                    for config in configs:
                        if iface not in addrs:
                            addrs[iface] = []
                        addrs[iface].append(config['addr'])
        print(addrs)
    elif mode == 'nl':
        g_slave = nlslave()
        g_slave.ifaces = g_dionaea.config()['listen']['interfaces']

    load_submodules()
Exemple #7
0
	def __init__(self):
		logger.debug("%s ready!" % (self.__class__.__name__))
		ihandler.__init__(self, "*")
		offers = g_dionaea.config()['modules']['python']['fail2ban']['offers']
		downloads = g_dionaea.config()['modules']['python']['fail2ban']['downloads']
		self.offers = open(offers, "a")
		self.downloads = open(downloads, "a")
Exemple #8
0
    def __init__(self, path):
        logger.debug("%s ready!" % (self.__class__.__name__))
        ihandler.__init__(self, path)
        self.apikey = g_dionaea.config()['modules']['python'][
            'virustotal']['apikey']
        self.cookies = {}
        self.loop = pyev.default_loop()

        self.backlog_timer = pyev.Timer(
            0, 20, self.loop, self.__handle_backlog_timeout)
        self.backlog_timer.start()
        p = g_dionaea.config()['modules']['python']['virustotal']['file']
        self.dbh = sqlite3.connect(p)
        self.cursor = self.dbh.cursor()
        self.cursor.execute("""
            CREATE TABLE IF NOT EXISTS backlogfiles (
                backlogfile INTEGER PRIMARY KEY,
                status TEXT NOT NULL, -- new, submit, query, comment
                md5_hash TEXT NOT NULL,
                path TEXT NOT NULL,
                timestamp INTEGER NOT NULL,
                scan_id TEXT,
                lastcheck_time INTEGER,
                submit_time INTEGER
            );""")
Exemple #9
0
    def __init__(self, proto='tcp'):
        logger.debug("http test")
        connection.__init__(self, proto)
        self.state = 'HEADER'
        self.rwchunksize = 64 * 1024
        self._out.speed.limit = 16 * 1024
        self.env = None
        self.boundary = None
        self.fp_tmp = None
        self.cur_length = 0
        max_request_size = 32768

        try:
            if 'max-request-size' in g_dionaea.config(
            )['modules']['python']['http']:
                # try to convert value to int
                max_request_size = int(g_dionaea.config()['modules']['python']
                                       ['http']['max-request-size'])
            else:
                logger.info(
                    "Value for 'max-request-size' not found, using default value."
                )
        except:
            logger.warning(
                "Error while converting 'max-request-size' to an integer value. Using default value."
            )

        self.max_request_size = max_request_size * 1024
Exemple #10
0
    def __init__(self, proto='udp'):
        connection.__init__(self, proto)
        self.state = 'HEADER'
        self.rwchunksize = 64 * 1024
        self._out.speed.limit = 16 * 1024
        self.env = None
        self.boundary = None
        self.fp_tmp = None
        self.cur_length = 0
        max_request_size = 32768
        self.personalities = ''
        self.loaded = ''

        try:
            if 'max-request-size' in g_dionaea.config(
            )['modules']['python']['upnp']:
                # try to convert value to int
                max_request_size = int(g_dionaea.config()['modules']['python']
                                       ['upnp']['max-request-size'])
            else:
                logger.info(
                    "Value for 'max-request-size' not found, using default value."
                )
        except:
            logger.warning(
                "Error while converting 'max-request-size' to an integer value. Using default value."
            )

        self.max_request_size = max_request_size * 1024

        # load the UPnP device personalities from dionaea.conf file
        try:
            if 'personalities-enable' in g_dionaea.config(
            )['modules']['python']['upnp']:
                loaded = g_dionaea.config(
                )['modules']['python']['upnp']['personalities-enable']
                self.personalities = g_dionaea.config()['modules']['python'][
                    'upnp']['personalities'][loaded]['cache']
                self.personalities += g_dionaea.config(
                )['modules']['python']['upnp']['personalities'][loaded]['st']
                self.personalities += g_dionaea.config(
                )['modules']['python']['upnp']['personalities'][loaded]['usn']
                self.personalities += g_dionaea.config()['modules']['python'][
                    'upnp']['personalities'][loaded]['server']
                self.personalities += g_dionaea.config()['modules']['python'][
                    'upnp']['personalities'][loaded]['location']
                self.personalities += g_dionaea.config(
                )['modules']['python']['upnp']['personalities'][loaded]['opt']

                logger.info(
                    "loading emulated UPnP device with personalities: '" +
                    loaded + "'")
            else:
                logger.info(
                    "Value for 'personalities' not found, using default value."
                )
        except:
            logger.warning(
                "Error while retrieve 'personalities'. Using default value.")
Exemple #11
0
 def handle_established(self):
     logger.debug("FTP DATA established")
     self.timeouts.idle = 30
     self.fileobj = tempfile.NamedTemporaryFile(
         delete=False,
         prefix="ftp-",
         suffix=g_dionaea.config()["downloads"]["tmp-suffix"],
         dir=g_dionaea.config()["downloads"]["dir"])
Exemple #12
0
 def handle_established(self):
     logger.debug("FTP DATA established")
     self.timeouts.idle = 30
     self.fileobj = tempfile.NamedTemporaryFile(
         delete=False,
         prefix='ftp-',
         suffix=g_dionaea.config()['downloads']['tmp-suffix'],
         dir=g_dionaea.config()['downloads']['dir'])
Exemple #13
0
 def handle_established(self):
     logger.debug("FTP DATA established")
     self.timeouts.idle = 30
     self.fileobj = tempfile.NamedTemporaryFile(
         delete=False,
         prefix="ftp-",
         suffix=g_dionaea.config()["downloads"]["tmp-suffix"],
         dir=g_dionaea.config()["downloads"]["dir"]
     )
Exemple #14
0
 def start(cls, addr, iface=None):
     daemons = []
     for proto in ("tcp", "tls", "udp"):
         if proto not in g_dionaea.config()['modules']['python']['sip']:
             continue
         port = int(g_dionaea.config()['modules']['python']['sip'][proto].get('port', 5060))
         daemon = SipSession(proto=proto)
         daemon.bind(addr, port, iface=iface)
         daemon.listen()
         daemons.append(daemon)
     return daemons
Exemple #15
0
def new():
    global g_slave
    global g_service_configs

    logger.info("Initializing services ...")
    dionaea_config = g_dionaea.config().get("dionaea")

    mode = dionaea_config.get("listen.mode")
    interface_names = dionaea_config.get("listen.interfaces")

    if mode == 'manual':
        addrs = {}

        addresses = dionaea_config.get("listen.addresses")
        ifaces = g_dionaea.getifaddrs()
        for iface in ifaces.keys():
            afs = ifaces[iface]
            for af in afs.keys():
                if af == 2 or af == 10:
                    configs = afs[af]
                    if iface not in addrs:
                        addrs[iface] = []
                    for config in configs:
                        if config["addr"] in addresses:
                            addrs[iface].append(config['addr'])
        g_slave = slave(addresses=addrs)
    elif mode == 'getifaddrs':
        ifaces = g_dionaea.getifaddrs()
        addrs = {}
        for iface in ifaces.keys():
            if interface_names is not None and iface not in interface_names:
                logger.debug("Skipping interface %s. Not in interface list.",
                             iface)
                continue
            afs = ifaces[iface]
            for af in afs.keys():
                if af == 2 or af == 10:
                    configs = afs[af]
                    for config in configs:
                        if iface not in addrs:
                            addrs[iface] = []
                        addrs[iface].append(config['addr'])
        g_slave = slave(addresses=addrs)
    elif mode == 'nl':
        # ToDo: handle error if ifaces is None
        g_slave = nlslave(ifaces=interface_names)

    load_submodules()

    module_config = g_dionaea.config().get("module")
    filename_patterns = module_config.get("service_configs", [])
    g_service_configs = load_config_from_files(filename_patterns)
Exemple #16
0
 def start(cls, addr, iface=None):
     daemons = []
     for proto in ("tcp", "tls", "udp"):
         if proto not in g_dionaea.config()['modules']['python']['sip']:
             continue
         port = int(
             g_dionaea.config()['modules']['python']['sip'][proto].get(
                 'port', 5060))
         daemon = SipSession(proto=proto)
         daemon.bind(addr, port, iface=iface)
         daemon.listen()
         daemons.append(daemon)
     return daemons
Exemple #17
0
def new():
    print("START")
    global g_slave
    global g_service_configs
    dionaea_config = g_dionaea.config().get("dionaea")

    mode = dionaea_config.get("listen.mode")
    interface_names = dionaea_config.get("listen.interfaces")

    if mode == 'manual':
        addrs = {}

        addresses = dionaea_config.get("listen.addresses")
        ifaces = g_dionaea.getifaddrs()
        for iface in ifaces.keys():
            afs = ifaces[iface]
            for af in afs.keys():
                if af == 2 or af == 10:
                    configs = afs[af]
                    if iface not in addrs:
                        addrs[iface] = []
                    for config in configs:
                        if config["addr"] in addresses:
                            addrs[iface].append(config['addr'])
        g_slave = slave(addresses=addrs)
    elif mode == 'getifaddrs':
        ifaces = g_dionaea.getifaddrs()
        addrs = {}
        for iface in ifaces.keys():
            if interface_names is not None and iface not in interface_names:
                logger.debug("Skipping interface %s. Not in interface list.", iface)
                continue
            afs = ifaces[iface]
            for af in afs.keys():
                if af == 2 or af == 10:
                    configs = afs[af]
                    for config in configs:
                        if iface not in addrs:
                            addrs[iface] = []
                        addrs[iface].append(config['addr'])
        print(addrs)
        g_slave = slave(addresses=addrs)
    elif mode == 'nl':
        # ToDo: handle error if ifaces is None
        g_slave = nlslave(ifaces=interface_names)

    load_submodules()

    module_config = g_dionaea.config().get("module")
    filename_patterns = module_config.get("service_configs", [])
    g_service_configs = load_config_from_files(filename_patterns)
Exemple #18
0
    def start(cls):
        handlers = []
        for client in g_dionaea.config()['modules']['python']['logxmpp']:
            conf = g_dionaea.config()['modules']['python']['logxmpp'][client]
            if 'resource' in conf:
                resource = conf['resource']
            else:
                resource = ''.join([choice(string.ascii_letters) for i in range(8)])
            print("client %s \n\tserver %s:%s username %s password %s resource %s muc %s\n\t%s" % (client, conf[
                  'server'], conf['port'], conf['username'], conf['password'], resource, conf['muc'], conf['config']))
            x = logxmpp(conf['server'], int(conf['port']), conf['username'], conf['password'], resource, conf['muc'], conf['config'])
            handlers.append(x)

        return handlers
Exemple #19
0
	def start(self):
		ihandler.__init__(self, self.path)
		
		self.submit_url = g_dionaea.config()['modules']['python']['jsonfeeds']['submit_url']
		
		certificate = g_dionaea.config()['modules']['python']['jsonfeeds'].get('certificate', False)
		if certificate:
			self.cert = (certificate['cert'], certificate['key'])
		else:
			self.cert = False

		self.sensor = g_dionaea.config()['modules']['python']['jsonfeeds'].get('sensor', {})

		# delete malware file after download -> True
		self.deleteFile = g_dionaea.config()['modules']['python']['jsonfeeds'].get('delete', False) == "True"
		self.verify = g_dionaea.config()['modules']['python']['jsonfeeds'].get('verify', False) == "True"

		self.externalIP = {
			"disable": g_dionaea.config()['modules']['python']['jsonfeeds']['externalIP'].get('disable', False) == "True",
			"cachetime": int(g_dionaea.config()['modules']['python']['jsonfeeds']['externalIP'].get('cachetime', 0)),
			"lastcheck": 0,
			"ip": g_dionaea.config()['modules']['python']['jsonfeeds']['externalIP'].get('ip', "")
		}
		
		# a cachetime of "0" implies to return self.externalIP["ip"] and to avoid updateExternalIP. So if the ip is set in the config we don't need to updateExternalIP
		if self.externalIP["ip"] != "":
			self.externalIP["cachetime"] = 0
		
		#mapping socket -> attackid
		self.attacks = {}
		'''
Exemple #20
0
    def makeport(self):
        self.datalistener = FTPData(ftp=self)
        try:
            portrange = g_dionaea.config()["modules"]["python"]["ftp"]["active-ports"]
            (minport, maxport) = portrange.split("-")
            minport = int(minport)
            maxport = int(maxport)
        except:
            minport = 62001
            maxport = 63000

        try:
            # for NAT setups
            host = g_dionaea.config()["modules"]["python"]["ftp"]["active-host"]
            if host == "0.0.0.0":
                host = self.ctrl.local.host
                logger.info("datalisten host %s", host)
            else:
                import socket
                host = socket.gethostbyname(host)
                logger.info("resolved host %s", host)
        except:
            host = self.ctrl.local.host
            logger.info("except datalisten host %s", self.ctrl.local.host)

        # NAT, use a port range which is forwarded to your honeypot
        ports = list(
            filter(
                lambda port: ((port >> 4) & 0xf) != 0,
                range(minport, maxport)
            )
        )
        random.shuffle(ports)
        port = None
        for port in ports:
            self.datalistener.bind(self.ctrl.local.host, port)
            if self.datalistener.listen() == True:
                port = self.datalistener.local.port
                i = incident("dionaea.connection.link")
                i.parent = self.ctrl
                i.child = self.datalistener
                i.report()
                break
        hbytes = host.split(".")
        pbytes = [repr(port // 256), repr(port % 256)]
        bytes = hbytes + pbytes
        port = ",".join(bytes)
        logger.debug("PORT CMD %s", port)
        return port
Exemple #21
0
    def makeport(self):
        self.datalistener = ftpdata(ftp=self)
        try:
            portrange = g_dionaea.config(
            )['modules']['python']['ftp']['active-ports']
            (minport, maxport) = portrange.split('-')
            minport = int(minport)
            maxport = int(maxport)
        except:
            minport = 62001
            maxport = 63000

        try:
            # for NAT setups
            host = g_dionaea.config(
            )['modules']['python']['ftp']['active-host']
            if host == '0.0.0.0':
                host = self.ctrl.local.host
                logger.info("datalisten host %s" % host)
            else:
                import socket
                host = socket.gethostbyname(host)
                logger.info("resolved host %s" % host)
        except:
            host = self.ctrl.local.host
            logger.info("except datalisten host %s" % self.ctrl.local.host)

        ports = list(
            filter(lambda port: ((port >> 4) & 0xf) != 0,
                   range(minport, maxport))
        )  # NAT, use a port range which is forwarded to your honeypot
        random.shuffle(ports)
        port = None
        for port in ports:
            self.datalistener.bind(self.ctrl.local.host, port)
            if self.datalistener.listen() == True:
                port = self.datalistener.local.port
                i = incident("dionaea.connection.link")
                i.parent = self.ctrl
                i.child = self.datalistener
                i.report()
                break
        hbytes = host.split('.')
        pbytes = [repr(port // 256), repr(port % 256)]
        bytes = hbytes + pbytes
        port = ','.join(bytes)
        logger.debug("PORT CMD %s" % (port))
        return port
Exemple #22
0
    def close(self):
        logger.debug("{!s} close".format(self))
        logger.debug("Closing stream dump (in)")
        connection.close(self)

        if len(self._bistream) == 0:
            return

        now = datetime.datetime.now()
        dirname = "%04i-%02i-%02i" % (now.year, now.month, now.day)
        bistream_path = os.path.join(
            g_dionaea.config()['bistreams']['python']['dir'], dirname)
        if not os.path.exists(bistream_path):
            os.makedirs(bistream_path)

        fp = tempfile.NamedTemporaryFile(
            delete = False,
            prefix = "SipCall-{local_port}-{remote_host}:{remote_port}-".format(
                local_port = self.local.port, remote_host = self.remote.host,
                remote_port = self.remote.port),
            dir = bistream_path
        )
        fp.write(b"stream = ")
        fp.write(str(self._bistream).encode())
        fp.close()
Exemple #23
0
 def start(self, addr, iface=None):
     port = int(
         g_dionaea.config()['modules']['python']['sip']['udp'].get('port', 5060))
     daemon = dionaea.sip.SipSession(proto = 'udp')
     daemon.bind(addr, port, iface=iface)
     daemon.listen()
     return daemon
Exemple #24
0
    def apply_config(self, config):
        """Applies the given configuration to this daemon
        """
        dionaea_config = g_dionaea.config().get("dionaea")
        self.download_dir = dionaea_config.get("download.dir")

        if self.download_dir is None:
            raise ServiceConfigError("download_dir not defined")
        if not os.path.isdir(self.download_dir):
            raise ServiceConfigError(
                "The PCL output directory '%s' is not a directory" %
                self.download_dir)
        if not os.access(self.download_dir, os.W_OK):
            raise ServiceConfigError("Unable to write files in '%s'" %
                                     self.download_dir)

        self.root = config.get("root")

        if self.root is None:
            raise ServiceConfigError("root not defined")
        if not os.path.isdir(self.root):
            raise ServiceConfigError(
                "The PJL filesystem '%s' is not a directory" % self.root)
        if not os.access(self.root, os.R_OK):
            raise ServiceConfigError("Unable to read files in '%s'" %
                                     self.root)

        self.pjl_responses.update(config.get("pjl_msgs", {}))
        self.pjl_response_regexes = convert_pjl_responses_to_regex(
            self.pjl_responses)
Exemple #25
0
 def start(self, addr, iface=None):
     port = int(g_dionaea.config()['modules']['python']['sip']['udp'].get(
         'port', 5060))
     daemon = dionaea.sip.SipSession(proto='udp')
     daemon.bind(addr, port, iface=iface)
     daemon.listen()
     return daemon
Exemple #26
0
    def handle_incident(self, icd):
        logger.debug("storing file")
        p = icd.path
        md5 = md5file(p)
        n = g_dionaea.config()["downloads"]["dir"] + "/" + md5
        i = incident("dionaea.download.complete.hash")
        i.file = n
        i.url = icd.url
        if hasattr(icd, "con"):
            i.con = icd.con
        i.md5hash = md5
        i.report()

        try:
            f = os.stat(n)
            i = incident("dionaea.download.complete.again")
            logger.debug("file %s already existed" % md5)
        except OSError:
            logger.debug("saving new file %s to %s" % (md5, n))
            os.link(p, n)
            i = incident("dionaea.download.complete.unique")
        i.file = n
        if hasattr(icd, "con"):
            i.con = icd.con
        i.url = icd.url
        i.md5hash = md5
        i.report()
Exemple #27
0
    def close(self):
        logger.debug("{!s} close".format(self))
        logger.debug("Closing stream dump (in)")
        connection.close(self)

        if len(self._bistream) == 0:
            return

        now = datetime.datetime.now()
        dirname = "%04i-%02i-%02i" % (now.year, now.month, now.day)
        bistream_path = os.path.join(
            g_dionaea.config()['bistreams']['python']['dir'], dirname)
        if not os.path.exists(bistream_path):
            os.makedirs(bistream_path)

        fp = tempfile.NamedTemporaryFile(
            delete=False,
            prefix="SipCall-{local_port}-{remote_host}:{remote_port}-".format(
                local_port=self.local.port,
                remote_host=self.remote.host,
                remote_port=self.remote.port),
            dir=bistream_path)
        fp.write(b"stream = ")
        fp.write(str(self._bistream).encode())
        fp.close()
Exemple #28
0
 def handle_established(self):
     logger.info("connection to %s established" % self.remote.host)
     logger.info("port %i established" % self.port)
     self.remote.port = self.port
     pkt = TftpPacketRRQ()
     pkt.filename = self.filename
     pkt.mode = "octet"  # FIXME - shouldn't hardcode this
     pkt.options = self.options
     self.last_packet = pkt.encode().buffer
     self.send(self.last_packet)
     self.state.state = 'rrq'
     self.fileobj = tempfile.NamedTemporaryFile(
         delete=False,
         prefix='tftp-',
         suffix=g_dionaea.config()['downloads']['tmp-suffix'],
         dir=g_dionaea.config()['downloads']['dir'])
Exemple #29
0
 def start(cls):
     from dionaea.core import g_dionaea
     from .controller import LogSQLHandler
     handlers = []
     for config in g_dionaea.config()['modules']['python']['log_db_sql']:
         handlers.append(LogSQLHandler("*", config=config))
     return handlers
Exemple #30
0
    def handle_incident(self, icd):
        logger.debug("storing file")
        p = icd.path
        md5 = md5file(p)
        n = g_dionaea.config()['downloads']['dir'] + '/' + md5
        i = incident("dionaea.download.complete.hash")
        i.file = n
        i.url = icd.url
        if hasattr(icd, 'con'):
            i.con = icd.con
        i.md5hash = md5
        i.report()

        try:
            f = os.stat(n)
            i = incident("dionaea.download.complete.again")
            logger.debug("file %s already existed" % md5)
        except OSError:
            logger.debug("saving new file %s to %s" % (md5, n))
            os.link(p, n)
            i = incident("dionaea.download.complete.unique")
        i.file = n
        if hasattr(icd, 'con'):
            i.con = icd.con
        i.url = icd.url
        i.md5hash = md5
        i.report()
Exemple #31
0
def new():
    global g_handler_configs
    logger.info("Load iHandlers")
    load_submodules()

    module_config = g_dionaea.config().get("module")
    filename_patterns = module_config.get("ihandler_configs", [])
    g_handler_configs = load_config_from_files(filename_patterns)
Exemple #32
0
    def handle_established(self):
        self.config = g_dionaea.config(
        )['modules']['python']['mysql']['databases']

        self.state = 'greeting'
        a = MySQL_Packet_Header(Number=0) / MySQL_Server_Greeting()
        a.show()
        self.send(a.build())
        self._open_db('information_schema')
Exemple #33
0
    def handle_established(self):
        self.config = g_dionaea.config()['modules']['python'][
            'mysql']['databases']

        self.state = 'greeting'
        a = MySQL_Packet_Header(Number=0) / MySQL_Server_Greeting()
        a.show()
        self.send(a.build())
        self._open_db('information_schema')
Exemple #34
0
    def handle_POST(self):
        """
		Handle the POST method. Send the head and the file. But ignore the POST params.
		Use the bistreams for a better analysis.
		"""
        if self.fp_tmp != None:
            self.fp_tmp.seek(0)
            form = cgi.FieldStorage(fp=self.fp_tmp, environ=self.env)
            for field_name in form.keys():
                # dump only files
                if form[field_name].filename == None:
                    continue

                fp_post = form[field_name].file

                data = fp_post.read(4096)

                # don't handle empty files
                if len(data) == 0:
                    continue

                fp_tmp = tempfile.NamedTemporaryFile(
                    delete=False,
                    prefix='http-',
                    suffix=g_dionaea.config()['downloads']['tmp-suffix'],
                    dir=g_dionaea.config()['downloads']['dir'])
                while data != b'':
                    fp_tmp.write(data)
                    data = fp_post.read(4096)

                icd = incident("dionaea.download.complete")
                icd.path = fp_tmp.name
                icd.con = self
                # We need the url for logging
                icd.url = ""
                fp_tmp.close()
                icd.report()
                os.unlink(fp_tmp.name)

            os.unlink(self.fp_tmp.name)

        x = self.send_head()
        if x:
            self.copyfile(x)
Exemple #35
0
    def start(cls):
        handlers = []
        for client in g_dionaea.config()['modules']['python']['logxmpp']:
            conf = g_dionaea.config()['modules']['python']['logxmpp'][client]
            if 'resource' in conf:
                resource = conf['resource']
            else:
                resource = ''.join(
                    [choice(string.ascii_letters) for i in range(8)])
            print(
                "client %s \n\tserver %s:%s username %s password %s resource %s muc %s\n\t%s"
                % (client, conf['server'], conf['port'], conf['username'],
                   conf['password'], resource, conf['muc'], conf['config']))
            x = logxmpp(conf['server'], int(conf['port']), conf['username'],
                        conf['password'], resource, conf['muc'],
                        conf['config'])
            handlers.append(x)

        return handlers
Exemple #36
0
    def apply_config(self, config):
        dionaea_config = g_dionaea.config().get("dionaea")
        self.download_dir = dionaea_config.get("download.dir")
        self.download_suffix = dionaea_config.get("download.suffix", ".tmp")

        default_headers = config.get("default_headers", self._default_headers)
        global_headers = config.get('global_headers', [])

        self.default_headers = Headers(default_headers,
                                       global_headers=global_headers)

        headers = config.get('headers', [])
        for header in headers:
            self.headers.append(
                Headers(header.get("headers", []),
                        global_headers=global_headers,
                        filename_pattern=header.get("filename_pattern"),
                        status_codes=header.get("status_codes")))

        self.headers.append(
            Headers([("Location", "{location}"),
                     ("Connection", "{connection}")],
                    global_headers=global_headers,
                    status_codes=[301, 302]))

        self.headers.append(
            Headers([("Allow", "{allow}"), ("Connection", "{connection}")],
                    global_headers=global_headers,
                    methods=["options"]))

        conf_max_request_size = config.get("max_request_size")
        if conf_max_request_size is not None:
            try:
                self.max_request_size = int(conf_max_request_size) * 1024
            except ValueError:
                logger.warning(
                    "Error while converting 'max_request_size' to an integer value. Using default value."
                )

        self.soap_enabled = True if config.get("soap_enabled") else False

        self.root = config.get("root")
        if self.root is None:
            logger.warningfigError("Root directory not configured")
        else:
            if not os.path.isdir(self.root):
                logger.warning("Root path '%s' is not a directory", self.root)
            elif not os.access(self.root, os.R_OK):
                logger.warning("Unable to read content of root directory '%s'",
                               self.root)

        template_config = config.get("template")
        if template_config is None:
            template_config = {}
        self._apply_template_config(template_config)
Exemple #37
0
	def __init__(self, proto='udp'):
		connection.__init__(self,proto)
		self.state = 'HEADER'
		self.rwchunksize = 64*1024
		self._out.speed.limit = 16*1024
		self.env = None
		self.boundary = None
		self.fp_tmp = None
		self.cur_length = 0
		max_request_size = 32768
		self.personalities = ''
		self.loaded = ''

		try:
			if 'max-request-size' in g_dionaea.config()['modules']['python']['upnp']:
				# try to convert value to int
				max_request_size = int(g_dionaea.config()['modules']['python']['upnp']['max-request-size'])
			else:
				logger.info("Value for 'max-request-size' not found, using default value.")
		except:
			logger.warning("Error while converting 'max-request-size' to an integer value. Using default value.")

		self.max_request_size = max_request_size * 1024

		# load the UPnP device personalities from dionaea.conf file 
		try:
			if 'personalities-enable' in g_dionaea.config()['modules']['python']['upnp']:
				loaded = g_dionaea.config()['modules']['python']['upnp']['personalities-enable']
				self.personalities = g_dionaea.config()['modules']['python']['upnp']['personalities'][loaded]['cache']
				self.personalities += g_dionaea.config()['modules']['python']['upnp']['personalities'][loaded]['st']
				self.personalities += g_dionaea.config()['modules']['python']['upnp']['personalities'][loaded]['usn']
				self.personalities += g_dionaea.config()['modules']['python']['upnp']['personalities'][loaded]['server']
				self.personalities += g_dionaea.config()['modules']['python']['upnp']['personalities'][loaded]['location']
				self.personalities += g_dionaea.config()['modules']['python']['upnp']['personalities'][loaded]['opt']

				logger.info("loading emulated UPnP device with personalities: '" + loaded + "'")
			else:
				logger.info("Value for 'personalities' not found, using default value.")
		except:
			logger.warning("Error while retrieve 'personalities'. Using default value.")
Exemple #38
0
    def __init__(self, path, config=None):
        logger.debug("%s ready!" % (self.__class__.__name__))
        ihandler.__init__(self, path)

        dionaea_config = g_dionaea.config().get("dionaea")
        self.download_dir = dionaea_config.get("download.dir")
        if self.download_dir is None:
            raise LoaderError("Setting download.dir not configured")
        else:
            if not os.path.isdir(self.download_dir):
                raise LoaderError("'%s' is not a directory", self.download_dir)
            if not os.access(self.download_dir, os.W_OK):
                raise LoaderError("Not allowed to create files in the '%s' directory", self.download_dir)
Exemple #39
0
    def __init__(self, path, config=None):
        logger.warning("%s ready!" % (self.__class__.__name__))
        ihandler.__init__(self, path)

        dionaea_config = g_dionaea.config().get("dionaea")
        self.download_dir = dionaea_config.get("download.dir")
        if self.download_dir is None:
            raise LoaderError("Setting download.dir not configured")
        else:
            if not os.path.isdir(self.download_dir):
                raise LoaderError("'%s' is not a directory", self.download_dir)
            if not os.access(self.download_dir, os.W_OK):
                raise LoaderError("Not allowed to create files in the '%s' directory", self.download_dir)
Exemple #40
0
 def __init__(self, path):
     logger.info("%s ready!" % (self.__class__.__name__))
     ihandler.__init__(self, path)
     self.mwsconfig = g_dionaea.config()['mycert_sensor']['submit']
     self.sensorid = self.mwsconfig['sensorid']
     self.connection_url = self.mwsconfig['connection_url'].format(id=self.sensorid)
     self.artifact_url = self.mwsconfig['artifact_url']
     self.cookies = {}
     self.attacker = {}
     self.connection = {}
     self.mysql = {}
     self.mssql = {}
     self.ftp = {}
Exemple #41
0
 def handle_established(self):
     logger.info("connection to %s established" % self.remote.host)
     logger.info("port %i established" % self.port)
     self.remote.port = self.port
     pkt = TftpPacketRRQ()
     pkt.filename = self.filename
     pkt.mode = "octet" # FIXME - shouldn't hardcode this
     pkt.options = self.options
     self.last_packet = pkt.encode().buffer
     self.send(self.last_packet)
     self.state.state = 'rrq'
     self.fileobj = tempfile.NamedTemporaryFile(delete=False, prefix='tftp-', suffix=g_dionaea.config(
     )['downloads']['tmp-suffix'], dir=g_dionaea.config()['downloads']['dir'])
Exemple #42
0
    def apply_config(self, config):
        dionaea_config = g_dionaea.config().get("dionaea")
        self.download_dir = dionaea_config.get("download.dir")
        self.download_suffix = dionaea_config.get("download.suffix", ".tmp")

        default_headers = config.get("default_headers", self._default_headers)
        global_headers = config.get('global_headers', [])

        self.default_headers = Headers(default_headers, global_headers=global_headers)

        headers = config.get('headers', [])
        for header in headers:
            self.headers.append(
                Headers(
                    header.get("headers", []),
                    global_headers=global_headers,
                    filename_pattern=header.get("filename_pattern"),
                    status_codes=header.get("status_codes")
                )
            )

        self.headers.append(
            Headers(
                [
                    ("Location", "{location}"),
                    ("Connection", "{connection}")
                ],
                global_headers=global_headers,
                status_codes=[301, 302]
            )
        )

        self.headers.append(
            Headers(
                [
                    ("Allow", "{allow}"),
                    ("Connection", "{connection}")
                ],
                global_headers=global_headers,
                methods=["options"]
            )
        )

        conf_max_request_size = config.get("max_request_size")
        if conf_max_request_size is not None:
            try:
                self.max_request_size = int(conf_max_request_size) * 1024
            except ValueError:
                logger.warning("Error while converting 'max_request_size' to an integer value. Using default value.")

        self.root = config.get("root")
Exemple #43
0
 def __init__(self, proto='tcp'):
     connection.__init__(self, proto)
     logger.debug("ftp test")
     self.state = self.UNAUTH
     self.user = '******'
     self.dtp = None
     self.cwd = '/'
     self.basedir = '/tmp/ranz'
     self.dtp = None
     self.dtf = None
     self.limits = {}  # { '_out' : 8192 }
     # Copy default response messages
     self._response_msgs = dict(RESPONSE.items())
     msgs = g_dionaea.config()["modules"]["python"]["ftp"].get("response_messages", {})
     self._response_msgs.update(msgs)
Exemple #44
0
 def __init__(self, proto='tcp'):
     connection.__init__(self, proto)
     logger.debug("ftp test")
     self.state = self.UNAUTH
     self.user = '******'
     self.dtp = None
     self.cwd = '/'
     self.basedir = '/tmp/ranz'
     self.dtp = None
     self.dtf = None
     self.limits = {}  # { '_out' : 8192 }
     # Copy default response messages
     self._response_msgs = dict(RESPONSE.items())
     msgs = g_dionaea.config()["modules"]["python"]["ftp"].get(
         "response_messages", {})
     self._response_msgs.update(msgs)
Exemple #45
0
def new():
    global g_handlers
    logger.info("Load iHandlers")
    load_submodules()
    g_handlers = {}

    for h in IHandlerLoader:
        if h.name not in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
            continue
        if h not in g_handlers:
            g_handlers[h] = []

        handlers = h.start()
        if isinstance(handlers, (list, tuple)):
            g_handlers[h] += handlers
        else:
            g_handlers[h].append(handlers)
 def __init__(self, path):
     self.disabled = False
     self.attacks = {}
     self.logger = logging.getLogger('honeysens')
     self.logger.setLevel(logging.WARNING)
     self.config = configparser.ConfigParser()
     try:
         with open(g_dionaea.config()['modules']['python']['honeysens']['config']) as f:
             self.config.read_file(f)
             self.server_name = self.config.get('server', 'name')
             self.key = RSA.importKey(open(self.config.get('general', 'keyfile'), 'r').read())
             self.servercertfile = self.config.get('server', 'certfile')
             self.sensor_id = self.config.get('general', 'sensor_id')
             self.logger.debug('HoneySens Configuration\n Server: {}\n Key file: {}\n Server certificate: {}\n Sensor ID: {}'.format(self.server_name, self.key, self.servercertfile, self.sensor_id))
             ihandler.__init__(self, path)
     except Exception:
         self.logger.debug('Error: Invalid HoneySens configuration, module disabled')
         self.disabled = True
Exemple #47
0
    def apply_config(self, config):
        self.config = config.get("databases")

        dionaea_config = g_dionaea.config().get("dionaea")
        self.download_dir = dionaea_config.get("download.dir")
        self.download_suffix = dionaea_config.get("download.suffix", ".tmp")

        from .var import CFG_VARS
        self.vars.load(CFG_VARS)
        vars = config.get("vars")
        if not isinstance(vars, dict):
            vars = {}

        for name, value in vars.items():
            obj = self.vars.values.get(name)
            if obj is None:
                logger.warning("Config value '%s' does not exist")
                continue
            obj.value = value
Exemple #48
0
    def __init__(self):
        logger.debug("nfqhandler")
        ihandler.__init__(self, 'dionaea.connection.tcp.pending')

        conf = g_dionaea.config()['modules']['python']['nfq']

        self.throttle_window = int(conf['throttle']['window'])
        self.window = [[0, 0] for x in range(self.throttle_window)]

        self.throttle_nfaction = int(conf['nfaction'])
        self.throttle_total = int(conf['throttle']['limits']['total'])
        self.throttle_slot = int(conf['throttle']['limits']['slot'])

        self.mirror_server_timeout_listen = int(
            conf['timeouts']['server']['listen'])
        self.mirror_client_timeout_idle = int(
            conf['timeouts']['client']['idle'])
        self.mirror_client_timeout_sustain = int(
            conf['timeouts']['client']['sustain'])
Exemple #49
0
    def __init__(self):
        logger.debug("nfqhandler")
        ihandler.__init__(self, 'dionaea.connection.tcp.pending')

        conf = g_dionaea.config()['modules']['python']['nfq']

        self.throttle_window = int(conf['throttle']['window'])
        self.window = [[0,0] for x in range(self.throttle_window)]

        self.throttle_nfaction = int(conf['nfaction'])
        self.throttle_total    = int(conf['throttle']['limits']['total'])
        self.throttle_slot     = int(conf['throttle']['limits']['slot'])

        self.mirror_server_timeout_listen = int(
            conf['timeouts']['server']['listen'])
        self.mirror_client_timeout_idle   = int(
            conf['timeouts']['client']['idle'])
        self.mirror_client_timeout_sustain= int(
            conf['timeouts']['client']['sustain'])
Exemple #50
0
    def apply_config(self, config):
        self.config = config.get("databases")

        dionaea_config = g_dionaea.config().get("dionaea")
        self.download_dir = dionaea_config.get("download.dir")
        self.download_suffix = dionaea_config.get("download.suffix", ".tmp")

        from .var import CFG_VARS
        self.vars.load(CFG_VARS)
        vars = config.get("vars")
        if not isinstance(vars, dict):
            vars = {}

        for name, value in vars.items():
            obj = self.vars.values.get(name)
            if obj is None:
                logger.warning("Config value '%s' does not exist")
                continue
            obj.value = value
Exemple #51
0
    def __init__(self, path, config=None):
        logger.debug("%s ready!", self.__class__.__name__)
        ihandler.__init__(self, path)
        self.port_min = 62001
        self.port_max = 63000

        port_range = config.get("active_ports")
        try:
            (port_min, port_max) = port_range.split("-")
            self.port_min = int(port_min)
            self.port_max = int(port_max)
        except Exception:
            logger.warning("Unable to pars port range")

        self.host = config.get("active_host")

        dionaea_config = g_dionaea.config().get("dionaea")
        self.download_dir = dionaea_config.get("download.dir")
        self.download_suffix = dionaea_config.get("download.suffix")
Exemple #52
0
	def __init__(self, path):
		logger.debug("%s ready!" % (self.__class__.__name__))
		ihandler.__init__(self, path)
		mwsconfig = g_dionaea.config()['modules']['python']['submit_http']
		self.backendurl = mwsconfig['url']
		self.email = 'email' in mwsconfig and mwsconfig['email'] or '*****@*****.**'
		self.user = '******' in mwsconfig and mwsconfig['user'] or ''
		self.passwd = 'pass' in mwsconfig and mwsconfig['pass'] or ''
		self.cookies = {}

		# heartbeats
		dinfo = g_dionaea.version()
		self.software = 'dionaea {0} {1}/{2} - {3} {4}'.format(
			dinfo['dionaea']['version'],
			dinfo['compiler']['os'],
			dinfo['compiler']['arch'],
			dinfo['compiler']['date'],
			dinfo['compiler']['time'],
		)
		self.loop = pyev.default_loop()
Exemple #53
0
    def handle_POST(self):
        """
        Handle the POST method. Send the head and the file. But ignore the POST params.
        Use the bistreams for a better analysis.
        """
        if self.fp_tmp != None:
            self.fp_tmp.seek(0)
            form = cgi.FieldStorage(fp = self.fp_tmp, environ = self.env)
            for field_name in form.keys():
                # dump only files
                if form[field_name].filename == None:
                    continue

                fp_post = form[field_name].file

                data = fp_post.read(4096)

                # don't handle empty files
                if len(data) == 0:
                    continue

                fp_tmp = tempfile.NamedTemporaryFile(delete=False, prefix='http-', suffix=g_dionaea.config(
                )['downloads']['tmp-suffix'], dir=g_dionaea.config()['downloads']['dir'])
                while data != b'':
                    fp_tmp.write(data)
                    data = fp_post.read(4096)

                icd = incident("dionaea.download.complete")
                icd.path = fp_tmp.name
                icd.con = self
                # We need the url for logging
                icd.url = ""
                fp_tmp.close()
                icd.report()
                os.unlink(fp_tmp.name)

            os.unlink(self.fp_tmp.name)

        x = self.send_head()
        if x :
            self.copyfile(x)
Exemple #54
0
 def start(self, addrs):
     print("STARTING SERVICES")
     try:
         for iface in addrs:
             print(iface)
             for addr in addrs[iface]:
                 print(addr)
                 self.daemons[addr] = {}
                 for service in ServiceLoader:
                     if service.name not in g_dionaea.config()['modules']['python']['services']['serve']:
                         continue
                     if service not in self.daemons[addr]:
                         self.daemons[addr][service] = []
                     print(service)
                     daemons = service.start(addr, iface=iface)
                     if isinstance(daemons, (list, tuple)):
                         self.daemons[addr][service] += daemons
                     else:
                         self.daemons[addr][service].append(daemons)
     except Exception as e:
         raise e
     print(self.daemons)
Exemple #55
0
    def __init__(self, path):
        logger.debug("%s ready!" % (self.__class__.__name__))
        ihandler.__init__(self, path)
        mwsconfig = g_dionaea.config()['modules']['python']['mwserv']
        self.backendurl = mwsconfig['url']
        self.maintainer = mwsconfig['maintainer']
        self.guid = mwsconfig['guid']
        self.secret = mwsconfig['secret']
        self.cookies = {}

        # heartbeats
        dinfo = g_dionaea.version()
        self.software = 'dionaea {0} {1}/{2} - {3} {4}'.format(
            dinfo['dionaea']['version'],
            dinfo['compiler']['os'],
            dinfo['compiler']['arch'],
            dinfo['compiler']['date'],
            dinfo['compiler']['time'],
        )
        self.loop = pyev.default_loop()
        self.heartbeat_timer = pyev.Timer(5., 120, self.loop, self._heartbeat)
        self.heartbeat_timer.start()