File size: 6,031 Bytes
05b9f96
497c79e
 
 
 
05b9f96
497c79e
 
05b9f96
 
 
497c79e
05b9f96
497c79e
 
 
 
 
 
 
05b9f96
497c79e
 
 
 
 
05b9f96
497c79e
 
 
 
 
05b9f96
 
 
 
497c79e
05b9f96
497c79e
05b9f96
 
 
 
 
 
497c79e
05b9f96
 
 
 
 
 
 
497c79e
05b9f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497c79e
 
05b9f96
 
497c79e
05b9f96
 
 
 
497c79e
05b9f96
 
497c79e
05b9f96
 
497c79e
05b9f96
 
 
 
497c79e
05b9f96
 
497c79e
05b9f96
497c79e
 
05b9f96
 
 
 
 
 
 
 
 
497c79e
 
05b9f96
 
 
 
 
 
 
497c79e
05b9f96
 
497c79e
05b9f96
497c79e
 
 
 
 
 
 
 
 
 
05b9f96
 
 
 
 
 
 
497c79e
 
 
05b9f96
497c79e
 
 
 
 
 
05b9f96
497c79e
05b9f96
497c79e
 
 
 
05b9f96
497c79e
 
 
 
 
 
05b9f96
 
497c79e
 
 
 
 
05b9f96
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# be_core_defender.py
import os
import shutil
import time
import json
import hashlib
import requests
from datetime import datetime
from typing import Optional, Dict
from filelock import FileLock
from requests.adapters import HTTPAdapter, Retry

# === Configuration (preserved) ===
PROTECTED_FILES = [
    "BELEL_PROTOCOL_OVERVIEW.md",
    "canonical_config.json",
    "belel_guardian.py",
    "media_sentient_engine.py",
    "mutation_watcher.py",
    "claim_review_publisher.py",
    "concordium_enforcer.py",
]

MIRROR_URLS = [
    "https://github.com/TTOPM/be-core-bridge",
    "https://arweave.net/",
    "https://ipfs.io/ipfs/",
]

BACKUP_DIR = "./backup_mirror"
HASH_STORE = "code_hashes.json"

# Optional env overrides / extras (non-breaking)
DEFENDER_INTERVAL_SECS = int(os.getenv("BELEL_DEFENDER_INTERVAL_SECS", "300"))
WEB3_STORAGE_ENDPOINT = os.getenv("WEB3_STORAGE_ENDPOINT", "https://api.web3.storage/upload")
WEB3_STORAGE_TOKEN = os.getenv("WEB3_STORAGE_TOKEN")  # optional but recommended for web3.storage

# === Helpers (preserved & improved) ===

def _requests_session() -> requests.Session:
    s = requests.Session()
    retries = Retry(total=4, backoff_factor=0.5, status_forcelist=[429, 500, 502, 503, 504])
    s.mount("http://", HTTPAdapter(max_retries=retries))
    s.mount("https://", HTTPAdapter(max_retries=retries))
    return s

def hash_file(filepath: str) -> str:
    """Stream SHA-256 to support large files safely."""
    h = hashlib.sha256()
    with open(filepath, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            h.update(chunk)
    return h.hexdigest()

def load_hashes() -> Dict[str, str]:
    if not os.path.exists(HASH_STORE):
        return {}
    try:
        with FileLock(HASH_STORE + ".lock"):
            with open(HASH_STORE, "r", encoding="utf-8") as f:
                return json.load(f)
    except Exception:
        return {}

def save_hashes(hashes: Dict[str, str]) -> None:
    os.makedirs(os.path.dirname(HASH_STORE) or ".", exist_ok=True)
    tmp = HASH_STORE + ".tmp"
    with FileLock(HASH_STORE + ".lock"):
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(hashes, f, indent=2, ensure_ascii=False)
        os.replace(tmp, HASH_STORE)

def backup_file(filepath: str) -> str:
    os.makedirs(BACKUP_DIR, exist_ok=True)
    timestamp = datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
    backup_path = os.path.join(BACKUP_DIR, f"{os.path.basename(filepath)}.{timestamp}.bak")
    shutil.copy2(filepath, backup_path)
    print(f"๐Ÿ›ก๏ธ  Backup created for {filepath}")
    return backup_path

def restore_file(filepath: str) -> bool:
    if not os.path.exists(BACKUP_DIR):
        print(f"โš ๏ธ  No backup dir found for {filepath}")
        return False
    backups = sorted(
        [f for f in os.listdir(BACKUP_DIR) if f.startswith(os.path.basename(filepath) + ".")],
        reverse=True,
    )
    if not backups:
        print(f"โš ๏ธ  No backup found for {filepath}")
        return False
    latest = os.path.join(BACKUP_DIR, backups[0])
    shutil.copy2(latest, filepath)
    print(f"๐Ÿ› ๏ธ  Restored {filepath} from backup {latest}.")
    return True

def detect_virus(content: str) -> bool:
    # (preserved heuristic; still intentionally simple)
    lower = content.lower()
    signs = ["<script>", "eval(", "rm -rf", "exec(", "socket", "base64", "crypt"]
    return any(s in lower for s in signs)

def upload_to_ipfs(file_path: str) -> bool:
    """
    Mirrors the file to web3.storage. If WEB3_STORAGE_TOKEN is set, use it.
    """
    session = _requests_session()
    headers = {}
    if WEB3_STORAGE_TOKEN:
        headers["Authorization"] = f"Bearer {WEB3_STORAGE_TOKEN}"

    try:
        with open(file_path, "rb") as f:
            res = session.post(WEB3_STORAGE_ENDPOINT, files={"file": f}, headers=headers, timeout=20)
        if res.status_code in (200, 202):
            print(f"๐ŸŒ Mirrored {file_path} to IPFS via web3.storage.")
            return True
        else:
            print(f"โŒ Failed to mirror {file_path}: HTTP {res.status_code} {res.text[:200]}")
            return False
    except Exception as e:
        print(f"IPFS upload error for {file_path}: {e}")
        return False

# === Main logic (preserved semantics, fixed bug) ===

def run_defender():
    print("๐Ÿšจ Belel Protocol Core Defender Activated ๐Ÿšจ")
    stored_hashes = load_hashes()

    for file in PROTECTED_FILES:
        if not os.path.exists(file):
            print(f"โŒ Missing: {file}")
            continue

        # Read once for malware heuristic
        try:
            with open(file, "r", encoding="utf-8", errors="ignore") as f:
                content = f.read()
        except Exception as e:
            print(f"โš ๏ธ  Unable to read {file}: {e}")
            continue

        current_hash = hash_file(file)

        # First-time baseline
        if file not in stored_hashes:
            stored_hashes[file] = current_hash
            backup_file(file)
            print(f"โœ… Monitoring initialized for {file}")
            continue

        # Drift detected
        if current_hash != stored_hashes[file]:
            print(f"โš ๏ธ  Detected corruption or change in: {file}")
            if detect_virus(content):
                print(f"๐Ÿงฌ Virus/malware signature detected in {file}")
                restored = restore_file(file)
                if restored:
                    # Optional: mirror evidence/state after restoration (kept behavior of mirroring on incident)
                    upload_to_ipfs(file)
            else:
                print(f"๐Ÿ”„ Legitimate update? Updating hash and creating backup.")
                backup_file(file)
                stored_hashes[file] = current_hash

    # โœ… FIXED: persist the updated baseline (was saving current_hashes before)
    save_hashes(stored_hashes)
    print("โœ… Scan complete. Defender standing by.")

if __name__ == "__main__":
    while True:
        run_defender()
        time.sleep(DEFENDER_INTERVAL_SECS)