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