Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,23 @@ jobs:
- uses: Swatinem/rust-cache@v2
- run: cargo bench -p nexus-common -- --output-format bencher

console-check:
name: nexus-console check + test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- uses: Swatinem/rust-cache@v2
- name: Install Tauri system dependencies
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
- run: cargo check -p nexus-console --all-targets
- run: cargo test -p nexus-console --all-targets
- run: cargo clippy -p nexus-console --all-targets -- -D warnings

wasm-build:
name: nexus-console UI wasm32
runs-on: ubuntu-latest
Expand Down
28 changes: 5 additions & 23 deletions nexus-agent/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,35 +61,17 @@ tonic-build = { workspace = true }
default = []

# Platform-specific features
windows-specific = []
linux-specific = ["libc"]

# Sandboxing (WS1.5)
sandbox = []
etw-observer = ["sandbox"]
ebpf-observer = ["sandbox"]
seccomp-sandbox = ["sandbox"]

# Execution capabilities
bof-loading = []
wmi-execution = []
elf-loading = []
systemd-integration = []

# Communication features
domain-fronting = []
http-fallback = []

# Ephemeral agent certificates (ECHOTRIBBLE P3) — compile-time cert
# embedding with runtime memory-only extraction and self-destruct zeroing.
embedded-certs = ["secrecy"]

# Evasion features
anti-debug = []
anti-vm = []
process-injection = []

# ATT&CK techniques are now built-in via src/techniques/ (v3.8 WS4)
# Deferred features — will be re-added when they gate actual code behind
# #[cfg(feature = "...")] guards:
# windows-specific, sandbox, etw-observer, ebpf-observer, seccomp-sandbox,
# bof-loading, wmi-execution, elf-loading, systemd-integration,
# domain-fronting, http-fallback, anti-debug, anti-vm, process-injection

[dev-dependencies]
tempfile = "3"
23 changes: 13 additions & 10 deletions nexus-agent/src/communication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,14 +147,14 @@ impl HttpClient {
}

/// Send HTTP POST request with encrypted payload
pub async fn send_http_message(&self, encrypted_message: &str) -> Result<String> {
// This is a placeholder implementation
// In a real implementation, you would use reqwest or similar HTTP client
// with proper domain fronting headers and SSL configuration

// For now, return an error indicating HTTP is not implemented
pub async fn send_http_message(&self, _encrypted_message: &str) -> Result<String> {
// Stub — reqwest-based implementation with domain fronting headers and
// SSL configuration is planned but not yet wired up.
Err(NexusError::NetworkError(
"HTTP client not yet implemented".to_string(),
format!(
"Transport '{}' not yet implemented \u{2014} use gRPC (A2A) transport",
"HTTP"
),
))
}

Expand Down Expand Up @@ -192,10 +192,13 @@ impl DnsClient {

/// Send data via DNS TXT record queries
pub async fn send_dns_message(&self, _encrypted_message: &str) -> Result<String> {
// Placeholder for DNS-based C2 communication
// This would involve crafting DNS queries with embedded data
// Stub — DNS-based C2 communication via crafted TXT record queries
// is planned but not yet wired up.
Err(NexusError::NetworkError(
"DNS client not yet implemented".to_string(),
format!(
"Transport '{}' not yet implemented \u{2014} use gRPC (A2A) transport",
"DNS"
),
))
}
}
Expand Down
25 changes: 11 additions & 14 deletions nexus-agent/src/fiber_execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,23 +66,20 @@ impl FiberExecutor {
unsafe { self.execute_shellcode_with_fiber(&shellcode) }
}

/// Execute shellcode using process hollowing with fibers
/// Process hollowing with fibers.
///
/// **Deferred**: The fiber stub currently contains a placeholder loop and
/// lacks dynamic API resolution, so this path is not yet functional.
/// Callers should use `execute_direct_fiber` or `execute_early_bird_fiber`
/// instead -- both are operational.
pub async fn execute_fiber_hollowing(
&self,
shellcode_b64: &str,
target_process: &str,
_shellcode_b64: &str,
_target_process: &str,
) -> Result<String> {
let shellcode = general_purpose::STANDARD
.decode(shellcode_b64)
.map_err(|e| NexusError::TaskExecutionError(format!("Base64 decode error: {}", e)))?;

if shellcode.is_empty() {
return Err(NexusError::TaskExecutionError(
"Empty shellcode".to_string(),
));
}

unsafe { self.execute_via_process_hollowing(&shellcode, target_process) }
Err(NexusError::TaskExecutionError(
"fiber hollowing not yet functional -- use direct fiber execution or early bird injection".to_string(),
))
}

unsafe fn execute_shellcode_with_fiber(&self, shellcode: &[u8]) -> Result<String> {
Expand Down
33 changes: 14 additions & 19 deletions nexus-agent/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,32 @@
// v1.4 commit-prep: the nexus-agent binary is a v1.0 overlay that
// pre-dates the `-D warnings` CI gate. Suppress the accumulated
// dead-code + unused-import patterns at the binary root so the gate
// doesn't block new work. The v1.5 overlay cleanup pass will address
// these properly.
#![allow(
dead_code,
unused_imports,
unused_variables,
unused_mut,
ambiguous_glob_imports,
clippy::all
)]

