src/IkarusScanner.py
author ft
Tue, 18 Feb 2014 15:38:00 +0100
changeset 0 ca2023eb2463
child 1 57ad4aea86dd
permissions -rwxr-xr-x
Initial commit
working ikarus scanner engine
ft@0
     1
#!/usr/bin/python
ft@0
     2
ft@0
     3
import ConfigParser
ft@0
     4
ft@0
     5
import sys
ft@0
     6
ft@0
     7
import logging
ft@0
     8
import os
ft@0
     9
import errno
ft@0
    10
import time
ft@0
    11
ft@0
    12
import urllib3
ft@0
    13
ft@0
    14
class IkarusScanner:
ft@0
    15
    
ft@0
    16
    # User the existing logger  instance
ft@0
    17
    __LOG = logging.getLogger("IkarusScanner")
ft@0
    18
    
ft@0
    19
    __MINOPTS = { "Main" : ["LocalScanserverURL", "RemoteScanserverURL", "MaxFileSize", "RetryTimeout"]}
ft@0
    20
    __CONFIG_NOT_READABLE = "Configfile is not readable"
ft@0
    21
    __CONFIG_WRONG = "Something is wrong with the config"
ft@0
    22
    __CONFIG_MISSING = "Section: \"%s\" Option: \"%s\" in configfile is missing"
ft@0
    23
    __LOCAL_SCANSERVER_URL = ""
ft@0
    24
    __REMOTE_SCANSERVER_URL = ""
ft@0
    25
    __STATUS_CODE_OK = 200
ft@0
    26
    __STATUS_CODE_INFECTED = 210
ft@0
    27
    __STATUS_CODE_NOT_FOUND = 404
ft@0
    28
    __MAX_SCAN_FILE_SIZE = 50 * 0x100000
ft@0
    29
    __SCANSERVER_RETRY_TIMEOUT = 60
ft@0
    30
    
ft@0
    31
    # Global http pool manager used to connect to the scan server
ft@0
    32
    __remoteScanserverReachable = True
ft@0
    33
    __scanserverTimestamp = 0
ft@0
    34
    __httpPool = urllib3.PoolManager(num_pools = 1, timeout = 3)
ft@0
    35
    
ft@0
    36
    def __init__ (self, scanner_config_path):
ft@0
    37
        config = self.loadConfig (scanner_config_path)
ft@0
    38
    
ft@0
    39
        self.__scanserverTimestamp = time.time()
ft@0
    40
    
ft@0
    41
        __LOCAL_SCANSERVER_URL = config.get("Main", "LocalScanserverURL")
ft@0
    42
        __REMOTE_SCANSERVER_URL = config.get("Main", "RemoteScanserverURL")
ft@0
    43
        __SCANSERVER_RETRY_TIMEOUT = int(config.get("Main", "RetryTimeout"))
ft@0
    44
    
ft@0
    45
        # Convert file size from MB to byte
ft@0
    46
        __MAX_SCAN_FILE_SIZE = int(config.get("Main", "MaxFileSize")) * 0x100000
ft@0
    47
    
ft@0
    48
ft@0
    49
    def checkMinimumOptions (self, config):
ft@0
    50
        for section, options in self.__MINOPTS.iteritems ():
ft@0
    51
            for option in options:
ft@0
    52
                if (config.has_option(section, option) == False):
ft@0
    53
                    self.__LOG.error (self.__CONFIG_MISSING % (section, option))
ft@0
    54
                    exit (129)
ft@0
    55
ft@0
    56
    def loadConfig (self, scanner_config_path):
ft@0
    57
ft@0
    58
        configfile = scanner_config_path
ft@0
    59
        config = ConfigParser.SafeConfigParser ()
ft@0
    60
    
ft@0
    61
        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)):
ft@0
    62
            self.__LOG.error(self.__CONFIG_NOT_READABLE);
ft@0
    63
            raise SystemError(self.__CONFIG_NOT_READABLE)
ft@0
    64
    
ft@0
    65
        try:
ft@0
    66
            config.read (scanner_config_path)
ft@0
    67
        except Exception, e:
ft@0
    68
            self.__LOG.error("Error: %s" % (e));
