-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathWHITEPAPER
More file actions
1647 lines (1381 loc) · 54.4 KB
/
Copy pathWHITEPAPER
File metadata and controls
1647 lines (1381 loc) · 54.4 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
```
Ᾰenebris: Next Gen Reverse Proxy
Technical White Paper & Development Roadmap
Version: 0.1.0
Date: 2025-11-12 - Project Name: Ᾰenebris
---
Abstract
Ᾰenebris is a production grade, security first reverse proxy built in Haskell
that aims to surpass nginx in performance, security, and developer
experience. By leveraging Haskell's type system, STM concurrency, and the
fast Warp web server, combined with ML based threat detection and
intelligent routing, Ᾰenebris provides a modern alternative to traditional
reverse proxies with native support for WebSockets, HTTP/3, streaming, and
advanced DDoS mitigation.
Key Innovation: While nginx requires complex configuration and external
modules for advanced features, Ᾰenebris provides security, intelligence, and
modern protocol support out of the box with a clean, type-safe
architecture.
---
Table of Contents
1. #problem-statement
2. #architecture-overview
3. #technical-specifications
4. #development-phases
5. #core-components
6. #security-model
7. #performance-targets
8. #deployment-strategy
9. #long-term-roadmap
10. #competitive-analysis
---
1. Problem Statement
Current State of Reverse Proxies
Nginx:
- Complex configuration syntax
- Requires external modules for WAF, bot detection
- WebSocket + streaming conflicts require manual tuning
- No native ML capabilities
- C codebase = memory safety concerns
- Difficult to extend without C knowledge
Traefik:
- Resource heavy (Go runtime overhead)
- Limited security features
- Configuration complexity at scale
Cloudflare:
- External dependency
- Privacy concerns (traffic routed through CF)
- Cost at scale
- No on-premise option for sensitive workloads
What Ᾰenebris Solves
1. Native streaming + WebSocket support - No configuration conflicts
2. Built in ML threat detection - No external services needed
3. Type safe configuration - Catch errors at compile time
4. Security first design - WAF, honeypots, and DDoS protection included
5. Production ready performance - Warp powers major Haskell web frameworks
6. Developer friendly - Clean config, hot reload, excellent error messages
7. Open source & self-hosted - Full control, no vendor lock in
---
2. Architecture Overview
High Level Design
┌─────────────────────────────────────────────────────────────┐
│ Ᾰenebris CORE │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Ingress │ │ Analysis │ │ Routing │ │
│ │ Manager │─▶│ Engine │─▶│ Engine │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Connection Manager │ │
│ │ (STM-based state management) │ │
│ └──────────────────────────────────────────────────┘ │
│ │ │
└───────────────────────────┼───────────────────────────────┘
│
┌───────────────────┼───────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Backend │ │ Backend │ │ Honeypot │
│ Server 1 │ │ Server 2 │ │ Server │
└──────────────┘ └──────────────┘ └──────────────┘
Component Interaction Flow
Client Request
│
▼
┌─────────────────────┐
│ TLS Termination │ (Native Haskell TLS)
└─────────────────────┘
│
▼
┌─────────────────────┐
│ Protocol Handler │ (HTTP/1.1, HTTP/2, HTTP/3, WebSocket)
└─────────────────────┘
│
▼
┌─────────────────────┐
│ Rate Limiter │ (Multi-strategy: Token Bucket, Adaptive, ML-based)
└─────────────────────┘
│
▼
┌─────────────────────┐
│ WAF Scanner │ (SQLi, XSS, Path Traversal detection)
└─────────────────────┘
│
▼
┌─────────────────────┐
│ ML Bot Detector │ (Behavioral analysis, request fingerprinting)
└─────────────────────┘
│
├─[Suspicious]──▶ Honeypot
│
▼
┌─────────────────────┐
│ Intelligent Router │ (Load balancing, health checks, A/B testing)
└─────────────────────┘
│
▼
┌─────────────────────┐
│ Backend Proxy │ (Zero-copy streaming, connection pooling)
└─────────────────────┘
│
▼
Response to Client
---
3. Technical Specifications
Language & Core Libraries
Primary Language: Haskell (GHC 9.6+)
Core Dependencies:
- warp (v3.3+) - HTTP server (handles 100k+ req/s)
- wai - Web Application Interface
- http-conduit - HTTP client for proxying
- stm - Software Transactional Memory
- websockets - WebSocket protocol
- tls - TLS 1.2/1.3 support
- http2 - HTTP/2 implementation
- quic - HTTP/3 (QUIC) support
- yaml / dhall - Configuration parsing
- aeson - JSON handling
- fast-logger - High performance logging
- prometheus-client - Metrics export
ML Component:
- hmatrix - Linear algebra in Haskell
- Models: Isolation Forest, Random Forest, LSTM for sequence analysis
External Integrations:
- Redis (caching, distributed rate limiting)
- PostgreSQL/SQLite (metrics, request logs)
- Prometheus/Grafana (observability)
- Let's Encrypt (ACME client for SSL)
System Requirements
Development:
- Linux/macOS/WSL
- GHC 9.6+
- Stack or Cabal
- 4GB RAM minimum
Production:
- Linux (primary target)
- 2+ CPU cores (multi-core scaling)
- 1GB RAM minimum (scales with traffic)
- Docker & Kubernetes support
---
4. Development Phases
Phase 0: Foundation (Week 0 - Setup)
Duration: 2-3 daysGoal: Project scaffolding
Tasks:
- Set up Haskell dev environment (Stack)
- Study Warp/WAI documentation
- Create project structure
- Set up Git repo + CI/CD (GitHub Actions)
- Design config file schema (YAML)
---
Phase 1: Core Proxy (Weeks 1-2)
Duration: 2 weeksGoal: Functional reverse proxy that can replace nginx in
dev
Milestone 1.1: Basic HTTP Proxying (Days 1-3)
- Parse incoming HTTP requests
- Forward to backend server
- Stream response back to client
- Handle connection errors gracefully
- Basic logging (stdout)
Milestone 1.2: Configuration System (Days 4-5)
- YAML config parsing
- Define upstream backends
- Host-based routing (virtual hosts)
- Path-based routing
- Config validation with type safety
Example config:
version: 1
listen:
- port: 80
- port: 443
tls:
cert: /path/to/cert.pem
key: /path/to/key.pem
upstreams:
- name: api-backend
servers:
- host: 127.0.0.1:8000
weight: 1
- host: 127.0.0.1:8001
weight: 1
health_check:
path: /health
interval: 10s
routes:
- host: api.example.com
paths:
- path: /
upstream: api-backend
rate_limit: 100/minute
Milestone 1.3: Load Balancing (Days 6-7)
- Round-robin algorithm
- Least connections algorithm
- Weighted distribution
- Health check system (active probing)
- Automatic backend removal on failure
Milestone 1.4: TLS/SSL Support (Days 8-10)
- TLS termination (Haskell tls library)
- SNI (Server Name Indication) support
- Cipher suite configuration
- TLS 1.2 & 1.3 support
- Automatic redirect HTTP → HTTPS
Milestone 1.5: WebSocket Support (Days 11-12)
- WebSocket handshake detection
- Upgrade HTTP connection to WebSocket
- Bidirectional streaming
- Backend WebSocket proxying
- Connection timeout handling
Milestone 1.6: Streaming Support (Days 13-14)
- Chunked transfer encoding
- SSE (Server-Sent Events) support
- No buffering for streaming responses
- CRITICAL: Test WebSocket + streaming simultaneously (your nginx issue)
- Verify AI model streaming works
Phase 1 Deliverable:
- Compiled binary (Ᾰenebris)
- Basic config file
- Can replace nginx for simple use cases
- Handles your website's traffic
- Test deployment to your projects
---
Phase 2: Security & Intelligence (Weeks 3-6)
Duration: 4 weeksGoal: Advanced security features that surpass nginx
Milestone 2.1: Rate Limiting (Week 3)
- Token bucket algorithm (classic)
- Leaky bucket algorithm
- Sliding window counters
- Fixed window counters
- Per-IP rate limiting
- Per-user rate limiting (auth token tracking)
- Per-endpoint rate limiting
- Adaptive rate limiting (based on server load)
- Geographic rate limiting
- Time-of-day adjustments
- Redis backend for distributed limiting
- Custom rate limit responses (429 with Retry-After)
Advanced Rate Limiting Strategies:
data RateLimitStrategy
= TokenBucket { capacity :: Int, refillRate :: Int }
| LeakyBucket { capacity :: Int, leakRate :: Int }
| SlidingWindow { windowSize :: Int, limit :: Int }
| Adaptive { baseRate :: Int, loadFactor :: Float }
| Behavioral { mlModel :: ModelHandle, threshold :: Float }
| ProofOfWork { difficulty :: Int }
Milestone 2.2: WAF (Web Application Firewall) (Week 4)
- SQL injection detection (regex + ML)
- XSS detection (script tag patterns, event handlers)
- Path traversal detection (../, %2e%2e%2f)
- Command injection detection
- SSRF (Server-Side Request Forgery) prevention
- CSRF token validation
- Header injection detection
- Multipart form bomb protection
- JSON/XML bomb protection
- Custom WAF rules (user-defined patterns)
- Rule bypass detection (encoding tricks)
Detection Engine:
data ThreatLevel = Low | Medium | High | Critical
data AttackSignature = AttackSignature
{ pattern :: Regex
, threatLevel :: ThreatLevel
, action :: Action -- Block | Log | Honeypot
, description :: Text
}
-- Example signatures
sqlInjectionSignatures :: [AttackSignature]
xssSignatures :: [AttackSignature]
pathTraversalSignatures :: [AttackSignature]
Milestone 2.3: ML-Based Bot Detection (Week 5)
- Request feature extraction (headers, timing, patterns)
- Training data collection system
- Isolation Forest for anomaly detection
- Random Forest classifier (bot vs human)
- LSTM for behavioral sequences
- Browser fingerprinting
- TLS fingerprinting (JA3 hash)
- Mouse movement analysis (if JavaScript SDK added later)
- Request entropy analysis
- Reputation scoring system
Features for ML Model:
features = [
'request_rate', # req/sec
'user_agent_entropy', # Shannon entropy
'header_count', # number of headers
'header_order_anomaly', # unusual ordering
'tls_ja3_hash', # TLS fingerprint
'request_method_dist', # GET/POST ratio
'path_entropy', # randomness in URLs
'referer_consistency', # legit navigation
'cookie_presence', # has cookies
'timing_variance', # human-like delays
]
Model Training Pipeline:
- Collect legitimate traffic (labeled "human")
- Collect bot traffic from honeypots (labeled "bot")
- Train ensemble model (Random Forest + Isolation Forest)
- Export to ONNX or pickle
- Load in Haskell via FFI or HTTP API
Milestone 2.4: DDoS Protection (Week 6)
- SYN flood protection (SYN cookies)
- Connection limiting (max concurrent per IP)
- Bandwidth throttling
- Slowloris protection (timeout slow requests)
- HTTP flood detection (abnormal request rates)
- Geographic blocking (block entire countries)
- IP reputation integration (AbuseIPDB, IPQualityScore)
- Challenge-response (CAPTCHA, proof-of-work)
- Automatic IP blacklisting (temporary bans)
- BGP-level mitigation (future: integrate with upstream)
Milestone 2.5: Honeypot System (Week 6)
- Fake backend deployment
- Route suspicious traffic to honeypot
- Log attacker behavior
- Infinite response generation (tarpit)
- Fake vulnerabilities (lure attackers)
- Collect attack signatures for ML training
- Integration with threat intel feeds
Phase 2 Deliverable:
- Security-hardened proxy
- ML model deployment
- Honeypot infrastructure
- WAF rule engine
- Production-ready security features
---
Phase 3: Performance & Scale (Weeks 7-10)
Duration: 4 weeksGoal: Optimize for production scale & performance
Milestone 3.1: HTTP/2 Support (Week 7)
- HTTP/2 protocol implementation
- Server push capability
- Stream multiplexing
- Header compression (HPACK)
- Priority scheduling
Milestone 3.2: HTTP/3 (QUIC) Support (Week 8)
- QUIC protocol integration
- UDP-based transport
- 0-RTT connection establishment
- Built-in encryption
- Loss recovery
Milestone 3.3: Zero-Copy Optimizations (Week 9)
- Splice syscall for direct kernel transfer
- Sendfile for static assets
- Memory-mapped I/O
- Buffer pooling
- Lazy ByteString optimization
Milestone 3.4: Caching Layer (Week 9)
- In-memory LRU cache
- Redis integration for distributed caching
- Cache invalidation strategies
- Conditional requests (ETag, If-Modified-Since)
- Vary header support
- Cache key customization
Milestone 3.5: Multi-Core Scaling (Week 10)
- Multi-threaded request handling
- CPU affinity tuning
- Work-stealing scheduler
- Non-blocking I/O everywhere
- Benchmark on 16+ core machine
Milestone 3.6: Connection Pooling (Week 10)
- Backend connection reuse
- Idle connection cleanup
- Connection health tracking
- Configurable pool size
- Per-backend pools
Performance Targets:
- Latency: <1ms added latency (p99)
- Throughput: 100k+ req/s on 4-core machine
- Memory: <500MB for typical workload
- CPU: <20% overhead vs direct connection
Phase 3 Deliverable:
- Production-ready performance
- HTTP/2 & HTTP/3 support
- Caching infrastructure
- Benchmark results vs nginx
---
Phase 4: Operations & Observability (Weeks 11-12)
Duration: 2 weeksGoal: Production operations tooling
Milestone 4.1: Logging & Metrics (Week 11)
- Structured JSON logging
- Log levels (debug, info, warn, error)
- Access logs (Apache/nginx format compatible)
- Error logs
- Prometheus metrics endpoint
- Custom metrics (request duration, backend health, etc.)
- Grafana dashboard templates
- OpenTelemetry integration (traces)
Key Metrics:
Ᾰenebris_requests_total{method, status, route}
Ᾰenebris_request_duration_seconds{method, route}
Ᾰenebris_backend_health{backend}
Ᾰenebris_active_connections{backend}
Ᾰenebris_rate_limit_hits{limiter}
Ᾰenebris_waf_blocks{attack_type}
Ᾰenebris_bot_detections{confidence}
Milestone 4.2: Hot Reload (Week 11)
- Watch config file for changes
- Parse & validate new config
- Swap config atomically (no dropped requests)
- Graceful backend rotation
- Zero-downtime deployments
Milestone 4.3: Admin API (Week 12)
- RESTful admin interface
- View current config
- View live metrics
- Manual IP ban/unban
- Drain backend (stop routing, wait for connections to finish)
- Runtime config updates
Milestone 4.4: Let's Encrypt Integration (Week 12)
- ACME protocol client
- Automatic cert provisioning
- Cert renewal (30 days before expiry)
- Multi-domain support (SAN certificates)
- HTTP-01 challenge handling
- DNS-01 challenge (optional, for wildcard certs)
Phase 4 Deliverable:
- Full observability stack
- Hot reload capability
- Admin API
- Automatic SSL
---
Phase 5: Deployment & Distribution (Weeks 13-14)
Duration: 2 weeksGoal: Make it easy to install & deploy
Milestone 5.1: Packaging (Week 13)
- Compile static binary (musl libc)
- Debian package (.deb)
- RPM package (.rpm)
- Homebrew formula (macOS)
- AUR package (Arch Linux)
- Nix package
- Binary releases on GitHub
Milestone 5.2: Docker Support (Week 13)
- Multi-stage Dockerfile
- Alpine-based image (<50MB)
- Docker Compose example
- Health check endpoint
- Graceful shutdown (SIGTERM handling)
- Non-root user in container
Milestone 5.3: Kubernetes Support (Week 14)
- Helm chart
- Kubernetes manifests (Deployment, Service, Ingress)
- ConfigMap for config
- Secret management
- Horizontal Pod Autoscaler
- Liveness & readiness probes
- Example ingress controller usage
Milestone 5.4: Documentation (Week 14)
- README with quickstart
- Configuration reference
- Architecture documentation
- Performance tuning guide
- Security best practices
- Migration guide from nginx
- API documentation
- Contribution guidelines
Milestone 5.5: Testing & CI/CD (Week 14)
- Unit tests (HSpec)
- Integration tests
- Performance benchmarks (criterion)
- Load testing (hey, wrk)
- GitHub Actions CI
- Automated releases
- Docker image builds
Phase 5 Deliverable:
- Installable packages for major distros
- Docker & Kubernetes support
- Complete documentation
- Automated testing & releases
---
5. Core Components
5.1 Ingress Manager
Responsibility: Accept incoming connections, TLS termination, protocol
detection
Implementation:
data IngressConfig = IngressConfig
{ listenPorts :: [Port]
, tlsConfig :: Maybe TLSConfig
, maxConnections :: Int
, connectionTimeout :: NominalDiffTime
}
ingressManager :: IngressConfig -> IO ()
ingressManager config = do
runSettings (warpSettings config) $ \req respond -> do
-- Protocol detection
protocol <- detectProtocol req
case protocol of
HTTP -> handleHTTP req respond
WebSocket -> handleWebSocket req respond
HTTP2 -> handleHTTP2 req respond
HTTP3 -> handleHTTP3 req respond
Key Features:
- Multi-port listening (80, 443, custom)
- SNI support for multi-domain TLS
- Connection limiting
- Protocol detection (HTTP/1.1, HTTP/2, HTTP/3, WebSocket)
---
5.2 Analysis Engine
Responsibility: Security scanning, bot detection, WAF
Implementation:
data AnalysisResult
= Clean
| Suspicious ThreatLevel [ThreatIndicator]
| Malicious AttackType
data ThreatIndicator
= SQLInjection Pattern
| XSSAttempt Pattern
| BotBehavior Float -- confidence score
| RateLimitExceeded
| IPReputationLow
analyzeRequest :: Request -> IO AnalysisResult
analyzeRequest req = do
wafResult <- runWAFChecks req
botScore <- mlBotDetector req
rateLimit <- checkRateLimit req
reputation <- checkIPReputation (remoteHost req)
return $ aggregateResults [wafResult, botScore, rateLimit, reputation]
Security Layers:
1. WAF Scanner - Regex + pattern matching
2. ML Bot Detector - Behavioral analysis
3. Rate Limiter - Multiple strategies
4. IP Reputation - External threat feeds
---
5.3 Routing Engine
Responsibility: Intelligent request routing, load balancing, A/B testing
Implementation:
data Route = Route
{ matcher :: RequestMatcher
, upstream :: Upstream
, middleware :: [Middleware]
}
data RequestMatcher
= HostMatch Hostname
| PathMatch PathPattern
| HeaderMatch HeaderName HeaderValue
| Composite [RequestMatcher]
data Upstream = Upstream
{ backends :: [Backend]
, balancer :: LoadBalancer
, healthCheck :: HealthCheckConfig
}
data LoadBalancer
= RoundRobin
| LeastConnections
| Weighted [(Backend, Int)]
| IPHash
| LatencyBased
Routing Strategies:
- Host-based (virtual hosts)
- Path-based (URL routing)
- Header-based (A/B testing, canary)
- Geographic routing
- Latency-based routing
---
5.4 Connection Manager
Responsibility: Backend connection pooling, health tracking
Implementation:
data ConnectionPool = ConnectionPool
{ available :: TVar [Connection]
, inUse :: TVar (Set Connection)
, maxSize :: Int
, backend :: Backend
}
acquireConnection :: ConnectionPool -> IO Connection
acquireConnection pool = atomically $ do
avail <- readTVar (available pool)
case avail of
(conn:rest) -> do
writeTVar (available pool) rest
modifyTVar' (inUse pool) (Set.insert conn)
return conn
[] -> retry -- STM will block until connection available
releaseConnection :: ConnectionPool -> Connection -> IO ()
releaseConnection pool conn = atomically $ do
modifyTVar' (inUse pool) (Set.delete conn)
modifyTVar' (available pool) (conn:)
Features:
- Per-backend connection pools
- Automatic connection recycling
- Health-based connection invalidation
- Configurable pool size
---
5.5 ML Bot Detection System
Architecture:
┌─────────────────────────────────────────────────────┐
│ Ᾰenebris Proxy │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Feature Extractor (Haskell) │ │
│ │ - Parse request headers │ │
│ │ - Calculate entropy, timing, patterns │ │
│ │ - Extract TLS fingerprint │ │
│ └──────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────┐ │
│ │ ML Model Inference (Python Service) │ │
│ │ - Load trained model (pickle/ONNX) │ │
│ │ - Predict: bot probability │ │
│ │ - Return confidence score │ │
│ └──────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Decision Engine (Haskell) │ │
│ │ - If score > 0.8 → Honeypot │ │
│ │ - If score > 0.5 → Rate limit │ │
│ │ - If score < 0.5 → Allow │ │
│ └──────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
Training Pipeline:
1. Data Collection:
- Legitimate traffic: Your production logs
- Bot traffic: Honeypot captures, public datasets
2. Feature Engineering:
def extract_features(request):
return {
'request_rate': calculate_rate(request.ip),
'ua_entropy': shannon_entropy(request.user_agent),
'header_count': len(request.headers),
'tls_fingerprint': ja3_hash(request.tls_info),
'timing_variance': np.std(request.timings),
# ... 20+ features
}
3. Model Training:
from sklearn.ensemble import RandomForestClassifier, IsolationForest
# Supervised: Random Forest
rf = RandomForestClassifier(n_estimators=100)
rf.fit(X_train, y_train)
# Unsupervised: Isolation Forest (anomaly detection)
iso = IsolationForest(contamination=0.1)
iso.fit(X_legitimate)
# Ensemble
def predict(features):
rf_score = rf.predict_proba(features)[1]
iso_score = iso.decision_function(features)
return 0.7 * rf_score + 0.3 * normalize(iso_score)
4. Deployment:
- Export model to ONNX
- Load in Python microservice (FastAPI)
- Haskell calls via HTTP (POST /predict)
- Cache predictions (1 min TTL per IP)
Continuous Learning:
- Feedback loop: Honeypot captures → retrain model
- Weekly model updates
- A/B test new models before deployment
---
6. Security Model
6.1 Threat Model
Attackers We Defend Against:
1. Script kiddies - Automated scanners, known exploits
2. Bot operators - Credential stuffing, scraping, spam
3. DDoS attackers - Volumetric attacks, application-layer floods
4. Sophisticated attackers - 0-day exploits, APTs (defense-in-depth)
Assets We Protect:
- Backend services (API, web apps)
- User data (prevent exfiltration)
- System availability (uptime)
- Infrastructure costs (prevent resource exhaustion)
6.2 Security Principles
1. Defense in Depth: Multiple layers (WAF → ML → Rate Limiting)
2. Fail Secure: Errors block traffic, not allow it
3. Least Privilege: Proxy runs as non-root user
4. Audit Everything: All security events logged
5. Type Safety: Haskell prevents memory corruption, buffer overflows
6.3 WAF Rule Engine
Rule Format:
waf_rules:
- name: sql-injection-basic
pattern: "(?i)(union|select|insert|update|delete|drop|create|alter)\\s"
threat_level: high
action: block
- name: xss-script-tag
pattern: "<script[^>]*>.*?</script>"
threat_level: high
action: block
- name: path-traversal
pattern: "\\.\\./|%2e%2e%2f"
threat_level: medium
action: log_and_block
Custom Rules:
Users can add their own regex patterns via config.
6.4 IP Reputation System
Data Sources:
- AbuseIPDB API
- IPQualityScore API
- Spamhaus DROP list
- Local blacklist/whitelist
Scoring System:
data ReputationScore = ReputationScore
{ score :: Float -- 0.0 (bad) to 1.0 (good)
, sources :: [ReputationSource]
, lastUpdated :: UTCTime
}
calculateReputation :: IP -> IO ReputationScore
calculateReputation ip = do
abuseScore <- queryAbuseIPDB ip
qualityScore <- queryIPQuality ip
spamhausListed <- checkSpamhaus ip
localScore <- checkLocalLists ip
return $ aggregateScores [abuseScore, qualityScore, spamhausListed,
localScore]
Actions Based on Score:
- Score < 0.3: Block immediately
- Score 0.3-0.6: Rate limit aggressively
- Score 0.6-0.8: Normal rate limits
- Score > 0.8: Trusted, higher limits
---
7. Performance Targets
7.1 Benchmarks
Target Performance (4-core machine, 16GB RAM):
| Metric | Target | Stretch Goal |
|---------------|-------------------|--------------|
| Requests/sec | 100,000 | 200,000 |
| Latency (p50) | <0.5ms | <0.3ms |
| Latency (p99) | <2ms | <1ms |
| Memory usage | <500MB | <300MB |
| CPU overhead | <20% | <10% |
| Connections | 10,000 concurrent | 50,000 |
Comparison to Nginx:
- Match or exceed nginx performance on similar hardware
- Lower latency for WebSocket/streaming workloads
- Comparable or better throughput for HTTP/2
7.2 Optimization Techniques
Haskell-Specific:
- Strictness annotations to avoid space leaks
- Unboxed types for performance-critical paths
- INLINE pragmas for hot functions
- Compiled with -O2 optimization
- Profile-guided optimization (PGO)
System-Level:
- Zero-copy via splice() syscall
- SO_REUSEPORT for multi-core scaling
- TCP_NODELAY for low latency
- Large buffer sizes for throughput
- Kernel bypass (io_uring) for extreme performance (future)
Application-Level:
- Connection pooling (reuse backend connections)
- HTTP keep-alive
- Request pipelining
- Lazy evaluation for streaming
- STM for lock-free concurrency
7.3 Benchmark Suite
Tools:
- wrk - HTTP benchmarking
- h2load - HTTP/2 benchmarking
- hey - Load testing
- criterion - Haskell microbenchmarks
Test Scenarios:
1. Static file serving (1KB, 10KB, 100KB)
2. Simple proxy (echo server backend)
3. WebSocket throughput
4. Streaming response (chunked transfer)
5. TLS handshake performance
6. HTTP/2 multiplexing
7. Rate limiting overhead
8. WAF scanning overhead
Continuous Benchmarking:
- Run benchmarks on every commit (GitHub Actions)
- Track performance regression
- Publish results publicly
---
8. Deployment Strategy
8.1 Installation Methods
Binary Installation:
# Linux (curl)
curl -sSL https://get.Ᾰenebris.sh | sh
# Homebrew (macOS/Linux)
brew install Ᾰenebris
# Debian/Ubuntu
sudo apt install Ᾰenebris
# Arch Linux
yay -S Ᾰenebris
From Source:
git clone https://github.com/username/Ᾰenebris
cd Ᾰenebris
stack build
stack install
Docker:
docker pull Ᾰenebris/Ᾰenebris:latest
docker run -p 80:80 -p 443:443 -v ./config.yaml:/etc/Ᾰenebris/config.yaml
Ᾰenebris/Ᾰenebris
Kubernetes:
helm repo add Ᾰenebris https://charts.Ᾰenebris.sh
helm install my-proxy Ᾰenebris/Ᾰenebris
8.2 Configuration Example
Minimal Config:
version: 1
listen:
- port: 80
- port: 443
tls:
auto: true # Let's Encrypt
upstreams:
- name: my-app
servers:
- host: localhost:8000
routes:
- host: example.com
upstream: my-app
Advanced Config:
version: 1
global:
worker_threads: 4
max_connections: 10000
log_level: info
listen:
- port: 80
- port: 443
tls:
auto: true
email: admin@example.com
upstreams: