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