ikarusscanner/IkarusScanner.py
author ft
Tue, 04 Nov 2014 16:28:40 +0100
changeset 22 23028352807f
permissions -rwxr-xr-x
initial commit of osefcs package
ft@22
     1
#!/usr/bin/python
ft@22
     2
ft@22
     3
# ------------------------------------------------------------
ft@22
     4
# opensecurity package file
ft@22
     5
#
ft@22
     6
# Autor:  Karlberger Christoph <Karlberger.C@ikarus.at>
ft@22
     7
#         X-Net Services GmbH <office@x-net.at>
ft@22
     8
#
ft@22
     9
# Copyright 2013-2014 X-Net and AIT Austrian Institute of Technology
ft@22
    10
#
ft@22
    11
#     IKARUS Security Software GmbH
ft@22
    12
#     Blechturmgasse 11
ft@22
    13
#     1050 Wien
ft@22
    14
#     AUSTRIA
ft@22
    15
#     http://www.ikarussecurity.com
ft@22
    16
#
ft@22
    17
#     X-Net Technologies GmbH
ft@22
    18
#     Elisabethstrasse 1
ft@22
    19
#     4020 Linz
ft@22
    20
#     AUSTRIA
ft@22
    21
#     https://www.x-net.at
ft@22
    22
#
ft@22
    23
#     AIT Austrian Institute of Technology
ft@22
    24
#     Donau City Strasse 1
ft@22
    25
#     1220 Wien
ft@22
    26
#     AUSTRIA
ft@22
    27
#     http://www.ait.ac.at
ft@22
    28
#
ft@22
    29
#
ft@22
    30
# Licensed under the Apache License, Version 2.0 (the "License");
ft@22
    31
# you may not use this file except in compliance with the License.
ft@22
    32
# You may obtain a copy of the License at
ft@22
    33
#
ft@22
    34
#    http://www.apache.org/licenses/LICENSE-2.0
ft@22
    35
#
ft@22
    36
# Unless required by applicable law or agreed to in writing, software
ft@22
    37
# distributed under the License is distributed on an "AS IS" BASIS,
ft@22
    38
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
ft@22
    39
# See the License for the specific language governing permissions and
ft@22
    40
# limitations under the License.
ft@22
    41
# ------------------------------------------------------------
ft@22
    42
ft@22
    43
import ConfigParser
ft@22
    44
ft@22
    45
import sys
ft@22
    46
ft@22
    47
import logging
ft@22
    48
import os
ft@22
    49
import errno
ft@22
    50
import time
ft@22
    51
ft@22
    52
import urllib3
ft@22
    53
import xml.etree.ElementTree as ET
ft@22
    54
ft@22
    55
class IkarusScanner:
ft@22
    56
    
ft@22
    57
    # User the existing logger  instance
ft@22
    58
    __LOG = logging.getLogger("IkarusScanner")
ft@22
    59
    
ft@22
    60
    __MINOPTS = { "Main" : ["LocalScanserverURL", "RemoteScanserverURL", "MaxFileSize", "RetryTimeout"]}
ft@22
    61
    __CONFIG_NOT_READABLE = "Configfile is not readable"
ft@22
    62
    __CONFIG_WRONG = "Something is wrong with the config"
ft@22
    63
    __CONFIG_MISSING = "Section: \"%s\" Option: \"%s\" in configfile is missing"
ft@22
    64
    __LOCAL_SCANSERVER_URL = ""
ft@22
    65
    __REMOTE_SCANSERVER_URL = ""
ft@22
    66
    __STATUS_CODE_OK = 200
ft@22
    67
    __STATUS_CODE_INFECTED = 210
ft@22
    68
    __STATUS_CODE_NOT_FOUND = 404
ft@22
    69
    __MAX_SCAN_FILE_SIZE = 50 * 0x100000
ft@22
    70
    __SCANSERVER_RETRY_TIMEOUT = 60
ft@22
    71
    
ft@22
    72
    # Global http pool manager used to connect to the scan server
ft@22
    73
    __remoteScanserverReachable = True
ft@22
    74
    __scanserverTimestamp = 0
ft@22
    75
    __httpPool = urllib3.PoolManager(num_pools = 1, timeout = 3)
ft@22
    76
    
ft@22
    77
    def __init__ (self, scanner_config_path):
ft@22
    78
        config = self.loadConfig (scanner_config_path)
ft@22
    79
    
ft@22
    80
        self.__scanserverTimestamp = time.time()
ft@22
    81
    
ft@22
    82
        self.__LOCAL_SCANSERVER_URL = config.get("Main", "LocalScanserverURL")
ft@22
    83
        self.__REMOTE_SCANSERVER_URL = config.get("Main", "RemoteScanserverURL")
ft@22
    84
        self.__SCANSERVER_RETRY_TIMEOUT = int(config.get("Main", "RetryTimeout"))
ft@22
    85
    
ft@22
    86
        # Convert file size from MB to byte
ft@22
    87
        self.__MAX_SCAN_FILE_SIZE = int(config.get("Main", "MaxFileSize")) * 0x100000
ft@22
    88
    
ft@22
    89
ft@22
    90
    def checkMinimumOptions (self, config):
ft@22
    91
        for section, options in self.__MINOPTS.iteritems ():
ft@22
    92
            for option in options:
