Initial commit
authorft
Tue, 18 Feb 2014 15:38:00 +0100
changeset 0ca2023eb2463
child 1 57ad4aea86dd
Initial commit
working ikarus scanner engine
config/IkarusScanner.cfg
src/IkarusScanner.py
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/config/IkarusScanner.cfg	Tue Feb 18 15:38:00 2014 +0100
     1.3 @@ -0,0 +1,12 @@
     1.4 +[Main]
     1.5 +# the maximum file size in MB that is scanned
     1.6 +MaxFileSize: 50
     1.7 +
     1.8 +# the URL of the local scan server
     1.9 +LocalScanserverURL: http://localhost/virusscan
    1.10 +
    1.11 +# the URL of the remote scan server
    1.12 +RemoteScanserverURL: http://192.168.63.129/virusscan
    1.13 +
    1.14 +# wait time in seconds until a new connection attempt to remote server is made
    1.15 +RetryTimeout: 600
    1.16 \ No newline at end of file
     2.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.2 +++ b/src/IkarusScanner.py	Tue Feb 18 15:38:00 2014 +0100
     2.3 @@ -0,0 +1,143 @@
     2.4 +#!/usr/bin/python
     2.5 +
     2.6 +import ConfigParser
     2.7 +
     2.8 +import sys
     2.9 +
    2.10 +import logging
    2.11 +import os
    2.12 +import errno
    2.13 +import time
    2.14 +
    2.15 +import urllib3
    2.16 +
    2.17 +class IkarusScanner:
    2.18 +    
    2.19 +    # User the existing logger  instance
    2.20 +    __LOG = logging.getLogger("IkarusScanner")
    2.21 +    
    2.22 +    __MINOPTS = { "Main" : ["LocalScanserverURL", "RemoteScanserverURL", "MaxFileSize", "RetryTimeout"]}
    2.23 +    __CONFIG_NOT_READABLE = "Configfile is not readable"
    2.24 +    __CONFIG_WRONG = "Something is wrong with the config"
    2.25 +    __CONFIG_MISSING = "Section: \"%s\" Option: \"%s\" in configfile is missing"
    2.26 +    __LOCAL_SCANSERVER_URL = ""
    2.27 +    __REMOTE_SCANSERVER_URL = ""
    2.28 +    __STATUS_CODE_OK = 200
    2.29 +    __STATUS_CODE_INFECTED = 210
    2.30 +    __STATUS_CODE_NOT_FOUND = 404
    2.31 +    __MAX_SCAN_FILE_SIZE = 50 * 0x100000
    2.32 +    __SCANSERVER_RETRY_TIMEOUT = 60
    2.33 +    
    2.34 +    # Global http pool manager used to connect to the scan server
    2.35 +    __remoteScanserverReachable = True
    2.36 +    __scanserverTimestamp = 0
    2.37 +    __httpPool = urllib3.PoolManager(num_pools = 1, timeout = 3)
    2.38 +    
    2.39 +    def __init__ (self, scanner_config_path):
    2.40 +        config = self.loadConfig (scanner_config_path)
    2.41 +    
    2.42 +        self.__scanserverTimestamp = time.time()
    2.43 +    
    2.44 +        __LOCAL_SCANSERVER_URL = config.get("Main", "LocalScanserverURL")
    2.45 +        __REMOTE_SCANSERVER_URL = config.get("Main", "RemoteScanserverURL")
    2.46 +        __SCANSERVER_RETRY_TIMEOUT = int(config.get("Main", "RetryTimeout"))
    2.47 +    
    2.48 +        # Convert file size from MB to byte
    2.49 +        __MAX_SCAN_FILE_SIZE = int(config.get("Main", "MaxFileSize")) * 0x100000
    2.50 +    
    2.51 +
    2.52 +    def checkMinimumOptions (self, config):
    2.53 +        for section, options in self.__MINOPTS.iteritems ():
    2.54 +            for option in options:
    2.55 +                if (config.has_option(section, option) == False):
    2.56 +                    self.__LOG.error (self.__CONFIG_MISSING % (section, option))
    2.57 +                    exit (129)
    2.58 +
    2.59 +    def loadConfig (self, scanner_config_path):
    2.60 +
    2.61 +        configfile = scanner_config_path
    2.62 +        config = ConfigParser.SafeConfigParser ()
    2.63 +    
    2.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)):
    2.65 +            self.__LOG.error(self.__CONFIG_NOT_READABLE);
    2.66 +            raise SystemError(self.__CONFIG_NOT_READABLE)
    2.67 +    
    2.68 +        try:
    2.69 +            config.read (scanner_config_path)
    2.70 +        except Exception, e:
    2.71 +            self.__LOG.error("Error: %s" % (e));
    2.72 +            raise SystemError("Error: %s" % (e))
    2.73 +
    2.74 +        self.checkMinimumOptions (config)
    2.75 +    
    2.76 +        return config
    2.77 +
    2.78 +    def contactScanserver(self, url, fields):
    2.79 +        return httpPool.request_encode_body('POST', url, fields = fields, retries = 0)
    2.80 +    
    2.81 +    def scanFile (self, path, fileobject):
    2.82 +        return self.scanFileIkarus (path, fileobject)
    2.83 +
    2.84 +    def scanFileIkarus (self, path, fileobject):
    2.85 +        retval = { "infected" : False, "virusname" : "Unknown" }
    2.86 +        self.__LOG.debug ("Scan File: %s" % (path))
    2.87 +        
    2.88 +        
    2.89 +    
    2.90 +        if (os.fstat(fileobject.fileno()).st_size > self.__MAX_SCAN_FILE_SIZE):
    2.91 +            self.__LOG.info("File max size exceeded. The file is not scanned.")
    2.92 +            retval["infected"] = True
    2.93 +            retval["virusname"] = "File is to big to be scanned."
    2.94 +            return retval
    2.95 +    
    2.96 +        fields = { 'up_file' : fileobject.read() }
    2.97 +    
    2.98 +        if (self.__remoteScanserverReachable == False) and ((self.__scanserverTimestamp + self.__SCANSERVER_RETRY_TIMEOUT) < time.time()):
    2.99 +            self.__remoteScanserverReachable = True
   2.100 +    
   2.101 +        if self.__remoteScanserverReachable:
   2.102 +            try:
   2.103 +                response = contactScanserver(self.__REMOTE_SCANSERVER_URL, fields)
   2.104 +                # We should catch socket.error here, but this does not work. Needs checking.
   2.105 +            except:
   2.106 +                self.__LOG.info("Remote scan server unreachable, using local scan server.")
   2.107 +                self.__LOG.info("Next check for remote server in %s seconds." % (self.__SCANSERVER_RETRY_TIMEOUT))
   2.108 +                
   2.109 +                self.__remoteScanserverReachable = False
   2.110 +                self.__scanserverTimestamp = time.time()
   2.111 +    
   2.112 +                try:
   2.113 +                    response = contactScanserver(self.__LOCAL_SCANSERVER_URL, fields)
   2.114 +                except:
   2.115 +                    self.__LOG.error ("Connection to local scan server could not be established.")
   2.116 +                    self.__LOG.error ("Exception: %s" %(sys.exc_info()[0]))
   2.117 +                    return retval
   2.118 +        else:
   2.119 +            try:
   2.120 +                response = contactScanserver(self.__LOCAL_SCANSERVER_URL, fields)
   2.121 +            except:
   2.122 +                self.__LOG.error ("Connection to local scan server could not be established.")
   2.123 +                self.__LOG.error ("Exception: %s" %(sys.exc_info()[0]))
   2.124 +                return retval
   2.125 +        
   2.126 +    
   2.127 +        if response.status == self.__STATUS_CODE_OK:
   2.128 +            retval["infected"] = False
   2.129 +        elif response.status == self.__STATUS_CODE_INFECTED:
   2.130 +            # Parse xml for info if desired
   2.131 +            #contentXML = r.content
   2.132 +            #root = ET.fromstring(contentXML)
   2.133 +            #status = root[1][2].text
   2.134 +            retval["infected"] = True
   2.135 +        else:
   2.136 +            self.__LOG.error ("Connection error to scan server.")
   2.137 +    
   2.138 +        if (retval["infected"] == True):
   2.139 +            self.__LOG.error ("Virus found, denying access.")
   2.140 +        else:
   2.141 +            self.__LOG.debug ("No virus found.")
   2.142 +        
   2.143 +        return retval
   2.144 +
   2.145 +    
   2.146 +