diff -r 000000000000 -r 23028352807f ikarusscanner/IkarusScanner.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ikarusscanner/IkarusScanner.py Tue Nov 04 16:28:40 2014 +0100 @@ -0,0 +1,185 @@ +#!/usr/bin/python + +# ------------------------------------------------------------ +# opensecurity package file +# +# Autor: Karlberger Christoph +# X-Net Services GmbH +# +# Copyright 2013-2014 X-Net and AIT Austrian Institute of Technology +# +# IKARUS Security Software GmbH +# Blechturmgasse 11 +# 1050 Wien +# AUSTRIA +# http://www.ikarussecurity.com +# +# X-Net Technologies GmbH +# Elisabethstrasse 1 +# 4020 Linz +# AUSTRIA +# https://www.x-net.at +# +# AIT Austrian Institute of Technology +# Donau City Strasse 1 +# 1220 Wien +# AUSTRIA +# http://www.ait.ac.at +# +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ------------------------------------------------------------ + +import ConfigParser + +import sys + +import logging +import os +import errno +import time + +import urllib3 +import xml.etree.ElementTree as ET + +class IkarusScanner: + + # User the existing logger instance + __LOG = logging.getLogger("IkarusScanner") + + __MINOPTS = { "Main" : ["LocalScanserverURL", "RemoteScanserverURL", "MaxFileSize", "RetryTimeout"]} + __CONFIG_NOT_READABLE = "Configfile is not readable" + __CONFIG_WRONG = "Something is wrong with the config" + __CONFIG_MISSING = "Section: \"%s\" Option: \"%s\" in configfile is missing" + __LOCAL_SCANSERVER_URL = "" + __REMOTE_SCANSERVER_URL = "" + __STATUS_CODE_OK = 200 + __STATUS_CODE_INFECTED = 210 + __STATUS_CODE_NOT_FOUND = 404 + __MAX_SCAN_FILE_SIZE = 50 * 0x100000 + __SCANSERVER_RETRY_TIMEOUT = 60 + + # Global http pool manager used to connect to the scan server + __remoteScanserverReachable = True + __scanserverTimestamp = 0 + __httpPool = urllib3.PoolManager(num_pools = 1, timeout = 3) + + def __init__ (self, scanner_config_path): + config = self.loadConfig (scanner_config_path) + + self.__scanserverTimestamp = time.time() + + self.__LOCAL_SCANSERVER_URL = config.get("Main", "LocalScanserverURL") + self.__REMOTE_SCANSERVER_URL = config.get("Main", "RemoteScanserverURL") + self.__SCANSERVER_RETRY_TIMEOUT = int(config.get("Main", "RetryTimeout")) + + # Convert file size from MB to byte + self.__MAX_SCAN_FILE_SIZE = int(config.get("Main", "MaxFileSize")) * 0x100000 + + + def checkMinimumOptions (self, config): + for section, options in self.__MINOPTS.iteritems (): + for option in options: + if (config.has_option(section, option) == False): + self.__LOG.error (self.__CONFIG_MISSING % (section, option)) + exit (129) + + def loadConfig (self, scanner_config_path): + + configfile = scanner_config_path + config = ConfigParser.SafeConfigParser () + + if ((os.path.exists (scanner_config_path) == False) or (os.path.isfile (scanner_config_path) == False) or (os.access (scanner_config_path, os.R_OK) == False)): + self.__LOG.error(self.__CONFIG_NOT_READABLE); + raise SystemError(self.__CONFIG_NOT_READABLE) + + try: + config.read (scanner_config_path) + except Exception, e: + self.__LOG.error("Error: %s" % (e)); + raise SystemError("Error: %s" % (e)) + + self.checkMinimumOptions (config) + + return config + + def contactScanserver(self, url, fields): + self.__LOG.debug("Contacting server %s" % url) + return self.__httpPool.request_encode_body('POST', url, fields = fields, retries = 0) + + def scanFile (self, path, fileobject): + return self.scanFileIkarus (path, fileobject) + + def scanFileIkarus (self, path, fileobject): + retval = { "infected" : False, "virusname" : "Unknown" } + self.__LOG.debug ("Scan File: %s" % (path)) + + if (os.fstat(fileobject.fileno()).st_size > self.__MAX_SCAN_FILE_SIZE): + self.__LOG.info("File max size exceeded. The file is not scanned.") + retval["infected"] = False + retval["virusname"] = "File is to big to be scanned." + return retval + + fields = { 'up_file' : fileobject.read() } + + if (self.__remoteScanserverReachable == False) and ((self.__scanserverTimestamp + self.__SCANSERVER_RETRY_TIMEOUT) < time.time()): + self.__remoteScanserverReachable = True + + if self.__remoteScanserverReachable: + try: + response = self.contactScanserver(self.__REMOTE_SCANSERVER_URL, fields) + # We should catch socket.error here, but this does not work. Needs checking. + except: + self.__LOG.info("Remote scan server unreachable, using local scan server.") + self.__LOG.debug("Exception: %s: %s" % (sys.exc_info()[0], sys.exc_info()[1])) + self.__LOG.info("Next check for remote server in %s seconds." % (self.__SCANSERVER_RETRY_TIMEOUT)) + + self.__remoteScanserverReachable = False + self.__scanserverTimestamp = time.time() + + try: + response = self.contactScanserver(self.__LOCAL_SCANSERVER_URL, fields) + except: + self.__LOG.error ("Connection to local scan server could not be established.") + self.__LOG.debug ("Exception: %s" % (sys.exc_info()[0])) + return retval + else: + try: + response = self.contactScanserver(self.__LOCAL_SCANSERVER_URL, fields) + except: + self.__LOG.error ("Connection to local scan server could not be established.") + self.__LOG.error ("Exception: %s" %(sys.exc_info()[0])) + return retval + + + if response.status == self.__STATUS_CODE_OK: + retval["infected"] = False + elif response.status == self.__STATUS_CODE_INFECTED: + # Parse xml for info + root = ET.fromstring(response.data) + + # this should be done in a more generic way + retval["virusname"] = root[1][3][0].text + retval["infected"] = True + else: + self.__LOG.error ("Connection error to scan server.") + + if (retval["infected"] == True): + self.__LOG.error ("Virus found, denying access.") + else: + self.__LOG.debug ("No virus found.") + + return retval + + +