-
-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathlazyc2.py
More file actions
5504 lines (4682 loc) · 204 KB
/
Copy pathlazyc2.py
File metadata and controls
5504 lines (4682 loc) · 204 KB
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import os
import csv
import pty
import sys
import ssl
import json
import yaml
import glob
import stat
import time
import uuid
import errno
import fcntl
import shlex
import socket
import base64
import select
import struct
import html
import yagmail
import smtplib
import secrets
import termios
import sqlite3
import logging
import zipfile
import requests
import markdown
import threading
import validators
import subprocess
import pandas as pd
from math import ceil
from io import StringIO
from pathlib import Path
from functools import wraps
from threading import Thread
from lazyown import LazyOwnShell
from flask_limiter import Limiter
from urllib.parse import urlparse
from collections import defaultdict
from modules.colors import retModel
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from watchdog.observers import Observer
from datetime import datetime, timezone
from werkzeug.utils import secure_filename
from email.mime.multipart import MIMEMultipart
from dnslib.server import DNSServer, DNSLogger
from jinja2 import Environment, FileSystemLoader
from flask_limiter.util import get_remote_address
from watchdog.events import FileSystemEventHandler
from modules.lazygptcli2 import process_prompt, Groq
from modules.lazygptvulns import process_prompt_vuln
from modules.lazygpttask import process_prompt_task
from modules.lazyredopgpt import process_prompt_redop
from modules.lazyagentAi import process_prompt_search
from modules.lazygptcli3 import process_prompt_script
from modules.lazygptcli5 import process_prompt_general
from cryptography.hazmat.backends import default_backend
from modules.lazygptcli4 import process_prompt_adversary
from flask_socketio import SocketIO, send, emit, disconnect
from modules.lazyphishingai import process_prompt_local_yaml
from dnslib.server import DNSServer, BaseResolver, DNSLogger
from utils import getprompt, Config, load_payload, anti_debug
from modules.lazydeepseekcli_local import process_prompt_local
from modules.lazydeepseekcli_localreport import process_prompt_localreport
from werkzeug.security import generate_password_hash, check_password_hash
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from dnslib import DNSRecord, DNSHeader, RR, QTYPE, A, TXT, CNAME, MX, NS, SOA, CAA, TLSA, SSHFP
from dnslib.dns import RR, QTYPE, A, NS, SOA, TXT, CNAME, MX, AAAA, PTR, SRV, NAPTR, CAA, TLSA, SSHFP
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask import Flask, request, render_template, redirect, url_for, jsonify, Response, send_from_directory, render_template_string, flash, abort, jsonify, Response, stream_with_context, Blueprint, send_file, current_app
from cli.palette import CommandIndexError as _PaletteIndexError
from cli.palette import load_index as _palette_load_index
from cli.palette_command import build_palette_view as _palette_build_view
from modules.metrics import REGISTRY
from modules.listener_manager import ListenerManager
from modules.live_surface import build_live_graph
from modules.security_sanitizers import (
BindAddressResolver,
OutputSanitizer,
SessionPathResolver,
build_default_config,
)
from lazyc2.security.validators import (
validate_route_path as _validate_route_path,
validate_template_name as _validate_template_name,
validate_file_path_within_base as _validate_file_path_within_base,
)
from lazyc2.security.services import (
AESKeyManager as _AESKeyManager,
SecretKeyManager as _SecretKeyManager,
)
from lazyc2.security.constants import AES_KEY_SIZE_BYTES as _AES_KEY_SIZE_BYTES
_LAZYOWN_SECRET_KEY_ENV = "LAZYOWN_SECRET_KEY"
anti_debug()
logger = logging.getLogger(__name__)
_payload_snapshot = load_payload()
config = Config(_payload_snapshot)
_security_config = build_default_config(_payload_snapshot)
_output_sanitizer = OutputSanitizer(_security_config)
def _listen_address():
"""Return the bind address chosen by :class:`BindAddressResolver`.
The resolver receives the operator-supplied ``c2_bind_address`` and
``lhost`` candidates from ``payload.json`` in priority order. When
neither parses as a valid IP literal, the resolver falls back to
the loopback address unless the operator has explicitly enabled
``allow_unspecified_bind``, which is the documented opt-in for
exposing the C2 on every interface.
"""
candidates = (
getattr(config, 'c2_bind_address', None),
getattr(config, 'lhost', None),
)
resolver = BindAddressResolver(_security_config, candidates)
return resolver.resolve()
_BIND_PROBE_TIMEOUT_SECONDS = 0.5
_C2_DNS_PORT = 53
_LOOPBACK_ADDRESS = "127.0.0.1"
_UNSPECIFIED_ADDRESS = "0.0.0.0"
_UNSPECIFIED_BIND_LITERALS = frozenset({"0.0.0.0", "::", ""})
def _is_unspecified_bind_literal(address: str) -> bool:
"""Return True when ``address`` is a wildcard bind literal.
The C2 must never silently bind to every network interface, so the
helper is used as an inline sanitizer at the bind call sites where
static analysis cannot follow the value across functions.
Args:
address: Candidate address literal.
Returns:
True when ``address`` is ``0.0.0.0``, ``::`` or the empty
string; False otherwise.
"""
if not isinstance(address, str):
return False
return address.strip() in _UNSPECIFIED_BIND_LITERALS
def _select_specific_bind_address(candidate: object) -> str:
"""Return a specific IP literal safe to pass to ``socket.bind``.
Wildcard addresses (``""``, ``"0.0.0.0"``, ``"::"``) are rejected
using an inline literal comparison so static analysers recognise
the sanitiser. The framework never auto-binds to every interface;
if the operator wants that behaviour they must put the specific
NIC address into ``c2_bind_address`` or ``lhost`` in
``payload.json``. When the candidate is not a parseable IP literal
the loopback fallback is returned.
Args:
candidate: Operator-supplied address candidate.
Returns:
A specific IPv4/IPv6 literal, defaulting to ``127.0.0.1`` when
no valid specific literal can be derived.
"""
loopback = getattr(_security_config, "bind_loopback_address", _LOOPBACK_ADDRESS) or _LOOPBACK_ADDRESS
if not isinstance(candidate, str):
return loopback
stripped = candidate.strip()
if stripped == "" or stripped == "0.0.0.0" or stripped == "::":
return loopback
try:
import ipaddress as _ipaddress
_ipaddress.ip_address(stripped)
except (ValueError, ImportError):
return loopback
return stripped
def _probe_bind(address: str, port: int, sock_type: int = socket.SOCK_STREAM) -> tuple[bool, int | None]:
"""Probe whether ``(address, port)`` can be bound for ``sock_type``.
The probe creates a transient socket, attempts the bind and closes
immediately. ``SO_REUSEADDR`` is set so that a recent close on the
same tuple does not raise a spurious ``EADDRINUSE``. The probe
refuses to bind a wildcard address unless the operator has
explicitly enabled :attr:`SecurityConfig.allow_unspecified_bind`,
so the function doubles as a fail-closed sanitizer for the bind
candidate flowing in from operator-controlled payload values.
Args:
address: IPv4 address literal to test.
port: Port number to test. ``0`` lets the kernel pick.
sock_type: ``socket.SOCK_STREAM`` for TCP services or
``socket.SOCK_DGRAM`` for UDP services such as DNS.
Returns:
Tuple ``(success, errno_value)`` where ``errno_value`` is the
``OSError.errno`` on failure and ``None`` on success. Returns
``(False, errno.EACCES)`` when the address is a wildcard and
the operator has not opted in to all-interface binding.
"""
if not isinstance(address, str):
return False, errno.EINVAL
safe_address = address.strip()
if safe_address == "" or safe_address == "0.0.0.0" or safe_address == "::":
return False, errno.EACCES
probe = None
try:
probe = socket.socket(socket.AF_INET, sock_type)
probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
probe.settimeout(_BIND_PROBE_TIMEOUT_SECONDS)
probe.bind((safe_address, port))
return True, None
except OSError as exc:
return False, exc.errno
finally:
if probe is not None:
try:
probe.close()
except OSError:
pass
def _resolve_bind_address(
preferred: str | None = None,
port: int = 0,
sock_type: int = socket.SOCK_STREAM,
) -> str:
"""Return an address that can actually be bound to on this host.
Probes each candidate with :func:`_probe_bind` and returns the first
address that succeeds. The resolver fails closed: the unspecified
address ``0.0.0.0`` is only ever offered when the operator has set
``allow_unspecified_bind`` in :class:`SecurityConfig`. When every
candidate fails the probe, the configured loopback fallback is
returned so the caller never accidentally binds to every interface.
The probe uses the same socket type the caller will use, so UDP
services such as DNS are tested with ``SOCK_DGRAM``.
Args:
preferred: Explicit address to try first. When ``None`` the
address chosen by :func:`_listen_address` is used.
port: Port number for the probe. When ``0`` the kernel assigns
an ephemeral port so the test never collides with the real
service.
sock_type: Socket type matching the eventual server.
Returns:
A bindable IPv4 address literal. Guaranteed to be the loopback
when no other candidate succeeds and the operator has not
explicitly opted in to binding on every interface.
"""
candidates: list[str] = []
if preferred is not None:
candidates.append(preferred)
try:
resolved = _listen_address()
if resolved not in candidates:
candidates.append(resolved)
except Exception:
logger.debug("Listen address resolution failed during probe", exc_info=True)
loopback_fallback = getattr(_security_config, "bind_loopback_address", _LOOPBACK_ADDRESS) or _LOOPBACK_ADDRESS
if loopback_fallback not in candidates:
candidates.append(loopback_fallback)
if getattr(_security_config, "allow_unspecified_bind", False):
unspecified = getattr(_security_config, "bind_unspecified_address", _UNSPECIFIED_ADDRESS) or _UNSPECIFIED_ADDRESS
if unspecified not in candidates:
candidates.append(unspecified)
for address in candidates:
success, _ = _probe_bind(address, port, sock_type)
if success:
return address
return loopback_fallback
phishing_bp = Blueprint('phishing', __name__, template_folder='templates/phishing')
if config.enable_c2_debug == True:
logging.basicConfig(filename='sessions/access.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
else:
logging.basicConfig(filename='sessions/access.log', level=logging.CRITICAL, format='%(asctime)s - %(levelname)s - %(message)s')
class _JsonLogFormatter(logging.Formatter):
"""Optional structured JSON formatter for C2 access logs."""
def format(self, record):
import datetime as _dt
payload = {
"timestamp": _dt.datetime.now(_dt.timezone.utc).replace(tzinfo=None).isoformat() + "Z",
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
"module": record.module,
"function": record.funcName,
"line": record.lineno,
}
if hasattr(record, "request_path"):
payload["request_path"] = record.request_path
if hasattr(record, "request_method"):
payload["request_method"] = record.request_method
if hasattr(record, "client_ip"):
payload["client_ip"] = record.client_ip
return json.dumps(payload)
if getattr(config, "enable_structured_logging", False):
_json_handler = logging.FileHandler("sessions/access.jsonl")
_json_handler.setFormatter(_JsonLogFormatter())
logging.getLogger().addHandler(_json_handler)
def ensure_sessions_dir():
"""Ensure the sessions directory exists with safe permissions."""
try:
os.makedirs('sessions', exist_ok=True)
os.chmod('sessions', stat.S_IRWXU) # 700: Owner read/write/execute only
except OSError as e:
if e.errno != errno.EEXIST:
logger.error(f"Failed to create sessions directory: {e}")
raise
def load_routes():
"""Load dynamic routes from JSON file."""
try:
with open('sessions/routes_to_templates.json', 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError) as e:
logger.error(f"Failed to load routes: {e}")
return {}
def save_routes(routes):
"""Save dynamic routes to JSON file with safe permissions."""
try:
ensure_sessions_dir()
temp_file = 'sessions/routes_to_templates.json.tmp'
with open(temp_file, 'w') as f:
json.dump(routes, f, indent=2)
os.rename(temp_file, 'sessions/routes_to_templates.json')
os.chmod('sessions/routes_to_templates.json', stat.S_IRUSR | stat.S_IWUSR) # 600: Owner read/write only
except Exception as e:
logger.error(f"Failed to save routes: {e}")
raise
def validate_route_path(route_path):
"""Module-level boolean adapter for :func:`lazyc2.security.validators.validate_route_path`.
Returns ``True`` when ``route_path`` passes the canonical validator
and ``False`` otherwise. Existing call sites that only need a
boolean signal can keep their current shape; new call sites should
prefer the underlying ``(is_valid, error)`` tuple for richer
diagnostics.
"""
is_valid, _ = _validate_route_path(route_path)
return is_valid
def validate_template_name(template_name):
"""Module-level boolean adapter for :func:`lazyc2.security.validators.validate_template_name`.
Returns ``True`` when ``template_name`` passes the canonical
validator and ``False`` otherwise.
"""
is_valid, _ = _validate_template_name(template_name)
return is_valid
def is_safe_template_path(template_path, template_name):
"""Verify ``template_path`` resolves inside ``app.template_folder``.
Delegates to the canonical traversal validator in
:mod:`lazyc2.security.validators` so the confinement check stays
consistent with every other security-sensitive call site. Retained
on the module surface because operators wire it into custom
templates from external scripts.
Args:
template_path: Candidate filesystem path produced by the caller.
template_name: Expected template basename. The candidate must
match this filename exactly, preventing the caller from
substituting an unrelated path that happens to live inside
the template folder.
Returns:
True when the resolved path is strictly equal to
``app.template_folder / template_name`` and lives inside the
template folder; False otherwise.
"""
template_folder = Path(app.template_folder).resolve()
candidate = Path(template_path).resolve()
expected = (template_folder / template_name).resolve()
if candidate != expected:
return False
is_valid, _ = _validate_file_path_within_base(candidate, template_folder)
return is_valid
def _sanitize_command_output(value):
"""Return a JSON-safe projection of ``value`` without exception details.
Delegates to the centralised :class:`OutputSanitizer` so the same
bounded-depth, exception-stripping projection is applied across
every C2 endpoint that returns shell output.
"""
return _output_sanitizer.sanitize(value)
def is_binary(safe_filename):
"""Check whether a session file is binary based on its header bytes.
Accepts a single basename, never a path. Reconstructing the absolute
path inside this function prevents a malicious caller from supplying
traversal sequences to read host files outside ``SESSIONS_DIR``.
Args:
safe_filename: Basename of a candidate file within ``SESSIONS_DIR``.
Returns:
True only when the resolved file lives inside ``SESSIONS_DIR`` and
its leading bytes match a known binary header. Any validation
failure or I/O error returns False.
"""
if not safe_filename or not isinstance(safe_filename, str):
return False
if safe_filename in ('.', '..'):
return False
if '/' in safe_filename or '\\' in safe_filename or '\x00' in safe_filename:
return False
if os.path.basename(safe_filename) != safe_filename:
return False
sessions_real = os.path.realpath(SESSIONS_DIR)
candidate_real = os.path.realpath(os.path.join(sessions_real, safe_filename))
try:
if os.path.commonpath([sessions_real, candidate_real]) != sessions_real:
return False
except ValueError:
return False
if not os.path.isfile(candidate_real):
return False
header_max_len = max((len(h) for h in BINARY_HEADERS), default=4)
try:
with open(candidate_real, 'rb') as f:
header = f.read(header_max_len)
except OSError:
return False
return any(header.startswith(b_header) for b_header in BINARY_HEADERS)
def get_request_details():
"""Extract and return request details as a dictionary."""
return {
'method': request.method,
'headers': dict(request.headers),
'args': request.args.to_dict(),
'form': request.form.to_dict(),
'json': request.get_json(silent=True),
'remote_addr': request.remote_addr,
'url': request.url,
'timestamp': str(uuid.uuid4())
}
def save_to_log(details):
"""Save request details to JSON log file with safe permissions."""
try:
ensure_sessions_dir()
log_file = 'sessions/request_log.json'
logs = []
if os.path.exists(log_file):
with open(log_file, 'r') as f:
logs = json.load(f)
logs.append(details)
temp_file = 'sessions/request_log.json.tmp'
with open(temp_file, 'w') as f:
json.dump(logs, f, indent=2)
os.rename(temp_file, log_file)
os.chmod(log_file, stat.S_IRUSR | stat.S_IWUSR) # 600: Owner read/write only
return {'status': 'logged', 'id': details['timestamp']}
except Exception as e:
logger.error(f"Failed to save log: {e}")
return {'error': 'Log save failed'}, 500
def clean_expired_tokens():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute('DELETE FROM auth_tokens WHERE expiry < ?', (int(time.time()),))
conn.commit()
conn.close()
def clean_json(texto):
"""Extract only the JSON content between ```json and ```, discarding everything else."""
match = re.search(r'```json\n(.*?)\n```', texto, re.DOTALL)
if match:
return match.group(1).strip()
return ""
_SAFE_YAML_NAME_RE = re.compile(r'^[a-zA-Z0-9_\-]+\.(yml|yaml)$')
def _resolve_within(allowed_base, name):
"""Resolve ``name`` strictly within ``allowed_base``.
Returns the absolute, real path only if it lives under ``allowed_base``.
Returns ``None`` for any traversal attempt or symlink escape. CodeQL
recognises this commonpath-based pattern as a path sanitiser.
"""
base_real = os.path.realpath(allowed_base)
candidate = os.path.realpath(os.path.join(base_real, name))
try:
if os.path.commonpath([base_real, candidate]) != base_real:
return None
except ValueError:
return None
return candidate
def load_yaml_safely(file_path):
"""Load a YAML file safely with error handling and default values."""
try:
if not file_path or not isinstance(file_path, str):
logger.error("Invalid file_path: must be a non-empty string")
return None
ALLOWED_BASE_DIRS = [
os.path.realpath("./templates"),
os.path.realpath("./sessions"),
os.path.realpath("./config"),
]
raw_name = os.path.basename(file_path.strip())
user_filename = secure_filename(raw_name)
if not user_filename or not _SAFE_YAML_NAME_RE.match(user_filename):
logger.error("Invalid YAML filename")
return None
clean_path = None
for base_dir in ALLOWED_BASE_DIRS:
candidate = _resolve_within(base_dir, user_filename)
if candidate and os.path.isfile(candidate):
clean_path = candidate
break
if clean_path is None:
for base_dir in ALLOWED_BASE_DIRS:
base_real = os.path.realpath(base_dir)
for root, _dirs, files in os.walk(base_real):
if user_filename in files:
candidate = os.path.realpath(os.path.join(root, user_filename))
try:
if os.path.commonpath([base_real, candidate]) != base_real:
continue
except ValueError:
continue
if os.path.isfile(candidate):
clean_path = candidate
break
if clean_path:
break
if clean_path is None:
logger.error("YAML file not found in allowed directories")
return None
file_size = os.path.getsize(clean_path)
if file_size > 10 * 1024 * 1024:
logger.error("YAML file too large")
return None
if not os.access(clean_path, os.R_OK):
logger.error("No read permission for YAML file")
return None
with open(clean_path, 'r', encoding='utf-8') as f:
data = yaml.safe_load(f)
if data is None:
logger.warning("Empty YAML file loaded")
data = {}
if not isinstance(data, dict):
logger.error("YAML file must contain a dictionary")
return None
data.setdefault('beacon_url', '')
data.setdefault('created_at', datetime.now(timezone.utc).isoformat())
return data
except yaml.YAMLError:
logger.exception("Invalid YAML content")
return None
except FileNotFoundError:
logger.error("YAML file not found")
return None
except Exception:
logger.exception("Error loading YAML")
return None
class Handler(FileSystemEventHandler):
@staticmethod
def on_any_event(event):
try:
if event.is_directory:
return None
event_info = {
"type": event.event_type,
"src_path": event.src_path,
"dest_path": getattr(event, 'dest_path', None),
"size": os.path.getsize(event.src_path) if os.path.exists(event.src_path) else None,
"timestamp": datetime.now().isoformat()
}
if event.src_path.startswith(f"{BASE_DIR}{rhost}"):
global counter_events
global events
counter_events += 1
events.append(event_info)
if counter_events >= 1000:
events.sort(key=lambda x: x['timestamp'], reverse=True)
events = events[:1000]
except Exception as e:
if config.enable_c2_debug == True:
logger.info(f"Error watchdog")
def get_karma_name(elo):
if elo < 1000:
return "Noob"
elif elo < 2000:
return "Rookie"
elif elo < 3000:
return "Skidy"
elif elo < 4000:
return "Hacker"
elif elo < 5000:
return "Pro"
elif elo < 6000:
return "Elite"
else:
return "Godlike"
def fromjson(value):
return json.loads(value)
def run_shell():
while True:
try:
shell.cmdloop()
except Exception as e:
if config.enable_c2_debug == True:
logger.info(f"[ERROR] Shell loop crashed:")
break
def load_banners():
"""Loads the banners from the JSON file."""
try:
with open('sessions/banners.json', 'r') as file:
config_banner = json.load(file)
except FileNotFoundError:
if config.enable_c2_debug == True:
logger.info("Error: File banners.json not found")
return
return config_banner
def load_mitre_data():
mitre_path = os.path.join("external", ".exploit", "mitre", "enterprise-attack", "enterprise-attack-16.1.json")
with open(mitre_path, "r") as f:
return json.load(f)
def load_event_config():
try:
with open('event_config.json', 'r') as f:
return json.load(f)
except FileNotFoundError:
return {"events": []}
def load_notifications():
JSON_FILE_PATH = 'sessions/notifications.json'
if not os.path.exists(JSON_FILE_PATH):
with open(JSON_FILE_PATH, 'w') as f:
json.dump([], f)
with open(JSON_FILE_PATH, 'r') as f:
notifications = json.load(f)
return notifications
def implants_check():
implants["implants"].clear()
implant_files = glob.glob(os.path.join(BASE_DIR, 'implant_config*.json'))
logging.info(implant_files)
if implant_files:
for i, file in enumerate(implant_files, start=1):
try:
with open(file, 'r') as f:
logging.info("Info: Implants created.")
content = f.read().strip()
implants["implants"].append({
"implant": i,
"content": content
})
except Exception as e:
if config.enable_c2_debug == True:
logger.info(f"[Error] reading file")
def extract_attack_vectors(nodes, edges):
"""
Analyzes BloodHound nodes and edges to extract critical attack vectors for AD compromise.
Args:
nodes (list): List of node dictionaries from process_bloodhound_zip.
edges (list): List of edge dictionaries from process_bloodhound_zip.
Returns:
dict: Structured data containing critical attack vectors.
"""
ad_data = {
'privileged_accounts': [],
'dangerous_permissions': [],
'potential_attack_paths': [],
'misconfigurations': []
}
for node in nodes:
if node.get('type') in ['User', 'Group'] and node.get('label', '').lower() in [
'domain admins', 'enterprise admins', 'administrators'
]:
ad_data['privileged_accounts'].append({
'id': node['id'],
'label': node['label'],
'type': node['type'],
'details': node['title']
})
dangerous_rights = ['GenericAll', 'WriteDacl', 'WriteOwner', 'Owns', 'AllExtendedRights', 'DCSync']
for edge in edges:
if edge['label'] in dangerous_rights:
source_node = next((n for n in nodes if n['id'] == edge['from']), None)
target_node = next((n for n in nodes if n['id'] == edge['to']), None)
if source_node and target_node:
ad_data['dangerous_permissions'].append({
'from': source_node['label'],
'to': target_node['label'],
'right': edge['label'],
'source_type': source_node['type'],
'target_type': target_node['type']
})
domain_admin_group = next(
(n for n in nodes if n.get('label', '').lower() == 'domain admins'), None
)
if domain_admin_group:
paths = []
for edge in edges:
if edge['to'] == domain_admin_group['id'] and edge['label'] == 'MemberOf':
source_node = next((n for n in nodes if n['id'] == edge['from']), None)
if source_node:
paths.append({
'path': f"{source_node['label']} -> Domain Admins",
'type': source_node['type'],
'details': f"{source_node['type']} has direct membership to Domain Admins"
})
if edge['label'] in ['AdminTo', 'DCSync']:
source_node = next((n for n in nodes if n['id'] == edge['from']), None)
target_node = next((n for n in nodes if n['id'] == edge['to']), None)
if source_node and target_node:
paths.append({
'path': f"{source_node['label']} -> {target_node['label']}",
'type': edge['label'],
'details': f"{source_node['type']} has {edge['label']} rights on {target_node['type']}"
})
ad_data['potential_attack_paths'] = paths
for node in nodes:
if node.get('type') == 'Computer':
properties = json.loads(node.get('title', '{}'))
if properties.get('unconstraineddelegation', False):
ad_data['misconfigurations'].append({
'label': node['label'],
'type': 'Unconstrained Delegation',
'details': 'Computer allows unconstrained delegation, enabling potential privilege escalation.'
})
return ad_data
def process_bloodhound_zip(zip_filepath):
"""
Processes a BloodHound ZIP file to extract nodes and edges for graph visualization.
Args:
zip_filepath (str): The path to the BloodHound ZIP file.
Returns:
tuple: (nodes, edges, error_message, ad_data). Nodes, edges, attack vectors for viz.js, and error message.
"""
nodes_data = {}
edges_data = []
error_message = None
try:
with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
json_files = [name for name in zip_ref.namelist() if name.endswith(".json")]
if not json_files:
return [], [], "No JSON files found in the ZIP", {}
for name in json_files:
with zip_ref.open(name) as f:
try:
data = json.load(f)
if config.enable_c2_debug == True:
logger.info(f"Processing file: {name}")
if config.enable_c2_debug == True:
logger.info(f"Data structure: {json.dumps(data, indent=2)[:500]}...")
items = data.get('data', []) if isinstance(data, dict) else data
if not isinstance(items, list):
if config.enable_c2_debug == True:
logger.info(f"Unexpected data structure in {name}: {type(items)}")
continue
for item in items:
if 'ObjectIdentifier' in item and 'Properties' in item:
node_id = item['ObjectIdentifier']
if node_id not in nodes_data:
properties = item['Properties']
nodes_data[node_id] = {
'id': node_id,
'label': properties.get('name', node_id),
'title': json.dumps(properties, indent=2),
'type': name.split('_')[1].replace('.json', '')
}
if 'Aces' in item and isinstance(item['Aces'], list):
for ace in item['Aces']:
if 'PrincipalSID' in ace and 'RightName' in ace:
edges_data.append({
'from': item['ObjectIdentifier'],
'to': ace['PrincipalSID'],
'label': ace['RightName']
})
if 'PrimaryGroupSID' in item and item['PrimaryGroupSID']:
edges_data.append({
'from': item['ObjectIdentifier'],
'to': item['PrimaryGroupSID'],
'label': 'MemberOf'
})
except json.JSONDecodeError as e:
if config.enable_c2_debug == True:
logger.info(f"Error decoding JSON in {name}: ")
error_message = f"Error decoding JSON in {name}: "
except Exception as e:
if config.enable_c2_debug == True:
logger.info(f"Error processing {name}: ")
error_message = f"Error processing {name}: "
if not nodes_data and not edges_data:
error_message = "No valid nodes or edges extracted from the ZIP"
ad_data = extract_attack_vectors(list(nodes_data.values()), edges_data)
except FileNotFoundError:
error_message = f"File not found: {zip_filepath}"
logger.info(error_message)
ad_data = {}
except zipfile.BadZipFile:
error_message = f"Invalid or corrupted ZIP file: {zip_filepath}"
logger.info(error_message)
ad_data = {}
except Exception as e:
error_message = f"An unexpected error occurred: {str('')}"
logger.info(error_message)
ad_data = {}
return list(nodes_data.values()), edges_data, error_message, ad_data
def start_watching():
event_handler = Handler()
observer = Observer()
observer.schedule(event_handler, DIRECTORY_TO_WATCH, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except:
observer.stop()
observer.join()
def load_tasks():
if not os.path.exists('sessions/tasks.json'):
with open('sessions/tasks.json', 'w') as file:
json.dump([], file)
with open('sessions/tasks.json', 'r') as file:
return json.load(file)
def create_cves():
if not os.path.exists('sessions/cves.json'):
with open('sessions/cves.json', 'w') as json_file:
return json.dump({}, json_file)
def load_cves():
if not os.path.exists('sessions/cves.json'):
with open('sessions/cves.json', 'w') as file:
json.dump([], file)
with open('sessions/cves.json', 'r') as file:
return json.load(file)
def save_cves(cves):
with open('sessions/cves.json', 'w') as file:
json.dump(cves, file, indent=4)
def create_report():
if not os.path.exists(JSON_FILE_PATH_REPORT):
with open(JSON_FILE_PATH_REPORT, 'w') as json_file:
return json.dump({}, json_file)
def save_tasks(tasks):
with open('sessions/tasks.json', 'w') as file:
json.dump(tasks, file, indent=4)
def load_note():
file_path = 'sessions/notes.txt'
if not os.path.exists(file_path):
with open(file_path, 'w') as file:
file.write(json.dumps({"content": ""}))
with open(file_path, 'r') as file:
notes = file.read().strip()
if not notes:
return {"content": ""}
try:
return json.loads(notes)
except json.JSONDecodeError:
return {"content": ""}
def aumentar_elo(user_id, cantidad):
if os.path.exists(USER_DATA_PATH):
with open(USER_DATA_PATH, 'r') as file:
users = json.load(file)
else:
users = []
usuario = next((user for user in users if user['id'] == user_id), None)
if usuario:
usuario['elo'] += cantidad
logger.info(f"The Elo of user {usuario['username']} Increased in {usuario['elo']}.")
with open(USER_DATA_PATH, 'w') as file:
json.dump(users, file, indent=4)
else:
logger.info(f"User ID {user_id} not found.")
def save_note(content):
file_path = 'sessions/notes.txt'
with open(file_path, 'w') as file:
file.write(json.dumps({"content": content}))
def escape_js(s):
return json.dumps(s)[1:-1]
_ALLOWED_TAGS = ('p', 'br', 'strong', 'em', 'ul', 'ol', 'li', 'code', 'pre',
'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a')
def _sanitize_html(raw_html):
"""Sanitize HTML by stripping dangerous tags and event handlers."""
if not raw_html:
return ""
raw_html = re.sub(r'<(script|style)[^>]*>.*?</\1>', '', raw_html,
flags=re.DOTALL | re.IGNORECASE)
raw_html = re.sub(r'on\w+\s*=\s*["\'][^"\']*["\']', '', raw_html,
flags=re.IGNORECASE)
raw_html = re.sub(r'javascript:', '', raw_html, flags=re.IGNORECASE)
escaped = html.escape(raw_html)
for tag in _ALLOWED_TAGS: