infrastructure capa

infrastructure-waf

Web Application Firewall - rate limiting, pattern detection, honeypots, IP banning

Web Application Firewall - rate limiting, pattern detection, honeypots, IP banning

Tierinfrastructure
Roleunclassified (baselined)
Pathcrates/infrastructure/waf
Edition2021
Targetsinfrastructure_waf
Public items86 across 4 modules
Tests26

What it is for

Web Application Firewall (WAF) for Axum.

A comprehensive security middleware providing:

# Architecture

Request → Rate Limiter → Pattern Detector → App
↓                ↓
Security Logger ← Strike Counter → Auto-Ban
↓
fail2ban / pf integration

# Usage

use infrastructure_waf::{
WafConfig, WafMiddleware,
honeypot::{honeypot_routes, HoneypotConfig},
};

// Create WAF middleware
let waf = WafMiddleware::new(WafConfig::default());

// Create honeypot routes
let honeypot = honeypot_routes(HoneypotConfig::default());

let app = Router::new()
.route("/", get(home))
.layer(waf.layer())
.merge(honeypot);

# fail2ban Integration

Configure fail2ban to watch the WAF log file:

# /etc/fail2ban/filter.d/waf.conf
Definition
failregex = ^\S+ \waf\ \S+ from <HOST>:.*$
^\S+ \waf\ BAN <HOST>.*$

# /etc/fail2ban/jail.local
waf
enabled = true
filter = waf
logpath = /var/log/waf/security.log
maxretry = 5
bantime = 900

# pf Integration (FreeBSD/OpenBSD)

Add to /etc/pf.conf:

table <waf_blocked> persist
block in quick on egress from <waf_blocked> to any

Reload: pfctl -f /etc/pf.conf

Capabilities

WafConfig

Web Application Firewall (WAF) for Axum.

Item
pub struct WafConfig
WafConfig :: fn default() -> Self

WafLayer

Web Application Firewall (WAF) for Axum.

Item
pub struct WafLayer
WafLayer :: fn layer(& self, inner : S) -> Self::Service

WafMiddleware

Web Application Firewall (WAF) for Axum.

Item
pub struct WafMiddleware
WafMiddleware :: fn new(config : WafConfig) -> std::io::Result <Self>
WafMiddleware :: fn layer(self) -> WafLayer
WafMiddleware :: fn layer_from_arc(waf : Arc <WafMiddleware>) -> WafLayer
WafMiddleware :: fn get_config(& self) -> & WafConfig
WafMiddleware :: fn get_logger(& self) -> & SecurityLogger
WafMiddleware :: fn get_rate_limiter(& self) -> & TokenBucketRateLimiter
WafMiddleware :: async fn process(& self, req : Request <Body>, connect_info : Option <SocketAddr>, next : Next,) -> Response

WafService

Web Application Firewall (WAF) for Axum.

Item
pub struct WafService<S>

WafService<S>

Web Application Firewall (WAF) for Axum.

Item
WafService<S> :: fn poll_ready(& mut self, cx : & mut std::task::Context <'_>,) -> std::task::Poll <Result <(), Self::Error>>
WafService<S> :: fn call(& mut self, req : Request <Body>) -> Self::Future

honeypot (other)

Honeypot routes for catching malicious login attempts.

Item
fn mask_password(password : & str) -> String

AdminerAuth

Honeypot routes for catching malicious login attempts.

Item
pub struct AdminerAuth

AdminerLoginForm

Honeypot routes for catching malicious login attempts.

Item
pub struct AdminerLoginForm

DjangoLoginForm

Honeypot routes for catching malicious login attempts.

Item
pub struct DjangoLoginForm

HoneypotConfig

Honeypot routes for catching malicious login attempts.

Item
pub struct HoneypotConfig
HoneypotConfig :: fn default() -> Self
fn honeypot_routes(config : HoneypotConfig) -> Router

PhpMyAdminLoginForm

Honeypot routes for catching malicious login attempts.

Item
pub struct PhpMyAdminLoginForm

WpLoginForm

Honeypot routes for catching malicious login attempts.

Item
pub struct WpLoginForm

DetectionResult:DetectionResult

Pattern detection for SQL injection, XSS, path traversal, and data leaks.

Item
pub struct DetectionResult

DetectionResult:detect

Pattern detection for SQL injection, XSS, path traversal, and data leaks.

Item
fn detect_sql_injection(text : & str) -> DetectionResult
fn detect_xss(text : & str) -> DetectionResult
fn detect_path_traversal(text : & str) -> DetectionResult
fn detect_all(text : & str) -> DetectionResult
fn detect_ssn(text : & str) -> DetectionResult
fn detect_credit_card(text : & str) -> DetectionResult
fn detect_api_keys(text : & str) -> DetectionResult

DetectionResult:detected

Pattern detection for SQL injection, XSS, path traversal, and data leaks.

Item
DetectionResult :: fn detected(pattern_type : & str, matched : & str) -> Self
DetectionResult :: fn detected_outbound(pattern_type : & str, matched : & str) -> Self

DetectionResult:none

Pattern detection for SQL injection, XSS, path traversal, and data leaks.

Item
DetectionResult :: fn none() -> Self
DetectionResult :: fn none_outbound() -> Self

DetectionResult:scan

Pattern detection for SQL injection, XSS, path traversal, and data leaks.

Item
fn scan_response(content : & str) -> DetectionResult

RateLimitResult

Rate limiting using token bucket algorithm.

Item
pub struct RateLimitResult

TokenBucketRateLimiter

Rate limiting using token bucket algorithm.

Item
pub struct TokenBucketRateLimiter
TokenBucketRateLimiter :: fn new(max_requests : u32, window : Duration) -> Self
TokenBucketRateLimiter :: fn check(& self, ip : IpAddr) -> RateLimitResult
TokenBucketRateLimiter :: fn get_remaining(& self, ip : IpAddr) -> u32
TokenBucketRateLimiter :: fn reset(& self, ip : IpAddr)
TokenBucketRateLimiter :: fn cleanup(& self)
TokenBucketRateLimiter :: fn default() -> Self

CapturedCredential

Security event logging with fail2ban and pf integration.

Item
pub struct CapturedCredential

HoneypotMode

Security event logging with fail2ban and pf integration.

Item
pub enum HoneypotMode

SecurityEvent

Security event logging with fail2ban and pf integration.

Item
pub struct SecurityEvent
SecurityEvent :: fn new(event_type : SecurityEventType, ip : IpAddr, path : & str) -> Self
SecurityEvent :: fn with_method(mut self, method : & str) -> Self
SecurityEvent :: fn with_user_agent(mut self, ua : & str) -> Self
SecurityEvent :: fn with_details(mut self, details : & str) -> Self
SecurityEvent :: fn with_action(mut self, action : & str) -> Self

SecurityEventType

Security event logging with fail2ban and pf integration.

Item
pub enum SecurityEventType
SecurityEventType :: fn as_str(& self) -> & 'static str

SecurityLogger:SecurityLogger

Security event logging with fail2ban and pf integration.

Item
pub struct SecurityLogger

SecurityLogger:ban

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn ban_ip(& self, ip : IpAddr, reason : & str)

SecurityLogger:cleanup

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn cleanup_old_strikes(& self, max_age : chrono::Duration)

SecurityLogger:fail2ban

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn fail2ban_unban(& self, ip : IpAddr, jail : & str) -> Result <(), std::io::Error>
SecurityLogger :: fn fail2ban_ban(& self, ip : IpAddr, jail : & str) -> Result <(), std::io::Error>
SecurityLogger :: fn fail2ban_available() -> bool

SecurityLogger:get

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn get_watched(& self, ip : IpAddr) -> Option <WatchedIpRecord>
SecurityLogger :: fn get_all_watched(& self) -> Vec <(IpAddr, WatchedIpRecord)>
SecurityLogger :: fn get_blackhole_delay(& self, ip : IpAddr) -> Option <std::time::Duration>
SecurityLogger :: fn get_strikes(& self, ip : IpAddr) -> u32

SecurityLogger:handle

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn handle_honeypot_hit(& self, ip : IpAddr, trap_type : & str, username : & str, password : & str, path : & str,)

SecurityLogger:is

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn is_watched(& self, ip : IpAddr) -> bool

SecurityLogger:log

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn log(& self, event : & SecurityEvent)
fn log_rate_limit(logger : & SecurityLogger, ip : IpAddr, limit : u32, path : & str)
fn log_pattern_detected(logger : & SecurityLogger, ip : IpAddr, pattern_type : & str, path : & str, matched : & str,)
fn log_honeypot_hit(logger : & SecurityLogger, ip : IpAddr, trap_type : & str, path : & str, username : & str,)
fn log_banned_access(logger : & SecurityLogger, ip : IpAddr, path : & str)

SecurityLogger:new

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn new(config : SecurityLoggerConfig) -> std::io::Result <Self>

SecurityLogger:pf

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn pf_remove_ip(& self, ip : IpAddr)
SecurityLogger :: fn pf_available() -> bool

SecurityLogger:record

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn record_credential(& self, ip : IpAddr, trap_type : & str, username : & str, password : & str, path : & str,)
SecurityLogger :: fn record_visit(& self, ip : IpAddr, path : & str, method : & str, user_agent : Option <& str>)
SecurityLogger :: fn record_strike(& self, event : & SecurityEvent) -> bool

SecurityLogger:reset

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn reset_strikes(& self, ip : IpAddr)

SecurityLogger:unban

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn unban_ip(& self, ip : IpAddr, reason : & str)

SecurityLogger:unwatch

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn unwatch_ip(& self, ip : IpAddr)

SecurityLogger:watch

Security event logging with fail2ban and pf integration.

Item
SecurityLogger :: fn watch_ip(& self, ip : IpAddr, reason : SecurityEventType)

SecurityLoggerConfig

Security event logging with fail2ban and pf integration.

Item
pub struct SecurityLoggerConfig
SecurityLoggerConfig :: fn default() -> Self

VisitedPath

Security event logging with fail2ban and pf integration.

Item
pub struct VisitedPath

WatchedIpRecord

Security event logging with fail2ban and pf integration.

Item
pub struct WatchedIpRecord

How to use it

From this crate's own rustdoc:


# Usage

From this crate's own rustdoc:


# fail2ban Integration

Configure fail2ban to watch the WAF log file:

Module structure

infrastructure_waf

flowchart TD
  n_infrastructure_waf["infrastructure_waf"]
  n_infrastructure_waf --> n_honeypot["honeypot"]
  n_infrastructure_waf --> n_pattern_detector["pattern_detector"]
  n_infrastructure_waf --> n_rate_limiter["rate_limiter"]
  n_infrastructure_waf --> n_security_logger["security_logger"]

Public surface

`crate root`

ItemWhat it is
pub struct WafConfigWAF configuration.
WafConfig :: fn default() -> Self
pub struct WafMiddlewareWAF middleware state.
WafMiddleware :: fn new(config : WafConfig) -> std::io::Result <Self>Create a new WAF middleware.
WafMiddleware :: fn layer(self) -> WafLayerCreate a tower Layer for this middleware.
WafMiddleware :: fn layer_from_arc(waf : Arc <WafMiddleware>) -> WafLayerCreate a tower Layer from an Arc of this middleware
WafMiddleware :: fn get_config(& self) -> & WafConfigGet the WAF configuration.
WafMiddleware :: fn get_logger(& self) -> & SecurityLoggerGet the security logger.
WafMiddleware :: fn get_rate_limiter(& self) -> & TokenBucketRateLimiterGet the rate limiter.
WafMiddleware :: async fn process(& self, req : Request <Body>, connect_info : Option <SocketAddr>, next : Next,) -> ResponseProcess a request through the WAF.
pub struct WafLayerTower Layer for WAF middleware.
WafLayer :: fn layer(& self, inner : S) -> Self::Service
pub struct WafService<S>Tower Service for WAF middleware.
WafService<S> :: fn poll_ready(& mut self, cx : & mut std::task::Context <'_>,) -> std::task::Poll <Result <(), Self::Error>>
WafService<S> :: fn call(& mut self, req : Request <Body>) -> Self::Future

`honeypot`

ItemWhat it is
pub struct HoneypotConfigConfiguration for honeypot behavior.
HoneypotConfig :: fn default() -> Self
fn honeypot_routes(config : HoneypotConfig) -> RouterCreate honeypot routes for common admin paths
pub struct DjangoLoginFormForm data for Django admin login.
pub struct WpLoginFormForm data for WordPress login.
pub struct PhpMyAdminLoginFormForm data for phpMyAdmin login.
pub struct AdminerLoginFormForm data for Adminer login.
pub struct AdminerAuth
fn mask_password(password : & str) -> StringMask password for logging (show first char and length).

`pattern_detector`

ItemWhat it is
pub struct DetectionResultResult of pattern detection.
DetectionResult :: fn none() -> SelfCreate a "nothing detected" result.
DetectionResult :: fn none_outbound() -> SelfCreate a "nothing detected" result for outbound scanning.
DetectionResult :: fn detected(pattern_type : & str, matched : & str) -> SelfCreate a detection result.
DetectionResult :: fn detected_outbound(pattern_type : & str, matched : & str) -> SelfCreate a detection result for outbound (data leak).
fn detect_sql_injection(text : & str) -> DetectionResultDetect SQL injection patterns in text.
fn detect_xss(text : & str) -> DetectionResultDetect XSS patterns in text.
fn detect_path_traversal(text : & str) -> DetectionResultDetect path traversal patterns in text.
fn detect_all(text : & str) -> DetectionResultDetect all attack patterns in text.
fn detect_ssn(text : & str) -> DetectionResultDetect Social Security Numbers in text
fn detect_credit_card(text : & str) -> DetectionResultDetect credit card numbers in text
fn detect_api_keys(text : & str) -> DetectionResultDetect API keys and secrets in text.
fn scan_response(content : & str) -> DetectionResultScan response content for data leaks.

`rate_limiter`

ItemWhat it is
pub struct RateLimitResultResult of a rate limit check.
pub struct TokenBucketRateLimiterToken bucket rate limiter
TokenBucketRateLimiter :: fn new(max_requests : u32, window : Duration) -> SelfCreate a new rate limiter
TokenBucketRateLimiter :: fn check(& self, ip : IpAddr) -> RateLimitResultCheck if a request from this IP is allowed.
TokenBucketRateLimiter :: fn get_remaining(& self, ip : IpAddr) -> u32Get remaining requests for an IP without consuming.
TokenBucketRateLimiter :: fn reset(& self, ip : IpAddr)Reset rate limit for an IP.
TokenBucketRateLimiter :: fn cleanup(& self)Clean up expired buckets (call periodically).
TokenBucketRateLimiter :: fn default() -> Self

`security_logger`

ItemWhat it is
pub enum SecurityEventTypeSecurity event types.
SecurityEventType :: fn as_str(& self) -> & 'static str
pub struct SecurityEventA security event to be logged.
SecurityEvent :: fn new(event_type : SecurityEventType, ip : IpAddr, path : & str) -> Self
SecurityEvent :: fn with_method(mut self, method : & str) -> Self
SecurityEvent :: fn with_user_agent(mut self, ua : & str) -> Self
SecurityEvent :: fn with_details(mut self, details : & str) -> Self
SecurityEvent :: fn with_action(mut self, action : & str) -> Self
pub enum HoneypotModeHow to handle honeypot hits.
pub struct SecurityLoggerConfigConfiguration for security logging.
SecurityLoggerConfig :: fn default() -> Self
pub struct WatchedIpRecordRecord for watched IPs (intelligence gathering mode).
pub struct CapturedCredentialCaptured credential attempt.
pub struct VisitedPathRecord of a path visit.
pub struct SecurityLoggerSecurity logger with fail2ban and pf integration.
SecurityLogger :: fn new(config : SecurityLoggerConfig) -> std::io::Result <Self>Create a new security logger.
SecurityLogger :: fn is_watched(& self, ip : IpAddr) -> boolCheck if an IP is being watched (intel gathering mode).
SecurityLogger :: fn get_watched(& self, ip : IpAddr) -> Option <WatchedIpRecord>Get the watch record for an IP.
SecurityLogger :: fn watch_ip(& self, ip : IpAddr, reason : SecurityEventType)Add an IP to the watch list (for intel gathering).
SecurityLogger :: fn unwatch_ip(& self, ip : IpAddr)Remove an IP from the watch list.
SecurityLogger :: fn record_credential(& self, ip : IpAddr, trap_type : & str, username : & str, password : & str, path : & str,)Record a credential attempt from a watched IP.
SecurityLogger :: fn record_visit(& self, ip : IpAddr, path : & str, method : & str, user_agent : Option <& str>)Record a path visit from a watched IP.
SecurityLogger :: fn get_all_watched(& self) -> Vec <(IpAddr, WatchedIpRecord)>Get all watched IPs with their records.
SecurityLogger :: fn handle_honeypot_hit(& self, ip : IpAddr, trap_type : & str, username : & str, password : & str, path : & str,)Handle a honeypot hit based on configured mode.
SecurityLogger :: fn get_blackhole_delay(& self, ip : IpAddr) -> Option <std::time::Duration>Get the blackhole delay if this IP should be tarpitted.
SecurityLogger :: fn log(& self, event : & SecurityEvent)Log a security event.
SecurityLogger :: fn record_strike(& self, event : & SecurityEvent) -> boolRecord a strike against an IP and potentially ban.
SecurityLogger :: fn ban_ip(& self, ip : IpAddr, reason : & str)Ban an IP address.
SecurityLogger :: fn pf_remove_ip(& self, ip : IpAddr)Remove IP from pf table.
SecurityLogger :: fn get_strikes(& self, ip : IpAddr) -> u32Get strike count for an IP.
SecurityLogger :: fn reset_strikes(& self, ip : IpAddr)Reset strikes for an IP.
SecurityLogger :: fn unban_ip(& self, ip : IpAddr, reason : & str)Unban an IP address
SecurityLogger :: fn fail2ban_unban(& self, ip : IpAddr, jail : & str) -> Result <(), std::io::Error>Execute fail2ban-client to unban an IP
SecurityLogger :: fn fail2ban_ban(& self, ip : IpAddr, jail : & str) -> Result <(), std::io::Error>Execute fail2ban-client to ban an IP
SecurityLogger :: fn fail2ban_available() -> boolCheck if fail2ban-client is available.
SecurityLogger :: fn pf_available() -> boolCheck if pfctl is available.
SecurityLogger :: fn cleanup_old_strikes(& self, max_age : chrono::Duration)Clean up old strike records.
fn log_rate_limit(logger : & SecurityLogger, ip : IpAddr, limit : u32, path : & str)Helper functions for common logging patterns.
fn log_pattern_detected(logger : & SecurityLogger, ip : IpAddr, pattern_type : & str, path : & str, matched : & str,)
fn log_honeypot_hit(logger : & SecurityLogger, ip : IpAddr, trap_type : & str, path : & str, username : & str,)
fn log_banned_access(logger : & SecurityLogger, ip : IpAddr, path : & str)

Re-exports. Exported here, defined elsewhere.

ExportDefined in
{CapturedCredential,HoneypotMode,SecurityEvent,SecurityEventType,SecurityLogger,SecurityLoggerConfig,VisitedPath,WatchedIpRecord,}security_logger::{CapturedCredential,HoneypotMode,SecurityEvent,SecurityEventType,SecurityLogger,SecurityLoggerConfig,VisitedPath,WatchedIpRecord,}
{RateLimitResult,TokenBucketRateLimiter}rate_limiter::{RateLimitResult,TokenBucketRateLimiter}
{detect_all,detect_path_traversal,detect_sql_injection,detect_xss,scan_response,DetectionResult,}pattern_detector::{detect_all,detect_path_traversal,detect_sql_injection,detect_xss,scan_response,DetectionResult,}
{honeypot_routes,mask_password,HoneypotConfig}honeypot::{honeypot_routes,mask_password,HoneypotConfig}

Boundary

Reaches into foundation.

Shares tier infrastructure with 82 other crates: infrastructure-acquire, infrastructure-adapters-google-calendar, infrastructure-adapters-google-gmail, infrastructure-adapters-google-places, infrastructure-adapters-google-trends, infrastructure-adapters-shodan, infrastructure-adapters-yelp, infrastructure-agent, … (82 total).

_What this crate deliberately does NOT own is a judgment. No committed registry records one for it, so none is stated here._

Where it sits

Tier (ontology)infrastructure
Architectural role (taxonomy)unclassified (baselined)
Locationcrates/infrastructure/waf
Vocabulary in force (lexicon)current

Tier flow. Which tiers this crate's own edges cross.

flowchart LR
  n_infrastructure["infrastructure"] --> n_foundation["foundation"]

Dependencies

Runtime, in this workspace.

CrateTierOptionalOnly on
`foundation-audit-log`foundationnoalways
`infrastructure-dlp-detect`infrastructurenoalways

Runtime, from outside the workspace.

CrateRequirementFeaturesOptionalOnly on
async-trait^0.1noalways
axum^0.7multipartnoalways
chrono^0.4serdenoalways
http^1.1noalways
once_cell^1noalways
regex^1noalways
serde^1derivenoalways
serde_json^1noalways
thiserror^2noalways
time^0.3noalways
tokio^1fullnoalways
tower^0.5noalways
tower-http^0.6fs, trace, cors, request-idnoalways
tracing^0.1noalways
uuid^1v4, v7, serde, jsnoalways

Development, from outside the workspace.

CrateRequirementFeaturesOptionalOnly on
tokio-test^0.4noalways

Build. None.

Depended on by. 2 workspace crates.

Signal flow — what reaches this crate, and what it reaches.

flowchart LR
  n_application_security["application-security"] -->|uses| SELF
  n_application_waf["application-waf"] -->|uses| SELF
  SELF["infrastructure-waf"]
  SELF -->|runtime| n_foundation_audit_log["foundation-audit-log"]
  SELF -->|runtime| n_infrastructure_dlp_detect["infrastructure-dlp-detect"]
  classDef self fill:#1f883d,stroke:#1f883d,color:#fff;
  class SELF self;

Feature flags

No Cargo features are defined: every capability is unconditional, so no consumer can receive a half-wired crate.

Targets

KindNameSource
libinfrastructure_waf`src/lib.rs`

Error model

No public error type was detected: no public item declares a type named *Error, and no public signature returns one.

Operational characteristics

PropertyEvidence
async public surfaceyes
async runtimeyes
database accessnone detected
network I/Oyes
unsafe codenone detected
environment variablesnone detected

No unsafe block, unsafe fn, unsafe impl or unsafe trait was found by the parser anywhere in this crate's source.

Configuration

No environment variable is read with a literal name anywhere in this crate. A variable whose key is computed at run time cannot be listed here, and is not claimed to be absent.

2 workspace crates depend on this one: application-security, application-waf.

Verification

KindCount
Unit tests26
Integration tests0
Examples0
Doctests3

Evidence by module. How often each public module is named by something executable.

ModuleTestsExamplesConsumers
crate root402
honeypot800
pattern_detector900
rate_limiter200
security_logger1200

What the tests establish, by name:

Documentation coverage

MeasureDocumentedTotal
Public items with rustdoc6986
Public modules with a //! block44
pie showData
    title Public items with rustdoc
    "Documented" : 69
    "No rustdoc detected" : 17

Metrics

MetricValue
Rust source files5
Source lines2934
Code lines2290
Public API items86
Public modules4
Tests26
Examples0
Cargo features0
Direct runtime dependencies17
Workspace reverse dependencies2
pie showData
    title Public API by kind
    "enum" : 2
    "function" : 14
    "method" : 51
    "struct" : 19
pie showData
    title Rust source composition
    "Code" : 2290
    "Blank or comment" : 644

Generation

Rendered by tools-corpus corpus readme from repository evidence alone, renderer schema 2, lexicon current. No model, network service or database was consulted. Regenerate with tools-corpus corpus readme --write; verify with --check.

Todas las infrastructure · Manual