src/OsecFS.py
author ft
Tue, 08 Apr 2014 15:45:34 +0200
changeset 13 df3d231adebb
parent 12 e1961a1cbb61
child 14 74a3519ac9b3
permissions -rwxr-xr-x
added missing status code
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@0
   119
    if flags | os.O_APPEND:
ft@0
   120
        m = m.replace('w', 'a', 1)
ft@0
   121
ft@0
   122
    return m
ft@0
   123
ft@11
   124
def scanFile (path, fileobject):
ft@11
   125
    LOG.debug ("Scan File \"%s\" with malware Scanner" %(path,) )
ft@11
   126
    return MalwareScanner.scanFile (path, fileobject)
ck@7
   127
ck@2
   128
ck@2
   129
def scanFileClamAV (path):
ft@0
   130
    infected = False
ft@0
   131
ft@0
   132
    LOG.debug ("Scan File: %s" % (path))
ft@0
   133
ck@2
   134
    result = pyclamav.scanfile (path)
ft@0
   135
    LOG.debug ("Result of file \"%s\": %s" % (path, result))
ck@2
   136
    if (result[0] != 0):
ft@0
   137
        infected = True
ft@0
   138
ft@0
   139
    if (infected == True):
ck@2
   140
        LOG.error ("Virus found, deny Access %s" % (result,))
ft@0
   141
ft@0
   142
    return infected
ft@0
   143
ft@0
   144
def whitelistFile (path):
ft@0
   145
    whitelisted = False;
ft@0
   146
ft@0
   147
    LOG.debug ("Execute \"%s\" command on \"%s\"" %(SYSTEM_FILE_COMMAND, path))
ft@0
   148
    
ft@0
   149
    result = None
ft@0
   150
    try:
ft@0
   151
        result = subprocess.check_output ([SYSTEM_FILE_COMMAND, path]);
ft@0
   152
        # ToDo replace with real whitelist
ft@0
   153
        whitelisted = True
ft@0
   154
    except Exception as e:
ft@0
   155
        LOG.error ("Call returns with an error!")
ft@0
   156
        LOG.error (e)
ft@0
   157
ft@0
   158
    LOG.debug ("Type: %s" %(result))
ft@0
   159
ft@0
   160
    return whitelisted
ft@0
   161
ft@8
   162
def sendNotification (type, message):
ft@8
   163
    netifaces.ifaddresses("eth0")[2][0]["addr"]
ft@8
   164
    
ft@8
   165
    # Get first address in network (0 = network ip -> 192.168.0.0)
ft@8
   166
    remote_ip = netaddr.IPNetwork("%s/%s" %(netifaces.ifaddresses("eth0")[2][0]["addr"], netifaces.ifaddresses("eth0")[2][0]["netmask"]))[1]
ft@8
   167
    
ft@8
   168
    url_options = {"type" : type, "message" : message }
ft@10
   169
    
ft@10
   170
    # BUG in urllib3. Starting / is missing -> workarround use 2 of them -.- 
ft@10
   171
    url = ("http://%s:8090//notification?%s" %(remote_ip, urllib.urlencode(url_options)))
ft@8
   172
    
ft@8
   173
    LOG.debug ("Send notification to \"%s\"" %(url, ))
ft@8
   174
    
ft@8
   175
    try:
ft@10
   176
        #response = httpPool.request_encode_body('GET', url, retries = 0)
ft@10
   177
        response = httpPool.request("GET", url, retries = 0)
ft@8
   178
    except:
ft@8
   179
        LOG.error("Remote host not reachable")
ft@8
   180
        LOG.error ("Exception: %s" %(sys.exc_info()[0]))
ft@8
   181
        return
ft@8
   182
    
ft@8
   183
    if response.status == STATUS_CODE_OK:
ft@8
   184
        LOG.info("Notification sent successfully")
ft@8
   185
    else:
ft@8
   186
        LOG.error("Server returned errorcode: %s" %(response.status,))
