15 from importlib import import_module
26 sys.stderr = open('/var/log/osecfs_error.log', 'a+')
29 MINOPTS = { "Main" : ["Logfile", "LogLevel", "Mountpoint", "Rootpath", "ScannerPath", "ScannerModuleName", "ScannerClassName", "ScannerConfig", "ReadOnly"]}
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"
43 SYSTEM_FILE_COMMAND = "file"
44 httpPool = urllib3.PoolManager(num_pools = 1, timeout = 3)
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))
55 print ("%s configfile mountpath ro/rw" % (sys.argv[0]))
61 if (len (sys.argv) < 4):
64 configfile = sys.argv[1]
65 config = ConfigParser.SafeConfigParser ()
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)
72 config.read (sys.argv[1])
75 print ("Error: %s" % (e))
78 config.set("Main", "Mountpoint", sys.argv[2])
79 if (sys.argv[3] == "rw"):
80 config.set("Main", "ReadOnly", "false")
82 config.set("Main", "ReadOnly", "true")
84 checkMinimumOptions (config)
92 logfile = config.get("Main", "Logfile")
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)
98 # ToDo move log level and maybe other things to config file
100 level = numeric_level,
101 format = "%(asctime)s %(name)-12s %(funcName)-15s %(levelname)-8s %(message)s",
102 datefmt = "%Y-%m-%d %H:%M:%S",
106 LOG = logging.getLogger("fuse_main")
110 return ".%s" % (path)
112 def rootPath (rootpath, path):
113 return "%s%s" % (rootpath, path)
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)]
119 if flags | os.O_APPEND:
120 m = m.replace('w', 'a', 1)
124 def scanFile (path, fileobject):
125 LOG.debug ("Scan File \"%s\" with malware Scanner" %(path,) )
126 return MalwareScanner.scanFile (path, fileobject)
129 def scanFileClamAV (path):
132 LOG.debug ("Scan File: %s" % (path))
134 result = pyclamav.scanfile (path)
135 LOG.debug ("Result of file \"%s\": %s" % (path, result))
139 if (infected == True):
140 LOG.error ("Virus found, deny Access %s" % (result,))
144 def whitelistFile (path):
147 LOG.debug ("Execute \"%s\" command on \"%s\"" %(SYSTEM_FILE_COMMAND, path))
151 result = subprocess.check_output ([SYSTEM_FILE_COMMAND, path]);
152 # ToDo replace with real whitelist
154 except Exception as e:
155 LOG.error ("Call returns with an error!")
158 LOG.debug ("Type: %s" %(result))
162 def sendNotification (type, message):
163 netifaces.ifaddresses("eth0")[2][0]["addr"]
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]
168 url_options = {"type" : type, "message" : message }
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)))
173 LOG.debug ("Send notification to \"%s\"" %(url, ))
176 #response = httpPool.request_encode_body('GET', url, retries = 0)
177 response = httpPool.request("GET", url, retries = 0)
179 LOG.error("Remote host not reachable")
180 LOG.error ("Exception: %s" %(sys.exc_info()[0]))
183 if response.status == STATUS_CODE_OK:
184 LOG.info("Notification sent successfully")
186 LOG.error("Server returned errorcode: %s" %(response.status,))
188 def sendReadOnlyNotification():
189 sendNotification("critical", "Filesystem is in read only mode. If you want to export files please initialize an encrypted filesystem.")
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.")
202 # defines that our working directory will be the __rootpath
204 os.chdir (self.__rootpath)
206 def getattr(self, path):
207 LOG.debug ("*** getattr (%s)" % (fixPath (path)))
208 return os.lstat (fixPath (path));
210 def getdir(self, path):
211 LOG.debug ("*** getdir (%s)" % (path));
212 return os.listdir (fixPath (path))
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)
219 def chmod (self, path, mode):
220 LOG.debug ("*** chmod %s %s" % (path, oct(mode)))
221 if (config.get("Main", "ReadOnly") == "true"):
222 sendReadOnlyNotification()
224 os.chmod (fixPath (path), mode)
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()
231 os.chown (fixPath (path), uid, gid)
233 def link (self, targetPath, linkPath):
234 LOG.debug ("*** link %s %s" % (targetPath, linkPath))
235 if (config.get("Main", "ReadOnly") == "true"):
236 sendReadOnlyNotification()
238 os.link (fixPath (targetPath), fixPath (linkPath))
240 def mkdir (self, path, mode):
241 LOG.debug ("*** mkdir %s %s" % (path, oct(mode)))
242 if (config.get("Main", "ReadOnly") == "true"):
243 sendReadOnlyNotification()
245 os.mkdir (fixPath (path), mode)
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()
252 os.mknod (fixPath (path), mode, dev)
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 ()
260 LOG.debug(self.__rootpath)
263 retval = scanFile (rootPath(self.__rootpath, path), self.file)
265 #if type(retval) is not dict:
266 if (isinstance(retval, dict) == False):
267 LOG.error(SCAN_WRONG_RETURN_VALUE)
271 if ((retval.has_key("infected") == False) or (retval.has_key("virusname") == False)):
272 LOG.error(SCAN_RETURN_VALUE_KEY_MISSING)
277 if (retval.get("infected") == True):
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"),))
284 whitelisted = whitelistFile (rootPath(self.__rootpath, path))
285 if (whitelisted == False):
287 sendNotification(NOTIFICATION_CRITICAL, "File not in whitelist. Access denied.")
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)
295 def readlink (self, path):
296 LOG.debug ("*** readlink %s" % (path))
297 return os.readlink (fixPath (path))
299 def release (self, path, flags):
300 LOG.debug ("*** release %s %s" % (path, oct (flags)))
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()
308 os.rename (fixPath (oldPath), fixPath (newPath))
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()
315 os.rmdir (fixPath (path))
318 LOG.debug ("*** statfs")
319 return os.statvfs(".")
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()
326 os.symlink (fixPath (targetPath), fixPath (linkPath))
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()
333 f = open (fixPath (path), "rw+")
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()
342 os.unlink (fixPath (path))
344 def utime (self, path, times):
345 LOG.debug ("*** utime %s %s" % (path, times))
346 os.utime (fixPath (path), times)
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"):
352 sendReadOnlyNotification()
354 self.file.seek (offset)
355 self.file.write (buf)
358 def access (self, path, mode):
359 LOG.debug ("*** access %s %s" % (path, oct (mode)))
360 if not os.access (fixPath (path), mode):
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()
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 ()
374 if __name__ == "__main__":
376 fuse.fuse_python_api = (0, 2)
377 fuse.feature_assert ('stateful_files', 'has_init')
379 config = loadConfig ()
382 #sendNotification("Info", "OsecFS started")
384 # Import the Malware Scanner
385 sys.path.append(config.get("Main", "ScannerPath"))
387 MalwareModule = import_module(config.get("Main", "ScannerModuleName"))
388 MalwareClass = getattr(MalwareModule, config.get("Main", "ScannerClassName"))
390 MalwareScanner = MalwareClass (config.get("Main", "ScannerConfig"));
392 osecfs = OsecFS (config.get ("Main", "Rootpath"))
394 osecfs.multithreaded = 0
396 fuse_args = [sys.argv[0], config.get ("Main", "Mountpoint")];
397 osecfs.main (fuse_args)