src/OsecFS.py
author ft
Wed, 09 Apr 2014 10:27:19 +0200
changeset 14 74a3519ac9b3
parent 13 df3d231adebb
child 15 0b4d2bf9d306
permissions -rwxr-xr-x
Fixed windows append isse
removed useless modes
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@11
    15
from importlib import import_module
ft@11
    16
ft@11
    17
ft@0
    18
import subprocess
ft@0
    19
ck@5
    20
import urllib3
ft@8
    21
import urllib
ft@8
    22
import netifaces
ft@8
    23
import netaddr
ck@1
    24
ck@1
    25
ft@11
    26
sys.stderr = open('/var/log/osecfs_error.log', 'a+')
ft@11
    27
ft@11
    28
ft@11
    29
MINOPTS = { "Main" : ["Logfile", "LogLevel", "Mountpoint", "Rootpath", "ScannerPath", "ScannerModuleName", "ScannerClassName", "ScannerConfig", "ReadOnly"]}
ft@0
    30
ft@0
    31
CONFIG_NOT_READABLE = "Configfile is not readable"
ft@0
    32
CONFIG_WRONG = "Something is wrong with the config"
ft@0
    33
CONFIG_MISSING = "Section: \"%s\" Option: \"%s\" in configfile is missing"
ft@11
    34
SCAN_WRONG_RETURN_VALUE = "The return Value of the malware scanner is wrong. Has to be an dictionary"
ft@11
    35
SCAN_RETURN_VALUE_KEY_MISSING = "The dictionary has to include key \"infected\" (True, False) and \"virusname\" (String)"
ft@11
    36
VIRUS_FOUND = "Virus found. Access denied"
ft@11
    37
NOTIFICATION_CRITICAL = "critical"
ft@11
    38
NOTIFICATION_INFO = "info"
ft@0
    39
LOG = None
ft@11
    40
MalwareScanner = None
ft@13
    41
STATUS_CODE_OK = 200
ft@0
    42
ft@0
    43
SYSTEM_FILE_COMMAND = "file"
ck@7
    44
httpPool = urllib3.PoolManager(num_pools = 1, timeout = 3)
ft@0
    45
ft@0
    46
def checkMinimumOptions (config):
ft@0
    47
    for section, options in MINOPTS.iteritems ():
ft@0
    48
        for option in options:
ft@0
    49
            if (config.has_option(section, option) == False):
ft@0
    50
                print (CONFIG_MISSING % (section, option))
ft@0
    51
                exit (129)
ft@0
    52
ft@0
    53
def printUsage ():
ft@0
    54
    print ("Usage:")
ft@3
    55
    print ("%s configfile mountpath ro/rw" % (sys.argv[0]))
ft@0
    56
    exit (128)
ft@0
    57
ft@0
    58
def loadConfig ():
ft@0
    59
    print ("load config")
ft@0
    60
ft@3
    61
    if (len (sys.argv) < 4):
ft@0
    62
        printUsage ()
ft@0
    63
ft@0
    64
    configfile = sys.argv[1]
ft@0
    65
    config = ConfigParser.SafeConfigParser ()
ft@0
    66
ft@0
    67
    if ((os.path.exists (configfile) == False) or (os.path.isfile (configfile) == False) or (os.access (configfile, os.R_OK) == False)):
ft@0
    68
        print (CONFIG_NOT_READABLE)
ft@0
    69
        printUsage ()
ft@0
    70
ft@0
    71
    try:
ft@0
    72
        config.read (sys.argv[1])
ft@0
    73
    except Exception, e:
ft@0
    74
        print (CONFIG_WRONG)
ft@0
    75
        print ("Error: %s" % (e))
ft@0
    76
ft@3
    77
ft@3
    78
    config.set("Main", "Mountpoint", sys.argv[2])
ft@3
    79
    if (sys.argv[3] == "rw"):
ft@3
    80
        config.set("Main", "ReadOnly", "false")
ft@3
    81
    else:
ft@3
    82
        config.set("Main", "ReadOnly", "true")
ft@3
    83
ft@0
    84
    checkMinimumOptions (config)
ft@0
    85
ft@0
    86
    return config
ft@0
    87
ft@0
    88
def initLog (config):
ft@0
    89
    print ("init log")
ft@0
    90
ft@0
    91
    global LOG
ft@0
    92
    logfile = config.get("Main", "Logfile")
ft@11
    93
    
ft@11
    94
    numeric_level = getattr(logging, config.get("Main", "LogLevel").upper(), None)
ft@11
    95
    if not isinstance(numeric_level, int):
ft@11
    96
        raise ValueError('Invalid log level: %s' % loglevel)
ft@0
    97
ft@0
    98
    # ToDo move log level and maybe other things to config file
ft@0
    99
    logging.basicConfig(
ft@11
   100
                        level = numeric_level,
ft@0
   101
                        format = "%(asctime)s %(name)-12s %(funcName)-15s %(levelname)-8s %(message)s",
ft@0
   102
                        datefmt = "%Y-%m-%d %H:%M:%S",
ft@0
   103
                        filename = logfile,
ft@0
   104
                        filemode = "a+",
ft@0
   105
    )
ft@0
   106
    LOG = logging.getLogger("fuse_main")
ft@0
   107
ft@0
   108
ft@0
   109
def fixPath (path):
ft@0
   110
    return ".%s" % (path)
ft@0
   111
ft@0
   112
def rootPath (rootpath, path):
ft@0
   113
    return "%s%s" % (rootpath, path)
ft@0
   114
ft@0
   115
def flag2mode (flags):
ft@0
   116
    md = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
ft@0
   117
    m = md[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
ft@0
   118
ft@14
   119
    # windows sets append even if it would overwrite the whole file (seek 0)
ft@14
   120
    # so ignore append option
ft@14
   121
    #if flags | os.O_APPEND:
ft@14
   122
    #    m = m.replace('w', 'a', 1)
ft@0
   123
ft@0
   124
    return m
ft@0
   125
ft@11
   126
def scanFile (path, fileobject):
ft@11
   127
    LOG.debug ("Scan File \"%s\" with malware Scanner" %(path,) )
ft@11
   128
    return MalwareScanner.scanFile (path, fileobject)
ck@7
   129
ck@2
   130
ck@2
   131
def scanFileClamAV (path):
ft@0
   132
    infected = False
ft@0
   133
ft@0
   134
    LOG.debug ("Scan File: %s" % (path))
ft@0
   135
ck@2
   136
    result = pyclamav.scanfile (path)
ft@0
   137
    LOG.debug ("Result of file \"%s\": %s" % (path, result))
ck@2
   138
    if (result[0] != 0):
ft@0
   139
        infected = True
ft@0
   140
ft@0
   141
    if (infected == True):
ck@2
   142
        LOG.error ("Virus found, deny Access %s" % (result,))
ft@0
   143
ft@0
   144
    return infected
ft@0
   145
ft@0
   146
def whitelistFile (path):
ft@0
   147
    whitelisted = False;
ft@0
   148
ft@0
   149
    LOG.debug ("Execute \"%s\" command on \"%s\"" %(SYSTEM_FILE_COMMAND, path))
ft@0
   150
    
ft@0
   151
    result = None
ft@0
   152
    try:
ft@0
   153
        result = subprocess.check_output ([SYSTEM_FILE_COMMAND, path]);
ft@0
   154
        # ToDo replace with real whitelist
ft@0
   155
        whitelisted = True
ft@0
   156
    except Exception as e:
ft@0
   157
        LOG.error ("Call returns with an error!")
ft@0
   158
        LOG.error (e)
ft@0
   159
ft@0
   160
    LOG.debug ("Type: %s" %(result))
ft@0
   161
ft@0
   162
    return whitelisted
ft@0
   163
ft@8
   164
def sendNotification (type, message):
ft@8
   165
    netifaces.ifaddresses("eth0")[2][0]["addr"]
ft@8
   166
    
ft@8
   167
    # Get first address in network (0 = network ip -> 192.168.0.0)
ft@8
   168
    remote_ip = netaddr.IPNetwork("%s/%s" %(netifaces.ifaddresses("eth0")[2][0]["addr"], netifaces.ifaddresses("eth0")[2][0]["netmask"]))[1]
ft@8
   169
    
ft@8
   170
    url_options = {"type" : type, "message" : message }
ft@10
   171
    
ft@10
   172
    # BUG in urllib3. Starting / is missing -> workarround use 2 of them -.- 
ft@10
   173
    url = ("http://%s:8090//notification?%s" %(remote_ip, urllib.urlencode(url_options)))
ft@8
   174
    
ft@8
   175
    LOG.debug ("Send notification to \"%s\"" %(url, ))
ft@8
   176
    
ft@8
   177
    try:
ft@10
   178
        #response = httpPool.request_encode_body('GET', url, retries = 0)
ft@10
   179
        response = httpPool.request("GET", url, retries = 0)
ft@8
   180
    except:
ft@8
   181
        LOG.error("Remote host not reachable")
ft@8
   182
        LOG.error ("Exception: %s" %(sys.exc_info()[0]))
ft@8
   183
        return
ft@8
   184
    
ft@8
   185
    if response.status == STATUS_CODE_OK:
ft@8
   186
        LOG.info("Notification sent successfully")
ft@8
   187
    else:
ft@8
   188
        LOG.error("Server returned errorcode: %s" %(response.status,))
ft@8
   189
ft@9
   190
def sendReadOnlyNotification():
ft@9
   191
    sendNotification("critical", "Filesystem is in read only mode. If you want to export files please initialize an encrypted filesystem.")
ft@9
   192
ft@0
   193
class OsecFS (Fuse):
ft@0
   194
ft@0
   195
    __rootpath = None
ft@0
   196
ft@0
   197
    # default fuse init
ft@0
   198
    def __init__(self, rootpath, *args, **kw):
ft@0
   199
        self.__rootpath = rootpath
ft@0
   200
        Fuse.__init__ (self, *args, **kw)
ft@0
   201
        LOG.debug ("Init complete.")
ft@9
   202
        sendNotification("information", "Filesystem successfully mounted.")
ft@0
   203
ft@0
   204
    # defines that our working directory will be the __rootpath
ft@0
   205
    def fsinit(self):
ft@0
   206
        os.chdir (self.__rootpath)
ft@0
   207
ft@0
   208
    def getattr(self, path):
ft@0
   209
        LOG.debug ("*** getattr (%s)" % (fixPath (path)))
ft@0
   210
        return os.lstat (fixPath (path));
ft@0
   211
ft@0
   212
    def getdir(self, path):
ft@0
   213
        LOG.debug ("*** getdir (%s)" % (path));
ft@0
   214
        return os.listdir (fixPath (path))
ft@0
   215
ft@0
   216
    def readdir(self, path, offset):
ft@0
   217
        LOG.debug ("*** readdir (%s %s)" % (path, offset));
ft@0
   218
        for e in os.listdir (fixPath (path)):
ft@0
   219
            yield fuse.Direntry(e)
ft@0
   220
ft@0
   221
    def chmod (self, path, mode):
ft@0
   222
        LOG.debug ("*** chmod %s %s" % (path, oct(mode)))
ft@3
   223
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   224
            sendReadOnlyNotification()
ft@3
   225
            return -errno.EACCES
ft@0
   226
        os.chmod (fixPath (path), mode)
ft@0
   227
ft@0
   228
    def chown (self, path, uid, gid):
ft@0
   229
        LOG.debug ("*** chown %s %s %s" % (path, uid, gid))
ft@3
   230
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   231
            sendReadOnlyNotification()
ft@3
   232
            return -errno.EACCES
ft@0
   233
        os.chown (fixPath (path), uid, gid)
ft@0
   234
ft@0
   235
    def link (self, targetPath, linkPath):
ft@0
   236
        LOG.debug ("*** link %s %s" % (targetPath, linkPath))
ft@3
   237
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   238
            sendReadOnlyNotification()
ft@3
   239
            return -errno.EACCES
ft@0
   240
        os.link (fixPath (targetPath), fixPath (linkPath))
ft@0
   241
ft@0
   242
    def mkdir (self, path, mode):
ft@0
   243
        LOG.debug ("*** mkdir %s %s" % (path, oct(mode)))
ft@3
   244
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   245
            sendReadOnlyNotification()
ft@3
   246
            return -errno.EACCES
ft@0
   247
        os.mkdir (fixPath (path), mode)
ft@0
   248
ft@0
   249
    def mknod (self, path, mode, dev):
ft@0
   250
        LOG.debug ("*** mknod %s %s %s" % (path, oct (mode), dev))
ft@3
   251
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   252
            sendReadOnlyNotification()
ft@3
   253
            return -errno.EACCES
ft@0
   254
        os.mknod (fixPath (path), mode, dev)
ft@0
   255
ft@0
   256
    # to implement virus scan
ft@0
   257
    def open (self, path, flags):
ft@0
   258
        LOG.debug ("*** open %s %s" % (path, oct (flags)))
ft@0
   259
        self.file = os.fdopen (os.open (fixPath (path), flags), flag2mode (flags))
ft@0
   260
        self.fd = self.file.fileno ()
ft@11
   261
        
ft@11
   262
        LOG.debug(self.__rootpath)
ft@11
   263
        LOG.debug(path)
ft@11
   264
        
ft@11
   265
        retval = scanFile (rootPath(self.__rootpath, path), self.file)
ft@11
   266
        
ft@11
   267
        #if type(retval) is not dict:
ft@11
   268
        if (isinstance(retval, dict) == False):
ft@11
   269
            LOG.error(SCAN_WRONG_RETURN_VALUE)
ft@0
   270
            self.file.close ()
ft@11
   271
            return -errno.EACCES
ft@11
   272
        
ft@11
   273
        if ((retval.has_key("infected") == False) or (retval.has_key("virusname") == False)):
ft@11
   274
            LOG.error(SCAN_RETURN_VALUE_KEY_MISSING)
ft@11
   275
            self.file.close ()
ft@11
   276
            return -errno.EACCES
ft@11
   277
            
ft@11
   278
        
ft@11
   279
        if (retval.get("infected") == True):
ft@11
   280
            self.file.close ()
ft@11
   281
            sendNotification(NOTIFICATION_CRITICAL, "%s\nFile: %s\nVirus: %s" %(VIRUS_FOUND, path, retval.get("virusname")))
ft@11
   282
            LOG.error("%s" %(VIRUS_FOUND,))
ft@11
   283
            LOG.error("Virus: %s" %(retval.get("virusname"),))
ft@0
   284
            return -errno.EACCES
ft@0
   285
        
ft@0
   286
        whitelisted = whitelistFile (rootPath(self.__rootpath, path))
ft@0
   287
        if (whitelisted == False):
ft@0
   288
            self.file.close ()
ft@11
   289
            sendNotification(NOTIFICATION_CRITICAL, "File not in whitelist. Access denied.")
ft@0
   290
            return -errno.EACCES
ft@0
   291
ft@0
   292
    def read (self, path, length, offset):
ft@0
   293
        LOG.debug ("*** read %s %s %s" % (path, length, offset))
ft@0
   294
        self.file.seek (offset)
ft@0
   295
        return self.file.read (length)
ft@0
   296
ft@0
   297
    def readlink (self, path):
ft@0
   298
        LOG.debug ("*** readlink %s" % (path))
ft@0
   299
        return os.readlink (fixPath (path))
ft@0
   300
ft@0
   301
    def release (self, path, flags):
ft@0
   302
        LOG.debug ("*** release %s %s" % (path, oct (flags)))
ft@0
   303
        self.file.close ()
ft@0
   304
ft@0
   305
    def rename (self, oldPath, newPath):
ft@3
   306
        LOG.debug ("*** rename %s %s %s" % (oldPath, newPath, config.get("Main", "ReadOnly")))
ft@3
   307
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   308
            sendReadOnlyNotification()
ft@3
   309
            return -errno.EACCES
ft@0
   310
        os.rename (fixPath (oldPath), fixPath (newPath))
ft@0
   311
ft@0
   312
    def rmdir (self, path):
ft@3
   313
        LOG.debug ("*** rmdir %s %s" % (path, config.get("Main", "ReadOnly")))
ft@3
   314
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   315
            sendReadOnlyNotification()
ft@3
   316
            return -errno.EACCES
ft@0
   317
        os.rmdir (fixPath (path))
ft@0
   318
ft@0
   319
    def statfs (self):
ft@0
   320
        LOG.debug ("*** statfs")
ft@0
   321
        return os.statvfs(".")
ft@0
   322
ft@0
   323
    def symlink (self, targetPath, linkPath):
ft@3
   324
        LOG.debug ("*** symlink %s %s %s" % (targetPath, linkPath, config.get("Main", "ReadOnly")))
ft@3
   325
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   326
            sendReadOnlyNotification()
ft@3
   327
            return -errno.EACCES
ft@0
   328
        os.symlink (fixPath (targetPath), fixPath (linkPath))
ft@0
   329
ft@0
   330
    def truncate (self, path, length):
ft@3
   331
        LOG.debug ("*** truncate %s %s %s" % (path, length, config.get("Main", "ReadOnly")))
ft@3
   332
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   333
            sendReadOnlyNotification()
ft@3
   334
            return -errno.EACCES
ft@14
   335
        f = open (fixPath (path), "w+")
ft@0
   336
        f.truncate (length)
ft@0
   337
        f.close ()
ft@0
   338
ft@0
   339
    def unlink (self, path):
ft@3
   340
        LOG.debug ("*** unlink %s %s" % (path, config.get("Main", "ReadOnly")))
ft@3
   341
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   342
            sendReadOnlyNotification()
ft@3
   343
            return -errno.EACCES
ft@0
   344
        os.unlink (fixPath (path))
ft@0
   345
ft@0
   346
    def utime (self, path, times):
ft@0
   347
        LOG.debug ("*** utime %s %s" % (path, times))
ft@0
   348
        os.utime (fixPath (path), times)
ft@0
   349
ft@0
   350
    def write (self, path, buf, offset):
ft@3
   351
        LOG.debug ("*** write %s %s %s %s" % (path, buf, offset, config.get("Main", "ReadOnly")))
ft@3
   352
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   353
            self.file.close()
ft@9
   354
            sendReadOnlyNotification()
ft@3
   355
            return -errno.EACCES
ft@0
   356
        self.file.seek (offset)
ft@0
   357
        self.file.write (buf)
ft@0
   358
        return len (buf)
ft@0
   359
ft@0
   360
    def access (self, path, mode):
ft@0
   361
        LOG.debug ("*** access %s %s" % (path, oct (mode)))
ft@0
   362
        if not os.access (fixPath (path), mode):
ft@0
   363
            return -errno.EACCES
ft@0
   364
ft@0
   365
    def create (self, path, flags, mode):
ft@3
   366
        LOG.debug ("*** create %s %s %s %s %s" % (fixPath (path), oct (flags), oct (mode), flag2mode (flags), config.get("Main", "ReadOnly")))
ft@3
   367
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   368
            sendReadOnlyNotification()
ft@3
   369
            return -errno.EACCES
ft@12
   370
        #self.file = os.fdopen (os.open (fixPath (path), flags, mode), flag2mode (flags))
ft@12
   371
        # fix strange Windows behaviour
ft@14
   372
        self.file = os.fdopen (os.open (fixPath (path), flags, mode), "w+")
ft@0
   373
        self.fd = self.file.fileno ()
ft@0
   374
ft@0
   375
ft@0
   376
if __name__ == "__main__":
ft@0
   377
    # Set api version
ft@0
   378
    fuse.fuse_python_api = (0, 2)
ft@0
   379
    fuse.feature_assert ('stateful_files', 'has_init')
ft@0
   380
ft@0
   381
    config = loadConfig ()
ft@0
   382
    initLog (config)
ft@8
   383
    
ft@8
   384
    #sendNotification("Info", "OsecFS started")
ft@11
   385
    
ft@11
   386
    # Import the Malware Scanner
ft@11
   387
    sys.path.append(config.get("Main", "ScannerPath"))
ft@11
   388
    
ft@11
   389
    MalwareModule = import_module(config.get("Main", "ScannerModuleName"))
ft@11
   390
    MalwareClass = getattr(MalwareModule, config.get("Main", "ScannerClassName"))
ft@11
   391
    
ft@11
   392
    MalwareScanner = MalwareClass (config.get("Main", "ScannerConfig"));
ck@7
   393
    
ft@0
   394
    osecfs = OsecFS (config.get ("Main", "Rootpath"))
ft@0
   395
    osecfs.flags = 0
ft@0
   396
    osecfs.multithreaded = 0
ft@0
   397
ft@0
   398
    fuse_args = [sys.argv[0], config.get ("Main", "Mountpoint")];
ft@0
   399
    osecfs.main (fuse_args)