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