Skip to content

Be-bibek/sentinelmark

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

57 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

SentinelMark Banner

Typing SVG

License Rust Version Build Status E2E Tests Python Phase

SentinelMark is a Behavior-Aware Continuous Trust Infrastructure Platform. Evolving from a cryptographic watermarking and forensic telemetry subsystem (v1) into a comprehensive, enterprise-grade security SDK (v2), SentinelMark redefines how systems evaluate user authenticity.

While traditional authentication mechanisms ask, "Did the user log in?", SentinelMark continually assesses: "Can the user still be trusted right now?"

By fusing long-term static hardware secrets with live, continuous behavioral entropy snapshots, SentinelMark ensures that emitted telemetry cannot be forged, replayed, or fabricated, providing an unshakeable foundation for high-stakes digital environments.


🌟 SentinelMark v2: Continuous Trust Infrastructure SDK

In v2, SentinelMark has matured into a robust, deterministic, and blockchain-agnostic trust authorization layer. External enterprise systemsβ€”such as automated treasuries, identity gateways, and high-security workflowsβ€”consume SentinelMark to dynamically authorize critical actions based on real-time behavior.

The architecture is driven by 7 deterministic Rust engines:

Engine Responsibility
Identity Engine Detects impossible-travel scenarios, novel device footprints, and credential reuse signals.
Workflow Engine Tracks session action sequences and identifies anomalous workflow deviations.
Behavior Engine Maintains historical behavioral profiles (typical usage hours, geolocation regions, and transaction volumes).
Risk Engine Quantifies deviations into deterministic, mathematically weighted Risk Assessments (0.0–1.0).
Trust Engine Inverts and scales raw risk into a dynamic, actionable Trust Score.
Policy Engine Enforces strict, customizable boundaries (Allow, RequireMFA, RequireApproval, Block) via an Abstract Syntax Tree (AST).
Explainability Engine Generates human-readable, compliance-ready narratives justifying every automated decision.

Integration: Delivered as a highly optimized Rust SDK (sentinelmark-rs), wrapped in a fully-featured REST API Gateway (Axum) for seamless enterprise deployment, alongside a modern Next.js Enterprise Dashboard.


πŸ”¬ Core Derivation Primitive (v1 Legacy Foundation)

SentinelMark Research Novelty Assessment

Valid watermark tokens require the strict mathematical intersection of both the secret key and the instantaneous runtime behavioral state of the host device.

The derivation equation is defined as:

$$W_i = \text{HKDF-SHA256}(K_{\text{static}} \parallel \text{BehaviorFingerprint}_i \parallel H_{\text{prev}})$$

Where:

  • $K_{\text{static}}$: The long-term static device secret (securely zeroized from stack/heap post-derivation).
  • $\text{BehaviorFingerprint}_i$: A deterministic serialization of the live rolling behavioral entropy snapshot (CPU scheduling jitter, thread allocations, virtual/physical memory boundaries).
  • $H_{\text{prev}}$: The SHA-256 hash commitment linking the current event to its immediate predecessor, establishing an unforgeable, append-only chronological hash chain.

πŸ—οΈ System Architecture

πŸ”— Open the Interactive Architecture Viewer β†’ β€” fully rendered diagrams with dot-grid canvas, ideal for LinkedIn/Twitter screenshots.

SentinelMark is engineered as a high-throughput, distributed policy evaluation platform. The system separates telemetry ingestion, behavioral scoring, and AST-based policy execution into independent, horizontally-scalable layers β€” each with a defined contract and no shared mutable state.


Architecture 1 β€” Full System Topology

Shows every layer of the platform from SDK ingestion to the live dashboard, including the API Gateway, engine pipeline, persistence tier, and WebSocket broadcast.

flowchart TD
    classDef sdk     fill:#0F172A,stroke:#38BDF8,stroke-width:2px,color:#fff
    classDef gateway fill:#1E293B,stroke:#818CF8,stroke-width:2px,color:#fff
    classDef engine  fill:#1E293B,stroke:#10B981,stroke-width:2px,color:#fff
    classDef storage fill:#1E293B,stroke:#F59E0B,stroke-width:2px,color:#fff
    classDef ui      fill:#0F172A,stroke:#F43F5E,stroke-width:2px,color:#fff

    subgraph Ingestion["Ingestion Layer β€” Multi-SDK"]
        PY["Python SDK"]:::sdk
        ND["Node.js SDK"]:::sdk
        RS["Rust SDK"]:::sdk
        GO["Go SDK"]:::sdk
    end

    subgraph Gateway["API Gateway β€” Axum / Rust"]
        AUTH["Auth Middleware\nBearer API Key"]:::gateway
        RL["Rate Limiter\nRedis Token Bucket"]:::gateway
        ROUTE["Request Router"]:::gateway
    end

    subgraph Pipeline["Evaluation Engine Pipeline"]
        CTX["Context Engine\nDevice Β· Geo Β· Time"]:::engine
        TRUST["Trust Engine\nScore 0.0 – 1.0"]:::engine
        POL["Policy Engine\nAST Evaluator"]:::engine
        EXP["Explainability Engine\nAudit Narrative"]:::engine
    end

    subgraph Persistence["Persistence & Cache Tier"]
        PG[("PostgreSQL\nTenants Β· Policies Β· Events")]:::storage
        RD[("Redis\nCache Β· Rate Limit Β· Pub/Sub")]:::storage
        LOGS[/"Audit Log\nAppend-Only Chain"/]:::storage
    end

    subgraph Realtime["Real-Time Layer"]
        WSS["WebSocket\nBroadcast Service"]:::ui
        DASH["Next.js\nEnterprise Dashboard"]:::ui
    end

    PY & ND & RS & GO -->|HTTPS + API Key| AUTH
    AUTH --> RL --> ROUTE
    ROUTE --> CTX --> TRUST --> POL --> EXP
    EXP --> PG
    EXP --> LOGS
    POL <-->|O1 Hash Lookup| RD
    EXP --> WSS --> DASH
Loading

Architecture 2 β€” Request Authorization Flow

Traces a single event from the developer's SDK call through every middleware checkpoint to a final decision, audit log, and dashboard update.

flowchart LR
    classDef start  fill:#0F172A,stroke:#38BDF8,color:#fff
    classDef mid    fill:#1E293B,stroke:#64748B,color:#fff
    classDef end_   fill:#064E3B,stroke:#10B981,color:#fff
    classDef deny   fill:#450A0A,stroke:#EF4444,color:#fff

    Dev["Developer"]:::start
    SDK["SDK\nclient.evaluate()"]:::start
    Key["Bearer API Key"]:::mid
    GW["API Gateway"]:::mid
    AuthMW["Auth Middleware"]:::mid
    TenantLookup["Tenant Lookup\nPostgreSQL"]:::mid
    ProdLookup["Product Lookup"]:::mid
    CtxE["Context Engine"]:::mid
    TrustE["Trust Engine"]:::mid
    PolE["Policy Engine"]:::mid

    ALLOW["βœ… ALLOW"]:::end_
    MFA["πŸ” REQUIRE MFA"]:::mid
    APPROVAL["πŸ“‹ REQUIRE APPROVAL"]:::mid
    BLOCK["🚫 BLOCK"]:::deny

    AuditLog["Audit Log\nAppend-Only"]:::mid
    WSBroadcast["WebSocket\nBroadcast"]:::mid
    Dashboard["Dashboard\nLive Update"]:::end_

    Dev --> SDK --> Key --> GW --> AuthMW
    AuthMW --> TenantLookup --> ProdLookup --> CtxE
    CtxE --> TrustE --> PolE
    PolE --> ALLOW & MFA & APPROVAL & BLOCK
    ALLOW --> AuditLog
    BLOCK --> AuditLog
    MFA --> AuditLog
    APPROVAL --> AuditLog
    AuditLog --> WSBroadcast --> Dashboard
Loading

Architecture 3 β€” Multi-Tenancy & Data Isolation

Resources, API keys, products, and policies are strictly isolated per tenant at the PostgreSQL row-level-security layer. Zero cross-tenant data leakage is guaranteed by design.

flowchart TD
    classDef tenant  fill:#0F172A,stroke:#F43F5E,stroke-width:3px,color:#fff
    classDef project fill:#1E293B,stroke:#818CF8,stroke-width:2px,color:#fff
    classDef leaf    fill:#1E293B,stroke:#38BDF8,stroke-width:1px,color:#fff

    ORG(("🏒 Organization\n Tenant")):::tenant

    PA["Project A\nHealthcare SDK"]:::project
    PB["Project B\nFintech SDK"]:::project
    PC["Project C\nIoT / 5G"]:::project
    TM["Team Members\nRBAC Roles"]:::project

    PA --> KA["API Key"] & PRA["Products"] & POA["Policies"] & EA["Events Log"]:::leaf
    PB --> KB["API Key"] & PRB["Products"] & POB["Policies"] & EB["Events Log"]:::leaf
    PC --> KC["API Key"] & PRC["Products"] & POC["Policies"] & EC["Events Log"]:::leaf

    ORG --> PA & PB & PC & TM
