Rullst Security ๐ก๏ธโก
rullst-security is the dedicated security suite for the Rullst Framework. It uses bounded in-memory state, established cryptographic primitives, and defense-in-depth middleware. Its WAF/RASP rules are heuristic controls and must be combined with secure application design, authentication, authorization, TLS, monitoring, and timely dependency updates.
๐ Modules & Features
๐ฏ 1. Rullst Honey (rullst::security::honey)
Deception Security & Botnet Mitigation Engine
- Synthetic Honeypot Traps: Intercepts reconnaissance bots attempting to scan paths like
/.env,/admin.php,/wp-login.php,/.git/config. - Bounded In-Memory Ban List: Tracks verified socket peers with an explicit TTL and cardinality limit. A request checks only its own peer; expired bans are pruned in expiry order when bans are added or counted, and a full list evicts the ban that expires soonest.
- Exact Route Matching: Trap paths are matched as complete paths; untrusted forwarding headers are not used as ban identities.
- Lure-Resistant Bans: Every trap hit is refused, but only a direct request bans its peer. A load that a page initiated (
Sec-Fetch-Siteofsame-origin,same-siteorcross-site, orOrigin/Refererfrom a browser without fetch metadata) is recorded without a ban, so an<img src="/.env">on another site or in user content cannot ban visitors or a shared NAT address. These headers are client-controlled: a scanner can avoid the ban, not the refusal, by sending them.
๐งน 2. Rullst Sanitizer (rullst::security::sanitizer)
XSS Prevention & Dynamic CSP Nonces
- Allowlisted HTML Sanitization: Uses
ammoniato strip scripts, inline event handlers, unsafe attributes, and unsupported SVG/HTML instead of trying to make arbitrary markup safe. - Dynamic Content Security Policy (CSP): Generates cryptographically secure base64 nonces (
nonce-<random>) per HTTP request. - Clickjacking & Security Headers: Enforces
X-Frame-Options: DENY,X-Content-Type-Options: nosniff, and strictReferrer-Policy.
๐ก๏ธ 3. Rullst RBAC Guard (rullst::security::rbac)
Role-Based Access Control & BOLA/IDOR Defense
- Declarative Authorization: Inspects
UserContextroles and fine-grained capabilities (RbacGuard::authorize). - BOLA / IDOR Prevention: Provides
RbacGuard::authorize_owner_or_roleto enforce resource ownership boundaries dynamically.
๐ 4. Rullst Audit Log (rullst::security::audit)
HMAC-SHA256 Tamper-Evident Trail
- Canonical Event Chaining: Signs a versioned, domain-separated, length-prefixed encoding of the sequence, timestamp, event fields, and predecessor hash.
- Offline Integrity Checks:
verify_recordchecks one record's HMAC;verify_sequenceadditionally validates genesis, monotonic sequence IDs, and predecessor continuity. - Extensible Sinks: Provides
AuditLoggertrait for database ORM logging or Cloud-Native stdout/JSON sinks.
๐ 5. TOTP Recovery Codes (rullst::security::recovery_codes)
- One-time plaintext: 80-bit codes are returned only during enrollment and zeroized on drop.
- Storage-safe records: Persist only the subject-bound salted HMAC-SHA256 verifiers.
- Single-use contract:
consume_recovery_coderemoves one verifier; database-backed callers must make compare-and-delete transactional.
๐ฒ 6. MFA & Login Abuse Controls
- TOTP enrollment: OS-random 160-bit secrets, RFC 6238 code generation,
constant-time six-digit verification,
otpauth://URIs, and bounded SVG QR generation throughbuild_mfa_qr_svg. - TOTP replay is the caller's job:
verify_totp_codeis stateless and accepts the previous, current and next 30-second step, so an observed code verifies again for about 90 seconds. To meet RFC 6238 section 5.2, find the matched step withmfa::generate_totp_at_counter, persist the last accepted step per secret atomically, and reject any step less than or equal to it. Theverify_totp_coderustdoc shows the complete check. - Applied tarpit:
LoginGuard::record_login_failure_and_waitrecords a failure and awaits its progressive delay; jail state is bounded and local to the process. Concurrent admission shares the configured identity ceiling. At capacity, a new identity evicts the least recently failed counter and a new offender evicts the jail that expires soonest, so a flood of unrelated identities cannot stop a later identity from being counted and jailed. It can still age out older counters, so pair the jail with upstream rate limits. - Local rate limiter: Fixed-window counters retain at most 16,384 identities
with keys up to 256 bytes, reclaim expired identities on subsequent requests,
and reject zero budgets or exhausted admission. Clones share state; this is
not a distributed limit across application instances. Prefer one
RateLimiterper policy. The legacy globalis_rate_limitedhelper keeps a separate budget per(key, max_requests, window), so policies on the same key neither share a count nor reset each other, but they share its capacity.rate_limit_middlewarekeys the verified socket peer per IPv4 address and per IPv6 /64 (IPv4-mapped IPv6 counts as IPv4), so rotating addresses inside one delegated prefix shares a budget instead of filling the identity table.
๐ 7. Bounded Payload, Log & Asset Guards
- Schema Guard: Rejects malformed JSON, recursive duplicate keys, excessive body size/depth, and ambiguous JSON content types. An application can also compile one bounded JSON Schema 2020-12 document or one explicit OpenAPI 3.1 component into route-scoped middleware. References stay local, pattern matching uses the linear-time regex engine, and schema construction performs no filesystem or network retrieval.
- Response DLP:
mask_response_payloadandDlpResponseLayermask complete PEM private-key blocks (PKCS#8 plain or encrypted, RSA, EC, DSA, OpenSSH and OpenPGP), AWS access-key IDs andpostgres/postgresql/mysql/redisURL passwords in bounded textual responses (at most 2 MiB). Every pass is linear in the body length. A URL password is recognized only inside the URL authority: credentials must be percent-encoded, and the authority ends at the first/,?,#, whitespace, quote,<,>, backtick or control character, or after 2,048 bytes. - Log redaction:
redact_secretshandles repeated Bearer/assignment, PEM, AWS, and database patterns, including escaped quoted values, in time linear in the record length. An assignment key (password,passwd,secret,api_key,token,authorization,cookie,session) also matches as the final component of a compound name joined by_,-or.(DB_PASSWORD,access_token,client-secret,app.db.password) or when a finalkey/idcomponent follows it (SECRET_KEY,session_id). An unquotedAuthorization/Proxy-AuthorizationorCookie/Set-Cookievalue is redacted to the end of its line, so later cookies and credentials containing spaces are covered; only a recognized authentication scheme such asBearer,Basic,DigestorTokenis kept. Records over 64 KiB are replaced wholesale by an oversized-record marker. The host must invoke it before emitting untrusted log fields; pattern matching is not a guarantee that arbitrary sensitive content can be recognized. - SRI: Generate escaped SHA-384 tags from bytes or bounded local JS/CSS
files with
sri_script_tag_from_fileandsri_link_tag_from_file.
๐งฉ 8. Deterministic Threat Sentinel
- Explainable assessment: Classifies caller-supplied aggregate windows
against explicit credential-stuffing, API-scraping and
distributed-automation thresholds; it does not claim AI attribution.
SentinelObservationdeserialization applies the same validation astry_new, so a zero window, zero requests or inconsistent counts are rejected rather than reaching the classifier. - Bounded proof of work: Issues OS-random, HMAC-authenticated, subject-bound challenges with bounded TTL, difficulty and local cardinality.
- One-shot verification: Exactly one concurrent verifier consumes an active challenge in the current process. Distributed replay state and traffic identity remain application/deployment responsibilities.
๐พ 9. Durable Local SIEM Spool
- Restart validation:
DurableSiemSpoolsynchronously appends normalized, unsignedLiveSecurityEventv1 records and validates the whole bounded file when it is reopened. - Fail-closed framing: A version header, exact length and SHA-256 digest detect truncation and accidental modification; byte and record ceilings stop unbounded growth.
- Explicit boundary: This is a single-process local spool. SHA-256 is not source authentication, and the application still owns trusted directories, permissions, rotation, retention, backup, delivery, retry, acknowledgement, dead-letter policy and any Splunk/Datadog/Elastic/Syslog adapter.
๐ 10. Authenticated Local SIEM Journal
- HMAC chain:
AuthenticatedSiemSpoolbinds every normalized event to its one-based sequence, named key, predecessor tag and exact payload using domain-separated HMAC-SHA256. - Explicit rotation:
SiemKeyRingwrites with one active key and verifies older frames with at most seven historical keys. Secret bytes live in zeroizing storage and are redacted fromDebug. - Fail-closed recovery: Restart rejects forged content, wrong or absent keys, reordered/removed interior frames, malformed encoding and quota or external-length violations. A trusted external checkpoint is still needed to detect removal of a complete valid tail.
๐ฆ Installation
Add rullst-security to your Cargo.toml:
[]
= "12.1.0"
โก Quickstart Code Examples
1. Honeypot & CSP Middleware Setup
use ;
use ;
async
2. XSS HTML Sanitization
use HtmlSanitizer;
let dirty_input = "<script>alert('xss')</script><p>Clean Text</p>";
let safe_html = sanitize;
assert_eq!;
3. Role & Ownership Authorization (RBAC)
use ;
let user = new;
// Authorize role
let is_allowed = authorize;
assert!;
// Authorize owner or admin
let resource_owner = "usr_100";
let is_owner = authorize_owner_or_role;
assert!;
4. Cryptographic Audit Log Chain
use Arc;
use ;
async
5. TOTP Enrollment QR
use ;
Store the secret encrypted, show the QR only during a protected enrollment ceremony, and require a verified code before enabling MFA.
6. Route-scoped JSON Schema enforcement
use ;
use ;
use json;
The compiled layer returns 415 for unsafe requests with a non-JSON media
type, 400 for malformed/duplicate/oversized/deep JSON, and 422 for a valid
JSON value that does not match the selected schema. Authentication,
authorization, ownership and domain validation remain separate.
7. Opt-in proof-of-work assessment
use ;
use Duration;
The host must derive the subject from trusted application state, provide an accessible alternative, limit issuance and explicitly verify the returned token/nonce before admitting the protected operation.
8. Persist a bounded local SIEM event
use ;
Create and permission the parent directory before opening the spool, use only one writer process per file, and deliver/rotate it through an application-owned operator. Reopening validates frames but does not authenticate the event source or confirm remote receipt.
9. Persist and verify an authenticated local SIEM event
use ;
Generate the key from a cryptographic secret manager rather than using the example literal. During rotation, reopen with the new active key and every historical key referenced by retained frames. This API does not send events to an external SIEM or acknowledge remote receipt.
๐ License
Licensed under the MIT License. Part of the Rullst Monorepo Framework.