WiseGuard is a TCP server protected from DDoS attacks using the Proof of Work (PoW) mechanism. After successfully solving the PoW challenge, the server sends a random quote to the client.
- TCP server with DDoS protection
- Proof of Work protocol implementation (based on SHA-256)
- Dynamic PoW difficulty adjustment based on server load
- Graceful shutdown
- Configurable timeouts and connection limits
- Efficient error handling and logging
- Docker containerization
- Built-in load testing tool
The PoW algorithm uses HashCash based on SHA-256. Clients must find a nonce where the hash of the concatenation prefix + nonce begins with a specified number of zero bits.
- Simple implementation
- Efficient server-side verification
- Scalable difficulty
- Cryptographic strength of SHA-256
- Dynamic Difficulty: Server automatically adjusts PoW difficulty based on current load
- Timeouts: All operations have configurable timeouts
- Connection Limiting: Configurable limit on simultaneous connections
- Solution Validation: Strict verification of all PoW solutions
WiseGuard implements multiple layers of protection against various types of attacks:
- IP-based rate limiting using token bucket algorithm
- Configurable requests per second limits
- Automatic temporary IP blocking after exceeding limits
PROTECTION_TOKEN_BUCKET_SIZE=100 # Maximum burst size
PROTECTION_TOKEN_FILL_RATE=10 # Tokens per second- Limits concurrent connections per IP
- Protection against connection flooding
SERVER_MAX_CONNECTIONS=1000
SERVER_READ_TIMEOUT=5s
SERVER_WRITE_TIMEOUT=5s- Tracks and limits failed authentication attempts
- Temporary IP blocking after multiple failures
PROTECTION_MAX_FAILED_ATTEMPTS=5
PROTECTION_FAILED_BLOCK_TIME=15m- Defends against Slowloris-type attacks
- Enforces minimum data transfer rates
PROTECTION_MIN_READ_RATE=100 # bytes per second
PROTECTION_READ_TIMEOUT=10s- Monitors and manages memory usage
- Prevents memory exhaustion attacks
PROTECTION_MEMORY_THRESHOLD=80 # percentage
PROTECTION_MEMORY_CHECK_INTERVAL=1mWiseGuard includes a protection testing tool that simulates various attacks:
- Invalid PoW Attack: Tests PoW verification
- Connection Limit Attack: Tests connection management
- Failed Attempts Attack: Tests brute force protection
- Slowloris Attack: Tests slow connection protection
# Run all protection tests
make run-protection
# Run specific attack test
./bin/protection -attack [attack_type] -clients [num] -duration [time]
# Example
./bin/protection -attack invalid_pow -clients 50 -duration 10sThe testing tool provides metrics including:
- Blocked/Failed/Successful request counts
- Requests per second (RPS)
- Success rate percentage
A successful test should show 0% success rate for attack attempts, indicating that protection mechanisms are working correctly.
- Go 1.22 or higher
- Docker and Docker Compose (for containerized deployment)
- Make (for using Makefile)
- Clone the repository:
git clone [email protected]:aturan23/WiseGuard.git
cd WiseGuard- Build the project:
make build- Run the server:
make run-server- In another terminal, run the client:
make run-client- Build Docker images:
make docker-build- Run containers:
make docker-runWiseGuard includes a tool for load testing and DDoS attack simulation.
# Standard test (100 clients, 30 seconds)
make run-ddos
# Heavy test (1000 clients, 60 seconds)
make run-ddos-heavy
# Custom test
./bin/ddos -clients 500 -duration 45s -server localhost:8080Total Requests: ~1000
Successful Requests: ~800
Success Rate: ~85%
Average Latency: ~2.6s
Average RPS: ~32
Total Requests: ~3750
Successful Requests: ~800
Success Rate: ~22%
Average Latency: ~3.8s
Average RPS: ~63
The system demonstrates effective DDoS protection:
-
Under Normal Load:
- High success rate (~85%)
- Lower latency (~2.6s)
- Stable RPS
- Most legitimate requests are processed
-
Under Heavy Load (DDoS Simulation):
- Lower success rate (~22%) - intentionally rejecting excess traffic
- Slightly increased latency (~3.8s)
- Maintained stable service for legitimate requests
- Successfully prevented system overload
This behavior shows that the PoW mechanism effectively:
- Throttles excessive traffic
- Maintains service for legitimate users
- Scales resource usage under load
- Prevents server overload
During heavy load:
-
Dynamic PoW Difficulty
- Automatically increases with load
- Makes attack more computationally expensive
-
Connection Management
- Limits concurrent connections
- Enforces timeouts
- Prevents resource exhaustion
-
Resource Protection
- Memory usage remains stable
- CPU load is distributed to clients
- Network bandwidth is preserved
Good performance indicators vary by scenario:
Normal Operation:
- Success Rate > 80%
- Latency < 3s
- Stable RPS
Under Attack:
- Success Rate: 20-30% is optimal
- Latency increase < 50%
- Consistent successful request count
make build- Build the projectmake test- Run all tests with coveragemake test-unit- Run unit tests onlymake test-integration- Run integration testsmake clean- Clean build artifactsmake fmt- Format codemake lint- Run lintermake bench- Run benchmarksmake race- Check for race conditionsmake run-server- Run server locallymake run-client- Run client locallymake docker-build- Build Docker imagesmake docker-run- Run Docker containersmake docker-stop- Stop Docker containersmake run-ddos- Run DDoS simulationmake run-ddos-heavy- Run heavy DDoS simulation
.
├── cmd/
│ ├── client/ # Client entry point
│ └── server/ # Server entry point
├── pkg/
│ ├── client/ # Client logic
│ ├── config/ # Configuration
│ ├── logger/ # Logging
│ ├── pow/ # Proof of Work implementation
│ ├── protocol/ # Network protocol
│ ├── quotes/ # Quotes service
│ ├── server/ # Server logic
│ └── utils/ # Helper functions
├── integration/ # Integration tests
├── configs/ # Configuration files
├── Dockerfile.client # Client Dockerfile
├── Dockerfile.server # Server Dockerfile
├── docker-compose.yml # Docker Compose config
└── Makefile # Make commands
Application configuration through environment variables or yaml files:
# Server settings
SERVER_ADDRESS=:8080
SERVER_READ_TIMEOUT=5s
SERVER_WRITE_TIMEOUT=5s
SERVER_SHUTDOWN_TIMEOUT=10s
SERVER_MAX_CONNECTIONS=1000
# Logging
LOG_LEVEL=debug
LOG_PRETTY=true
LOG_JSON=false
# PoW settings
POW_INITIAL_DIFFICULTY=4
POW_MAX_DIFFICULTY=8
POW_CHALLENGE_TTL=5m
POW_ADJUST_INTERVAL=10s# Client settings
CLIENT_SERVER_ADDRESS=localhost:8080
CLIENT_CONNECT_TIMEOUT=5s
CLIENT_READ_TIMEOUT=5s
CLIENT_WRITE_TIMEOUT=5s
CLIENT_MAX_ATTEMPTS=3
CLIENT_RETRY_DELAY=1s
CLIENT_MAX_RETRY_DELAY=30s
# Logging
LOG_LEVEL=debug
LOG_PRETTY=true
LOG_JSON=falseThe message exchange protocol between client and server:
- Client connects to server
- Server sends PoW challenge (prefix, difficulty, nonce)
- Client solves challenge and sends solution
- Server verifies solution:
- If successful, sends quote
- If failed, sends error
Each message has a header (8 bytes):
- Version (1 byte)
- Type (1 byte)
- Flags (2 bytes)
- Length (4 bytes)
The header is followed by a JSON payload.
TypeChallenge (1): Server sends PoW challengeTypeSolution (2): Client sends solutionTypeQuote (3): Server sends quoteTypeError (4): Error message
{
"prefix": "abc123",
"difficulty": 4,
"nonce": "xyz789",
"expires_at": "2024-01-01T12:00:00Z"
}{
"prefix": "abc123",
"solution": "def456",
"nonce": "xyz789"
}{
"text": "The journey of a thousand miles begins with one step.",
"author": "Lao Tzu"
}The project is covered by unit tests and integration tests. To run:
# All tests
make test
# Unit tests only
make test-unit
# Integration tests only
make test-integration
# Generate coverage report
make test-coverage- Protocol implementation
- PoW logic
- Client/Server interaction
- Configuration handling
- Error scenarios
- Load testing
The application uses structured logging via zerolog. Log levels are configurable:
LOG_LEVEL- Logging level (debug, info, warn, error)LOG_PRETTY- Human-readable log formatLOG_JSON- JSON log format
{
"level": "info",
"timestamp": "2024-11-08T12:00:00Z",
"component": "server",
"message": "client connected",
"remote_addr": "127.0.0.1:12345"
}-
DoS Protection
- PoW-based challenge-response
- Connection limits
- Timeouts
- Memory usage controls
-
Resource Management
- Connection pooling
- Garbage collection
- Buffer size limits
-
Error Handling
- Graceful degradation
- Proper error reporting
- Secure error messages