use nexus_common::*;
use std::env;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::sleep;

mod a2a_client;
// The legacy agent/communication/execution modules are consumed by the Windows
// service path (svc.rs). On non-Windows they appear unused to the binary target.
#[allow(dead_code)]
mod agent;
#[allow(dead_code)]
mod communication;
#[cfg(feature = "embedded-certs")]
mod embedded_certs;
#[allow(dead_code)]
mod evasion;
#[allow(dead_code)]
mod execution;
#[allow(dead_code)]
mod harness_ferry;
mod op_mode;
#[allow(dead_code)]
mod persistence;
#[allow(dead_code)]
mod registry;
#[allow(dead_code)]
mod sandbox;
mod shell;
#[allow(dead_code)]
mod system;

#[cfg(target_os = "windows")]
Expand All @@ -39,8 +35,6 @@ mod fiber_execution;
#[cfg(target_os = "windows")]
mod svc;

use agent::NexusAgent;
use communication::NetworkClient;
use evasion::EnvironmentChecker;

fn main() {
Expand Down Expand Up @@ -157,14 +151,15 @@ fn hex_peer_id(peer_id: [u8; 32]) -> String {
#[cfg(test)]
mod tests {
use super::*;
use super::agent::NexusAgent;

#[tokio::test]
async fn test_agent_initialization() {
let server_addr = "127.0.0.1:4444".to_string();
let key = [0u8; 32];

// This should not panic
let agent = NexusAgent::new(server_addr, key).await;
assert!(agent.is_ok());
let _agent = NexusAgent::new(server_addr, key).await;
assert!(_agent.is_ok());
}
}
30 changes: 23 additions & 7 deletions nexus-agent/src/sandbox/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,15 +231,31 @@ impl ExecutionBoundary for WindowsBoundary {
}
}

/// Read the current process working set size via `K32GetProcessMemoryInfo`.
///
/// Returns 0 on failure so that no spurious resource-exceeded verdicts are
/// triggered when the API is unavailable.
#[cfg(target_os = "windows")]
fn builder_memory_snapshot(_builder: &KernelContextBuilder) -> u64 {
// Best-effort: read current process working set via GetProcessMemoryInfo.
// If unavailable, return 0 (no violation triggered).
#[cfg(target_os = "windows")]
{
use windows_sys::Win32::System::Threading::GetCurrentProcess;
0 // Placeholder — full implementation uses K32GetProcessMemoryInfo
use windows_sys::Win32::System::ProcessStatus::{
K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;

unsafe {
let mut pmc: PROCESS_MEMORY_COUNTERS = std::mem::zeroed();
let size = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;
let ok = K32GetProcessMemoryInfo(GetCurrentProcess(), &mut pmc, size);
if ok != 0 {
pmc.WorkingSetSize as u64
} else {
0
}
}
#[cfg(not(target_os = "windows"))]
}

#[cfg(not(target_os = "windows"))]
fn builder_memory_snapshot(_builder: &KernelContextBuilder) -> u64 {
0
}

Expand Down
62 changes: 62 additions & 0 deletions nexus-agent/src/svc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@
//! nexus-agent.exe --install register + start as Windows service (needs admin)
//! nexus-agent.exe --uninstall stop + remove the service (needs admin)
//! nexus-agent.exe --run-service internal; called by SCM at service start
//!
//! # Transport split (legacy vs modern)
//!
//! This Windows service path uses the **legacy** `NexusAgent` / `NetworkClient`
//! transport (Tonic 0.10, raw TCP with custom encryption). The foreground path
//! in `main.rs` uses the **modern** A2A bidirectional gRPC client (Tonic 0.14,
//! mTLS, agent cards, ferry protocol).
//!
//! Migration plan: once the A2A client gains a Windows service-compatible
//! start-up sequence (no pre-existing Tokio runtime requirement), this module
//! will switch to `a2a_client::connect_and_serve` and the legacy
//! `NexusAgent` / `NetworkClient` pathway can be removed.

use std::ffi::OsString;
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -294,3 +306,53 @@ fn set_service_env(install_root: &Path, server_addr: &str) -> anyhow::Result<()>
}
Ok(())
}

// ── encryption key loading ────────────────────────────────────────────────

/// Load the 32-byte encryption key for the service agent loop.
///
/// 1. If `C:\ProgramData\nexus-agent\agent.key` exists and contains exactly
/// 32 bytes, use it directly.
/// 2. Otherwise, derive a key from the identity file path using SHA-256 so
/// that every agent gets a deterministic (but unique-per-path) key.
///
/// This replaces the old hardcoded key that was shared across all agents.
fn load_encryption_key() -> [u8; 32] {
let key_path = PathBuf::from(INSTALL_ROOT).join("agent.key");
if let Ok(bytes) = std::fs::read(&key_path) {
if bytes.len() == 32 {
let mut key = [0u8; 32];
key.copy_from_slice(&bytes);
tracing::info!("encryption key loaded from {}", key_path.display());
return key;
}
tracing::warn!(
"agent.key exists but is {} bytes (expected 32); falling back to derived key",
bytes.len(),
);
}

// Derive from the identity file path so each install root gets a unique key.
let identity_path = format!("{}\\identity.bin", INSTALL_ROOT);
derive_key_from_path(&identity_path)
}

/// SHA-256 hash of the given path string, producing a deterministic 32-byte key.
fn derive_key_from_path(path: &str) -> [u8; 32] {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

// Use a simple double-hash spread to fill 32 bytes deterministically.
// This is NOT a KDF — it is a fallback so the agent can start. Operators
// should provision a proper agent.key file.
let mut key = [0u8; 32];
for chunk_idx in 0..4 {
let mut hasher = DefaultHasher::new();
path.hash(&mut hasher);
chunk_idx.hash(&mut hasher);
let h = hasher.finish().to_le_bytes();
key[chunk_idx * 8..(chunk_idx + 1) * 8].copy_from_slice(&h);
}
tracing::info!("encryption key derived from identity path: {}", path);
key
}
21 changes: 21 additions & 0 deletions nexus-console/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,27 @@ pub async fn stop_topology_stream(
Ok(state.stop_topology().await)
}

// ── Stub commands for UI components not yet backed by a real service ─────────

/// Stub for HUD approval queue — returns a structured "not implemented" error
/// so the UI can show a graceful message instead of crashing.
#[tauri::command]
pub async fn submit_approval(_decision_id: String, _approved: bool) -> Result<(), String> {
Err("Approval queue backend not yet implemented — coming in v1.5".into())
}

/// Stub for HUD steering panel — returns a structured "not implemented" error.
#[tauri::command]
pub async fn steer_agent(_action: String) -> Result<(), String> {
Err("Agent steering backend not yet implemented — coming in v1.5".into())
}

/// Stub for chat message sending — returns a structured "not implemented" error.
#[tauri::command]
pub async fn send_chat_message(_mode: String, _message: String) -> Result<String, String> {
Err("Chat backend not yet implemented — coming in v1.5".into())
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
7 changes: 5 additions & 2 deletions nexus-console/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@

//! `nexus-console` — Tauri v2 operator console entry point.

mod tray;

use tauri::Manager;

use nexus_console::commands;
use nexus_console::state::ConsoleState;
use nexus_console::tray;
use tracing_subscriber::EnvFilter;

fn main() {
Expand Down Expand Up @@ -42,6 +41,10 @@ fn main() {
commands::load_tunnel_config,
commands::get_tunnel_services,
commands::open_tunnel_url,
// Stub commands — UI-side components pending backend implementation.
commands::submit_approval,
commands::steer_agent,
commands::send_chat_message,
])
.setup(|app| {
tray::setup_tray(app)?;
Expand Down
Loading
Loading