- 
        Couldn't load subscription status. 
- Fork 1.2k
Create codeql.yml #593
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            yokeep9-rgb
  wants to merge
  2
  commits into
  Jasonchenlijian:master
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
yokeep9-rgb:master
  
      
      
   
  
    
  
  
  
 
  
      
    base: master
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
                
     Open
            
            Create codeql.yml #593
Conversation
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
    """
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
                                                                                                                                                                                                                                                                                                                                                                                                                                 …
    
              
                    Cbnc-Mk
  
              
              approved these changes
              
                  
                    Aug 12, 2025 
                  
              
              
            
            
              
                    Cbnc-Mk
  
              
              approved these changes
              
                  
                    Aug 12, 2025 
                  
              
              
            
            
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
      
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
No description provided.