1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/src/IkarusScanner.py Tue Feb 18 15:38:00 2014 +0100
1.3 @@ -0,0 +1,143 @@
1.4 +#!/usr/bin/python
1.5 +
1.6 +import ConfigParser
1.7 +
1.8 +import sys
1.9 +
1.10 +import logging
1.11 +import os
1.12 +import errno
1.13 +import time
1.14 +
1.15 +import urllib3
1.16 +
1.17 +class IkarusScanner:
1.18 +
1.19 + # User the existing logger instance
1.20 + __LOG = logging.getLogger("IkarusScanner")
1.21 +
1.22 + __MINOPTS = { "Main" : ["LocalScanserverURL", "RemoteScanserverURL", "MaxFileSize", "RetryTimeout"]}
1.23 + __CONFIG_NOT_READABLE = "Configfile is not readable"
1.24 + __CONFIG_WRONG = "Something is wrong with the config"
1.25 + __CONFIG_MISSING = "Section: \"%s\" Option: \"%s\" in configfile is missing"
1.26 + __LOCAL_SCANSERVER_URL = ""
1.27 + __REMOTE_SCANSERVER_URL = ""
1.28 + __STATUS_CODE_OK = 200
1.29 + __STATUS_CODE_INFECTED = 210
1.30 + __STATUS_CODE_NOT_FOUND = 404
1.31 + __MAX_SCAN_FILE_SIZE = 50 * 0x100000
1.32 + __SCANSERVER_RETRY_TIMEOUT = 60
1.33 +
1.34 + # Global http pool manager used to connect to the scan server
1.35 + __remoteScanserverReachable = True
1.36 + __scanserverTimestamp = 0
1.37 + __httpPool = urllib3.PoolManager(num_pools = 1, timeout = 3)
1.38 +
1.39 + def __init__ (self, scanner_config_path):
1.40 + config = self.loadConfig (scanner_config_path)
1.41 +
1.42 + self.__scanserverTimestamp = time.time()
1.43 +
1.44 + __LOCAL_SCANSERVER_URL = config.get("Main", "LocalScanserverURL")
1.45 + __REMOTE_SCANSERVER_URL = config.get("Main", "RemoteScanserverURL")
1.46 + __SCANSERVER_RETRY_TIMEOUT = int(config.get("Main", "RetryTimeout"))
1.47 +
1.48 + # Convert file size from MB to byte
1.49 + __MAX_SCAN_FILE_SIZE = int(config.get("Main", "MaxFileSize")) * 0x100000
1.50 +
1.51 +
1.52 + def checkMinimumOptions (self, config):
1.53 + for section, options in self.__MINOPTS.iteritems ():
1.54 + for option in options:
1.55 + if (config.has_option(section, option) == False):
1.56 + self.__LOG.error (self.__CONFIG_MISSING % (section, option))
1.57 + exit (129)
1.58 +
1.59 + def loadConfig (self, scanner_config_path):
1.60 +
1.61 + configfile = scanner_config_path
1.62 + config = ConfigParser.SafeConfigParser ()
1.63 +
1.64 + 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)):
1.65 + self.__LOG.error(self.__CONFIG_NOT_READABLE);
1.66 + raise SystemError(self.__CONFIG_NOT_READABLE)
1.67 +
1.68 + try:
1.69 + config.read (scanner_config_path)
1.70 + except Exception, e:
1.71 + self.__LOG.error("Error: %s" % (e));
1.72 + raise SystemError("Error: %s" % (e))
1.73 +
1.74 + self.checkMinimumOptions (config)
1.75 +
1.76 + return config
1.77 +
1.78 + def contactScanserver(self, url, fields):
1.79 + return httpPool.request_encode_body('POST', url, fields = fields, retries = 0)
1.80 +
1.81 + def scanFile (self, path, fileobject):
1.82 + return self.scanFileIkarus (path, fileobject)
1.83 +
1.84 + def scanFileIkarus (self, path, fileobject):
1.85 + retval = { "infected" : False, "virusname" : "Unknown" }
1.86 + self.__LOG.debug ("Scan File: %s" % (path))
1.87 +
1.88 +
1.89 +
1.90 + if (os.fstat(fileobject.fileno()).st_size > self.__MAX_SCAN_FILE_SIZE):
1.91 + self.__LOG.info("File max size exceeded. The file is not scanned.")
1.92 + retval["infected"] = True
1.93 + retval["virusname"] = "File is to big to be scanned."
1.94 + return retval
1.95 +
1.96 + fields = { 'up_file' : fileobject.read() }
1.97 +
1.98 + if (self.__remoteScanserverReachable == False) and ((self.__scanserverTimestamp + self.__SCANSERVER_RETRY_TIMEOUT) < time.time()):
1.99 + self.__remoteScanserverReachable = True
1.100 +
1.101 + if self.__remoteScanserverReachable:
1.102 + try:
1.103 + response = contactScanserver(self.__REMOTE_SCANSERVER_URL, fields)
1.104 + # We should catch socket.error here, but this does not work. Needs checking.
1.105 + except:
1.106 + self.__LOG.info("Remote scan server unreachable, using local scan server.")
1.107 + self.__LOG.info("Next check for remote server in %s seconds." % (self.__SCANSERVER_RETRY_TIMEOUT))
1.108 +
1.109 + self.__remoteScanserverReachable = False
1.110 + self.__scanserverTimestamp = time.time()
1.111 +
1.112 + try:
1.113 + response = contactScanserver(self.__LOCAL_SCANSERVER_URL, fields)
1.114 + except:
1.115 + self.__LOG.error ("Connection to local scan server could not be established.")
1.116 + self.__LOG.error ("Exception: %s" %(sys.exc_info()[0]))
1.117 + return retval
1.118 + else:
1.119 + try:
1.120 + response = contactScanserver(self.__LOCAL_SCANSERVER_URL, fields)
1.121 + except:
1.122 + self.__LOG.error ("Connection to local scan server could not be established.")
1.123 + self.__LOG.error ("Exception: %s" %(sys.exc_info()[0]))
1.124 + return retval
1.125 +
1.126 +
1.127 + if response.status == self.__STATUS_CODE_OK:
1.128 + retval["infected"] = False
1.129 + elif response.status == self.__STATUS_CODE_INFECTED:
1.130 + # Parse xml for info if desired
1.131 + #contentXML = r.content
1.132 + #root = ET.fromstring(contentXML)
1.133 + #status = root[1][2].text
1.134 + retval["infected"] = True
1.135 + else:
1.136 + self.__LOG.error ("Connection error to scan server.")
1.137 +
1.138 + if (retval["infected"] == True):
1.139 + self.__LOG.error ("Virus found, denying access.")
1.140 + else:
1.141 + self.__LOG.debug ("No virus found.")
1.142 +
1.143 + return retval
1.144 +
1.145 +
1.146 +