src/OsecFS.py
author ck
Fri, 06 Dec 2013 13:15:45 +0100
changeset 7 e75bc05c279d
parent 6 b4b18827d89d
child 8 0a5ba0ef1058
permissions -rwxr-xr-x
Shorter timeout for remote scan server.
Limit number of connection pools to 1.
Remote server is not contacted for a certain time when connection fails.
ft@0
     1
#!/usr/bin/python
ft@0
     2
ft@0
     3
from fuse import Fuse
ft@0
     4
import fuse
ft@0
     5
ft@0
     6
import ConfigParser
ft@0
     7
ft@0
     8
import sys
ft@0
     9
ft@0
    10
import logging
ft@0
    11
import os
ft@0
    12
import errno
ck@7
    13
import time
ft@0
    14
ft@0
    15
# ToDo replace with ikarus
ck@1
    16
#import pyclamav
ft@0
    17
import subprocess
ft@0
    18
ck@5
    19
import urllib3
ck@1
    20
ck@1
    21
ft@3
    22
MINOPTS = { "Main" : ["Logfile", "Mountpoint", "Rootpath", "LocalScanserverURL", "RemoteScanserverURL", "ReadOnly"]}
ft@0
    23
ft@0
    24
CONFIG_NOT_READABLE = "Configfile is not readable"
ft@0
    25
CONFIG_WRONG = "Something is wrong with the config"
ft@0
    26
CONFIG_MISSING = "Section: \"%s\" Option: \"%s\" in configfile is missing"
ft@0
    27
LOG = None
ck@1
    28
LOCAL_SCANSERVER_URL = ""
ck@1
    29
REMOTE_SCANSERVER_URL = ""
ck@1
    30
STATUS_CODE_OK = 200
ck@1
    31
STATUS_CODE_INFECTED = 210
ck@1
    32
STATUS_CODE_NOT_FOUND = 404
ft@0
    33
ft@0
    34
SYSTEM_FILE_COMMAND = "file"
ft@0
    35
ck@7
    36
MAX_SCAN_FILE_SIZE = 50 * 0x100000
ck@7
    37
SCANSERVER_RETRY_TIMEOUT = 60
ck@7
    38
ck@5
    39
# Global http pool manager used to connect to the scan server
ck@7
    40
remoteScanserverReachable = True
ck@7
    41
scanserverTimestamp = 0
ck@7
    42
httpPool = urllib3.PoolManager(num_pools = 1, timeout = 3)
ft@0
    43
ft@0
    44
def checkMinimumOptions (config):
ft@0
    45
    for section, options in MINOPTS.iteritems ():
ft@0
    46
        for option in options:
ft@0
    47
            if (config.has_option(section, option) == False):
ft@0
    48
                print (CONFIG_MISSING % (section, option))
ft@0
    49
                exit (129)
ft@0
    50
ft@0
    51
def printUsage ():
ft@0
    52
    print ("Usage:")
ft@3
    53
    print ("%s configfile mountpath ro/rw" % (sys.argv[0]))
ft@0
    54
    exit (128)
ft@0
    55
ft@0
    56
def loadConfig ():
ft@0
    57
    print ("load config")
ft@0
    58
ft@3
    59
    if (len (sys.argv) < 4):
ft@0
    60
        printUsage ()
ft@0
    61
ft@0
    62
    configfile = sys.argv[1]
ft@0
    63
    config = ConfigParser.SafeConfigParser ()
ft@0
    64
ft@0
    65
    if ((os.path.exists (configfile) == False) or (os.path.isfile (configfile) == False) or (os.access (configfile, os.R_OK) == False)):
ft@0
    66
        print (CONFIG_NOT_READABLE)
ft@0
    67
        printUsage ()
ft@0
    68
ft@0
    69
    try:
ft@0
    70
        config.read (sys.argv[1])
ft@0
    71
    except Exception, e:
ft@0
    72
        print (CONFIG_WRONG)
ft@0
    73
        print ("Error: %s" % (e))
ft@0
    74
ft@3
    75
ft@3
    76
    config.set("Main", "Mountpoint", sys.argv[2])
ft@3
    77
    if (sys.argv[3] == "rw"):
