@@ -189,6 +189,175 @@ Common utilities for code reuse between bssh client and server implementations:
189189
190190The ` security ` and ` jump::rate_limiter ` modules re-export from shared for backward compatibility.
191191
192+ ### Server Security Module
193+
194+ Security features for the SSH server (` src/server/security/ ` ):
195+
196+ - ** AuthRateLimiter** : Fail2ban-like authentication rate limiting
197+ - Tracks failed authentication attempts per IP address
198+ - Automatic banning after exceeding configurable threshold
199+ - Time-windowed failure counting (failures outside window not counted)
200+ - Configurable ban duration with automatic expiration
201+ - IP whitelist for exempting trusted addresses from banning
202+ - Memory-safe with configurable maximum tracked IPs
203+ - Automatic cleanup of expired records via background task
204+ - Thread-safe async implementation with ` Arc<RwLock<>> `
205+
206+ - ** IpAccessControl** : IP-based connection filtering
207+ - Whitelist mode: Only allow connections from specified CIDR ranges
208+ - Blacklist mode: Block connections from specified CIDR ranges
209+ - Blacklist takes priority over whitelist (blocked IPs are always denied)
210+ - Support for both IPv4 and IPv6 addresses and CIDR notation
211+ - Dynamic updates: Add/remove rules at runtime via ` SharedIpAccessControl `
212+ - Early rejection at connection level before handler creation
213+ - Thread-safe with fail-closed behavior on lock contention
214+ - Configuration via ` allowed_ips ` and ` blocked_ips ` in server config
215+
216+ ### Audit Logging Module
217+
218+ Comprehensive audit logging infrastructure for the SSH server (` src/server/audit/ ` ):
219+
220+ ** Structure** :
221+ - ` mod.rs ` - ` AuditManager ` for collecting and distributing audit events
222+ - ` event.rs ` - ` AuditEvent ` type definitions and builder pattern
223+ - ` exporter.rs ` - ` AuditExporter ` trait and ` NullExporter ` implementation
224+ - ` file.rs ` - ` FileExporter ` for JSON Lines output with rotation support
225+
226+ ** Key Components** :
227+
228+ - ** AuditEvent** : Represents discrete auditable actions with fields for:
229+ - Unique event ID (UUID v4)
230+ - Timestamp (UTC)
231+ - Event type, session ID, username, client IP
232+ - File paths, bytes transferred, operation result
233+ - Protocol and additional details
234+
235+ - ** EventType** : Categorizes security and operational events:
236+ - Authentication: ` AuthSuccess ` , ` AuthFailure ` , ` AuthRateLimited `
237+ - Sessions: ` SessionStart ` , ` SessionEnd `
238+ - Commands: ` CommandExecuted ` , ` CommandBlocked `
239+ - File operations: ` FileOpenRead ` , ` FileOpenWrite ` , ` FileRead ` , ` FileWrite ` , ` FileClose ` , ` FileUploaded ` , ` FileDownloaded ` , ` FileDeleted ` , ` FileRenamed `
240+ - Directory operations: ` DirectoryCreated ` , ` DirectoryDeleted ` , ` DirectoryListed `
241+ - Filters: ` TransferDenied ` , ` TransferAllowed `
242+ - Security: ` IpBlocked ` , ` IpUnblocked ` , ` SuspiciousActivity `
243+
244+ - ** EventResult** : Operation outcomes (` Success ` , ` Failure ` , ` Denied ` , ` Error ` )
245+
246+ - ** AuditExporter Trait** : Interface for audit event destinations
247+ - ` export() ` - Export single event
248+ - ` export_batch() ` - Export multiple events (optimizable)
249+ - ` flush() ` - Ensure pending events are written
250+ - ` close() ` - Clean up resources
251+
252+ - ** NullExporter** : No-op exporter for testing and disabled audit logging
253+
254+ - ** FileExporter** : File-based exporter writing events in JSON Lines format
255+ - Append mode to preserve existing data
256+ - Optional log rotation based on file size (` RotateConfig ` )
257+ - Optional gzip compression for rotated files
258+ - Thread-safe using async Mutex
259+ - Async I/O using tokio
260+ - Automatic parent directory creation
261+ - Restrictive file permissions (0o600 on Unix)
262+
263+ - ** AuditManager** : Central manager with async processing
264+ - Background worker for non-blocking event processing
265+ - Configurable buffering (buffer size, batch size)
266+ - Periodic flush intervals
267+ - Multiple exporter support
268+ - Graceful shutdown with event flush
269+
270+ ** Configuration** :
271+ ``` rust
272+ let config = AuditConfig :: new ()
273+ . with_enabled (true )
274+ . with_buffer_size (1000 )
275+ . with_batch_size (100 )
276+ . with_flush_interval (5 );
277+ ```
278+
279+ ** File Exporter Usage** :
280+ ``` rust
281+ use bssh :: server :: audit :: file :: {FileExporter , RotateConfig };
282+ use std :: path :: Path ;
283+
284+ // Simple file exporter
285+ let exporter = FileExporter :: new (Path :: new (" /var/log/audit.log" ))? ;
286+
287+ // With rotation (50 MB, 10 backups, gzip compression)
288+ let rotate_config = RotateConfig :: new ()
289+ . with_max_size (50 * 1024 * 1024 )
290+ . with_max_backups (10 )
291+ . with_compress (true );
292+
293+ let exporter = FileExporter :: new (Path :: new (" /var/log/audit.log" ))?
294+ . with_rotation (rotate_config );
295+ ```
296+
297+ ** Output Format** (JSON Lines - one JSON object per line):
298+ ``` json
299+ {"id" :" uuid" ,"timestamp" :" 2024-01-15T10:30:00Z" ,"event_type" :" file_uploaded" ,"session_id" :" sess-001" ,"user" :" admin" ,"client_ip" :" 192.168.1.100" ,"path" :" /data/report.pdf" ,"bytes" :1048576 ,"result" :" success" ,"protocol" :" sftp" }
300+ ```
301+
302+ - ** OtelExporter** : OpenTelemetry exporter for distributed tracing and observability
303+ - OTLP/gRPC protocol support using tonic
304+ - Event to LogRecord mapping with proper attribute conversion
305+ - Severity level mapping based on event types and results
306+ - Resource attributes including service.name and service.version
307+ - Graceful shutdown and flush methods
308+ - TLS support for secure audit data transmission
309+
310+ - ** LogstashExporter** : Logstash exporter for ELK stack integration
311+ - TCP connection with JSON Lines protocol (newline-delimited JSON)
312+ - Optional TLS encryption for secure transmission
313+ - Automatic reconnection on connection failure
314+ - Batch support for efficient event transmission
315+ - Connection timeout handling (default: 10 seconds)
316+ - Configurable host and port
317+
318+ ** OtelExporter Usage** :
319+ ``` rust
320+ use bssh :: server :: audit :: otel :: OtelExporter ;
321+ use bssh :: server :: audit :: exporter :: AuditExporter ;
322+ use bssh :: server :: audit :: event :: {AuditEvent , EventType };
323+
324+ // Create exporter with OTLP endpoint
325+ let exporter = OtelExporter :: new (" http://localhost:4317" )? ;
326+
327+ // Export an audit event
328+ let event = AuditEvent :: new (
329+ EventType :: AuthSuccess ,
330+ " alice" . to_string (),
331+ " session-123" . to_string (),
332+ );
333+ exporter . export (event ). await ? ;
334+
335+ // Graceful shutdown
336+ exporter . close (). await ? ;
337+ ```
338+
339+ ** LogstashExporter Usage** :
340+ ``` rust
341+ use bssh :: server :: audit :: logstash :: LogstashExporter ;
342+ use bssh :: server :: audit :: exporter :: AuditExporter ;
343+ use bssh :: server :: audit :: event :: {AuditEvent , EventType };
344+
345+ // Create exporter (unencrypted by default)
346+ let exporter = LogstashExporter :: new (" logstash.example.com" , 5044 )?
347+ . with_tls (true ); // Enable TLS for production
348+
349+ // Export an audit event
350+ let event = AuditEvent :: new (
351+ EventType :: AuthSuccess ,
352+ " alice" . to_string (),
353+ " session-123" . to_string (),
354+ );
355+ exporter . export (event ). await ? ;
356+
357+ // Graceful shutdown
358+ exporter . close (). await ? ;
359+ ```
360+
192361### Server CLI Binary
193362** Binary** : ` bssh-server `
194363
@@ -251,6 +420,7 @@ SSH server implementation using the russh library for accepting incoming connect
251420- ` sftp.rs ` - SFTP subsystem handler with path traversal prevention
252421- ` scp.rs ` - SCP protocol handler with sink/source modes
253422- ` auth/ ` - Authentication provider infrastructure
423+ - ` audit/ ` - Audit logging infrastructure (event types, exporters, manager)
254424
255425** Key Components** :
256426
@@ -285,7 +455,8 @@ SSH server implementation using the russh library for accepting incoming connect
285455
286456- ** SshHandler** : Per-connection handler for SSH protocol events
287457 - Public key authentication via AuthProvider trait
288- - Rate limiting for authentication attempts
458+ - Rate limiting for authentication attempts (token bucket)
459+ - Auth rate limiting with ban support (fail2ban-like)
289460 - Channel operations (open, close, EOF, data)
290461 - PTY, exec, shell, and subsystem request handling
291462 - Command execution with stdout/stderr streaming
0 commit comments