Skip to content

Conversation

@yokeep9-rgb
Copy link

No description provided.

"""
Core Defense Module
- Integrity monitoring (SHA256 tripwire)
- Decoy file layer generator
- Encrypted read-only snapshot (ghost copy)
- Key rotation (symmetric keys)
- Alerts via Telegram
- Best-effort auto-isolation (requires root for full effect)

Configure the CONFIG block below before running.
"""

import os
import sys
import time
import json
import hashlib
import shutil
import threading
import tempfile
import traceback
from datetime import datetime, timedelta
from pathlib import Path

# External libs (install with pip): watchdog, cryptography, requests
try:
    from watchdog.observers import Observer
        from watchdog.events import FileSystemEventHandler
            from cryptography.fernet import Fernet
                import requests
                except Exception as e:
                    print("Missing dependencies. Run: pip install watchdog cryptography requests")
                        raise

                        # -------- CONFIG --------
                        CONFIG = {
                            "MONITOR_DIRS": ["/data/data/com.termux/files/home/core"],  # directories to watch (list)
                                "SNAPSHOT_DIR": "/data/data/com.termux/files/home/core_snapshots",  # where to keep encrypted snapshots
                                    "DECoy_DIR": "/data/data/com.termux/files/home/core_decoys",  # decoy files live here
                                        "TRIPWIRE_DB": "/data/data/com.termux/files/home/.core_tripwire.json",  # stored hash db
                                            "KEY_FILE": "/data/data/com.termux/files/home/.core_defense_key",  # current symmetric key
                                                "KEY_ROTATION_DAYS": 7,  # rotate key every N days
                                                    "SNAPSHOT_ON_BREACH": True,
                                                        "MAX_SNAPSHOTS": 6,
                                                            "TELEGRAM_BOT_TOKEN": "CHANGE_THIS",  # set to your bot token or leave blank
                                                                "TELEGRAM_CHAT_ID": "CHANGE_THIS",  # set to your chat id or leave blank
                                                                    "ALERT_ON_EVENTS": True,
                                                                        "ISOLATE_ON_BREACH": True,
                                                                            "ISOLATION_TIMEOUT_SECONDS": 30,
                                                                                "DECoy_COUNT": 5,
                                                                                    "LOG_FILE": "/data/data/com.termux/files/home/core_defense.log"
                                                                                    }
                                                                                    # ------------------------

                                                                                    def log(msg):
                                                                                        ts = datetime.utcnow().isoformat() + "Z"
                                                                                            entry = f"[{ts}] {msg}"
                                                                                                print(entry)
                                                                                                    try:
                                                                                                            with open(CONFIG["LOG_FILE"], "a") as f:
                                                                                                                        f.write(entry + "\n")
                                                                                                                            except Exception:
                                                                                                                                    pass

                                                                                                                                    # ---------- Key Management ----------
                                                                                                                                    def ensure_key():
                                                                                                                                        key_path = Path(CONFIG["KEY_FILE"])
                                                                                                                                            if key_path.exists():
                                                                                                                                                    key = key_path.read_bytes().strip()
                                                                                                                                                            return key
                                                                                                                                                                else:
                                                                                                                                                                        key = Fernet.generate_key()
                                                                                                                                                                                key_path.write_bytes(key)
                                                                                                                                                                                        os.chmod(key_path, 0o600)
                                                                                                                                                                                                log("Generated new symmetric key.")
                                                                                                                                                                                                        return key

                                                                                                                                                                                                        def rotate_key_if_needed():
                                                                                                                                                                                                            key_path = Path(CONFIG["KEY_FILE"])
                                                                                                                                                                                                                if not key_path.exists():
                                                                                                                                                                                                                        return ensure_key()
                                                                                                                                                                                                                            mtime = datetime.utcfromtimestamp(key_path.stat().st_mtime)
                                                                                                                                                                                                                                if datetime.utcnow() - mtime > timedelta(days=CONFIG["KEY_ROTATION_DAYS"]):
                                                                                                                                                                                                                                        # rotate - archive old key
                                                                                                                                                                                                                                                archive = str(key_path) + ".old-" + datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
                                                                                                                                                                                                                                                        shutil.copy2(str(key_path), archive)
                                                                                                                                                                                                                                                                key = Fernet.generate_key()
                                                                                                                                                                                                                                                                        key_path.write_bytes(key)
                                                                                                                                                                                                                                                                                os.chmod(key_path, 0o600)
                                                                                                                                                                                                                                                                                        log(f"Key rotated. Old key saved as {archive}")
                                                                                                                                                                                                                                                                                                return key
                                                                                                                                                                                                                                                                                                    return key_path.read_bytes().strip()

                                                                                                                                                                                                                                                                                                    # ---------- Tripwire (SHA256 hashes) ----------
                                                                                                                                                                                                                                                                                                    def file_sha256(path: Path):
                                                                                                                                                                                                                                                                                                        h = hashlib.sha256()
                                                                                                                                                                                                                                                                                                            try:
                                                                                                                                                                                                                                                                                                                    with path.open("rb") as f:
                                                                                                                                                                                                                                                                                                                                for chunk in iter(lambda: f.read(8192), b""):
                                                                                                                                                                                                                                                                                                                                                h.update(chunk)
                                                                                                                                                                                                                                                                                                                                                        return h.hexdigest()
                                                                                                                                                                                                                                                                                                                                                            except Exception:
                                                                                                                                                                                                                                                                                                                                                                    return None

                                                                                                                                                                                                                                                                                                                                                                    def scan_and_update_hashes():
                                                                                                                                                                                                                                                                                                                                                                        tripwire = {}
                                                                                                                                                                                                                                                                                                                                                                            for base in CONFIG["MONITOR_DIRS"]:
                                                                                                                                                                                                                                                                                                                                                                                    basep = Path(base)
                                                                                                                                                                                                                                                                                                                                                                                            if not basep.exists():
                                                                                                                                                                                                                                                                                                                                                                                                        continue
                                                                                                                                                                                                                                                                                                                                                                                                                for p in basep.rglob("*"):
                                                                                                                                                                                                                                                                                                                                                                                                                            if p.is_file():
                                                                                                                                                                                                                                                                                                                                                                                                                                            s = file_sha256(p)
                                                                                                                                                                                                                                                                                                                                                                                                                                                            if s:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                tripwire[str(p)] = s
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    # persist
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        try:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                with open(CONFIG["TRIPWIRE_DB"], "w") as f:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            json.dump({"scanned_at": datetime.utcnow().isoformat(), "data": tripwire}, f)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                except Exception as e:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        log(f"Failed to write tripwire DB: {e}")
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            return tripwire

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            def load_tripwire():
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                try:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        with open(CONFIG["TRIPWIRE_DB"], "r") as f:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    db = json.load(f)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                return db.get("data", {})
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    except Exception:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            return {}

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            # ---------- Alerts ----------
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            def send_telegram(text):
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                if not CONFIG["TELEGRAM_BOT_TOKEN"] or "CHANGE_THIS" in CONFIG["TELEGRAM_BOT_TOKEN"]:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        log("Telegram not configured; skipping alert: " + text[:120])
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                return False
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    try:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            url = f"https://api.telegram.org/bot{CONFIG['TELEGRAM_BOT_TOKEN']}/sendMessage"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    resp = requests.post(url, json={"chat_id": CONFIG["TELEGRAM_CHAT_ID"], "text": text})
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            if resp.status_code == 200:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        return True
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                else:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            log("Telegram send failed: " + resp.text)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        return False
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            except Exception as e:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    log("Telegram exception: " + str(e))
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            return False

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            def alert(msg):
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                log("ALERT: " + msg)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    if CONFIG["ALERT_ON_EVENTS"]:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            send_telegram(msg)

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            # ---------- Snapshot (encrypted ghost copy) ----------
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            def make_encrypted_snapshot(key):
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                stamp = datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    snapshot_temp = tempfile.mkdtemp(prefix="core_snapshot_")
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        try:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                # copy monitored dirs
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        for base in CONFIG["MONITOR_DIRS"]:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    basep = Path(base)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                if basep.exists():
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                dest = Path(snapshot_temp) / basep.name
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                shutil.copytree(str(basep), str(dest))
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        # archive the snapshot
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                archive_path = Path(CONFIG["SNAPSHOT_DIR"])
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        archive_path.mkdir(parents=True, exist_ok=True)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                tarfile = str(archive_path / f"snapshot_{stamp}.tar.gz")
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        shutil.make_archive(str(archive_path / f"snapshot_{stamp}"), 'gztar', snapshot_temp)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                # encrypt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        f = Fernet(key)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                with open(tarfile, "rb") as tf:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            data = tf.read()
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    enc = f.encrypt(data)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            enc_path = tarfile + ".enc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    with open(enc_path, "wb") as ef:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                ef.write(enc)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        os.remove(tarfile)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                # cleanup old snapshots
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        snapshots = sorted(Path(CONFIG["SNAPSHOT_DIR"]).glob("snapshot_*.tar.gz.enc"), key=os.path.getmtime, reverse=True)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                for old in snapshots[CONFIG["MAX_SNAPSHOTS"]:]:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            try:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            old.unlink()
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        except: pass
                                                                                                                                                                                                                                                                                                                                                                                                                                 …
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants