Security Rust Attack Detection Library
Security rust English | 中文
An attack detection library written in Rust, covering 27 detectors across 4 categories: injection attacks, protocol attacks, data/serialization attacks, and file/sensitive data leaks. Zero external framework dependencies, pure string scanning.
Design philosophy Why “detection” rather than “blocking” This library is positioned as a pure input scanner — it takes a string and returns structured detection results. It binds to no web framework, does no HTTP request/response parsing, and implements no real-time blocking. That way you can embed it in any pipeline: a WAF rule engine, log auditing, pre-flight validation in an API gateway, a CLI security scanner, and so on.
Architectural principles
Single responsibility — each detector handles exactly one attack type and internally holds a compiled set of regex patterns
One interface — the Detector trait is the only contract every detector implements: fn detect(&self, input: &str) -> Option<DetectionResult>
Default coverage — Scanner::default() wires up all 27 detectors in one call, usable with zero configuration
Optional configuration — Scanner::builder() supports on-demand customization, assembling detectors selectively with .with_detector()
Trade-offs
Decision
Choice
Rationale
Regex vs. parser
Regex
In detection scenarios speed comes first, and regex covers mutated/bypass patterns better
First hit wins vs. scan everything
Scan everything
One input can trigger several attack types at once — nothing should be missed
Zero dependencies vs. pulling in serde
Zero dependencies
Only depends on regex + thiserror: fast to compile, small footprint
Architecture 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ┌──────────────────────────────────┐ │ Scanner │ │ ┌────────────────────────────┐ │ user input ───────►│ │ scan(input) │ │ Vec<DetectionResult> │ │ scan_with(input, &[...]) │──┼──►──────────────────────► │ └─────────────┬──────────────┘ │ │ │ │ │ ┌─────────────▼──────────────┐ │ │ │ Vec<Box<dyn Detector>> │ │ │ │ ├─ XssDetector │ │ │ │ ├─ SqlInjectionDetector │ │ │ │ ├─ ... ×27 │ │ │ └────────────────────────────┘ │ └──────────────┬───────────────────┘ │ ┌──────────────────────────────┐ │ Detector trait │ │ fn name(&self) -> &str │ │ fn detect(&self, &str) │ │ -> Option<Result> │ └──────────────┬───────────────┘ │ ┌──────────────┼──────────────┐ │ │ │ ┌────┴────┐ ┌──────┴──────┐ ┌───┴────┐ ┌────┴────┐ │injection│ │ protocol │ │ data │ │ file │ │ 10 │ │ 9 │ │ 5 │ │ 3 │ └─────────┘ └─────────────┘ └────────┘ └─────────┘
Module responsibilities
Module
Path
Detectors
Responsibility
Core
src/lib.rs result.rs scanner.rs
—
Detector trait, DetectionResult, Scanner/ScannerBuilder
Injection
src/injection/
10
XSS, SQL injection, command injection, NoSQL, LDAP, XPATH, JNDI, SSI, GraphQL, SSTI
Protocol
src/protocol/
9
SSRF, XXE, header injection, host header attack, request smuggling, open redirect, CORS, WebSocket, DNS rebinding
Data
src/data/
5
PHP deserialization, CSV formula injection, mail header injection, JWT attack, prototype pollution
File
src/file/
3
Path traversal, malicious file upload, sensitive data leak
Detection result structure 1 2 3 4 5 6 7 8 pub struct DetectionResult { pub attack_type: String , pub category: AttackCategory, pub severity: Severity, pub matched_pattern: String , pub offset: usize , pub message: String , }
What it implements Injection attacks (10 detectors)
Detector
Patterns covered
Severity
xss
<script>, event handlers such as onerror=, javascript: pseudo-protocol, <svg>/<iframe> tags, CSS expression(), eval(), document.cookie
Critical
sql_injection
UNION SELECT, time-based injection via sleep()/benchmark()/pg_sleep(), information_schema enumeration, exec sp_/xp_ stored procedures, boolean blind patterns ' OR '1'='1, LOAD_FILE()/INTO OUTFILE
Critical
command_injection
Backtick commands, $() subshells, chained execution through pipes, /dev/tcp reverse shell, PHP functions passthru()/shell_exec()/system(), cmd.exe/powershell invocation
Critical
nosql_injection
MongoDB $ne/$gt/$regex/$where operators, $or injection, auth bypass with {"$gt": ""}
Critical
ldap_injection
(& `(
`(! filter operators, *(cn= attribute enumeration, objectClass/uid injection
High
xpath_injection
' or '1'='1 boolean bypass, ' or true() function injection, `’]
‘` node traversal
High
jndi_injection
${jndi:ldap://, ${lower:j} obfuscation, ${upper:j} obfuscation, ${::-j} empty-string obfuscation, ${env:} environment variable lookup, ${sys:} system properties
Critical
ssi_injection
<!--#exec cmd= command execution, <!--#include file= file inclusion, <!--#echo var= variable output, <!--#fsize/<!--#flastmod file information
High
graphql_injection
__schema/__type introspection queries, deeply nested DoS (≥5 levels)
Medium
ssti
Jinja2 {{}}, FreeMarker ${}, ERB <%= <%@, Velocity #set(), Python MRO sandbox escape via __mro__/__subclasses__()
Critical
Protocol and request attacks (9 detectors)
Detector
Patterns covered
Severity
ssrf
169.254.169.254 cloud metadata, RFC1918 private IPs (10.x, 172.16-31.x, 192.168.x), 127.x loopback, ::1 IPv6 loopback, 0.0.0.0, dangerous protocols gopher:///dict:///ftp:///file://
Critical
xxe
<!ENTITY entity declarations, SYSTEM/PUBLIC external references, % parameter entities, <!DOCTYPE DTD declarations
Critical
header_injection
%0d%0a URL-encoded CRLF, raw \r\n CRLF injection
High
host_header
Multiple Host headers, X-Forwarded-Host/X-Original-URL/X-Rewrite-URL poisoning, CRLF carrying a Host
High
request_smuggling
Duplicate Transfer-Encoding headers, Content-Length: 0 smuggling, \r\n0\r\n chunked terminator obfuscation
High
open_redirect
//evil.com protocol-relative URLs, javascript:/data:text/html pseudo-protocol redirects
Medium
cors
Origin: null bypass, the Access-Control-Allow-Origin: * + Credentials combination
Medium
websocket
Upgrade: websocket handshakes, cross-origin WS with Origin: null, plaintext ws:// connections
High
dns_rebinding
Host header set to a private IP 127.x/10.x/192.168.x/172.16-31.x, localhost, ::1, 0.0.0.0
High
Data and serialization attacks (5 detectors)
Detector
Patterns covered
Severity
deserialization
PHP O:number:/C:number: serialized objects, a:number:{ arrays, unserialize() calls, magic methods such as __wakeup/__destruct/__toString
Critical
csv_injection
Leading formula characters =/+/-/@, DDE dynamic data exchange, `cmd
command pipes,@SUM()` functions
Medium
mail_header
Bcc:/Cc: blind-carbon-copy injection, multiple From: senders, MIME-Version:/Content-Type: multipart MIME header injection, boundary= manipulation
Medium
jwt_attack
alg: none empty-algorithm bypass, kid path traversal injection, empty signature segment, empty payload segment
High
prototype_pollution
__proto__/constructor.prototype prototype chain pollution, __defineGetter__/__defineSetter__/__lookupGetter__/__lookupSetter__ property hijacking
High
Files and sensitive data (3 detectors)
Detector
Patterns covered
Severity
path_traversal
..//..\\ directory traversal, %2e%2e URL-encoded bypass, php://filter/php://input/phar:///zip:///data:///expect:///glob:// stream wrappers, %00 null byte truncation
Critical
upload
<?php/<?= PHP tags, <%@/<%= ASP tags, backdoor patterns eval($_/system($_/exec($_/passthru($_, superglobals $_GET/$_POST/$_REQUEST/$_SERVER, base64_decode() encoding bypass
Critical
data_leak
16-digit credit card PANs (Visa/MasterCard/AmEx/Discover/JCB/Diners), AWS Access Keys AKIA..., PEM private key headers -----BEGIN, OpenAI/LLM API keys sk-..., database connection strings mongodb:///mysql:///postgresql:///redis:///jdbc:, JWT tokens
Critical
Usage Installation 1 2 [dependencies] security-rust = { path = "." }
Quick start 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 use security_rust::Scanner;fn main () { let scanner = Scanner::default (); let results = scanner.scan ("<script>alert('xss')</script>" ); for r in &results { println! ("[{}] {} — offset: {}, pattern: {}" , r.severity, r.message, r.offset, r.matched_pattern); } }
Selective scanning 1 2 3 4 5 6 7 let scanner = Scanner::default ();let results = scanner.scan_with ( "1 UNION SELECT password FROM users" , &["sql_injection" , "xss" ], );
Custom configuration 1 2 3 4 5 6 7 use security_rust::injection::{XssDetector, SqlInjectionDetector};let scanner = Scanner::builder () .with_detector (Box ::new (XssDetector)) .with_detector (Box ::new (SqlInjectionDetector)) .build ();
Assembling only some detectors 1 2 3 4 5 6 use security_rust::injection::{XssDetector, SqlInjectionDetector};let scanner = Scanner::builder () .with_detector (Box ::new (XssDetector)) .with_detector (Box ::new (SqlInjectionDetector)) .build ();
Displaying severity 1 2 3 4 use security_rust::Severity;let r = &results[0 ];println! ("{}" , r.severity);
In a release build, a single detector scans in ~100ns per call (precompiled RegexSet), and all 27 detectors together scan in about ~5μs per call. That makes it a good fit for high-throughput scenarios (API gateways, log pipelines).
Development 1 2 3 4 5 6 7 8 cargo build --release cargo test cargo clippy -- -D warnings
License MIT — Copyright (c) 2026 erik erik@erik.xyz — https://erik.xyz