ft@3
    78
        config.set("Main", "ReadOnly", "false")
ft@3
    79
    else:
ft@3
    80
        config.set("Main", "ReadOnly", "true")
ft@3
    81
ft@0
    82
    checkMinimumOptions (config)
ft@0
    83
ft@0
    84
    return config
ft@0
    85
ft@0
    86
def initLog (config):
ft@0
    87
    print ("init log")
ft@0
    88
ft@0
    89
    global LOG
ft@0
    90
    logfile = config.get("Main", "Logfile")
ft@0
    91
ft@0
    92
    # ToDo move log level and maybe other things to config file
ft@0
    93
    logging.basicConfig(
ft@0
    94
                        level = logging.DEBUG,
ft@0
    95
                        format = "%(asctime)s %(name)-12s %(funcName)-15s %(levelname)-8s %(message)s",
ft@0
    96
                        datefmt = "%Y-%m-%d %H:%M:%S",
ft@0
    97
                        filename = logfile,
ft@0
    98
                        filemode = "a+",
ft@0
    99
    )
ft@0
   100
    LOG = logging.getLogger("fuse_main")
ft@0
   101
ft@0
   102
ft@0
   103
def fixPath (path):
ft@0
   104
    return ".%s" % (path)
ft@0
   105
ft@0
   106
def rootPath (rootpath, path):
ft@0
   107
    return "%s%s" % (rootpath, path)
ft@0
   108
ft@0
   109
def flag2mode (flags):
ft@0
   110
    md = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
