{"id":30271759,"url":"https://github.com/anipaleja/nginx-defender","last_synced_at":"2025-08-16T05:03:07.754Z","repository":{"id":297642339,"uuid":"997456254","full_name":"Anipaleja/nginx-defender","owner":"Anipaleja","description":"A lightweight, real-time log monitoring tool designed to detect and block IP addresses exhibiting abusive behavior such as brute force attacks, excessive requests, or suspicious patterns. Automatically integrates with your server’s firewall (iptables or ufw) to block offenders and protect web services without relying on external services.","archived":false,"fork":false,"pushed_at":"2025-08-15T14:52:59.000Z","size":13683,"stargazers_count":40,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-15T16:31:23.442Z","etag":null,"topics":["docker","go","ip-blocking","iptables","nginx","ufw"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Anipaleja.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY_ADVISORY_TEMPLATE.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-06T14:56:53.000Z","updated_at":"2025-08-15T14:53:01.000Z","dependencies_parsed_at":"2025-06-06T15:45:50.822Z","dependency_job_id":"7e70a5e9-4071-4e7e-8fac-abff75b86525","html_url":"https://github.com/Anipaleja/nginx-defender","commit_stats":null,"previous_names":["anipaleja/nginx-defender"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/Anipaleja/nginx-defender","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Anipaleja%2Fnginx-defender","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Anipaleja%2Fnginx-defender/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Anipaleja%2Fnginx-defender/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Anipaleja%2Fnginx-defender/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Anipaleja","download_url":"https://codeload.github.com/Anipaleja/nginx-defender/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Anipaleja%2Fnginx-defender/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270643196,"owners_count":24621327,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-15T02:00:12.559Z","response_time":110,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["docker","go","ip-blocking","iptables","nginx","ufw"],"created_at":"2025-08-16T05:01:08.440Z","updated_at":"2025-08-16T05:03:07.739Z","avatar_url":"https://github.com/Anipaleja.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# nginx-defender\n\n\u003cdiv align=\"center\"\u003e\n  \n[![Build Status](https://github.com/anipaleja/nginx-defender/workflows/Build%20and%20Publish/badge.svg)](https://github.com/anipaleja/nginx-defender/actions)\n[![Docker Version](https://img.shields.io/badge/GHCR-nginx--defender-blue?logo=github)](https://github.com/anipaleja/nginx-defender/pkgs/container/nginx-defender)\n[![Go Report Card](https://goreportcard.com/badge/github.com/anipaleja/nginx-defender)](https://goreportcard.com/report/github.com/anipaleja/nginx-defender)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)\n[![Go Version](https://img.shields.io/badge/Go-1.21+-00ADD8?logo=go)](https://golang.org/)\n[![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20FreeBSD-orange)](https://github.com/anipaleja/nginx-defender)\n\n**Enterprise-Grade Web Application Firewall with Advanced Threat Intelligence**\n\n\u003c/div\u003e\n\n---\n\n## Table of Contents\n\n\u003cdetails\u003e\n\u003csummary\u003eClick to expand\u003c/summary\u003e\n\n- [Overview](#overview)\n- [Architecture](#architecture)\n- [Core Features](#core-features)\n  - [Threat Detection Engine](#threat-detection-engine)\n  - [Firewall Management](#firewall-management)\n  - [Monitoring \u0026 Analytics](#monitoring--analytics)\n  - [Notification System](#notification-system)\n- [Technical Specifications](#technical-specifications)\n- [Installation](#installation)\n  - [Binary Installation](#binary-installation)\n  - [Docker Deployment](#docker-deployment)\n  - [Kubernetes Deployment](#kubernetes-deployment)\n- [Configuration](#configuration)\n- [API Reference](#api-reference)\n- [Performance Benchmarks](#performance-benchmarks)\n- [Security Considerations](#security-considerations)\n- [Development](#development)\n- [License](#license)\n\n\u003c/details\u003e\n\n---\n\n## Overview\n\n**nginx-defender** is a high-performance, enterprise-grade Web Application Firewall (WAF) and threat detection system engineered for modern web infrastructure. Built with Go and designed for scalability, it provides real-time threat mitigation, machine learning-based anomaly detection, and comprehensive security analytics.\n\n### Key Differentiators\n\n```mermaid\ngraph TD\n    A[Incoming Traffic] --\u003e B[Log Parser]\n    B --\u003e C[Threat Detection Engine]\n    C --\u003e D[ML Anomaly Detection]\n    C --\u003e E[Pattern Matching]\n    C --\u003e F[Rate Limiting]\n    D --\u003e G[Firewall Manager]\n    E --\u003e G\n    F --\u003e G\n    G --\u003e H[iptables/nftables/pf]\n    G --\u003e I[Notification System]\n    I --\u003e J[Dashboard/API]\n```\n\n| Feature | nginx-defender | Commercial WAFs | Open Source WAFs |\n|---------|----------------|-----------------|------------------|\n| **Real-time ML Detection** | Native | Limited | None |\n| **Multi-backend Firewall** | 5+ backends | Proprietary | Limited |\n| **Advanced Analytics** | Built-in | Expensive addon | Basic |\n| **Geographic Intelligence** | Integrated | Licensed | Manual |\n| **Clustering Support** | Native | Enterprise only | None |\n| **Container Ready** | OCI compliant | Legacy | Configuration heavy |\n\n---\n\n## Architecture\n\n### System Architecture\n\n\u003cdetails\u003e\n\u003csummary\u003eHigh-Level Architecture Diagram\u003c/summary\u003e\n\n```\n┌────────────────────────────────────────────────────────────────┐\n│                        nginx-defender                          │\n├────────────────────────────────────────────────────────────────┤\n│  ┌───────────────┐  ┌──────────────┐  ┌─────────────────────┐  │\n│  │  Log Monitor  │  │ Threat Intel │  │   Web Dashboard     │  │\n│  │   (Async)     │  │   (Real-time)│  │   (WebSocket)       │  │\n│  └───────┬───────┘  └──────┬───────┘  └─────────┬───────────┘  │\n│          │                 │                    │              │\n│  ┌───────▼─────────────────▼────────────────────▼───────────┐  │\n│  │                Threat Detection Engine                   │  │\n│  │  ┌─────────────┐ ┌──────────────┐ ┌─────────────────┐    │  │\n│  │  │   Pattern   │ │ ML Anomaly   │ │ Rate Limiting   │    │  │\n│  │  │   Matcher   │ │  Detection   │ │    Engine       │    │  │\n│  │  └─────────────┘ └──────────────┘ └─────────────────┘    │  │\n│  └─────────────────────────┬────────────────────────────────┘  │\n│                            │                                   │\n│  ┌─────────────────────────▼────────────────────────────────┐  │\n│  │                  Firewall Manager                        │  │\n│  │  ┌─────────────┐ ┌──────────────┐ ┌─────────────────┐    │  │\n│  │  │  iptables   │ │   nftables   │ │      pf         │    │  │\n│  │  │   Backend   │ │   Backend    │ │   Backend       │    │  │\n│  │  └─────────────┘ └──────────────┘ └─────────────────┘    │  │\n│  └─────────────────────────┬────────────────────────────────┘  │\n│                            │                                   │\n│  ┌─────────────────────────▼────────────────────────────────┐  │\n│  │            Multi-Channel Notification System             │  │\n│  │    Telegram │ Slack │ Email │ Webhook │ Discord          │  │\n│  └──────────────────────────────────────────────────────────┘  │\n└────────────────────────────────────────────────────────────────┘\n```\n\n\u003c/details\u003e\n\n### Component Overview\n\n| Component | Responsibility | Technology | Scalability |\n|-----------|---------------|------------|-------------|\n| **Log Monitor** | Real-time log parsing and streaming | Go channels, fsnotify | Horizontal |\n| **Detection Engine** | Threat analysis and classification | Regex, ML algorithms | Vertical |\n| **Firewall Manager** | Rule application and management | System calls, netlink | Horizontal |\n| **Notification System** | Alert distribution and escalation | HTTP clients, WebSockets | Horizontal |\n| **Web Dashboard** | Management interface and analytics | HTTP server, static assets | Horizontal |\n| **Metrics Collector** | Performance and security metrics | Prometheus client | Horizontal |\n\n---\n\n## Core Features\n\n### Threat Detection Engine\n\n\u003cdetails\u003e\n\u003csummary\u003eAdvanced Pattern Recognition System\u003c/summary\u003e\n\n#### Machine Learning Integration\n- **Behavioral Analysis**: Statistical anomaly detection using sliding windows\n- **Attack Vectorization**: Feature extraction from HTTP requests\n- **Model Training**: Continuous learning from threat patterns\n- **False Positive Reduction**: Adaptive threshold adjustment\n\n#### Pattern Matching Engine\n```yaml\n# Example threat patterns\npatterns:\n  sql_injection:\n    regex: \"(?i)(union|select|insert|update|delete|drop|exec|script)\"\n    severity: 9\n    categories: [\"injection\", \"database\"]\n    \n  xss_detection:\n    regex: \"(?i)(\u003cscript|javascript:|vbscript:|onload=|onerror=)\"\n    severity: 8\n    categories: [\"xss\", \"injection\"]\n    \n  directory_traversal:\n    regex: \"(?i)(\\\\.\\\\.[\\\\/\\\\\\\\]|%2e%2e%2f|%252e%252e%252f)\"\n    severity: 7\n    categories: [\"path_traversal\", \"file_access\"]\n```\n\n#### Rate Limiting Algorithm\n```go\ntype RateLimiter struct {\n    Window    time.Duration\n    Threshold int\n    Algorithm string // \"sliding_window\", \"token_bucket\", \"leaky_bucket\"\n}\n```\n\n\u003c/details\u003e\n\n### Firewall Management\n\n\u003cdetails\u003e\n\u003csummary\u003eMulti-Backend Firewall System\u003c/summary\u003e\n\n#### Supported Backends\n\n| Backend | Platform | Features | Performance |\n|---------|----------|----------|-------------|\n| **iptables** | Linux | Legacy compatibility, wide support | ~10k rules/sec |\n| **nftables** | Linux | Modern netfilter, better performance | ~50k rules/sec |\n| **pf** | FreeBSD/macOS | Advanced filtering, built-in NAT | ~30k rules/sec |\n| **Windows Firewall** | Windows | Native Windows integration | ~5k rules/sec |\n| **Mock** | All | Testing and development | Unlimited |\n\n#### Rule Management\n```go\ntype Rule struct {\n    ID          string            `json:\"id\"`\n    IP          string            `json:\"ip\"`\n    Action      Action            `json:\"action\"`\n    Duration    time.Duration     `json:\"duration\"`\n    CreatedAt   time.Time         `json:\"created_at\"`\n    ExpiresAt   time.Time         `json:\"expires_at\"`\n    Reason      string            `json:\"reason\"`\n    ThreatLevel string            `json:\"threat_level\"`\n    Metadata    map[string]string `json:\"metadata\"`\n}\n```\n\n#### Action Types\n- `BLOCK`: Complete traffic blocking\n- `DROP`: Silent packet dropping\n- `REJECT`: Explicit connection rejection\n- `RATE_LIMIT`: Bandwidth throttling\n- `TARPIT`: Connection delay injection\n- `ALLOW`: Whitelist override\n\n\u003c/details\u003e\n\n### Monitoring \u0026 Analytics\n\n\u003cdetails\u003e\n\u003csummary\u003eReal-time Dashboard and Metrics\u003c/summary\u003e\n\n#### Web Dashboard Features\n- **Real-time Threat Map**: Geographic visualization of attacks\n- **Performance Metrics**: Request processing and response times\n- **Rule Management**: Interactive firewall rule configuration\n- **Log Analysis**: Advanced filtering and search capabilities\n- **Alert Management**: Notification configuration and history\n\n#### Prometheus Metrics\n```plaintext\n# HELP nginx_defender_requests_total Total number of requests processed\n# TYPE nginx_defender_requests_total counter\nnginx_defender_requests_total{status=\"blocked\",reason=\"sql_injection\"} 1234\n\n# HELP nginx_defender_response_duration_seconds Request processing duration\n# TYPE nginx_defender_response_duration_seconds histogram\nnginx_defender_response_duration_seconds_bucket{le=\"0.1\"} 8932\n```\n\n#### WebSocket API\n```javascript\nconst ws = new WebSocket('ws://localhost:8080/ws');\nws.onmessage = function(event) {\n    const data = JSON.parse(event.data);\n    console.log('New threat detected:', data);\n};\n```\n\n\u003c/details\u003e\n\n### Notification System\n\n\u003cdetails\u003e\n\u003csummary\u003eMulti-Channel Alert Distribution\u003c/summary\u003e\n\n#### Supported Channels\n\n| Channel | Features | Configuration |\n|---------|----------|---------------|\n| **Telegram** | Rich formatting, bot integration | Bot token, chat ID |\n| **Slack** | Channel posting, thread replies | Webhook URL, channel |\n| **Email** | HTML templates, attachments | SMTP configuration |\n| **Webhook** | Custom integrations, JSON payload | Endpoint URL, headers |\n| **Discord** | Server notifications, embeds | Webhook URL |\n| **PagerDuty** | Incident management, escalation | Integration key |\n\n#### Alert Severity Levels\n```yaml\nseverity_mapping:\n  critical: 9-10    # Immediate response required\n  high: 7-8         # Urgent attention needed\n  medium: 4-6       # Standard monitoring\n  low: 1-3          # Informational only\n```\n\n\u003c/details\u003e\n\n---\n\n## Technical Specifications\n\n### System Requirements\n\n#### Minimum Requirements\n```yaml\nhardware:\n  cpu: \"1 core (x86_64/ARM64)\"\n  memory: \"256 MB RAM\"\n  storage: \"100 MB disk space\"\n  network: \"1 Mbps bandwidth\"\n\nsoftware:\n  os: \"Linux 4.0+, macOS 10.15+, FreeBSD 12+\"\n  privileges: \"root/administrator (for firewall management)\"\n  dependencies: \"None (statically linked binary)\"\n```\n\n#### Recommended Production Setup\n```yaml\nhardware:\n  cpu: \"4+ cores (x86_64)\"\n  memory: \"2+ GB RAM\"\n  storage: \"10+ GB SSD\"\n  network: \"100+ Mbps bandwidth\"\n\nsoftware:\n  os: \"Linux 5.4+ (Ubuntu 20.04+, CentOS 8+)\"\n  kernel: \"nftables support enabled\"\n  monitoring: \"Prometheus + Grafana\"\n```\n\n### Performance Characteristics\n\n| Metric | Value | Notes |\n|--------|-------|-------|\n| **Log Processing** | 100k+ entries/sec | Single instance |\n| **Rule Application** | 50k+ rules/sec | nftables backend |\n| **Memory Usage** | \u003c100 MB | Base configuration |\n| **CPU Usage** | \u003c5% | Idle state |\n| **Response Time** | \u003c1ms | Rule matching |\n| **Concurrent Connections** | 10k+ | Web dashboard |\n\n### Network Architecture\n\n```\n┌─────────────┐    ┌─────────────┐    ┌─────────────┐\n│   Client    │────│  nginx-     │────│  Backend    │\n│  Traffic    │    │  defender   │    │  Services   │\n└─────────────┘    └─────────────┘    └─────────────┘\n                          │\n                   ┌─────────────┐\n                   │  Firewall   │\n                   │   Rules     │\n                   └─────────────┘\n```\n\n---\n\n## Installation\n\n### Binary Installation\n\n#### Linux (x86_64)\n```bash\n# Download latest release\ncurl -L https://github.com/anipaleja/nginx-defender/releases/latest/download/nginx-defender-linux-amd64.tar.gz | tar -xz\n\n# Install system-wide\nsudo mv nginx-defender /usr/local/bin/\nsudo chmod +x /usr/local/bin/nginx-defender\n\n# Create configuration directory\nsudo mkdir -p /etc/nginx-defender\nsudo wget -O /etc/nginx-defender/config.yaml https://raw.githubusercontent.com/anipaleja/nginx-defender/main/config.yaml\n\n# Create systemd service\nsudo tee /etc/systemd/system/nginx-defender.service \u003e /dev/null \u003c\u003cEOF\n[Unit]\nDescription=nginx-defender WAF\nAfter=network.target\n\n[Service]\nType=simple\nUser=root\nExecStart=/usr/local/bin/nginx-defender -config /etc/nginx-defender/config.yaml\nRestart=always\nRestartSec=5\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\n# Enable and start service\nsudo systemctl enable nginx-defender\nsudo systemctl start nginx-defender\n```\n\n#### macOS (Homebrew)\n```bash\n# Add tap (if available)\nbrew tap anipaleja/nginx-defender\n\n# Install via Homebrew\nbrew install nginx-defender\n\n# Start service\nbrew services start nginx-defender\n```\n\n### Docker Deployment\n\n#### Basic Docker Run\n```bash\n# Pull latest image\ndocker pull ghcr.io/anipaleja/nginx-defender:latest\n\n# Run with host networking (recommended for firewall functionality)\ndocker run -d \\\n  --name nginx-defender \\\n  --network host \\\n  --cap-add NET_ADMIN \\\n  --cap-add NET_RAW \\\n  -v /var/log/nginx:/var/log/nginx:ro \\\n  -v ./config.yaml:/app/config.yaml:ro \\\n  ghcr.io/anipaleja/nginx-defender:latest\n```\n\n#### Docker Compose\n```yaml\nversion: '3.8'\n\nservices:\n  nginx-defender:\n    image: ghcr.io/anipaleja/nginx-defender:latest\n    container_name: nginx-defender\n    restart: unless-stopped\n    network_mode: host\n    cap_add:\n      - NET_ADMIN\n      - NET_RAW\n    volumes:\n      - /var/log/nginx:/var/log/nginx:ro\n      - ./config.yaml:/app/config.yaml:ro\n      - ./data:/app/data\n    environment:\n      - LOG_LEVEL=info\n      - DRY_RUN=false\n    healthcheck:\n      test: [\"CMD\", \"curl\", \"-f\", \"http://localhost:8080/health\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n\n  prometheus:\n    image: prom/prometheus:latest\n    container_name: prometheus\n    ports:\n      - \"9090:9090\"\n    volumes:\n      - ./prometheus.yml:/etc/prometheus/prometheus.yml\n    command:\n      - '--config.file=/etc/prometheus/prometheus.yml'\n      - '--storage.tsdb.path=/prometheus'\n      - '--web.console.libraries=/etc/prometheus/console_libraries'\n      - '--web.console.templates=/etc/prometheus/consoles'\n\n  grafana:\n    image: grafana/grafana:latest\n    container_name: grafana\n    ports:\n      - \"3000:3000\"\n    environment:\n      - GF_SECURITY_ADMIN_PASSWORD=admin\n    volumes:\n      - grafana-storage:/var/lib/grafana\n\nvolumes:\n  grafana-storage:\n```\n\n### Kubernetes Deployment\n\n\u003cdetails\u003e\n\u003csummary\u003eComplete Kubernetes Manifests\u003c/summary\u003e\n\n#### Namespace and ConfigMap\n```yaml\napiVersion: v1\nkind: Namespace\nmetadata:\n  name: nginx-defender\n---\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: nginx-defender-config\n  namespace: nginx-defender\ndata:\n  config.yaml: |\n    firewall:\n      backend: \"iptables\"\n      whitelist:\n        - \"10.0.0.0/8\"\n        - \"172.16.0.0/12\"\n        - \"192.168.0.0/16\"\n    \n    detection:\n      enabled: true\n      patterns_file: \"pkg/patterns/common.yaml\"\n      rate_limiting:\n        enabled: true\n        window: \"1m\"\n        max_requests: 100\n    \n    server:\n      host: \"0.0.0.0\"\n      port: 8080\n    \n    metrics:\n      enabled: true\n      prometheus:\n        enabled: true\n        host: \"0.0.0.0\"\n        port: 9090\n```\n\n#### DaemonSet Deployment\n```yaml\napiVersion: apps/v1\nkind: DaemonSet\nmetadata:\n  name: nginx-defender\n  namespace: nginx-defender\nspec:\n  selector:\n    matchLabels:\n      app: nginx-defender\n  template:\n    metadata:\n      labels:\n        app: nginx-defender\n    spec:\n      hostNetwork: true\n      hostPID: true\n      containers:\n      - name: nginx-defender\n        image: ghcr.io/anipaleja/nginx-defender:latest\n        imagePullPolicy: Always\n        securityContext:\n          privileged: true\n          capabilities:\n            add:\n              - NET_ADMIN\n              - NET_RAW\n              - SYS_ADMIN\n        ports:\n        - containerPort: 8080\n          name: web\n        - containerPort: 9090\n          name: metrics\n        volumeMounts:\n        - name: config\n          mountPath: /app/config.yaml\n          subPath: config.yaml\n        - name: log-files\n          mountPath: /var/log/nginx\n          readOnly: true\n        - name: proc\n          mountPath: /host/proc\n          readOnly: true\n        - name: sys\n          mountPath: /host/sys\n          readOnly: true\n      volumes:\n      - name: config\n        configMap:\n          name: nginx-defender-config\n      - name: log-files\n        hostPath:\n          path: /var/log/nginx\n      - name: proc\n        hostPath:\n          path: /proc\n      - name: sys\n        hostPath:\n          path: /sys\n      tolerations:\n      - operator: Exists\n        effect: NoSchedule\n```\n\n#### Service and Ingress\n```yaml\napiVersion: v1\nkind: Service\nmetadata:\n  name: nginx-defender-service\n  namespace: nginx-defender\nspec:\n  selector:\n    app: nginx-defender\n  ports:\n  - name: web\n    port: 8080\n    targetPort: 8080\n  - name: metrics\n    port: 9090\n    targetPort: 9090\n  type: ClusterIP\n---\napiVersion: networking.k8s.io/v1\nkind: Ingress\nmetadata:\n  name: nginx-defender-ingress\n  namespace: nginx-defender\n  annotations:\n    nginx.ingress.kubernetes.io/rewrite-target: /\nspec:\n  rules:\n  - host: nginx-defender.example.com\n    http:\n      paths:\n      - path: /\n        pathType: Prefix\n        backend:\n          service:\n            name: nginx-defender-service\n            port:\n              number: 8080\n```\n\n\u003c/details\u003e\n\n---\n\n## Configuration\n\n### Configuration File Structure\n\n\u003cdetails\u003e\n\u003csummary\u003eComplete Configuration Reference\u003c/summary\u003e\n\n```yaml\n# nginx-defender configuration file\n# Version: 2.0\n\n# Firewall configuration\nfirewall:\n  # Backend type: iptables, nftables, pf, mock\n  backend: \"iptables\"\n  \n  # Whitelisted IP addresses and ranges\n  whitelist:\n    - \"127.0.0.1\"\n    - \"::1\"\n    - \"192.168.0.0/16\"\n    - \"10.0.0.0/8\"\n    - \"172.16.0.0/12\"\n  \n  # Default action for threats\n  default_action: \"BLOCK\"\n  \n  # Rule cleanup interval\n  cleanup_interval: \"5m\"\n  \n  # Maximum number of rules\n  max_rules: 10000\n\n# Threat detection configuration\ndetection:\n  enabled: true\n  \n  # Machine learning model file (optional)\n  ml_model: \"/app/models/threat_detection.model\"\n  \n  # Threat patterns file\n  patterns_file: \"pkg/patterns/common.yaml\"\n  \n  # Rate limiting configuration\n  rate_limiting:\n    enabled: true\n    window: \"1m\"\n    max_requests: 100\n    algorithm: \"sliding_window\"\n  \n  # Geographic blocking\n  geo_blocking:\n    enabled: true\n    blocked_countries: [\"CN\", \"RU\", \"KP\"]\n    allowed_countries: []\n    geoip_database: \"/app/data/GeoLite2-City.mmdb\"\n  \n  # Honeypot integration\n  honeypot:\n    enabled: false\n    boost_factor: 2.0\n    services: [\"ssh\", \"http\", \"ftp\"]\n\n# Log monitoring configuration\nlogs:\n  level: \"info\"\n  format: \"json\"\n  output: \"stdout\"\n  \n  # Log sources to monitor\n  sources:\n    - path: \"/var/log/nginx/access.log\"\n      format: \"combined\"\n      follow: true\n    - path: \"/var/log/nginx/error.log\"\n      format: \"error\"\n      follow: true\n    - path: \"/var/log/apache2/access.log\"\n      format: \"combined\"\n      follow: false\n\n# Web server configuration\nserver:\n  host: \"0.0.0.0\"\n  port: 8080\n  \n  # TLS configuration\n  tls:\n    enabled: false\n    cert_file: \"/app/certs/server.crt\"\n    key_file: \"/app/certs/server.key\"\n  \n  # CORS configuration\n  cors:\n    enabled: true\n    allowed_origins: [\"*\"]\n    allowed_methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\"]\n\n# Metrics and monitoring\nmetrics:\n  enabled: true\n  \n  # Prometheus configuration\n  prometheus:\n    enabled: true\n    host: \"0.0.0.0\"\n    port: 9090\n    path: \"/metrics\"\n  \n  # Performance monitoring\n  performance:\n    enabled: true\n    interval: \"30s\"\n\n# Notification configuration\nnotifications:\n  enabled: true\n  \n  # Notification channels\n  channels:\n    console:\n      enabled: true\n      level: \"info\"\n    \n    email:\n      enabled: false\n      smtp_host: \"smtp.example.com\"\n      smtp_port: 587\n      username: \"alerts@example.com\"\n      password: \"password\"\n      to: [\"admin@example.com\"]\n      subject_prefix: \"[nginx-defender]\"\n    \n    telegram:\n      enabled: false\n      bot_token: \"BOT_TOKEN\"\n      chat_id: \"CHAT_ID\"\n    \n    slack:\n      enabled: false\n      webhook_url: \"WEBHOOK_URL\"\n      channel: \"#security\"\n      username: \"nginx-defender\"\n    \n    webhook:\n      enabled: false\n      url: \"https://api.example.com/webhooks/security\"\n      headers:\n        Authorization: \"Bearer TOKEN\"\n        Content-Type: \"application/json\"\n\n# Clustering configuration (Enterprise)\nclustering:\n  enabled: false\n  node_id: \"node-1\"\n  discovery:\n    method: \"static\"\n    endpoints: [\"node-2:8081\", \"node-3:8081\"]\n  \n  # Distributed rule synchronization\n  sync:\n    enabled: true\n    interval: \"10s\"\n```\n\n\u003c/details\u003e\n\n### Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `NGINX_DEFENDER_CONFIG` | Configuration file path | `config.yaml` |\n| `NGINX_DEFENDER_LOG_LEVEL` | Log level (debug, info, warn, error) | `info` |\n| `NGINX_DEFENDER_DRY_RUN` | Enable dry-run mode | `false` |\n| `NGINX_DEFENDER_BACKEND` | Firewall backend override | - |\n| `NGINX_DEFENDER_WEB_PORT` | Web server port | `8080` |\n| `NGINX_DEFENDER_METRICS_PORT` | Metrics server port | `9090` |\n\n---\n\n## API Reference\n\n### REST API Endpoints\n\n\u003cdetails\u003e\n\u003csummary\u003eComplete API Documentation\u003c/summary\u003e\n\n#### System Information\n```http\nGET /api/v1/status\n```\n**Response:**\n```json\n{\n  \"status\": \"healthy\",\n  \"version\": \"2.0.0\",\n  \"uptime\": \"2h30m15s\",\n  \"build_info\": {\n    \"version\": \"v2.0.0\",\n    \"commit\": \"abc123\",\n    \"build_time\": \"2025-07-27T10:00:00Z\"\n  }\n}\n```\n\n#### Firewall Rules Management\n```http\nGET /api/v1/rules\nPOST /api/v1/rules\nDELETE /api/v1/rules/{id}\n```\n\n**Create Rule:**\n```json\n{\n  \"ip\": \"192.168.1.100\",\n  \"action\": \"BLOCK\",\n  \"duration\": \"1h\",\n  \"reason\": \"SQL injection attempt\",\n  \"metadata\": {\n    \"threat_level\": \"high\",\n    \"pattern\": \"sql_injection\"\n  }\n}\n```\n\n#### Statistics and Metrics\n```http\nGET /api/v1/stats\nGET /api/v1/metrics\n```\n\n**Statistics Response:**\n```json\n{\n  \"firewall\": {\n    \"backend\": \"iptables\",\n    \"total_rules\": 1234,\n    \"active_rules\": 987,\n    \"expired_rules\": 247\n  },\n  \"detection\": {\n    \"total_requests\": 50000,\n    \"blocked_requests\": 1234,\n    \"threat_detections\": {\n      \"sql_injection\": 456,\n      \"xss\": 234,\n      \"brute_force\": 344\n    }\n  },\n  \"performance\": {\n    \"avg_response_time\": \"0.5ms\",\n    \"memory_usage\": \"89MB\",\n    \"cpu_usage\": \"3.2%\"\n  }\n}\n```\n\n#### Configuration Management\n```http\nGET /api/v1/config\nPUT /api/v1/config\nPOST /api/v1/config/reload\n```\n\n#### Log Analysis\n```http\nGET /api/v1/logs?limit=100\u0026level=error\nGET /api/v1/threats?since=1h\u0026severity=high\n```\n\n\u003c/details\u003e\n\n### WebSocket API\n\n\u003cdetails\u003e\n\u003csummary\u003eReal-time Event Streaming\u003c/summary\u003e\n\n#### Connection\n```javascript\nconst ws = new WebSocket('ws://localhost:8080/ws');\n```\n\n#### Event Types\n```javascript\n// Threat detection event\n{\n  \"type\": \"threat_detected\",\n  \"timestamp\": \"2025-07-27T12:00:00Z\",\n  \"data\": {\n    \"ip\": \"192.168.1.100\",\n    \"threat_type\": \"sql_injection\",\n    \"severity\": 9,\n    \"blocked\": true\n  }\n}\n\n// Rule creation event\n{\n  \"type\": \"rule_created\",\n  \"timestamp\": \"2025-07-27T12:00:01Z\",\n  \"data\": {\n    \"rule_id\": \"rule-123\",\n    \"ip\": \"192.168.1.100\",\n    \"action\": \"BLOCK\",\n    \"expires_at\": \"2025-07-27T13:00:01Z\"\n  }\n}\n\n// System metrics update\n{\n  \"type\": \"metrics_update\",\n  \"timestamp\": \"2025-07-27T12:00:00Z\",\n  \"data\": {\n    \"cpu_usage\": 3.2,\n    \"memory_usage\": 89,\n    \"active_connections\": 1234\n  }\n}\n```\n\n\u003c/details\u003e\n\n---\n\n## Performance Benchmarks\n\n### Throughput Testing\n\n\u003cdetails\u003e\n\u003csummary\u003ePerformance Test Results\u003c/summary\u003e\n\n#### Test Environment\n- **Hardware**: Intel Xeon E5-2686v4 (4 cores), 16GB RAM\n- **OS**: Ubuntu 22.04 LTS\n- **Network**: 10Gbps Ethernet\n- **Backend**: nftables\n\n#### Results\n\n| Test Scenario | Throughput | Latency (p95) | CPU Usage | Memory Usage |\n|---------------|------------|---------------|-----------|--------------|\n| **Log Processing** | 150k entries/sec | 2ms | 15% | 120MB |\n| **Pattern Matching** | 100k requests/sec | 1ms | 25% | 95MB |\n| **Rule Application** | 75k rules/sec | 0.5ms | 10% | 85MB |\n| **API Requests** | 50k requests/sec | 5ms | 20% | 100MB |\n| **WebSocket Events** | 25k events/sec | 3ms | 12% | 90MB |\n\n#### Scaling Characteristics\n```\nLog Processing Rate vs CPU Cores:\n  1 core:  50k entries/sec\n  2 cores: 95k entries/sec\n  4 cores: 150k entries/sec\n  8 cores: 180k entries/sec (diminishing returns)\n```\n\n\u003c/details\u003e\n\n### Memory Optimization\n\n\u003cdetails\u003e\n\u003csummary\u003eMemory Usage Analysis\u003c/summary\u003e\n\n| Component | Base Memory | Per Rule | Per Connection |\n|-----------|-------------|----------|----------------|\n| **Core Engine** | 45MB | 64 bytes | 2KB |\n| **Pattern Matcher** | 25MB | - | 512 bytes |\n| **Web Server** | 15MB | - | 4KB |\n| **Metrics Collector** | 10MB | 128 bytes | 1KB |\n| **Total Baseline** | 95MB | 192 bytes | 7.5KB |\n\n#### Memory Growth Projections\n- **10k rules**: ~97MB\n- **100k rules**: ~114MB\n- **1M rules**: ~287MB\n- **10k concurrent connections**: ~170MB\n\n\u003c/details\u003e\n\n---\n\n## Security Considerations\n\n### Security Architecture\n\n\u003cdetails\u003e\n\u003csummary\u003eSecurity Design Principles\u003c/summary\u003e\n\n#### Defense in Depth\n1. **Input Validation**: All user inputs are validated and sanitized\n2. **Principle of Least Privilege**: Minimal required permissions\n3. **Fail-Safe Defaults**: Secure defaults for all configurations\n4. **Complete Mediation**: All access attempts are checked\n5. **Open Design**: Security through design, not obscurity\n\n#### Threat Model\n```mermaid\ngraph LR\n    A[External Attacker] --\u003e|HTTP Requests| B[nginx-defender]\n    C[Malicious Insider] --\u003e|Config Changes| B\n    D[Compromised System] --\u003e|Local Access| B\n    \n    B --\u003e|Validated Traffic| E[Protected Services]\n    B --\u003e|Blocked Traffic| F[Firewall Drop]\n    B --\u003e|Alerts| G[Security Team]\n```\n\n#### Security Controls\n\n| Layer | Control | Implementation |\n|-------|---------|----------------|\n| **Network** | Traffic filtering | iptables/nftables rules |\n| **Application** | Input validation | Regex patterns, ML detection |\n| **Authentication** | API access control | JWT tokens, API keys |\n| **Authorization** | Role-based access | RBAC system |\n| **Audit** | Activity logging | Structured logging, SIEM integration |\n| **Encryption** | Data protection | TLS 1.3, AES-256 |\n\n\u003c/details\u003e\n\n### Vulnerability Management\n\n\u003cdetails\u003e\n\u003csummary\u003eSecurity Practices\u003c/summary\u003e\n\n#### Regular Security Assessments\n- **Static Analysis**: Weekly automated scans\n- **Dynamic Testing**: Monthly penetration testing\n- **Dependency Scanning**: Daily vulnerability checks\n- **Configuration Audits**: Quarterly security reviews\n\n#### Incident Response\n1. **Detection**: Automated threat detection and alerting\n2. **Analysis**: Log correlation and forensic analysis\n3. **Containment**: Automatic rule application and isolation\n4. **Recovery**: System restoration and patch application\n5. **Lessons Learned**: Post-incident review and improvements\n\n#### Compliance Standards\n- **OWASP Top 10**: Protection against common web vulnerabilities\n- **NIST Cybersecurity Framework**: Risk management alignment\n- **ISO 27001**: Information security management\n- **PCI DSS**: Payment card industry compliance (where applicable)\n\n\u003c/details\u003e\n\n---\n\n## Development\n\n### Building from Source\n\n\u003cdetails\u003e\n\u003csummary\u003eDevelopment Setup\u003c/summary\u003e\n\n#### Prerequisites\n```bash\n# Install Go 1.21+\ncurl -L https://go.dev/dl/go1.21.linux-amd64.tar.gz | sudo tar -C /usr/local -xz\nexport PATH=$PATH:/usr/local/go/bin\n\n# Install development tools\ngo install github.com/golangci/golangci-lint/cmd/golangci-lint@latest\ngo install github.com/securecodewarrior/sast-scan@latest\n```\n\n#### Build Process\n```bash\n# Clone repository\ngit clone https://github.com/anipaleja/nginx-defender.git\ncd nginx-defender\n\n# Install dependencies\ngo mod download\n\n# Run tests\ngo test -v ./...\n\n# Build binary\ngo build -o nginx-defender ./cmd/nginx-defender\n\n# Build for multiple platforms\nmake build-all\n```\n\n#### Development Workflow\n```bash\n# Run with hot reload\nair -c .air.toml\n\n# Run tests with coverage\ngo test -coverprofile=coverage.out ./...\ngo tool cover -html=coverage.out\n\n# Lint code\ngolangci-lint run\n\n# Security scan\ngosec ./...\n```\n\n\u003c/details\u003e\n\n### Contributing Guidelines\n\n\u003cdetails\u003e\n\u003csummary\u003eContribution Process\u003c/summary\u003e\n\n#### Code Standards\n- **Go Style**: Follow effective Go guidelines\n- **Documentation**: Comprehensive godoc comments\n- **Testing**: Minimum 80% test coverage\n- **Performance**: Benchmark critical paths\n- **Security**: Static analysis and vulnerability scanning\n\n#### Pull Request Process\n1. **Fork** the repository\n2. **Create** feature branch (`git checkout -b feature/amazing-feature`)\n3. **Commit** changes (`git commit -m 'Add amazing feature'`)\n4. **Push** to branch (`git push origin feature/amazing-feature`)\n5. **Open** Pull Request with detailed description\n\n#### Issue Reporting\n```markdown\n## Bug Report Template\n\n**Environment:**\n- OS: [e.g., Ubuntu 22.04]\n- Version: [e.g., v2.0.0]\n- Backend: [e.g., iptables]\n\n**Steps to Reproduce:**\n1. Configuration used\n2. Command executed\n3. Expected vs actual behavior\n\n**Logs:**\n```\n[Paste relevant logs here]\n```\n\n**Additional Context:**\n[Any other relevant information]\n```\n\n\u003c/details\u003e\n\n---\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE.md) file for details.\n\n### Third-Party Licenses\n\n\u003cdetails\u003e\n\u003csummary\u003eOpen Source Dependencies\u003c/summary\u003e\n\n| Dependency | License | Usage |\n|------------|---------|-------|\n| **gorilla/mux** | BSD-3-Clause | HTTP routing |\n| **gorilla/websocket** | BSD-2-Clause | WebSocket support |\n| **sirupsen/logrus** | MIT | Structured logging |\n| **prometheus/client_golang** | Apache-2.0 | Metrics collection |\n| **oschwald/geoip2-golang** | ISC | Geographic lookup |\n| **go-telegram-bot-api/telegram-bot-api** | MIT | Telegram integration |\n| **slack-go/slack** | BSD-2-Clause | Slack integration |\n\n\u003c/details\u003e\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\n**nginx-defender** - Protecting the modern web, one request at a time.\n\n[Documentation](https://nginx-defender.com/docs) • [Community](https://github.com/anipaleja/nginx-defender/discussions) • [Security](https://github.com/anipaleja/nginx-defender/security)\n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanipaleja%2Fnginx-defender","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fanipaleja%2Fnginx-defender","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanipaleja%2Fnginx-defender/lists"}