ft@8
   187
ft@9
   188
def sendReadOnlyNotification():
ft@9
   189
    sendNotification("critical", "Filesystem is in read only mode. If you want to export files please initialize an encrypted filesystem.")
ft@9
   190
ft@0
   191
class OsecFS (Fuse):
ft@0
   192
ft@0
   193
    __rootpath = None
ft@0
   194
ft@0
   195
    # default fuse init
ft@0
   196
    def __init__(self, rootpath, *args, **kw):
ft@0
   197
        self.__rootpath = rootpath
ft@0
   198
        Fuse.__init__ (self, *args, **kw)
ft@0
   199
        LOG.debug ("Init complete.")
ft@9
   200
        sendNotification("information", "Filesystem successfully mounted.")
ft@0
   201
ft@0
   202
    # defines that our working directory will be the __rootpath
ft@0
   203
    def fsinit(self):
ft@0
   204
        os.chdir (self.__rootpath)
ft@0
   205
ft@0
   206
    def getattr(self, path):
ft@0
   207
        LOG.debug ("*** getattr (%s)" % (fixPath (path)))
ft@0
   208
        return os.lstat (fixPath (path));
ft@0
   209
ft@0
   210
    def getdir(self, path):
ft@0
   211
        LOG.debug ("*** getdir (%s)" % (path));
ft@0
   212
        return os.listdir (fixPath (path))
ft@0
   213
ft@0
   214
    def readdir(self, path, offset):
ft@0
   215
        LOG.debug ("*** readdir (%s %s)" % (path, offset));
ft@0
   216
        for e in os.listdir (fixPath (path)):
ft@0
   217
            yield fuse.Direntry(e)
ft@0
   218
ft@0
   219
    def chmod (self, path, mode):
ft@0
   220
        LOG.debug ("*** chmod %s %s" % (path, oct(mode)))
ft@3
   221
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   222
            sendReadOnlyNotification()
ft@3
   223
            return -errno.EACCES
ft@0
   224
        os.chmod (fixPath (path), mode)
ft@0
   225
ft@0
   226
    def chown (self, path, uid, gid):
ft@0
   227
        LOG.debug ("*** chown %s %s %s" % (path, uid, gid))
ft@3
   228
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   229
            sendReadOnlyNotification()
ft@3
   230
            return -errno.EACCES
ft@0
   231
        os.chown (fixPath (path), uid, gid)
ft@0
   232
ft@0
   233
    def link (self, targetPath, linkPath):
ft@0
   234
        LOG.debug ("*** link %s %s" % (targetPath, linkPath))
ft@3
   235
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   236
            sendReadOnlyNotification()
ft@3
   237
            return -errno.EACCES
ft@0
   238
        os.link (fixPath (targetPath), fixPath (linkPath))
ft@0
   239
ft@0
   240
    def mkdir (self, path, mode):
ft@0
   241
        LOG.debug ("*** mkdir %s %s" % (path, oct(mode)))
ft@3
   242
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   243
            sendReadOnlyNotification()
ft@3
   244
            return -errno.EACCES
ft@0
   245
        os.mkdir (fixPath (path), mode)
ft@0
   246
ft@0
   247
    def mknod (self, path, mode, dev):
ft@0
   248
        LOG.debug ("*** mknod %s %s %s" % (path, oct (mode), dev))
ft@3
   249
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   250
            sendReadOnlyNotification()
ft@3
   251
            return -errno.EACCES
ft@0
   252
        os.mknod (fixPath (path), mode, dev)
ft@0
   253
ft@0
   254
    # to implement virus scan
ft@0
   255
    def open (self, path, flags):
ft@0
   256
        LOG.debug ("*** open %s %s" % (path, oct (flags)))
ft@0
   257
        self.file = os.fdopen (os.open (fixPath (path), flags), flag2mode (flags))
ft@0
   258
        self.fd = self.file.fileno ()
ft@11
   259
        
ft@11
   260
        LOG.debug(self.__rootpath)
ft@11
   261
        LOG.debug(path)
ft@11
   262
        
ft@11
   263
        retval = scanFile (rootPath(self.__rootpath, path), self.file)
ft@11
   264
        
ft@11
   265
        #if type(retval) is not dict:
ft@11
   266
        if (isinstance(retval, dict) == False):
ft@11
   267
            LOG.error(SCAN_WRONG_RETURN_VALUE)
ft@0
   268
            self.file.close ()
ft@11
   269
            return -errno.EACCES
ft@11
   270
        
ft@11
   271
        if ((retval.has_key("infected") == False) or (retval.has_key("virusname") == False)):
ft@11
   272
            LOG.error(SCAN_RETURN_VALUE_KEY_MISSING)
ft@11
   273
            self.file.close ()
ft@11
   274
            return -errno.EACCES
ft@11
   275
            
ft@11
   276
        
ft@11
   277
        if (retval.get("infected") == True):
ft@11
   278
            self.file.close ()
ft@11
   279
            sendNotification(NOTIFICATION_CRITICAL, "%s\nFile: %s\nVirus: %s" %(VIRUS_FOUND, path, retval.get("virusname")))
ft@11
   280
            LOG.error("%s" %(VIRUS_FOUND,))
ft@11
   281
            LOG.error("Virus: %s" %(retval.get("virusname"),))
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@11
   287
            sendNotification(NOTIFICATION_CRITICAL, "File not in whitelist. Access denied.")
ft@0
   288
            return -errno.EACCES
ft@0
   289
ft@0
   290
    def read (self, path, length, offset):
ft@0
   291
        LOG.debug ("*** read %s %s %s" % (path, length, offset))
ft@0
   292
        self.file.seek (offset)
ft@0
   293
        return self.file.read (length)
ft@0
   294
ft@0
   295
    def readlink (self, path):
ft@0
   296
        LOG.debug ("*** readlink %s" % (path))
ft@0
   297
        return os.readlink (fixPath (path))
ft@0
   298
ft@0
   299
    def release (self, path, flags):
ft@0
   300
        LOG.debug ("*** release %s %s" % (path, oct (flags)))
ft@0
   301
        self.file.close ()
ft@0
   302
ft@0
   303
    def rename (self, oldPath, newPath):
ft@3
   304
        LOG.debug ("*** rename %s %s %s" % (oldPath, newPath, config.get("Main", "ReadOnly")))
ft@3
   305
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   306
            sendReadOnlyNotification()
ft@3
   307
            return -errno.EACCES
ft@0
   308
        os.rename (fixPath (oldPath), fixPath (newPath))
ft@0
   309
ft@0
   310
    def rmdir (self, path):
ft@3
   311
        LOG.debug ("*** rmdir %s %s" % (path, config.get("Main", "ReadOnly")))
ft@3
   312
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   313
            sendReadOnlyNotification()
ft@3
   314
            return -errno.EACCES
ft@0
   315
        os.rmdir (fixPath (path))
ft@0
   316
ft@0
   317
    def statfs (self):
ft@0
   318
        LOG.debug ("*** statfs")
ft@0
   319
        return os.statvfs(".")
ft@0
   320
ft@0
   321
    def symlink (self, targetPath, linkPath):
ft@3
   322
        LOG.debug ("*** symlink %s %s %s" % (targetPath, linkPath, config.get("Main", "ReadOnly")))
ft@3
   323
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   324
            sendReadOnlyNotification()
ft@3
   325
            return -errno.EACCES
ft@0
   326
        os.symlink (fixPath (targetPath), fixPath (linkPath))
ft@0
   327
ft@0
   328
    def truncate (self, path, length):
ft@3
   329
        LOG.debug ("*** truncate %s %s %s" % (path, length, config.get("Main", "ReadOnly")))
