fix: correct 7 bugs found in security audit

Critical:
- crypto.rs (server): use BTreeMap for canonical JSON so key order
  matches JS client's JSON.stringify sort — sig verification was always
  failing silently
- heartbeat.js: capture sentSalt before rotating to next_salt so both
  sides compute next_chain_hash with the same salt — chain was broken
  after the first heartbeat

High:
- trust.rs: avg_speed = total_dist / total_time_ms (px/ms), not
  distance/event_count — legitimate users were always rejected
- ratelimit.rs: add evict_stale() to drain expired entries and prevent
  unbounded HashMap memory growth
- cleanup.rs: call rl.evict_stale() from the periodic cleanup loop

Medium:
- vm.rs: op 0x08 (NOT) is unary — split from binary-op arm so depth
  is not decremented incorrectly
- wasm/crypto.rs: replace unwrap() panics in sign_message /
  get_public_key with unwrap_or_default(); add JS-side guard

Low:
- shared/Cargo.toml, wasm/Cargo.toml: remove leftover add-this comments
- Dockerfile: rust:1.88-bookworm -> rust:1.87-bookworm (1.88 non-existent)
This commit is contained in:
thakares committed 2026-05-08 14:27:41 +05:30
1 parent 3f779a5295
commit b75d586b86
10 files changed
+103 -43

No files matched your search

+16 -6
View File
@@ -4,11 +4,21 @@ use crate::session::AppState;
pub async fn cleanup_loop(state: Arc<AppState>) {
loop {
tokio::time::sleep(std::time::Duration::from_secs(60)).await;
let db = state.db.lock().await; // this is infallible
let now = crate::storage::current_time_ms();
let _ = db.execute(
"DELETE FROM sessions WHERE expires_at < ?1",
rusqlite::params![now],
);
// Evict expired sessions from SQLite.
{
let db = state.db.lock().await;
let now = crate::storage::current_time_ms();
let _ = db.execute(
"DELETE FROM sessions WHERE expires_at < ?1",
rusqlite::params![now],
);
}
// Evict stale rate-limiter entries to prevent unbounded HashMap growth.
{
let mut rl = state.rate_limiter.lock().await;
rl.evict_stale();
}
}
}
+12 -10
View File
@@ -1,5 +1,6 @@
use ed25519_dalek::{VerifyingKey, Signature};
use ed25519_dalek::{Signature, VerifyingKey};
use shared::protocol::HeartbeatRequest;
use std::collections::BTreeMap;
pub fn verify_signature(
pub_key_bytes: &[u8],
@@ -11,15 +12,16 @@ pub fn verify_signature(
let sig_bytes = hex::decode(&req.signature)?;
let sig = Signature::from_slice(&sig_bytes)?;
// Build canonical JSON exactly as client signed (sorted keys, no extra spaces)
let payload = serde_json::json!({
"sessionId": req.session_id,
"prevHash": req.prev_hash,
"timestamp": req.timestamp,
"entropyData": req.entropy_data,
"stackState": req.stack_state,
"fingerprint": req.fingerprint,
});
// Build canonical JSON with BTreeMap so keys are sorted alphabetically,
// matching the JS client's JSON.stringify(obj, Object.keys(obj).sort()).
// Sorted order: entropyData, fingerprint, prevHash, sessionId, stackState, timestamp
let mut payload: BTreeMap<&str, serde_json::Value> = BTreeMap::new();
payload.insert("entropyData", serde_json::to_value(&req.entropy_data)?);
payload.insert("fingerprint", serde_json::to_value(&req.fingerprint)?);
payload.insert("prevHash", serde_json::json!(req.prev_hash));
payload.insert("sessionId", serde_json::json!(req.session_id));
payload.insert("stackState", serde_json::to_value(&req.stack_state)?);
payload.insert("timestamp", serde_json::json!(req.timestamp));
let message = serde_json::to_string(&payload)?;
pk.verify_strict(message.as_bytes(), &sig)?;
+10
View File
@@ -11,6 +11,7 @@ impl RateLimiter {
pub fn new(limit: u32, window_secs: u64) -> Self {
Self { buckets: HashMap::new(), limit, window_secs }
}
pub fn check(&mut self, key: &str) -> bool {
let now = Instant::now();
let entry = self.buckets.entry(key.to_string()).or_insert((0, now));
@@ -24,4 +25,13 @@ impl RateLimiter {
true
}
}
/// Remove entries whose rate-limit window has fully elapsed.
/// Call this periodically (e.g. from the cleanup loop) to bound memory usage.
pub fn evict_stale(&mut self) {
let window = self.window_secs;
let now = Instant::now();
self.buckets
.retain(|_, (_, ts)| now.duration_since(*ts).as_secs() < window);
}
}
+10 -5
View File
@@ -5,22 +5,27 @@ pub fn validate_mouse(data: &EntropyData) -> Result<(), Box<dyn std::error::Erro
if events.len() < 3 {
return Err("few events".into());
}
let mut total_dist = 0.0;
let mut total_dist = 0.0f64;
let mut pauses = 0u32;
for i in 1..events.len() {
let p = &events[i-1];
let p = &events[i - 1];
let c = &events[i];
let dx = c.x - p.x;
let dy = c.y - p.y;
let dt = (c.timestamp_ms - p.timestamp_ms).max(1.0);
let dist = (dx*dx + dy*dy).sqrt();
let dist = (dx * dx + dy * dy).sqrt();
total_dist += dist;
if dist < 0.2 && dt > 50.0 { pauses += 1; }
if dist < 0.2 && dt > 50.0 {
pauses += 1;
}
}
if total_dist < shared::constants::MIN_MOUSE_TOTAL_DIST {
return Err("insufficient distance".into());
}
let avg_speed = total_dist / events.len() as f64;
// Speed in px/ms: total distance over elapsed wall-clock time of the event window.
let total_time_ms =
(events.last().unwrap().timestamp_ms - events[0].timestamp_ms).max(1.0);
let avg_speed = total_dist / total_time_ms;
if avg_speed > shared::constants::MAX_MOUSE_AVG_SPEED {
return Err("speed too high".into());
}
+18 -5
View File
@@ -1,28 +1,41 @@
use rand::Rng;
pub fn generate_random_program(len_range: std::ops::RangeInclusive<usize>) -> Vec<u8> {
// Same logic as earlier, using shared::hashing for HASH if needed
let mut rng = rand::thread_rng();
let count = rng.gen_range(len_range);
let mut ops = Vec::new();
let mut depth: i32 = 0;
for _ in 0..count {
if depth < 2 {
ops.push(0x00); // PUSH
// Not enough operands for any binary op — push a literal.
ops.push(0x00);
let val = rng.gen::<u32>();
ops.extend_from_slice(&val.to_le_bytes());
depth += 1;
} else {
let op = rng.gen_range(0..10);
let op = rng.gen_range(0u8..10);
match op {
0x00 => {
// PUSH literal
ops.push(0x00);
let val = rng.gen::<u32>();
ops.extend_from_slice(&val.to_le_bytes());
depth += 1;
}
0x01..=0x08 => { ops.push(op as u8); depth -= 1; }
0x09 => { ops.push(0x09); depth = 1; }
0x01..=0x07 => {
// Binary ops (ADD, SUB, MUL, XOR, AND, OR, ROT): pops 2, pushes 1 → net −1
ops.push(op);
depth -= 1;
}
0x08 => {
// Unary NOT: pops 1, pushes 1 → net 0; depth unchanged
ops.push(0x08);
}
0x09 => {
// HASH: collapses entire stack to one u32 → depth becomes 1
ops.push(0x09);
depth = 1;
}
_ => unreachable!(),
}
}