ft@0
    69
            raise SystemError("Error: %s" % (e))
ft@0
    70
ft@0
    71
        self.checkMinimumOptions (config)
ft@0
    72
    
ft@0
    73
        return config
ft@0
    74
ft@0
    75
    def contactScanserver(self, url, fields):
ft@0
    76
        return httpPool.request_encode_body('POST', url, fields = fields, retries = 0)
ft@0
    77
    
ft@0
    78
    def scanFile (self, path, fileobject):
ft@0
    79
        return self.scanFileIkarus (path, fileobject)
ft@0
    80
ft@0
    81
    def scanFileIkarus (self, path, fileobject):
ft@0
    82
        retval = { "infected" : False, "virusname" : "Unknown" }
ft@0
    83
        self.__LOG.debug ("Scan File: %s" % (path))
ft@0
    84
        
ft@0
    85
        
ft@0
    86
    
ft@0
    87
        if (os.fstat(fileobject.fileno()).st_size > self.__MAX_SCAN_FILE_SIZE):
ft@0
    88
            self.__LOG.info("File max size exceeded. The file is not scanned.")
ft@0
    89
            retval["infected"] = True
ft@0
    90
            retval["virusname"] = "File is to big to be scanned."
ft@0
    91
            return retval
ft@0
    92
    
ft@0
    93
        fields = { 'up_file' : fileobject.read() }
ft@0
    94
    
ft@0
    95
        if (self.__remoteScanserverReachable == False) and ((self.__scanserverTimestamp + self.__SCANSERVER_RETRY_TIMEOUT) < time.time()):
ft@0
    96
            self.__remoteScanserverReachable = True
ft@0
    97
    
ft@0
    98
        if self.__remoteScanserverReachable:
ft@0
    99
            try:
ft@0
   100
                response = contactScanserver(self.__REMOTE_SCANSERVER_URL, fields)
ft@0
   101
                # We should catch socket.error here, but this does not work. Needs checking.
ft@0
   102
            except:
ft@0
   103
                self.__LOG.info("Remote scan server unreachable, using local scan server.")
ft@0
   104
                self.__LOG.info("Next check for remote server in %s seconds." % (self.__SCANSERVER_RETRY_TIMEOUT))
ft@0
   105
                
ft@0
   106
                self.__remoteScanserverReachable = False
ft@0
   107
                self.__scanserverTimestamp = time.time()
ft@0
   108
    
ft@0
   109
                try:
ft@0
   110
                    response = contactScanserver(self.__LOCAL_SCANSERVER_URL, fields)
ft@0
   111
                except:
ft@0
   112
                    self.__LOG.error ("Connection to local scan server could not be established.")
ft@0
   113
                    self.__LOG.error ("Exception: %s" %(sys.exc_info()[0]))
ft@0
   114
                    return retval
ft@0
   115
        else:
ft@0
   116
            try:
ft@0
   117
                response = contactScanserver(self.__LOCAL_SCANSERVER_URL, fields)
ft@0
   118
            except:
ft@0
   119
                self.__LOG.error ("Connection to local scan server could not be established.")
ft@0
   120
                self.__LOG.error ("Exception: %s" %(sys.exc_info()[0]))
ft@0
   121
                return retval
ft@0
   122
        
ft@0
   123
    
ft@0
   124
        if response.status == self.__STATUS_CODE_OK:
ft@0
   125
            retval["infected"] = False
ft@0
   126
        elif response.status == self.__STATUS_CODE_INFECTED:
ft@0
   127
            # Parse xml for info if desired
ft@0
   128
            #contentXML = r.content
ft@0
   129
            #root = ET.fromstring(contentXML)
ft@0
   130
            #status = root[1][2].text
ft@0
   131
            retval["infected"] = True
ft@0
   132
        else:
ft@0
   133
            self.__LOG.error ("Connection error to scan server.")
ft@0
   134
    
ft@0
   135
        if (retval["infected"] == True):
ft@0
   136
            self.__LOG.error ("Virus found, denying access.")
ft@0
   137
        else:
ft@0
   138
            self.__LOG.debug ("No virus found.")
ft@0
   139
        
ft@0
   140
        return retval
ft@0
   141
ft@0
   142
    
ft@0
   143