ft@3
   330
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   331
            sendReadOnlyNotification()
ft@3
   332
            return -errno.EACCES
ft@12
   333
        f = open (fixPath (path), "rw+")
ft@0
   334
        f.truncate (length)
ft@0
   335
        f.close ()
ft@0
   336
ft@0
   337
    def unlink (self, path):
ft@3
   338
        LOG.debug ("*** unlink %s %s" % (path, config.get("Main", "ReadOnly")))
ft@3
   339
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   340
            sendReadOnlyNotification()
ft@3
   341
            return -errno.EACCES
ft@0
   342
        os.unlink (fixPath (path))
ft@0
   343
ft@0
   344
    def utime (self, path, times):
ft@0
   345
        LOG.debug ("*** utime %s %s" % (path, times))
ft@0
   346
        os.utime (fixPath (path), times)
ft@0
   347
ft@0
   348
    def write (self, path, buf, offset):
ft@3
   349
        LOG.debug ("*** write %s %s %s %s" % (path, buf, offset, config.get("Main", "ReadOnly")))
ft@3
   350
        if (config.get("Main", "ReadOnly") == "true"):
ft@3
   351
            self.file.close()
ft@9
   352
            sendReadOnlyNotification()
ft@3
   353
            return -errno.EACCES
ft@0
   354
        self.file.seek (offset)
ft@0
   355
        self.file.write (buf)
ft@0
   356
        return len (buf)
ft@0
   357
ft@0
   358
    def access (self, path, mode):
ft@0
   359
        LOG.debug ("*** access %s %s" % (path, oct (mode)))
ft@0
   360
        if not os.access (fixPath (path), mode):
ft@0
   361
            return -errno.EACCES
ft@0
   362
ft@0
   363
    def create (self, path, flags, mode):
ft@3
   364
        LOG.debug ("*** create %s %s %s %s %s" % (fixPath (path), oct (flags), oct (mode), flag2mode (flags), config.get("Main", "ReadOnly")))
ft@3
   365
        if (config.get("Main", "ReadOnly") == "true"):
ft@9
   366
            sendReadOnlyNotification()
ft@3
   367
            return -errno.EACCES
ft@12
   368
        #self.file = os.fdopen (os.open (fixPath (path), flags, mode), flag2mode (flags))
ft@12
   369
        # fix strange Windows behaviour
ft@12
   370
        self.file = os.fdopen (os.open (fixPath (path), flags, mode), "rw+")
ft@0
   371
        self.fd = self.file.fileno ()
ft@0
   372
ft@0
   373
ft@0
   374
if __name__ == "__main__":
ft@0
   375
    # Set api version
ft@0
   376
    fuse.fuse_python_api = (0, 2)
ft@0
   377
    fuse.feature_assert ('stateful_files', 'has_init')
ft@0
   378
ft@0
   379
    config = loadConfig ()
ft@0
   380
    initLog (config)
ft@8
   381
    
ft@8
   382
    #sendNotification("Info", "OsecFS started")
ft@11
   383
    
ft@11
   384
    # Import the Malware Scanner
ft@11
   385
    sys.path.append(config.get("Main", "ScannerPath"))
ft@11
   386
    
ft@11
   387
    MalwareModule = import_module(config.get("Main", "ScannerModuleName"))
ft@11
   388
    MalwareClass = getattr(MalwareModule, config.get("Main", "ScannerClassName"))
ft@11
   389
    
ft@11
   390
    MalwareScanner = MalwareClass (config.get("Main", "ScannerConfig"));
ck@7
   391
    
ft@0
   392
    osecfs = OsecFS (config.get ("Main", "Rootpath"))
ft@0
   393
    osecfs.flags = 0
ft@0
   394
    osecfs.multithreaded = 0
ft@0
   395
ft@0
   396
    fuse_args = [sys.argv[0], config.get ("Main", "Mountpoint")];
ft@0
   397
    osecfs.main (fuse_args)