ft@0
   111
    m = md[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
ft@0
   112
ft@0
   113
    if flags | os.O_APPEND:
ft@0
   114
        m = m.replace('w', 'a', 1)
ft@0
   115
ft@0
   116
    return m
ck@7
   117
    
ck@7
   118
def contactScanserver(url, fields):
ck@7
   119
    return httpPool.request_encode_body('POST', url, fields = fields, retries = 0)
ck@7
   120
    
ft@0
   121
ck@2
   122
def scanFileIkarus (path, fileobject):
ck@7
   123
    global remoteScanserverReachable
ck@7
   124
    global scanserverTimestamp
ck@7
   125
ck@2
   126
    infected = False
ck@2
   127
    LOG.debug ("Scan File: %s" % (path))
ft@0
   128
ck@5
   129
    if (os.fstat(fileobject.fileno()).st_size > MAX_SCAN_FILE_SIZE):
ck@5
   130
        LOG.info("File max size exceeded. The file is not scanned.")
ft@4
   131
        return False
ft@4
   132
ck@6
   133
    fields = { 'up_file' : fileobject.read() }
ck@1
   134
ck@7
   135
    if (remoteScanserverReachable == False) and ((scanserverTimestamp + SCANSERVER_RETRY_TIMEOUT) < time.time()):
ck@7
   136
        remoteScanserverReachable = True
ck@5
   137
ck@7
   138
    if remoteScanserverReachable:
ck@5
   139
        try:
ck@7
   140
            response = contactScanserver(REMOTE_SCANSERVER_URL, fields)
ck@7
   141
            # We should catch socket.error here, but this does not work. Needs checking.
ck@7
   142
        except:
ck@7
   143
            LOG.info("Remote scan server unreachable, using local scan server.")
ck@7
   144
            LOG.info("Next check for remote server in %s seconds." % (SCANSERVER_RETRY_TIMEOUT))
ck@7
   145
            
ck@7
   146
            remoteScanserverReachable = False
ck@7
   147
            scanserverTimestamp = time.time()
ck@7
   148
ck@7
   149
            try:
ck@7
   150
                response = contactScanserver(LOCAL_SCANSERVER_URL, fields)
ck@7
   151
            except:
ck@7
   152
                LOG.error ("Connection to local scan server could not be established.")
ck@7
   153
                LOG.error ("Exception: %s" %(sys.exc_info()[0]))
ck@7
   154
                return False
ck@7
   155
    else:
ck@7
   156
        try:
ck@7
   157
            response = contactScanserver(LOCAL_SCANSERVER_URL, fields)
ck@5
   158
        except:
ck@5
   159
            LOG.error ("Connection to local scan server could not be established.")
ck@5
   160
            LOG.error ("Exception: %s" %(sys.exc_info()[0]))
ck@5
   161
            return False
ck@7
   162
    
ck@5
   163
ck@5
   164
    if response.status == STATUS_CODE_OK:
ck@2
   165
        infected = False
ck@5
   166
    elif response.status == STATUS_CODE_INFECTED:
ck@1
   167
        # Parse xml for info if desired
ck@1
   168
        #contentXML = r.content
ck@1
   169
        #root = ET.fromstring(contentXML)
ck@1
   170
        #status = root[1][2].text
ck@2
   171
        infected = True
ck@1
   172
    else:
ck@2
   173
        LOG.error ("Connection error to scan server.")
ck@1
   174
ck@2
   175
    if (infected == True):
ck@2
   176
        LOG.error ("Virus found, denying access.")
ck@2
   177
    else:
ck@2
   178
        LOG.debug ("No virus found.")
ck@2
   179
ck@2
   180
    return infected
ck@2
   181
ck@2
   182
def scanFileClamAV (path):
ft@0
   183
    infected = False
ft@0
   184
ft@0
   185
    LOG.debug ("Scan File: %s" % (path))
ft@0
   186
ck@2
   187
    result = pyclamav.scanfile (path)
ft@0
   188
    LOG.debug ("Result of file \"%s\": %s" % (path, result))
ck@2
   189
    if (result[0] != 0):
ft@0
   190
        infected = True
ft@0
   191
ft@0
   192
    if (infected == True):
ck@2
   193
        LOG.error ("Virus found, deny Access %s" % (result,))
ft@0
   194
ft@0
   195
    return infected
ft@0
   196
ft@0
   197
def whitelistFile (path):
ft@0
   198
    whitelisted = False;
ft@0
   199
ft@0
   200
    LOG.debug ("Execute \"%s\" command on \"%s\"" %(SYSTEM_FILE_COMMAND, path))
ft@0
   201
    
ft@0
   202
    result = None
ft@0
   203
    try:
ft@0
   204
        result = subprocess.check_output ([SYSTEM_FILE_COMMAND, path]);
ft@0
   205
        # ToDo replace with real whitelist
ft@0
   206
        whitelisted = True
ft@0
   207
    except Exception as e:
ft@0
   208
        LOG.error ("Call returns with an error!")
ft@0
   209
        LOG.error (e)
ft@0
   210
ft@0
   211
    LOG.debug ("Type: %s" %(result))
ft@0
   212
ft@0
   213
    return whitelisted
ft@0
   214
ft@0
   215
class OsecFS (Fuse):
ft@0
   216
ft@0
   217
    __rootpath = None
ft@0
   218
ft@0
   219
    # default fuse init
ft@0
   220
    def __init__(self, rootpath, *args, **kw):
ft@0
   221
        self.__rootpath = rootpath
ft@0
   222
        Fuse.__init__ (self, *args, **kw)
ft@0
   223
        LOG.debug ("Init complete.")
ft@0
   224
ft@0
   225
    # defines that our working directory will be the __rootpath
ft@0
   226
    def fsinit(self):
ft@0
   227
        os.chdir (self.__rootpath)
ft@0
   228
ft@0
   229
    def getattr(self, path):
ft@0
   230
        LOG.debug ("*** getattr (%s)" % (fixPath (path)))
ft@0
   231
        return os.lstat (fixPath (path));
ft@0
   232
ft@0
   233
    def getdir(self, path):
ft@0
   234
        LOG.debug ("*** getdir (%s)" % (path));
ft@0
   235
        return os.listdir (fixPath (path))
ft@0
   236
ft@0
   237
    def readdir(self, path, offset):
ft@0
   238
        LOG.debug ("*** readdir (%s %s)" % (path, offset));
ft@0
   239
        for e in os.listdir (fixPath (path)):
ft@0
   240
            yield fuse.Direntry(e)
ft@0
   241
ft@0
   242
    def chmod (self, path, mode):
ft@0
   243
        LOG.debug ("*** chmod %s %s" % (path, oct(mode)))
ft@3
   244
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   245
            return -errno.EACCES
ft@0
   246
        os.chmod (fixPath (path), mode)
ft@0
   247
ft@0
   248
    def chown (self, path, uid, gid):
ft@0
   249
        LOG.debug ("*** chown %s %s %s" % (path, uid, gid))
ft@3
   250
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   251
            return -errno.EACCES
ft@0
   252
        os.chown (fixPath (path), uid, gid)
ft@0
   253
ft@0
   254
    def link (self, targetPath, linkPath):
ft@0
   255
        LOG.debug ("*** link %s %s" % (targetPath, linkPath))
ft@3
   256
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   257
            return -errno.EACCES
ft@0
   258
        os.link (fixPath (targetPath), fixPath (linkPath))
ft@0
   259
ft@0
   260
    def mkdir (self, path, mode):
ft@0
   261
        LOG.debug ("*** mkdir %s %s" % (path, oct(mode)))
ft@3
   262
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   263
            return -errno.EACCES
ft@0
   264
        os.mkdir (fixPath (path), mode)
ft@0
   265
ft@0
   266
    def mknod (self, path, mode, dev):
ft@0
   267
        LOG.debug ("*** mknod %s %s %s" % (path, oct (mode), dev))
ft@3
   268
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   269
            return -errno.EACCES
ft@0
   270
        os.mknod (fixPath (path), mode, dev)
ft@0
   271
ft@0
   272
    # to implement virus scan
ft@0
   273
    def open (self, path, flags):
ft@0
   274
        LOG.debug ("*** open %s %s" % (path, oct (flags)))
ft@0
   275
        self.file = os.fdopen (os.open (fixPath (path), flags), flag2mode (flags))
ft@0
   276
        self.fd = self.file.fileno ()
ft@0
   277
ck@2
   278
        infected = scanFileIkarus (rootPath(self.__rootpath, path), self.file)
ck@2
   279
        #infected = scanFileClamAV (rootPath(self.__rootpath, path))
ft@0
   280
        if (infected == True):
ft@0
   281
            self.file.close ()
ft@0
   282
            return -errno.EACCES
ft@0
   283
        
ft@0
   284
        whitelisted = whitelistFile (rootPath(self.__rootpath, path))
ft@0
   285
        if (whitelisted == False):
ft@0
   286
            self.file.close ()
ft@0
   287
            return -errno.EACCES
ft@0
   288
ft@0
   289
    def read (self, path, length, offset):
ft@0
   290
        LOG.debug ("*** read %s %s %s" % (path, length, offset))
ft@0
   291
        self.file.seek (offset)
ft@0
   292
        return self.file.read (length)
ft@0
   293
ft@0
   294
    def readlink (self, path):
ft@0
   295
        LOG.debug ("*** readlink %s" % (path))
ft@0
   296
        return os.readlink (fixPath (path))
ft@0
   297
ft@0
   298
    def release (self, path, flags):
ft@0
   299
        LOG.debug ("*** release %s %s" % (path, oct (flags)))
ft@0
   300
        self.file.close ()
ft@0
   301
ft@0
   302
    def rename (self, oldPath, newPath):
ft@3
   303
        LOG.debug ("*** rename %s %s %s" % (oldPath, newPath, config.get("Main", "ReadOnly")))
ft@3
   304
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   305
            return -errno.EACCES
ft@0
   306
        os.rename (fixPath (oldPath), fixPath (newPath))
ft@0
   307
ft@0
   308
    def rmdir (self, path):
ft@3
   309
        LOG.debug ("*** rmdir %s %s" % (path, config.get("Main", "ReadOnly")))
ft@3
   310
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   311
            return -errno.EACCES
ft@0
   312
        os.rmdir (fixPath (path))
ft@0
   313
ft@0
   314
    def statfs (self):
ft@0
   315
        LOG.debug ("*** statfs")
ft@0
   316
        return os.statvfs(".")
ft@0
   317
ft@0
   318
    def symlink (self, targetPath, linkPath):
ft@3
   319
        LOG.debug ("*** symlink %s %s %s" % (targetPath, linkPath, config.get("Main", "ReadOnly")))
ft@3
   320
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   321
            return -errno.EACCES
ft@0
   322
        os.symlink (fixPath (targetPath), fixPath (linkPath))
ft@0
   323
ft@0
   324
    def truncate (self, path, length):
ft@3
   325
        LOG.debug ("*** truncate %s %s %s" % (path, length, config.get("Main", "ReadOnly")))
ft@3
   326
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   327
            return -errno.EACCES
ft@0
   328
        f = open (fixPath (path), "a")
ft@0
   329
        f.truncate (length)
ft@0
   330
        f.close ()
ft@0
   331
ft@0
   332
    def unlink (self, path):
ft@3
   333
        LOG.debug ("*** unlink %s %s" % (path, config.get("Main", "ReadOnly")))
ft@3
   334
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   335
            return -errno.EACCES
ft@0
   336
        os.unlink (fixPath (path))
ft@0
   337
ft@0
   338
    def utime (self, path, times):
ft@0
   339
        LOG.debug ("*** utime %s %s" % (path, times))
ft@0
   340
        os.utime (fixPath (path), times)
ft@0
   341
ft@0
   342
    def write (self, path, buf, offset):
ft@3
   343
        LOG.debug ("*** write %s %s %s %s" % (path, buf, offset, config.get("Main", "ReadOnly")))
ft@3
   344
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   345
            self.file.close()
ft@3
   346
            return -errno.EACCES
ft@0
   347
        self.file.seek (offset)
ft@0
   348
        self.file.write (buf)
ft@0
   349
        return len (buf)
ft@0
   350
ft@0
   351
    def access (self, path, mode):
ft@0
   352
        LOG.debug ("*** access %s %s" % (path, oct (mode)))
ft@0
   353
        if not os.access (fixPath (path), mode):
ft@0
   354
            return -errno.EACCES
ft@0
   355
ft@0
   356
    def create (self, path, flags, mode):
ft@3
   357
        LOG.debug ("*** create %s %s %s %s %s" % (fixPath (path), oct (flags), oct (mode), flag2mode (flags), config.get("Main", "ReadOnly")))
ft@3
   358
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   359
            return -errno.EACCES
ft@0
   360
        self.file = os.fdopen (os.open (fixPath (path), flags, mode), flag2mode (flags))
ft@0
   361
        self.fd = self.file.fileno ()
ft@0
   362
ft@0
   363
ft@0
   364
if __name__ == "__main__":
ft@0
   365
    # Set api version
ft@0
   366
    fuse.fuse_python_api = (0, 2)
ft@0
   367
    fuse.feature_assert ('stateful_files', 'has_init')
ft@0
   368
ft@0
   369
    config = loadConfig ()
ft@0
   370
    initLog (config)
ft@0
   371
ck@7
   372
    scanserverTimestamp = time.time()
ck@7
   373
ck@1
   374
    LOCAL_SCANSERVER_URL = config.get("Main", "LocalScanserverURL")
ck@1
   375
    REMOTE_SCANSERVER_URL = config.get("Main", "RemoteScanserverURL")
ck@7
   376
    SCANSERVER_RETRY_TIMEOUT = int(config.get("Main", "RetryTimeout"))
ck@1
   377
ck@5
   378
    # Convert file size from MB to byte
ck@5
   379
    MAX_SCAN_FILE_SIZE = int(config.get("Main", "MaxFileSize")) * 0x100000
ck@7
   380
    
ft@0
   381
    osecfs = OsecFS (config.get ("Main", "Rootpath"))
ft@0
   382
    osecfs.flags = 0
ft@0
   383
    osecfs.multithreaded = 0
ft@0
   384
ft@0
   385
    # osecfs.parser.add_option (mountopt=config.get("Main", "Mountpoint"),
ft@0
   386
    #                      metavar="PATH",
ft@0
   387
    #                      default=config.get("Main", "Rootpath"),
ft@0
   388
    #                      help="mirror filesystem from under PATH [default: %default]")
ft@0
   389
    # osecfs.parse(values=osecfs, errex=1)
ft@0
   390
ft@0
   391
    fuse_args = [sys.argv[0], config.get ("Main", "Mountpoint")];
ft@0
   392
    osecfs.main (fuse_args)