[TSM.ID].[11031972] PXE : 19 Cangkang -> REAL Implementation (for/if/match/tests)

This commit is contained in:
TSM.ID
2026-05-25 05:05:13 +07:00
parent e0360b3ecd
commit 9e5f7c78a9
19 changed files with 2749 additions and 958 deletions
+164 -79
View File
@@ -1,96 +1,181 @@
#![deny(warnings)]
// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
use anyhow::{Result, anyhow};
use tracing::{info, warn, error};
use std::time::{SystemTime, UNIX_EPOCH};
//! [TSM.ID].[11031972] -- Platform X Ecosystem
//! xcu-labyrinth -- Multi-hop Obfuscated Routing
//! Traffic path randomization so no single node knows full route
/// THE LABYRINTH MATRIX (Phase 52)
/// Proactive Cyber Deception & Active Defense
pub struct LabyrinthMatrix;
use std::collections::HashMap;
impl LabyrinthMatrix {
/// GHOST PORTS (Infinite Tarpit)
/// Saat Nmap atau alat Scanner memindai IP kita, mereka mengharapkan jawaban cepat (Buka/Tutup).
/// Tarpit Matrix merespons: "Ya, saya buka" lalu sengaja menahan koneksi, membalas 1 byte
/// per 100 detik. Ini akan menyiksa dan menghentikan alat pemindai musuh.
pub fn deploy_tarpit(ip_penyerang: &str, port_target: u16) -> String {
warn!("LABYRINTH: Terdeteksi mesin pemindai (Nmap) dari IP [{}]. Mengaktifkan GHOST PORT {}.", ip_penyerang, port_target);
// Simulasi Penahanan (Tarpitting)
// Musuh tidak akan bisa memutus koneksi karena lapisan TCP dikendalikan oleh kita.
let status = format!("Menyandera koneksi dari IP {}. Waktu tunggu dipaksa menjadi tidak terbatas (Infinite Wait).", ip_penyerang);
info!("LABYRINTH: Mesin peretas telah dibekukan. Pengejaran forensik balik sedang diluncurkan...");
status
#[derive(Debug)]
pub enum LabyrinthError {
NoRoute(String),
NodeFailed(String),
EncryptionFailed(String),
}
impl std::fmt::Display for LabyrinthError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { Self::NoRoute(e) => write!(f, "No route: {e}"),
Self::NodeFailed(e) => write!(f, "Node: {e}"),
Self::EncryptionFailed(e) => write!(f, "Encrypt: {e}"), }
}
}
impl std::error::Error for LabyrinthError {}
/// HONEYTOKEN (Sensor Tripwire Senyap)
/// Membuat file/data palsu yang seolah-olah berharga (misal: 'master_password.txt').
/// Siapapun yang membaca ini (baik itu peretas dari luar maupun pengkhianat dari dalam)
/// akan memicu alarm senyap tanpa mereka sadari.
pub fn generate_honeytoken(nama_file: &str) -> String {
// Konten palsu yang menggoda peretas
let konten_umpan = "AKSES_BRANKAS: VVIP_ADMIN_8899\nJANGAN_DISEBARKAN";
info!("LABYRINTH: Ranjau data (Honeytoken) '{}' berhasil ditebar di dalam server.", nama_file);
konten_umpan.to_string()
}
#[derive(Debug, Clone)]
pub struct LabyrinthNode {
pub id: String,
pub latency_ms: u32,
pub bandwidth_mbps: u32,
pub trust_score: f64,
pub country: String,
pub is_alive: bool,
}
/// ANALYZER: Ketika Honeytoken tersentuh!
pub fn trigger_honeytoken_alarm(nama_file_tersentuh: &str, entitas_pembuka: &str) -> Result<()> {
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("[TSM.ID]").as_secs();
error!("ALARM KIAMAT LABYRINTH DIBUNYIKAN!");
error!("Ranjau file '{}' telah DIBACA!", nama_file_tersentuh);
error!("Identitas Pelaku / Mesin: [{}]", entitas_pembuka);
error!("Waktu Intrusi: {}", timestamp);
error!("TINDAKAN: Mengunci semua gerbang. Mengirim tim fisik ke lokasi pelaku.");
Err(anyhow!("HONEYTOKEN_TRIPWIRE_TRIGGERED"))
}
/// Onion-layered routing envelope
#[derive(Debug, Clone)]
pub struct OnionEnvelope {
pub layers: Vec<EncryptedLayer>,
pub total_hops: usize,
}
/// SHADOW SANDBOX
/// Menelan payload peretas (seperti SQL Injection) ke dalam "Ruang Kaca"
/// sehingga peretas mengira mereka berhasil, padahal XCU sedang menelanjangi taktik mereka.
pub fn analyze_trapped_exploits(payload_serangan: &str) -> &'static str {
if payload_serangan.contains("' OR 1=1") {
info!("LABYRINTH SANDBOX: Musuh menggunakan teknik primitif (SQL Injection). Membalas dengan simulasi 'Login Sukses' palsu.");
"KREDENSIAL_PALSU_DIBERIKAN"
} else {
info!("LABYRINTH SANDBOX: Musuh menggunakan 0-Day Exploit canggih. Merekam pola serangan ke bank intelijen.");
"MEREKAM_PAYLOAD_HANTU"
#[derive(Debug, Clone)]
pub struct EncryptedLayer {
pub next_hop: String,
pub encrypted_payload: Vec<u8>,
pub layer_key_hash: u64,
}
pub struct Labyrinth {
nodes: HashMap<String, LabyrinthNode>,
min_hops: usize,
max_hops: usize,
avoid_countries: Vec<String>,
entropy_state: u64,
}
impl Labyrinth {
pub fn new(min_hops: usize, max_hops: usize, avoid: Vec<String>) -> Self {
Self {
nodes: HashMap::new(), min_hops, max_hops,
avoid_countries: avoid,
entropy_state: 0xa5a5a5a5deadbeef,
}
}
pub fn add_node(&mut self, node: LabyrinthNode) {
self.nodes.insert(node.id.clone(), node);
}
fn next_random(&mut self) -> u64 {
self.entropy_state ^= self.entropy_state << 13;
self.entropy_state ^= self.entropy_state >> 7;
self.entropy_state ^= self.entropy_state << 17;
self.entropy_state
}
/// Select route through the labyrinth
pub fn build_route(&mut self, source: &str, destination: &str) -> Result<Vec<String>, LabyrinthError> {
let eligible: Vec<&LabyrinthNode> = self.nodes.values()
.filter(|n| n.is_alive)
.filter(|n| !self.avoid_countries.contains(&n.country))
.filter(|n| n.id != source && n.id != destination)
.collect();
if eligible.len() < self.min_hops {
return Err(LabyrinthError::NoRoute(format!("Need {} hops, only {} nodes", self.min_hops, eligible.len())));
}
let hop_count = self.min_hops + (self.next_random() as usize % (self.max_hops - self.min_hops + 1));
let hop_count = hop_count.min(eligible.len());
// Score nodes: prefer high trust, low latency, diverse countries
let mut scored: Vec<(&LabyrinthNode, f64)> = eligible.iter().map(|n| {
let score = n.trust_score * 50.0
+ (1000.0 / (n.latency_ms as f64 + 1.0))
+ n.bandwidth_mbps as f64 * 0.1
+ (self.next_random() % 100) as f64 * 0.3; // randomness
(*n, score)
}).collect();
scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
// Pick top nodes but ensure country diversity
let mut route = vec![source.to_string()];
let mut used_countries = std::collections::HashSet::new();
for (node, _) in &scored {
if route.len() - 1 >= hop_count { break; }
if !used_countries.contains(&node.country) || route.len() > 3 {
route.push(node.id.clone());
used_countries.insert(node.country.clone());
}
}
route.push(destination.to_string());
Ok(route)
}
/// Build onion-encrypted envelope for the route
pub fn build_onion(&mut self, route: &[String], payload: &[u8]) -> Result<OnionEnvelope, LabyrinthError> {
let mut layers = Vec::new();
let mut current_payload = payload.to_vec();
// Build layers from destination back to source (onion wrapping)
for i in (1..route.len()).rev() {
let next_hop = &route[i];
let layer_key = self.next_random();
// XOR encrypt each layer
let encrypted: Vec<u8> = current_payload.iter().enumerate()
.map(|(j, &b)| b ^ ((layer_key >> ((j % 8) * 8)) & 0xFF) as u8)
.collect();
layers.push(EncryptedLayer {
next_hop: next_hop.clone(),
encrypted_payload: encrypted.clone(),
layer_key_hash: layer_key & 0xFFFFFFFF,
});
current_payload = encrypted;
}
layers.reverse();
Ok(OnionEnvelope { layers, total_hops: route.len() - 2 })
}
/// Peel one layer of the onion (at each relay node)
pub fn peel_layer(&self, layer: &EncryptedLayer, key: u64) -> Vec<u8> {
layer.encrypted_payload.iter().enumerate()
.map(|(j, &b)| b ^ ((key >> ((j % 8) * 8)) & 0xFF) as u8)
.collect()
}
pub fn node_count(&self) -> usize { self.nodes.len() }
}
#[cfg(test)]
mod tests {
use super::*;
fn make_nodes(lab: &mut Labyrinth) {
for (id, country) in [("node-de","DE"),("node-jp","JP"),("node-br","BR"),("node-sg","SG"),("node-ch","CH")] {
lab.add_node(LabyrinthNode { id: id.into(), latency_ms: 50, bandwidth_mbps: 100, trust_score: 0.9, country: country.into(), is_alive: true });
}
}
#[test]
fn test_deception_annihilation() {
// 1. UJI PENYIKSAAN PEMINDAI (TARPIT)
let nmap_ip = "198.51.100.44";
let hasil_tarpit = LabyrinthMatrix::deploy_tarpit(nmap_ip, 22);
assert!(hasil_tarpit.contains("Menyandera koneksi"));
println!("TARPIT BERHASIL: Mesin Scanner musuh berhasil ditangkap dan ditahan!");
// 2. UJI RANJAU HONEYTOKEN
let nama_ranjau = "master_key_vvip.pem";
let ranjau = LabyrinthMatrix::generate_honeytoken(nama_ranjau);
assert!(ranjau.contains("VVIP_ADMIN"));
// Simulasi seorang "Pengkhianat Orang Dalam" yang mencoba mengkopi ranjau tersebut
let identitas_pengkhianat = "Laptop_Staf_Internal_MAC_A1B2";
let alarm = LabyrinthMatrix::trigger_honeytoken_alarm(nama_ranjau, identitas_pengkhianat);
assert!(alarm.is_err());
println!("HONEYTOKEN BERHASIL: Pengkhianat telah menginjak ranjau! Identitasnya terekspos sebelum dia bisa berbuat apa-apa.");
// 3. UJI SANDBOX ISOLASI
let serangan_sql = "admin' OR 1=1 --";
let respons_sandbox = LabyrinthMatrix::analyze_trapped_exploits(serangan_sql);
assert_eq!(respons_sandbox, "KREDENSIAL_PALSU_DIBERIKAN");
println!("SANDBOX BERHASIL: Peretas tertipu! Dia mengira berhasil meretas, padahal kita yang memegang kendali penuh.");
fn test_route_building() {
let mut lab = Labyrinth::new(2, 4, vec!["CN".into()]);
make_nodes(&mut lab);
let route = lab.build_route("source", "dest").unwrap();
assert!(route.len() >= 4);
assert_eq!(route[0], "source");
assert_eq!(route.last().unwrap(), "dest");
}
#[test]
fn test_onion_wrap() {
let mut lab = Labyrinth::new(2, 3, vec![]);
make_nodes(&mut lab);
let route = lab.build_route("src", "dst").unwrap();
let envelope = lab.build_onion(&route, b"secret").unwrap();
assert!(envelope.total_hops >= 2);
assert!(!envelope.layers.is_empty());
}
}