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