src/IkarusScanner.py
author ck
Mon, 24 Feb 2014 16:47:02 +0100
changeset 1 57ad4aea86dd
parent 0 ca2023eb2463
child 2 0c88ae943fa6
permissions -rwxr-xr-x
Added virus name to the return value of the scan function.
Fixed errors.
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
ck@1
    13
import xml.etree.ElementTree as ET
ft@0
    14
ft@0
    15
class IkarusScanner:
ft@0
    16
    
ft@0
    17
    # User the existing logger  instance
ft@0
    18
    __LOG = logging.getLogger("IkarusScanner")
ft@0
    19
    
ft@0
    20
    __MINOPTS = { "Main" : ["LocalScanserverURL", "RemoteScanserverURL", "MaxFileSize", "RetryTimeout"]}
ft@0
    21
    __CONFIG_NOT_READABLE = "Configfile is not readable"
ft@0
    22
    __CONFIG_WRONG = "Something is wrong with the config"
ft@0
    23
    __CONFIG_MISSING = "Section: \"%s\" Option: \"%s\" in configfile is missing"
ft@0
    24
    __LOCAL_SCANSERVER_URL = ""
ft@0
    25
    __REMOTE_SCANSERVER_URL = ""
ft@0
    26
    __STATUS_CODE_OK = 200
ft@0
    27
    __STATUS_CODE_INFECTED = 210
ft@0
    28
    __STATUS_CODE_NOT_FOUND = 404
ft@0
    29
    __MAX_SCAN_FILE_SIZE = 50 * 0x100000
ft@0
    30
    __SCANSERVER_RETRY_TIMEOUT = 60
ft@0
    31
    
ft@0
    32
    # Global http pool manager used to connect to the scan server
ft@0
    33
    __remoteScanserverReachable = True
ft@0
    34
    __scanserverTimestamp = 0
ft@0
    35
    __httpPool = urllib3.PoolManager(num_pools = 1, timeout = 3)
ft@0
    36
    
ft@0
    37
    def __init__ (self, scanner_config_path):
ft@0
    38
        config = self.loadConfig (scanner_config_path)
ft@0
    39
    
ft@0
    40
        self.__scanserverTimestamp = time.time()
ft@0
    41
    
ck@1
    42
        self.__LOCAL_SCANSERVER_URL = config.get("Main", "LocalScanserverURL")
ck@1
    43
        self.__REMOTE_SCANSERVER_URL = config.get("Main", "RemoteScanserverURL")
ck@1
    44
        self.__SCANSERVER_RETRY_TIMEOUT = int(config.get("Main", "RetryTimeout"))
ft@0
    45
    
ft@0
    46
        # Convert file size from MB to byte
ck@1
    47
        self.__MAX_SCAN_FILE_SIZE = int(config.get("Main", "MaxFileSize")) * 0x100000
ft@0
    48
    
ft@0
    49
ft@0
    50
    def checkMinimumOptions (self, config):
ft@0
    51
        for section, options in self.__MINOPTS.iteritems ():
ft@0
    52
            for option in options:
ft@0
    53
                if (config.has_option(section, option) == False):
ft@0
    54
                    self.__LOG.error (self.__CONFIG_MISSING % (section, option))
ft@0
    55
                    exit (129)
ft@0
    56
ft@0
    57
    def loadConfig (self, scanner_config_path):
ft@0
    58
ft@0
    59
        configfile = scanner_config_path
ft@0
    60
        config = ConfigParser.SafeConfigParser ()
ft@0
    61
    
ft@0
    62
        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
    63
            self.__LOG.error(self.__CONFIG_NOT_READABLE);
ft@0
    64
            raise SystemError(self.__CONFIG_NOT_READABLE)
ft@0
    65
    
ft@0
    66
        try:
ft@0
    67
            config.read (scanner_config_path)
ft@0
    68
        except Exception, e:
ft@0
    69
            self.__LOG.error("Error: %s" % (e));
ft@0
    70
            raise SystemError("Error: %s" % (e))
ft@0
    71
ft@0
    72
        self.checkMinimumOptions (config)
ft@0
    73
    
ft@0
    74
        return config
ft@0
    75
ft@0
    76
    def contactScanserver(self, url, fields):
ck@1
    77
        self.__LOG.debug("Contacting server %s" % url)
ck@1
    78
        return self.__httpPool.request_encode_body('POST', url, fields = fields, retries = 0)
ft@0
    79
    
ft@0
    80
    def scanFile (self, path, fileobject):
ft@0
    81
        return self.scanFileIkarus (path, fileobject)
ft@0
    82
ft@0
    83
    def scanFileIkarus (self, path, fileobject):
ft@0
    84
        retval = { "infected" : False, "virusname" : "Unknown" }
ft@0
    85
        self.__LOG.debug ("Scan File: %s" % (path))
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.")
ck@1
    89
            retval["infected"] = False
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:
ck@1
   100
                response = self.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.")
ck@1
   104
                self.__LOG.debug("Exception: %s: %s" % (sys.exc_info()[0], sys.exc_info()[1]))
ft@0
   105
                self.__LOG.info("Next check for remote server in %s seconds." % (self.__SCANSERVER_RETRY_TIMEOUT))
ft@0
   106
                
ft@0
   107
                self.__remoteScanserverReachable = False
ft@0
   108
                self.__scanserverTimestamp = time.time()
ft@0
   109
    
ft@0
   110
                try:
ck@1
   111
                    response = self.contactScanserver(self.__LOCAL_SCANSERVER_URL, fields)
ft@0
   112
                except:
ft@0
   113
                    self.__LOG.error ("Connection to local scan server could not be established.")
ck@1
   114
                    self.__LOG.debug ("Exception: %s" % (sys.exc_info()[0]))
ft@0
   115
                    return retval
ft@0
   116
        else:
ft@0
   117
            try:
ck@1
   118
                response = self.contactScanserver(self.__LOCAL_SCANSERVER_URL, fields)
ft@0
   119
            except:
ft@0
   120
                self.__LOG.error ("Connection to local scan server could not be established.")
ft@0
   121
                self.__LOG.error ("Exception: %s" %(sys.exc_info()[0]))
ft@0
   122
                return retval
ft@0
   123
        
ft@0
   124
    
ft@0
   125
        if response.status == self.__STATUS_CODE_OK:
ft@0
   126
            retval["infected"] = False
ft@0
   127
        elif response.status == self.__STATUS_CODE_INFECTED:
ck@1
   128
            # Parse xml for info
ck@1
   129
            root = ET.fromstring(response.data)
ck@1
   130
            
ck@1
   131
            # this should be done in a more generic way
ck@1
   132
            retval["virusname"] = root[1][3][0].text
ft@0
   133
            retval["infected"] = True
ft@0
   134
        else:
ft@0
   135
            self.__LOG.error ("Connection error to scan server.")
ft@0
   136
    
ft@0
   137
        if (retval["infected"] == True):
ft@0
   138
            self.__LOG.error ("Virus found, denying access.")
ft@0
   139
        else:
ft@0
   140
            self.__LOG.debug ("No virus found.")
ft@0
   141
        
ft@0
   142
        return retval
ft@0
   143
ft@0
   144
    
ft@0
   145