Loading

Architecture 4 β€” Dynamic Policy Engine (AST)

Rules are not hardcoded if/else chains. They are serialized as an Abstract Syntax Tree that the engine traverses at evaluation time β€” enabling zero-downtime rule updates and dry-run simulation.

flowchart TD
    classDef input   fill:#0F172A,stroke:#38BDF8,color:#fff
    classDef parse   fill:#1E293B,stroke:#818CF8,color:#fff
    classDef gate    fill:#1E293B,stroke:#64748B,color:#fff
    classDef allow   fill:#064E3B,stroke:#10B981,color:#fff
    classDef block   fill:#450A0A,stroke:#EF4444,color:#fff

    Event["Incoming Event\nJSON Telemetry"]:::input
    Ctx["Context Enrichment\nGeo Β· Device Β· Time Β· Amount"]:::input
    Vars["Policy Variables\nNamed Constants"]:::parse
    AST["AST Parser\nDeserialize Rule Tree"]:::parse

    subgraph LogicGates["Logical Evaluation"]
        AND["AND Gate"]:::gate
        OR["OR Gate"]:::gate
        NOT["NOT Gate"]:::gate
    end

    Prio["Priority Resolution\nHighest-priority matching rule wins"]:::parse
    DryRun["Dry Run Mode\nSimulate without enforcement"]:::parse

    ALLOW["Decision: ALLOW"]:::allow
    MFA["Decision: REQUIRE MFA"]:::gate
    BLOCK["Decision: BLOCK"]:::block
    Explain["Explainability Narrative\nHuman-readable audit reason"]:::allow

    Event --> Ctx --> Vars --> AST
    AST --> LogicGates
    LogicGates --> Prio
    Prio --> DryRun
    Prio --> ALLOW & MFA & BLOCK
    ALLOW & MFA & BLOCK --> Explain
Loading

Architecture 5 β€” Real-Time WebSocket State Synchronization

Instead of client polling (expensive), state mutations stream over persistent WebSocket connections. Every policy update, trust score change, or session event triggers an immediate push to all authorized dashboard clients.

flowchart LR
    classDef backend fill:#1E293B,stroke:#10B981,color:#fff
    classDef ws      fill:#0F172A,stroke:#38BDF8,color:#fff
    classDef client  fill:#064E3B,stroke:#10B981,color:#fff

    subgraph BackendEmitters["Backend Event Emitters"]
        PE["Policy Engine\nDecision Event"]:::backend
        TE["Trust Engine\nScore Change"]:::backend
        SE["Session Engine\nNew Session / Anomaly"]:::backend
    end

    RedisPubSub["Redis Pub/Sub\nEvent Bus"]:::ws
    WSServer["WebSocket\nBroadcast Server"]:::ws

    subgraph Clients["Authorized Dashboard Clients"]
        C1["Analyst Tab 1"]:::client
        C2["Analyst Tab 2"]:::client
        C3["Mobile Client"]:::client
    end

    PE & TE & SE -->|Publish| RedisPubSub
    RedisPubSub -->|Subscribe| WSServer
    WSServer -->|Push β€” no polling| C1 & C2 & C3
Loading

Architecture 6 β€” Cryptographic Watermark Chain (v1 Core)

The foundational cryptographic primitive. Every telemetry event is bound to both the device's static hardware secret and the instantaneous behavioral entropy of the host β€” making watermarks impossible to forge, replay, or fabricate.

flowchart TD
    classDef key     fill:#450A0A,stroke:#EF4444,color:#fff
    classDef behavior fill:#0F172A,stroke:#38BDF8,color:#fff
    classDef chain   fill:#064E3B,stroke:#10B981,color:#fff
    classDef output  fill:#1E293B,stroke:#818CF8,color:#fff

    SK["Static Key β€” K_static\nHardware Secret\nZeroized on drop"]:::key
    BS["Behavioral Snapshot\nCPU Jitter Β· Memory Β· OS Scheduler\nEntropy Fingerprint_i"]:::behavior
    HP["H_prev\nSHA-256 of previous event\nChain Linkage"]:::chain

    HKDF["HKDF-SHA256\nW_i = HKDF(K_static βˆ₯ BehaviorFingerprint_i βˆ₯ H_prev)"]:::output

    EV["Telemetry Event\nSigned + Chained"]:::chain
    VERIFY["Remote Verifier\nConstant-Time Recompute"]:::output
    REPLAY["Replay Cache\nO1 Nonce Store\nSliding Window"]:::behavior

    RESULT_VALID["βœ… Valid β€” Trust Scored"]:::chain
    RESULT_REJECT["🚫 Rejected β€” Forgery / Replay"]:::key

    SK & BS & HP --> HKDF --> EV
    EV --> VERIFY
    VERIFY --> REPLAY
    REPLAY --> RESULT_VALID & RESULT_REJECT
