-
Notifications
You must be signed in to change notification settings - Fork 0
/
Passthrough.py
615 lines (518 loc) · 20.5 KB
/
Passthrough.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
#!/usr/bin/env python
from __future__ import with_statement
import os
import sys
basedir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..'))
if (os.path.exists(os.path.join(basedir, 'setup.py')) and
os.path.exists(os.path.join(basedir, 'src', 'pyfuse3.pyx'))):
sys.path.insert(0, os.path.join(basedir, 'src'))
import errno
import random
import os.path
import time
from pymongo import MongoClient
import shutil
import pyclamd
import pyfuse3
from argparse import ArgumentParser
import errno
import logging
import stat as stat_m
from pyfuse3 import FUSEError
from os import fsencode, fsdecode
from collections import defaultdict
import trio
import codecs
import faulthandler
faulthandler.enable()
import pyfuse3
from pyfuse3 import FUSEError
from pymongo import MongoClient
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import trio
cliente = MongoClient('mongodb://localhost:27017/')
mongo = cliente['fuse']
class Passthrough(pyfuse3.Operations):
def __init__(self, root):
# caminho do moutpoint
super().__init__()
self._inode_path_map = { pyfuse3.ROOT_INODE: root }
self._lookup_cnt = defaultdict(lambda : 0)
self._fd_inode_map = dict()
self._inode_fd_map = dict()
self._fd_open_count = dict()
# variavel que indica que user esta autenticado
self.autenticadoB = False
# tempo em que foi requisitado o codigo
self.tinicial = time.time()
self.safenumber = 0
self.lastContextt = None
self.clamav = pyclamd.ClamdAgnostic()
def _inode_to_path(self, inode):
try:
val = self._inode_path_map[inode]
except KeyError:
raise FUSEError(errno.ENOENT)
if isinstance(val, set):
# In case of hardlinks, pick any path
val = next(iter(val))
return val
def _add_path(self, inode, path):
self._lookup_cnt[inode] += 1
# With hardlinks, one inode may map to multiple paths.
if inode not in self._inode_path_map:
self._inode_path_map[inode] = path
return
val = self._inode_path_map[inode]
if isinstance(val, set):
val.add(path)
elif val != path:
self._inode_path_map[inode] = { path, val }
async def forget(self, inode_list):
for (inode, nlookup) in inode_list:
if self._lookup_cnt[inode] > nlookup:
self._lookup_cnt[inode] -= nlookup
continue
assert inode not in self._inode_fd_map
del self._lookup_cnt[inode]
try:
del self._inode_path_map[inode]
except KeyError: # may have been deleted
pass
async def lookup(self, inode_p, name, ctx=None):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
name = fsdecode(name)
path = os.path.join(self._inode_to_path(inode_p), name)
attr = self._getattr(path=path)
if name != '.' and name != '..':
self._add_path(attr.st_ino, path)
return attr
async def getattr(self, inode, ctx=None):
if ctx == None:
raise FUSEError(1)
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
if inode in self._inode_fd_map:
return self._getattr(fd=self._inode_fd_map[inode])
else:
return self._getattr(path=self._inode_to_path(inode))
def _getattr(self, path=None, fd=None):
assert fd is None or path is None
assert not(fd is None and path is None)
try:
if fd is None:
stat = os.lstat(path)
else:
stat = os.fstat(fd)
except OSError as exc:
raise FUSEError(exc.errno)
entry = pyfuse3.EntryAttributes()
for attr in ('st_ino', 'st_mode', 'st_nlink', 'st_uid', 'st_gid',
'st_rdev', 'st_size', 'st_atime_ns', 'st_mtime_ns',
'st_ctime_ns'):
setattr(entry, attr, getattr(stat, attr))
entry.generation = 0
entry.entry_timeout = 0
entry.attr_timeout = 0
entry.st_blksize = 512
entry.st_blocks = ((entry.st_size+entry.st_blksize-1) // entry.st_blksize)
return entry
async def readlink(self, inode, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
path = self._inode_to_path(inode)
try:
target = os.readlink(path)
except OSError as exc:
raise FUSEError(exc.errno)
return fsencode(target)
async def opendir(self, inode, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
return inode
async def readdir(self, inode, off, token):
path = self._inode_to_path(inode)
entries = []
for name in os.listdir(path):
if name == '.' or name == '..':
continue
attr = self._getattr(path=os.path.join(path, name))
entries.append((attr.st_ino, name, attr))
# This is not fully posix compatible. If there are hardlinks
# (two names with the same inode), we don't have a unique
# offset to start in between them. Note that we cannot simply
# count entries, because then we would skip over entries
# (or return them more than once) if the number of directory
# entries changes between two calls to readdir().
for (ino, name, attr) in sorted(entries):
if ino <= off:
continue
if not pyfuse3.readdir_reply(
token, fsencode(name), attr, ino):
break
self._add_path(attr.st_ino, os.path.join(path, name))
async def unlink(self, inode_p, name, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
name = fsdecode(name)
parent = self._inode_to_path(inode_p)
path = os.path.join(parent, name)
try:
inode = os.lstat(path).st_ino
os.unlink(path)
except OSError as exc:
raise FUSEError(exc.errno)
if inode in self._lookup_cnt:
self._forget_path(inode, path)
async def rmdir(self, inode_p, name, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
name = fsdecode(name)
parent = self._inode_to_path(inode_p)
path = os.path.join(parent, name)
try:
inode = os.lstat(path).st_ino
os.rmdir(path)
except OSError as exc:
raise FUSEError(exc.errno)
if inode in self._lookup_cnt:
self._forget_path(inode, path)
def _forget_path(self, inode, path):
val = self._inode_path_map[inode]
if isinstance(val, set):
val.remove(path)
if len(val) == 1:
self._inode_path_map[inode] = next(iter(val))
else:
del self._inode_path_map[inode]
async def symlink(self, inode_p, name, target, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
name = fsdecode(name)
target = fsdecode(target)
parent = self._inode_to_path(inode_p)
path = os.path.join(parent, name)
try:
os.symlink(target, path)
os.chown(path, ctx.uid, ctx.gid, follow_symlinks=False)
except OSError as exc:
raise FUSEError(exc.errno)
stat = os.lstat(path)
self._add_path(stat.st_ino, path)
return await self.getattr(stat.st_ino,ctx)
async def rename(self, inode_p_old, name_old, inode_p_new, name_new,
flags, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
if flags != 0:
raise FUSEError(errno.EINVAL)
name_old = fsdecode(name_old)
name_new = fsdecode(name_new)
parent_old = self._inode_to_path(inode_p_old)
parent_new = self._inode_to_path(inode_p_new)
path_old = os.path.join(parent_old, name_old)
path_new = os.path.join(parent_new, name_new)
try:
os.rename(path_old, path_new)
inode = os.lstat(path_new).st_ino
except OSError as exc:
raise FUSEError(exc.errno)
if inode not in self._lookup_cnt:
return
val = self._inode_path_map[inode]
if isinstance(val, set):
assert len(val) > 1
val.add(path_new)
val.remove(path_old)
else:
assert val == path_old
self._inode_path_map[inode] = path_new
async def link(self, inode, new_inode_p, new_name, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
new_name = fsdecode(new_name)
parent = self._inode_to_path(new_inode_p)
path = os.path.join(parent, new_name)
try:
os.link(self._inode_to_path(inode), path, follow_symlinks=False)
except OSError as exc:
raise FUSEError(exc.errno)
self._add_path(inode, path)
return await self.getattr(inode,ctx)
async def setattr(self, inode, attr, fields, fh, ctx):
# We use the f* functions if possible so that we can handle
# a setattr() call for an inode without associated directory
# handle.
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
if fh is None:
path_or_fh = self._inode_to_path(inode)
truncate = os.truncate
chmod = os.chmod
chown = os.chown
stat = os.lstat
else:
path_or_fh = fh
truncate = os.ftruncate
chmod = os.fchmod
chown = os.fchown
stat = os.fstat
try:
if fields.update_size:
truncate(path_or_fh, attr.st_size)
if fields.update_mode:
# Under Linux, chmod always resolves symlinks so we should
# actually never get a setattr() request for a symbolic
# link.
assert not stat_m.S_ISLNK(attr.st_mode)
chmod(path_or_fh, stat_m.S_IMODE(attr.st_mode))
if fields.update_uid:
chown(path_or_fh, attr.st_uid, -1, follow_symlinks=False)
if fields.update_gid:
chown(path_or_fh, -1, attr.st_gid, follow_symlinks=False)
if fields.update_atime and fields.update_mtime:
if fh is None:
os.utime(path_or_fh, None, follow_symlinks=False,
ns=(attr.st_atime_ns, attr.st_mtime_ns))
else:
os.utime(path_or_fh, None,
ns=(attr.st_atime_ns, attr.st_mtime_ns))
elif fields.update_atime or fields.update_mtime:
# We can only set both values, so we first need to retrieve the
# one that we shouldn't be changing.
oldstat = stat(path_or_fh)
if not fields.update_atime:
attr.st_atime_ns = oldstat.st_atime_ns
else:
attr.st_mtime_ns = oldstat.st_mtime_ns
if fh is None:
os.utime(path_or_fh, None, follow_symlinks=False,
ns=(attr.st_atime_ns, attr.st_mtime_ns))
else:
os.utime(path_or_fh, None,
ns=(attr.st_atime_ns, attr.st_mtime_ns))
except OSError as exc:
raise FUSEError(exc.errno)
return await self.getattr(inode,ctx)
async def mknod(self, inode_p, name, mode, rdev, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
path = os.path.join(self._inode_to_path(inode_p), fsdecode(name))
try:
os.mknod(path, mode=(mode & ~ctx.umask), device=rdev)
os.chown(path, ctx.uid, ctx.gid)
except OSError as exc:
raise FUSEError(exc.errno)
attr = self._getattr(path=path)
self._add_path(attr.st_ino, path)
return attr
async def mkdir(self, inode_p, name, mode, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
path = os.path.join(self._inode_to_path(inode_p), fsdecode(name))
try:
os.mkdir(path, mode=(mode & ~ctx.umask))
os.chown(path, ctx.uid, ctx.gid)
except OSError as exc:
raise FUSEError(exc.errno)
attr = self._getattr(path=path)
self._add_path(attr.st_ino, path)
return attr
async def statfs(self, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
root = self._inode_path_map[pyfuse3.ROOT_INODE]
stat_ = pyfuse3.StatvfsData()
try:
statfs = os.statvfs(root)
except OSError as exc:
raise FUSEError(exc.errno)
for attr in ('f_bsize', 'f_frsize', 'f_blocks', 'f_bfree', 'f_bavail',
'f_files', 'f_ffree', 'f_favail'):
setattr(stat_, attr, getattr(statfs, attr))
stat_.f_namemax = statfs.f_namemax - (len(root)+1)
return stat_
async def open(self, inode, flags, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
fdt = os.open(self._inode_to_path(inode), os.O_RDONLY)
os.lseek(fdt, 0, 0)
buffe = os.read(fdt,os.stat(self._inode_to_path(inode)).st_size)
self.backupFile = buffe
os.close(fdt)
if inode in self._inode_fd_map:
print("AKI")
fd = self._inode_fd_map[inode]
print("Foi buscar o File descriptor " + str(fd) )
self._fd_open_count[fd] += 1
return pyfuse3.FileInfo(fh=fd)
assert flags & os.O_CREAT == 0
try:
fd = os.open(self._inode_to_path(inode), flags)
print("Abriu o file descriptor " + str(fd))
except OSError as exc:
raise FUSEError(exc.errno)
self._inode_fd_map[inode] = fd
self._fd_inode_map[fd] = inode
self._fd_open_count[fd] = 1
return pyfuse3.FileInfo(fh=fd)
async def create(self, inode_p, name, mode, flags, ctx):
self.autenticado(ctx)
self.lastContextt = ctx
if not self.autenticadoB:
raise FUSEError(1)
path = os.path.join(self._inode_to_path(inode_p), fsdecode(name))
try:
fd = os.open(path, flags | os.O_CREAT | os.O_TRUNC)
print("Criou o ficheiro " + str(fd))
os.read(fd,1)
except OSError as exc:
raise FUSEError(exc.errno)
attr = self._getattr(fd=fd)
self._add_path(attr.st_ino, path)
self._inode_fd_map[attr.st_ino] = fd
self._fd_inode_map[fd] = attr.st_ino
self._fd_open_count[fd] = 1
return (fd, attr)
async def read(self, fd, offset, length):
os.lseek(fd, offset, os.SEEK_SET)
return os.read(fd, length)
async def write(self, fd, offset, buf):
#se 92% dos elementos inseridos estiverem com uma presença similar á probabilidade média
# de todos os elementos é copiado o ficheiro por segrança
inodel = self._fd_inode_map[fd]
path = self._inode_to_path(inodel)
print("Caminho -> " + path)
print(buf)
virus = self.clamav.scan_stream((codecs.getdecoder("unicode_escape")(buf)[0]).encode("utf-8"))
print(virus)
if not virus is None:
print("Encontrou Virus")
mongo.virus.insert({"userId": self.lastContextt.uid, "time": time.time(), "virus": virus })
return os.write(fd,self.backupFile)
if not self.entropia(buf):
names = path.split("/")
dirpath = ""
for i in range(1,len(names)-1):
dirpath = dirpath + "/" + names[i]
if len(names) > 1:
dirpath = dirpath + "/"
try:
#cria diretoria com permissões de leitura apenas
if not os.path.isdir("/safe"):
os.mkdir("safe")
print("Created Safe")
except:
print("directory exists!!")
file_path = names[len(names)-1]
#copia para o diretório safe
if not os.path.isdir("safe/" + dirpath):
os.system("mkdir -p " + "safe/"+ dirpath)
#renomeia o ficheiro guardado para precaver vários ataques diferentes
try:
file_d = os.open("safe/" + dirpath + str(self.safenumber)+ file_path,os.O_WRONLY | os.O_TRUNC | os.O_CREAT)
os.lseek(file_d,0,0)
os.write(file_d,self.backupFile)
os.close(file_d)
#shutil.copyfile(path,"safe/" + dirpath + str(self.safenumber)+ file_path,follow_symlinks=True)
#os.system("cp " + path + " " + names[0] + "/" + "safe/" + dirpath + str(self.safenumber)+ file_path)
os.system("chmod 0200 " +"safe/" + dirpath + str(self.safenumber)+ file_path)
except :
print("Deu Exception")
self.safenumber += 1
mongo.ransomware.insert({"userId": self.lastContextt.uid, "time": time.time()})
os.lseek(fd, offset, os.SEEK_SET)
return os.write(fd, buf)
async def release(self, fd):
print("Entrei no Release")
if self._fd_open_count[fd] > 1:
self._fd_open_count[fd] -= 1
print("decrementou 1")
return
del self._fd_open_count[fd]
inode = self._fd_inode_map[fd]
del self._inode_fd_map[inode]
del self._fd_inode_map[fd]
try:
os.close(fd)
print("fechou " + str(fd))
except OSError as exc:
raise FUSEError(exc.errno)
def autenticado(self,ctx):
# Vai buscar user
timedif = 0
#print("Acesso feito por" + str(ctx.uid))
resultado = mongo.log.find_one({"userId": str(ctx.uid),"acess": "valid"})
if not resultado == None:
timedif = time.time() - resultado["time"]
self.autenticadoB = True
# user tem 2 mnutos de acesso
if self.autenticadoB == True and timedif > 120000000:
mongo.log.update({"userId": str(ctx.uid),"acess": "valid"},{"userId": str(ctx.uid),"time": resultado["time"],"acess": "invalid"})
self.autenticadoB = False
def entropia(self,buf):
ocorrencias = {}
for c in buf:
if c in ocorrencias:
ocorrencias[c] = ocorrencias[c] + 1
else:
ocorrencias[c] = 1
prob = []
length = len(buf)
# calcula probabilidade de cada elemento distinto
for c in ocorrencias:
prob.append(ocorrencias[c]/length)
length2 = len(ocorrencias)
randomelements = 0
probmedia = 1/len(ocorrencias)
# Caso 92% dos elementos ou mais tenham uma distribuicao entre 48% e 52% assume-se que e um elemento usado para cifrar
for p in prob:
if p > (probmedia -0.02) and p < (probmedia + 0.02):
randomelements += 1
if randomelements/length2 > 0.92:
return True
return False
def main(mountpoint, root):
passt = Passthrough(root)
fuse_options = set()
fuse_options.add('fsname=passthroughfs')
fuse_options.add('allow_other')
try:
pyfuse3.init(passt,mountpoint,fuse_options)
trio.run(pyfuse3.main)
except:
pyfuse3.close(unmount=False)
raise
if __name__ == '__main__':
main(sys.argv[2], sys.argv[1])