K9Shield is a comprehensive security middleware for Node.js applications, providing robust protection against various web security threats. It offers advanced features like DDoS protection, rate limiting, IP management, and security headers management.
- Simplified configuration structures
- Enhanced code readability
- Removed redundant logging and configuration details
- Improved request pattern anomaly detection
- More robust IP blocking mechanism
- Enhanced logging for attack detection
- Refined anomaly scoring algorithm
- More concise log message formatting
- Removed unnecessary log details
- Added more context to security-related logs
- Improved error handling in logging system
- Reduced default configuration complexity
- Made configuration more minimal and focused
- Removed unnecessary default settings
- Improved configuration validation
- Streamlined request processing
- More efficient IP and request tracking
- Reduced overhead in security checks
- Optimized memory usage in tracking mechanisms
- More granular IP management
- Improved request pattern detection
- Enhanced rate limiting mechanisms
- More precise DDoS attack prevention strategies
- More informative error messages
- Better error tracking
- Improved error response generation
- Enhanced debugging capabilities
Note: These updates focus on improving code quality, performance, and maintainability while preserving the core security features of K9Shield.
- Features
- Installation
- Quick Start
- Core Components
- Configuration
- Security Features
- API Reference
- Testing
- Examples
- Contributing
- License
-
DDoS Protection
- Progressive penalty system
- Connection tracking
- Burst detection
- Path-based rate limiting
- Configurable thresholds and block durations
-
Rate Limiting
- Route-specific limits
- Flexible time windows
- Throttling support
- Ban duration management
- Distributed system support
-
IP Management
- CIDR notation support
- IPv6 support with IPv4 mapping
- Private IP detection
- Whitelist/Blacklist functionality
- Proxy support
-
Request Validation
- Method validation
- Payload size limits
- Header validation
- Pattern detection (SQL Injection, XSS, Path Traversal)
- User Agent and Referer filtering
-
Security Headers
- Content Security Policy (CSP)
- Permissions Policy
- HSTS support
- XSS protection
- Frame options
- Content type options
-
Pattern Detection
- SQL Injection patterns
- XSS patterns
- Path traversal attempts
- Custom pattern support
- Regular expression based detection
-
Logging System
- Multiple log levels
- Automatic rotation
- Archive management
- Performance metrics
- Security event tracking
-
Request Tracking
- IP tracking
- Request duration
- Path monitoring
- Error logging
- Detailed request information
npm install k9shield
const express = require('express');
const K9Shield = require('k9shield');
const app = express();
const shield = new K9Shield();
// Protect all routes
app.use(shield.protect());
app.get('/', (req, res) => {
res.json({ message: 'A secure endpoint' });
});
app.listen(3000, () => {
console.log('Server running securely');
});
const shield = new K9Shield({
rateLimiting: {
enabled: true,
default: {
maxRequests: 10, // 10 requests per minute
timeWindow: 60000, // 1 minute
banDuration: 300000 // 5 minutes ban
},
routes: {
'/api/sensitive-endpoint': {
'POST': {
maxRequests: 3, // Stricter control for sensitive endpoint
timeWindow: 60000, // 1 minute
banDuration: 600000 // 10 minutes ban
}
}
}
},
security: {
maxBodySize: 1024 * 100, // 100KB payload limit
allowedMethods: ['GET', 'POST', 'PUT', 'DELETE'],
userAgentBlacklist: ['bad-bot', 'malicious-crawler']
},
ddosProtection: {
enabled: true,
config: {
maxConnections: 50,
blockDuration: 300,
requestThreshold: 30,
rateLimitByPath: {
'/api/*': 20, // Special limit for API routes
'*': 50 // General limit for all routes
}
}
}
});
// Block a specific IP
shield.blockIP('192.168.1.100');
// Whitelist an IP
shield.whitelistIP('10.0.0.1');
// Unblock a previously blocked IP
shield.unblockIP('192.168.1.100');
// Remove an IP from whitelist
shield.unwhitelistIP('10.0.0.1');
// Custom patterns for SQL Injection and XSS
shield.addSuspiciousPattern(/SELECT.*FROM/i);
shield.addSuspiciousPattern(/<script>|javascript:/i);
const shield = new K9Shield({
errorHandling: {
includeErrorDetails: true,
customHandlers: {
// Custom response for rate limit exceeded
'rateLimitExceeded': (res, data) => {
res.status(429).json({
message: 'Too many requests',
retryAfter: data.retryAfter,
limit: data.limit
});
},
// Custom response for DDoS attack
'ddosAttack': (res) => {
res.status(403).json({
message: 'Suspicious traffic detected',
action: 'Access denied'
});
}
}
}
});
// Get all log records
const logs = shield.getLogs();
// Get archived log records
const archivedLogs = shield.getArchivedLogs();
// Reset all settings and statistics
shield.reset();
// More flexible settings for development environment
process.env.NODE_ENV = 'development';
const shield = new K9Shield({
rateLimiting: { enabled: false }, // Rate limit disabled in development
ddosProtection: { enabled: false } // DDoS protection disabled
});
// Strict security settings for production
process.env.NODE_ENV = 'production';
const shield = new K9Shield({
rateLimiting: {
enabled: true,
default: { maxRequests: 100, timeWindow: 60000 }
},
security: {
maxBodySize: 1024 * 1024, // 1MB
allowPrivateIPs: false
},
ddosProtection: {
enabled: true,
config: {
maxConnections: 200,
blockDuration: 1800000 // 30 minutes block
}
},
logging: {
level: 'warning', // Log only critical warnings
maxLogSize: 10000 // More log storage
}
});
The main class that orchestrates all security features:
const shield = new K9Shield({
security: {
trustProxy: true,
allowPrivateIPs: false,
maxBodySize: 1024 * 1024 // 1MB
}
});
Handles IP address management and validation:
// IP management examples
shield.blockIP('192.168.1.100');
shield.whitelistIP('10.0.0.1');
shield.unblockIP('192.168.1.100');
shield.unwhitelistIP('10.0.0.1');
Manages security patterns and request validation:
// Add custom security patterns
shield.addSuspiciousPattern(/eval\(/i);
shield.addSuspiciousPattern(/(document|window)\./i);
Controls request rates and implements throttling:
const config = {
rateLimiting: {
enabled: true,
default: {
maxRequests: 100,
timeWindow: 60000, // 1 minute
banDuration: 3600000 // 1 hour
},
routes: {
'/api/data': {
'POST': { maxRequests: 5, timeWindow: 30000 }
}
}
}
};
Provides DDoS attack prevention:
const config = {
ddosProtection: {
enabled: true,
config: {
maxConnections: 200,
timeWindow: 60000,
blockDuration: 1800000,
requestThreshold: 500,
burstThreshold: 50
}
}
};
const shield = new K9Shield({
security: {
trustProxy: true,
allowPrivateIPs: false,
maxBodySize: 1024 * 1024,
allowedMethods: ['GET', 'POST', 'PUT', 'DELETE'],
userAgentBlacklist: ['bad-bot', 'malicious-crawler'],
refererBlacklist: ['malicious.com'],
securityHeaders: {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
},
csp: {
'default-src': ["'self'"],
'script-src': ["'self'", "'unsafe-inline'"],
'style-src': ["'self'", "'unsafe-inline'"],
'img-src': ["'self'", 'data:', 'https:']
},
permissions: {
'geolocation': '()',
'camera': '()',
'microphone': '()'
}
},
rateLimiting: {
enabled: true,
default: {
maxRequests: 100,
timeWindow: 60000,
banDuration: 3600000,
throttleDuration: 60000,
throttleDelay: 1000
},
routes: {
'/api/data': {
'POST': { maxRequests: 5, timeWindow: 30000 }
}
}
},
ddosProtection: {
enabled: true,
config: {
maxConnections: 200,
timeWindow: 60000,
blockDuration: 1800000,
requestThreshold: 500,
burstThreshold: 50,
slowRequestThreshold: 10,
rateLimitByPath: {
'/api/*': 100,
'/auth/*': 20,
'*': 500
}
}
},
logging: {
enable: true,
level: 'info',
maxLogSize: 5000,
archiveLimit: 5
},
errorHandling: {
includeErrorDetails: true,
customHandlers: {
'rateLimitExceeded': (res, data) => {
res.status(429).json({
message: 'Too many requests',
retryAfter: data.retryAfter,
limit: data.limit,
windowMs: data.windowMs
});
}
}
},
bypassRoutes: ['/health', '/metrics']
});
- Global Limits: Set default limits for all routes
- Route-Specific Limits: Configure different limits for specific routes
- Throttling: Progressive slowdown of requests
- Ban System: Temporary IP bans for limit violations
- Connection Tracking: Monitor connection counts
- Burst Detection: Identify sudden request spikes
- Progressive Penalties: Increasing restrictions for violations
- Path-Based Limits: Different limits for different paths
- CSP: Content Security Policy configuration
- HSTS: HTTP Strict Transport Security
- XSS Protection: Cross-site scripting prevention
- Frame Options: Clickjacking prevention
- SQL Injection: Detect SQL injection attempts
- XSS: Cross-site scripting pattern detection
- Path Traversal: Directory traversal prevention
- Custom Patterns: Add your own detection patterns
// IP Management
shield.blockIP(ip)
shield.unblockIP(ip)
shield.whitelistIP(ip)
shield.unwhitelistIP(ip)
// Pattern Management
shield.addSuspiciousPattern(pattern)
// Configuration
shield.setConfig(config)
// Logging
shield.getLogs()
shield.getArchivedLogs()
// Reset
shield.reset()
Run the test server:
node test.js
- Basic Request Test
curl http://localhost:3000/
- Rate Limit Test
for i in $(seq 1 10); do
curl http://localhost:3000/api/test
echo ""
sleep 1
done
- SQL Injection Test
curl -X POST http://localhost:3000/search \
-H "Content-Type: application/json" \
-d '{"query": "1 UNION SELECT * FROM users"}'
- XSS Test
curl -X POST http://localhost:3000/comment \
-H "Content-Type: application/json" \
-d '{"comment": "<script>alert(\"XSS\")</script>"}'
- IP Information
curl http://localhost:3000/ip
- Bypass Routes Test
curl http://localhost:3000/health
curl http://localhost:3000/metrics
- DDoS Test
for i in $(seq 1 100); do
curl http://localhost:3000/ &
done
- Large Payload Test
curl -X POST http://localhost:3000/comment \
-H "Content-Type: application/json" \
-d '{"comment": "A...(100KB+)..."}'
K9Shield provides detailed error responses:
- 403: Access Denied / Suspicious Request
- 405: Method Not Allowed
- 413: Payload Too Large
- 429: Too Many Requests
- 500: Internal Server Error
Each error includes:
- Error message
- Error code
- Timestamp
- Additional details (when enabled)
-
Rate Limiting
- Set appropriate limits based on your application needs
- Use route-specific limits for sensitive endpoints
- Implement proper retry-after headers
-
DDoS Protection
- Configure thresholds based on your server capacity
- Monitor and adjust settings based on traffic patterns
- Use bypass routes for critical endpoints
-
Security Headers
- Implement strict CSP policies
- Enable HSTS in production
- Configure appropriate frame options
-
Logging
- Set appropriate log levels
- Implement log rotation
- Monitor security events regularly
We welcome contributions! Please follow these steps:
- Fork the repository
- Create your feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.