Loading

Architecture 7 β€” Developer SDK Integration

SentinelMark prioritizes a Stripe-quality developer experience. Installation is a single pip command. Evaluation is one idempotent function call. The SDK handles retry logic, serialization, and connection management transparently.

flowchart LR
    classDef dev    fill:#0F172A,stroke:#38BDF8,color:#fff
    classDef sdk    fill:#1E293B,stroke:#818CF8,color:#fff
    classDef api    fill:#064E3B,stroke:#10B981,color:#fff
    classDef result fill:#0F172A,stroke:#F43F5E,color:#fff

    Install["pip install sentinelmark\nnpm install @sentinelmark/sdk\ncargo add sentinelmark"]:::dev

    subgraph ClientCode["Developer Code"]
        Init["client = SentinelMark(api_key)"]:::sdk
        Call["result = client.evaluate(event)"]:::sdk
    end

    subgraph SDKInternals["SDK Internals β€” Transparent"]
        Serialize["Serialize Event\nIdempotency Key"]:::sdk
        Retry["Retry Logic\nExponential Backoff"]:::sdk
        TLS["TLS 1.3\nHTTPS Transport"]:::sdk
    end

    GW["API Gateway\nAxum / Rust"]:::api
    Eval["Evaluation Pipeline\n< 1ms p99"]:::api

    Result["result.decision β†’ ALLOW / MFA / BLOCK\nresult.trust_score β†’ 0.0–1.0\nresult.explanation β†’ Human narrative"]:::result

    Install --> ClientCode
    ClientCode --> SDKInternals
    SDKInternals --> GW --> Eval --> Result
Loading

Key Design Decisions

Decision Why
Rust for all engines Zero-cost abstractions, compile-time memory safety, sub-millisecond P99 latency
PostgreSQL over NoSQL ACID transactions mandatory for multi-tenant policy and audit data
Redis for rate limiting & cache O(1) token bucket operations; Pub/Sub for WebSocket fan-out
WebSockets over polling Eliminates NΓ—(clients) REST requests/sec; push-only model scales linearly
AST for policy rules Zero-downtime rule updates; dry-run simulation without code deployment
API Keys over JWT for SDKs Machine-to-machine auth; no expiry rotation complexity; simpler audit trail
Idempotency keys Prevents duplicate financial evaluations on network retry
Append-only hash chains Tamper-evident audit log; any deletion corrupts all subsequent hashes

πŸ“Š Performance & Security Trade-offs

```mermaid xychart-beta title "Execution Efficiency: Pure Rust Determinism vs AI/ML Inference (ms)" x-axis ["SentinelMark (v2)", "Rules Engine (Java)", "ML Pipeline (Python)"] y-axis "Latency (ms)" 0 --> 150 bar [0.8, 45, 120] ```

πŸ›‘οΈ Security Best Practices Enforced

  1. Constant-Time Verification: All security-critical array and digest comparisons pass directly through subtle::ConstantTimeEq to completely neutralize timing side-channel attacks.
  2. Key Material Zeroization: Static secret arrays implement zeroize::ZeroizeOnDrop ensuring sensitive key material is wiped directly from register arrays and stack pointers immediately upon scope exit.
  3. Immutability Boundaries: Payloads are locked into immutable arrays prior to dispatch. Network transport cannot modify context states.

πŸ“¦ Getting Started

Prerequisites

  • Rust Toolchain 1.75 or higher β€” for the Core Engine and API Gateway.
  • Python 3.10+ and pip / poetry β€” for Legacy Verification scripts.
  • Node.js 18+ β€” for the Next.js Enterprise Frontend.

Rust API Gateway & SDK

# Run tests for the Rust SDK and Policy Engine
cargo test --workspace

# Start the Axum API Gateway
cargo run -p api-gateway