ft@22
    93
                if (config.has_option(section, option) == False):
ft@22
    94
                    self.__LOG.error (self.__CONFIG_MISSING % (section, option))
ft@22
    95
                    exit (129)
ft@22
    96
ft@22
    97
    def loadConfig (self, scanner_config_path):
ft@22
    98
ft@22
    99
        configfile = scanner_config_path
ft@22
   100
        config = ConfigParser.SafeConfigParser ()
ft@22
   101
    
ft@22
   102
        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@22
   103
            self.__LOG.error(self.__CONFIG_NOT_READABLE);
ft@22
   104
            raise SystemError(self.__CONFIG_NOT_READABLE)
ft@22
   105
    
ft@22
   106
        try:
ft@22
   107
            config.read (scanner_config_path)
ft@22
   108
        except Exception, e:
ft@22
   109
            self.__LOG.error("Error: %s" % (e));
ft@22
   110
            raise SystemError("Error: %s" % (e))
ft@22
   111
ft@22
   112
        self.checkMinimumOptions (config)
ft@22
   113
    
ft@22
   114
        return config
ft@22
   115
ft@22
   116
    def contactScanserver(self, url, fields):
ft@22
   117
        self.__LOG.debug("Contacting server %s" % url)
ft@22
   118
        return self.__httpPool.request_encode_body('POST', url, fields = fields, retries = 0)
ft@22
   119
    
ft@22
   120
    def scanFile (self, path, fileobject):
ft@22
   121
        return self.scanFileIkarus (path, fileobject)
ft@22
   122
ft@22
   123
    def scanFileIkarus (self, path, fileobject):
ft@22
   124
        retval = { "infected" : False, "virusname" : "Unknown" }
ft@22
   125
        self.__LOG.debug ("Scan File: %s" % (path))
ft@22
   126
    
ft@22
   127
        if (os.fstat(fileobject.fileno()).st_size > self.__MAX_SCAN_FILE_SIZE):
ft@22
   128
            self.__LOG.info("File max size exceeded. The file is not scanned.")
ft@22
   129
            retval["infected"] = False
ft@22
   130
            retval["virusname"] = "File is to big to be scanned."
ft@22
   131
            return retval
ft@22
   132
    
ft@22
   133
        fields = { 'up_file' : fileobject.read() }
ft@22
   134
    
ft@22
   135
        if (self.__remoteScanserverReachable == False) and ((self.__scanserverTimestamp + self.__SCANSERVER_RETRY_TIMEOUT) < time.time()):
ft@22
   136
            self.__remoteScanserverReachable = True
ft@22
   137
    
ft@22
   138
        if self.__remoteScanserverReachable:
ft@22
   139
            try:
ft@22
   140
                response = self.contactScanserver(self.__REMOTE_SCANSERVER_URL, fields)
ft@22
   141
                # We should catch socket.error here, but this does not work. Needs checking.
ft@22
   142
            except:
ft@22
   143
                self.__LOG.info("Remote scan server unreachable, using local scan server.")
ft@22
   144
                self.__LOG.debug("Exception: %s: %s" % (sys.exc_info()[0], sys.exc_info()[1]))
ft@22
   145
                self.__LOG.info("Next check for remote server in %s seconds." % (self.__SCANSERVER_RETRY_TIMEOUT))
ft@22
   146
                
ft@22
   147
                self.__remoteScanserverReachable = False
ft@22
   148
                self.__scanserverTimestamp = time.time()
ft@22
   149
    
ft@22
   150
                try:
ft@22
   151
                    response = self.contactScanserver(self.__LOCAL_SCANSERVER_URL, fields)
ft@22
   152
                except:
ft@22
   153
                    self.__LOG.error ("Connection to local scan server could not be established.")
ft@22
   154
                    self.__LOG.debug ("Exception: %s" % (sys.exc_info()[0]))
ft@22
   155
                    return retval
ft@22
   156
        else:
ft@22
   157
            try:
ft@22
   158
                response = self.contactScanserver(self.__LOCAL_SCANSERVER_URL, fields)
ft@22
   159
            except:
ft@22
   160
                self.__LOG.error ("Connection to local scan server could not be established.")
ft@22
   161
                self.__LOG.error ("Exception: %s" %(sys.exc_info()[0]))
ft@22
   162
                return retval
ft@22
   163
        
ft@22
   164
    
ft@22
   165
        if response.status == self.__STATUS_CODE_OK:
ft@22
   166
            retval["infected"] = False
ft@22
   167
        elif response.status == self.__STATUS_CODE_INFECTED:
ft@22
   168
            # Parse xml for info
ft@22
   169
            root = ET.fromstring(response.data)
ft@22
   170
            
ft@22
   171
            # this should be done in a more generic way
ft@22
   172
            retval["virusname"] = root[1][3][0].text
ft@22
   173
            retval["infected"] = True
ft@22
   174
        else:
ft@22
   175
            self.__LOG.error ("Connection error to scan server.")
ft@22
   176
    
ft@22
   177
        if (retval["infected"] == True):
ft@22
   178
            self.__LOG.error ("Virus found, denying access.")
ft@22
   179
        else:
ft@22
   180
            self.__LOG.debug ("No virus found.")
ft@22
   181
        
ft@22
   182
        return retval
ft@22
   183
ft@22
   184
    
ft@22
   185