GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — VortexPanel/panel/malware.py at main · BrowserlessAPI/VortexPanel

Expand file tree

/

malware.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
322 lines (285 loc) · 12.6 KB
/

malware.py

Copy path

File metadata and controls

322 lines (285 loc) · 12.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""Security > Malware scan.
Engines, in one background job ('malware_scan'):
signatures the PHP webshell rules (panel/routes/settings.py WEBSHELL_PATTERNS)
uploads PHP files inside upload folders (wp-content/uploads, uploads/,
images/...) - code there is almost always an intrusion
clamav ClamAV (clamdscan when the daemon runs, else clamscan) when installed
Findings can be quarantined (moved to data/quarantine, 0700, restorable),
deleted, or marked "not a threat" (by sha256, so a changed file is checked again).
A daily schedule scans every site and sends an alert (rule "malware") when it
finds something new.
"""
import hashlib
import json
import os
import re
import shutil
import subprocess
import threading
import time
import uuid
DATA = '/opt/vortexpanel/data'
QDIR = os.path.join(DATA, 'quarantine')
IGNORE_FILE = os.path.join(DATA, 'malware_ignore.json')
SCHED_FILE = os.path.join(DATA, 'malware_schedule.json')
JOB = 'malware_scan'
_UPLOAD_DIR_RE = re.compile(r'/(wp-content/uploads|uploads?|user_?uploads|sites/default/files|media/uploads)(/|$)', re.I)
_CODE_DIR_RE = re.compile(r'/(wp-includes|wp-admin|vendor|node_modules)(/|$)')
_PHP_EXT = ('.php', '.phtml', '.php3', '.php4', '.php5', '.php7', '.pht', '.phar')
_SKIP = {'node_modules', '.git', '.svn'}
def _load(p, default):
try:
return json.load(open(p))
except Exception:
return default
def _save(p, data):
os.makedirs(os.path.dirname(p), exist_ok=True)
tmp = p + '.tmp'
with open(tmp, 'w') as f:
json.dump(data, f, indent=2)
os.chmod(tmp, 0o600)
os.replace(tmp, p)
def _sha(path):
h = hashlib.sha256()
try:
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(1 << 16), b''):
h.update(chunk)
except OSError:
return ''
return h.hexdigest()
def clamav_info():
clamd = shutil.which('clamdscan') and subprocess.run(['systemctl', 'is-active', 'clamav-daemon'],
capture_output=True, text=True).stdout.strip() == 'active'
return {'installed': bool(shutil.which('clamscan')), 'daemon': bool(clamd)}
def _state():
from panel.routes.job_state import load_job, save_job
st = load_job(JOB, {'running': False})
if st.get('running') and time.time() - (st.get('heartbeat') or 0) > 180:
st.update(running=False, done=True, error='The scan stopped (the panel restarted). Start it again.')
save_job(JOB, st)
return st
def status():
return _state()
def start(path, use_clamav=True, trigger='manual', wait=False):
from panel.routes.job_state import save_job
path = os.path.realpath(path)
if not os.path.isdir(path):
return False, f'Directory not found: {path}'
if path in ('/', '/proc', '/sys', '/dev'):
return False, 'Choose a website folder'
if _state().get('running'):
return False, 'A scan is already running'
st = {'running': True, 'done': False, 'path': path, 'trigger': trigger, 'started': time.time(),
'heartbeat': time.time(), 'scanned': 0, 'findings': [], 'engines': []}
save_job(JOB, st)
if wait:
_run(path, use_clamav, st)
else:
threading.Thread(target=_run, args=(path, use_clamav, st), daemon=True).start()
return True, ''
def _run(path, use_clamav, st):
from panel.routes.job_state import save_job
from panel.routes.settings import _scan_php_file
ignore = set(_load(IGNORE_FILE, []))
findings, scanned, last = [], 0, 0.0
t0 = time.time()
st['engines'] = ['signatures', 'uploads']
# Heartbeat while this thread lives: ClamAV can run for hours without any
# PHP file passing through the loop below, and a stale heartbeat made the
# status call report the scan as stopped (and allowed a second one to start).
beat_stop = threading.Event()
def _beat():
while not beat_stop.wait(30):
st['heartbeat'] = time.time()
try:
save_job(JOB, st)
except Exception: # noqa: BLE001
pass
beat = threading.Thread(target=_beat, daemon=True)
beat.start()
try:
for root, dirs, files in os.walk(path):
dirs[:] = [d for d in dirs if d not in _SKIP]
for fn in files:
if not fn.lower().endswith(_PHP_EXT):
continue
fp = os.path.join(root, fn)
if os.path.islink(fp):
continue
scanned += 1
try:
with open(fp, 'r', errors='replace') as fh:
content = fh.read(2 * 1024 * 1024)
except OSError:
continue
found = _scan_php_file(fp, content)
if _UPLOAD_DIR_RE.search(root) and not _CODE_DIR_RE.search(root) and fn.lower() != 'index.php':
found.append({'file': fp, 'line': 0, 'severity': 'HIGH',
'pattern': 'PHP file in an upload folder (uploads should only hold media)', 'snippet': ''})
if found:
sha = _sha(fp)
if sha in ignore:
continue
worst = min(found, key=lambda f: {'CRITICAL': 0, 'HIGH': 1, 'MEDIUM': 2}.get(f['severity'], 3))
findings.append({**worst, 'engine': 'signatures', 'sha256': sha, 'matches': len(found)})
now = time.time()
if now - last > 1:
st.update(scanned=scanned, current=root, heartbeat=now, total=len(findings))
save_job(JOB, st)
last = now
if time.time() - t0 > 3600:
break
if use_clamav and clamav_info()['installed']:
st['engines'].append('clamav')
st.update(current='ClamAV', heartbeat=time.time())
save_job(JOB, st)
info = clamav_info()
cmd = (['clamdscan', '--infected', '--no-summary', '--multiscan', '--fdpass', path] if info['daemon']
else ['clamscan', '-r', '--infected', '--no-summary', '--max-filesize=50M', path])
try:
r = subprocess.run(cmd, capture_output=True, text=True, timeout=6 * 3600)
for line in r.stdout.splitlines():
m = re.match(r'^(.*): (.+) FOUND$', line)
if m and not any(f['file'] == m.group(1) for f in findings):
sha = _sha(m.group(1))
if sha in ignore:
continue
findings.append({'file': m.group(1), 'line': 0, 'severity': 'CRITICAL', 'engine': 'clamav',
'pattern': 'ClamAV: ' + m.group(2), 'snippet': '', 'sha256': sha, 'matches': 1})
except subprocess.TimeoutExpired:
st['clamav_error'] = 'ClamAV did not finish within 6 hours'
except Exception as e:
st['error'] = f'{type(e).__name__}: {e}'
beat_stop.set()
beat.join(timeout=5)
findings.sort(key=lambda x: {'CRITICAL': 0, 'HIGH': 1, 'MEDIUM': 2}.get(x['severity'], 3))
st.update(running=False, done=True, scanned=scanned, current='', heartbeat=time.time(), finished=time.time(),
duration=round(time.time() - t0, 1), total=len(findings),
critical=sum(1 for f in findings if f['severity'] == 'CRITICAL'),
high=sum(1 for f in findings if f['severity'] == 'HIGH'),
medium=sum(1 for f in findings if f['severity'] == 'MEDIUM'),
findings=findings[:1000])
save_job(JOB, st)
if st.get('trigger') == 'schedule':
sched = _load(SCHED_FILE, {})
prev = set(sched.get('last_files') or [])
new = [f for f in findings if f['file'] not in prev and f['severity'] in ('CRITICAL', 'HIGH')]
sched.update(last_run=time.time(), last_total=len(findings), last_files=[f['file'] for f in findings][:2000])
_save(SCHED_FILE, sched)
if new:
try:
from panel.alerts import notify_event
lines = '\n'.join(f'- {f["file"]}: {f["pattern"]}' for f in new[:20])
notify_event('malware', f'Malware scan found {len(new)} new suspicious file(s)',
f'The daily scan of {path} found:\n{lines}\n\nReview them under Security > Malware scan.')
except Exception:
pass
def _valid_target(fp):
"""Only regular files inside website folders can be quarantined or ignored."""
if not fp or os.path.islink(fp):
return None
real = os.path.realpath(fp)
roots = ['/www/', '/var/www/', '/home/', '/srv/']
try:
from panel.routes.websites_core import get_webroot
roots.append(get_webroot().rstrip('/') + '/')
except Exception:
pass
if not os.path.isfile(real) or not real.startswith(tuple(roots)) or real.startswith('/opt/vortexpanel'):
return None
return real
def quarantine(fp):
real = _valid_target(fp)
if not real:
return False, 'Not a file inside a website folder'
qid = time.strftime('%Y%m%d-%H%M%S-') + uuid.uuid4().hex[:6]
d = os.path.join(QDIR, qid)
os.makedirs(d, mode=0o700, exist_ok=True)
os.chmod(QDIR, 0o700)
st = os.stat(real)
meta = {'id': qid, 'path': real, 'mode': st.st_mode & 0o7777, 'uid': st.st_uid, 'gid': st.st_gid,
'size': st.st_size, 'time': time.time(), 'sha256': _sha(real)}
shutil.move(real, os.path.join(d, 'file'))
os.chmod(os.path.join(d, 'file'), 0o400)
_save(os.path.join(d, 'meta.json'), meta)
return True, qid
def quarantine_list():
out = []
try:
for qid in sorted(os.listdir(QDIR), reverse=True):
m = _load(os.path.join(QDIR, qid, 'meta.json'), None)
if m:
out.append(m)
except OSError:
pass
return out
def restore(qid):
if not re.fullmatch(r'[0-9-]+[0-9a-f]{6}', qid or ''):
return False, 'Invalid id'
d = os.path.join(QDIR, qid)
m = _load(os.path.join(d, 'meta.json'), None)
if not m:
return False, 'Not found'
if os.path.exists(m['path']):
return False, f'{m["path"]} exists again; move it away first'
os.makedirs(os.path.dirname(m['path']), exist_ok=True)
shutil.move(os.path.join(d, 'file'), m['path'])
os.chmod(m['path'], m['mode'])
os.chown(m['path'], m['uid'], m['gid'])
shutil.rmtree(d, ignore_errors=True)
return True, m['path']
def delete_quarantined(qid):
if not re.fullmatch(r'[0-9-]+[0-9a-f]{6}', qid or ''):
return False
shutil.rmtree(os.path.join(QDIR, qid), ignore_errors=True)
return True
def ignore(fp):
real = _valid_target(fp)
if not real:
return False
lst = _load(IGNORE_FILE, [])
sha = _sha(real)
if sha and sha not in lst:
lst.append(sha)
_save(IGNORE_FILE, lst[-5000:])
st = _state()
if st.get('findings'):
from panel.routes.job_state import save_job
st['findings'] = [f for f in st['findings'] if f['file'] != fp]
st['total'] = len(st['findings'])
save_job(JOB, st)
return True
def schedule_get():
s = _load(SCHED_FILE, {})
return {'enabled': bool(s.get('enabled')), 'hour': int(s.get('hour', 3)), 'clamav': bool(s.get('clamav', True)),
'path': s.get('path', ''), 'last_run': s.get('last_run'), 'last_total': s.get('last_total')}
def schedule_set(enabled, hour, clamav, path=''):
s = _load(SCHED_FILE, {})
s.update(enabled=bool(enabled), hour=max(0, min(23, int(hour))), clamav=bool(clamav), path=path or '')
_save(SCHED_FILE, s)
def run_due():
"""Called by the backups timer every 5 minutes."""
s = _load(SCHED_FILE, {})
if not s.get('enabled'):
return
now = time.localtime()
if now.tm_hour != int(s.get('hour', 3)):
return
if time.time() - (s.get('last_start') or 0) < 20 * 3600:
return
path = s.get('path') or ''
if not path:
try:
from panel.routes.websites_core import get_webroot
path = get_webroot()
except Exception:
path = '/www/wwwroot'
s['last_start'] = time.time()
_save(SCHED_FILE, s)
# Its own transient unit: the timer's process exits right after this.
subprocess.run(['systemd-run', '--unit=vortexpanel-malware-scan', '--collect', '--quiet',
'--property=Nice=15', '--property=IOSchedulingClass=idle',
'--working-directory=/opt/vortexpanel', '/opt/vortexpanel/venv/bin/python3', '-m',
'panel.tasks', 'malware-scan', path, '1' if s.get('clamav', True) else '0'],
capture_output=True, timeout=30)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.