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