Next.js Enterprise Frontend

cd frontend
npm install
npm run dev
# The Policy Builder and Dashboard will be available at http://localhost:3000

Adversarial Attack Simulations (Python)

cd verify-py
python benchmarks/attacks/sim_replay.py          # ATK-01: Replay attack
python benchmarks/attacks/sim_entropy_collapse.py # ATK-02: Forgery attack
# Results written to benchmarks/results/

πŸ“œ Usage Example (v2 SDK)

use sentinelmark_rs::SentinelMark;
use telemetry_engine::{TelemetryEvent, ActionType};

// Initialize the continuous trust SDK
let engine = SentinelMark::new();

// A high-value treasury transfer is attempted from an unknown region
let event = TelemetryEvent {
    user_id: UserId("alice123".to_string()),
    action_type: ActionType::Transaction,
    transaction_amount: Some(50_000.0),
    geo_region: "RU-Moscow".to_string(),
    // ... timestamps, device_id, IP
};

// Evaluate trust deterministically against the user's historical profile
let result = engine.evaluate(&event, &historical_profile);

println!("Decision: {:?}", result.decision); 
// Output: RequireApproval (Escalates to Multi-Sig)

println!("Explanation: {}", result.explanation);
// Output: "High risk (0.65). Significant behavioral anomalies detected."

πŸ“œ Usage Example (v1 Core Engine)

use sentinelmark_core::{
    behavior::BehaviorSnapshot,
    chain::{ChainManager, GENESIS_HASH},
    telemetry::TelemetryEvent,
    watermark::{StaticKey, WatermarkEngine},
};

// 1. Initialize Long-Term Secrets
let secret_key = StaticKey::from_bytes([0xAA; 32]);
let mut engine = WatermarkEngine::new(secret_key);
let mut chain = ChainManager::new();

// 2. Generate and Watermark Telemetry Payload
let payload = serde_json::json!({"action": "kernel_auth", "user_id": 1024});
// Bind device ID, monotonic sequence number, previous hash linkage, and payload
let mut event = TelemetryEvent::new("device-host-001", 1, GENESIS_HASH, payload).unwrap();

// Derive BEW Watermark binding current behavior digest, previous hash, and unique nonce
let snapshot = BehaviorSnapshot::capture().unwrap();
let behavior_digest = snapshot.to_digest();
let watermark = engine.derive(&behavior_digest, &event.prev_hash, &event.nonce).unwrap();
event.set_watermark(watermark.into_bytes());

// 3. Finalize Hash Linkage
event.finalize().unwrap();
chain.append(&event).unwrap();

// Payload is ready for immutable transport dispatch!

🎬 Step-by-Step Live Demo Script

Want to see SentinelMark in action? Follow these exact steps in your terminal to reproduce the security guarantees, attack prevention, and performance metrics.

1. Compile-Time Safety Guarantee (Rust Core)

cargo check

What this proves: Zero memory safety issues or undefined behavior. The Rust compiler enforces our security guarantees at compile time.

2. Cryptographic Subsystem Verification

cargo test --workspace

What this proves: All core cryptographic unit tests pass (hash chain integrity, watermark derivation, replay detection).

3. Defeating 7 Attack Vectors (Python Verifier)

cd verify-py
python -m pytest tests/ -v

What this proves: The system correctly handles every major attack scenario:

  • Forged Watermarks: Rejected in constant-time (neutralizing timing oracles).
  • Replay Attacks: Penalized trust scores and rejected duplicate nonces.
  • Timestamp Skew: Rejects events outside the 60-second valid window.
  • Entropy Collapse: Flags synthetic/repetitive behavior as compromised.

4. Volumetric Flood Stress Test

cd verify-py
python benchmarks/attacks/sim_volumetric_replay.py

What this proves: Simulates an adversary flooding the server with 10,000 events (50% replays).

  • Performance: Reaches ~1,794 events/sec verified throughput on SQLite WAL.
  • Accuracy: Exactly 5,000 replays correctly identified and rejected with zero false positives.

πŸŽ“ Author & Attribution

Bibek Das


βš–οΈ License

This project is open-sourced under the Apache License 2.0. See the LICENSE file for complete details and patent grant conditions.


Footer Wave

About

SentinelMark is the core cryptographic trust primitive and forensic telemetry subsystem for the ProofTrace cybersecurity infrastructure platform. It introduces a highly resilient, research-grade implementation of Behavior-Entangled Watermarking (BEW).

Resources

License

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors