Skip to content

dwin-gharibi/parvahan

Repository files navigation

Parvahan Logo

Parvahan - Enterprise-Grade Intelligent Proxy Management Platform

Built from scratch with Python asyncio β€’ AI-Powered Security β€’ Full-Featured Dashboard

License Python Django Next.js Docker Kubernetes


πŸ“‹ Table of Contents


🌟 Overview

Parvahan (ΩΎΩŽΨ±ΩˆΩŽΩ‡Ψ§Ω† - Persian for "Revealer") is a comprehensive, enterprise-grade proxy management platform designed to provide organizations with complete control over their network traffic. Built entirely from scratch using Python's asyncio framework, Parvahan offers unmatched performance, security, and flexibility.

Parvahan System Design

Why Parvahan?

Feature Parvahan Traditional Proxies
AI-Powered Security βœ… ML-based threat detection ❌ Rule-based only
Multi-Protocol βœ… HTTP/HTTPS/SOCKS5/WebSocket ⚠️ Usually HTTP only
Real-time Dashboard βœ… Beautiful Next.js UI ❌ CLI or basic web
Iranian Mirror Support βœ… Built-in support ❌ Not available
Horizontal Scaling βœ… Kubernetes-ready ⚠️ Limited
Open Source βœ… MIT License ⚠️ Varies

Architecture Components

Component Technology Description
parvahan-core Python/asyncio High-performance proxy server (HTTP/HTTPS/SOCKS5)
parvahan-admin Django REST API backend for management and configuration
parvahan-ui Next.js/React Modern web dashboard with real-time updates
parvahan-cli Python/Click Command-line interface for automation

🎯 Key Features

πŸ” Proxy Protocols

  • HTTP/HTTPS Proxy - Full HTTP/1.1 and HTTP/2 support with CONNECT tunneling
  • SOCKS5 Proxy - Complete RFC 1928/1929 implementation with UDP support
  • WebSocket Proxy - Bidirectional WebSocket tunneling with frame inspection
  • Transparent Proxy - Network-level proxying without client configuration
  • DNS-over-HTTPS/TLS - Secure DNS resolution with privacy protection

πŸ›‘οΈ Advanced Security

  • 6-Layer Security Model - Defense in depth with firewall, IDS/IPS, encryption
  • GeoIP Blocking - Block/allow traffic by country with MaxMind integration
  • IP Reputation System - Automatic scoring based on behavior patterns
  • DDoS Protection - Rate limiting, SYN flood protection, challenge-response
  • Honeypot System - Trap and analyze attacker behavior
  • Two-Factor Authentication - TOTP-based 2FA for all users
  • Browser Fingerprinting - Detect bots and automated tools

🧠 AI & Machine Learning

  • Anomaly Detection - Isolation Forest algorithm for unusual pattern detection
  • Threat Classification - Neural network-based threat type identification
  • Predictive Analytics - Forecast attacks and traffic patterns
  • User Behavior Analytics (UBA) - Baseline learning and deviation detection
  • Smart Routing - Reinforcement learning for optimal path selection
  • Continuous Learning - Models improve with every request

🚫 Content Filtering

  • Ad Blocking - EasyList, EasyPrivacy integration
  • Malware Protection - Google Safe Browsing, PhishTank integration
  • Category Filtering - Block social media, gambling, adult content
  • Custom Blocklists - Import and sync external blocklists
  • Regex Patterns - Flexible URL matching rules

⚑ Performance

  • 100,000+ RPS - Handle massive traffic with async architecture
  • < 5ms Latency - Minimal overhead on proxied requests
  • Intelligent Caching - LRU cache with smart TTL management
  • Connection Pooling - Reuse upstream connections
  • Compression - Gzip, Deflate, Brotli support

πŸ“Š Monitoring & Observability

  • Real-time Dashboard - Live metrics with beautiful visualizations
  • Prometheus Metrics - Full metrics export for monitoring
  • Grafana Dashboards - Pre-built dashboards included
  • Alerting System - Email, Slack, SMS, PagerDuty, Webhook
  • Comprehensive Logging - Proxy logs, security events, audit trails

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                              INTERNET                                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                  β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                           TRAEFIK                                            β”‚
β”‚              (Reverse Proxy / Load Balancer / SSL Termination)              β”‚
β”‚                         Ports: 80, 443                                       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                  β”‚
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚                       β”‚                       β”‚
          β–Ό                       β–Ό                       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  parvahan-ui    β”‚     β”‚ parvahan-admin  β”‚     β”‚  parvahan-core  β”‚
β”‚    (Next.js)    β”‚     β”‚    (Django)     β”‚     β”‚    (Proxy)      β”‚
β”‚   Port: 3000    β”‚     β”‚   Port: 8099    β”‚     β”‚  Ports: 8080,   β”‚
β”‚                 β”‚     β”‚                 β”‚     β”‚   1080, 8442    β”‚
β”‚  β€’ Dashboard    β”‚     β”‚  β€’ REST API     β”‚     β”‚                 β”‚
β”‚  β€’ Real-time    β”‚     β”‚  β€’ Auth/RBAC    β”‚     β”‚  β€’ HTTP Proxy   β”‚
β”‚  β€’ Config UI    β”‚     β”‚  β€’ Rules Engine β”‚     β”‚  β€’ SOCKS5       β”‚
β”‚  β€’ Reports      β”‚     β”‚  β€’ Webhooks     β”‚     β”‚  β€’ WebSocket    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β”‚  β€’ Security     β”‚
                                 β”‚              β”‚  β€’ Caching      β”‚
                                 β”‚              β”‚  β€’ AI/ML        β”‚
                                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚                           β”‚                           β”‚
                    β–Ό                           β–Ό                           β–Ό
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚   PostgreSQL    β”‚         β”‚      Redis      β”‚         β”‚     Celery      β”‚
          β”‚    Database     β”‚         β”‚   Cache/Queue   β”‚         β”‚    Workers      β”‚
          β”‚                 β”‚         β”‚                 β”‚         β”‚                 β”‚
          β”‚  β€’ Users        β”‚         β”‚  β€’ Sessions     β”‚         β”‚  β€’ Email tasks  β”‚
          β”‚  β€’ Rules        β”‚         β”‚  β€’ Metrics      β”‚         β”‚  β€’ Reports      β”‚
          β”‚  β€’ Logs         β”‚         β”‚  β€’ Rate limits  β”‚         β”‚  β€’ Cleanup      β”‚
          β”‚  β€’ Config       β”‚         β”‚  β€’ Pub/Sub      β”‚         β”‚  β€’ Sync tasks   β”‚
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚                           β”‚                           β”‚
                    β–Ό                           β–Ό                           β–Ό
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚   Prometheus    β”‚         β”‚     Grafana     β”‚         β”‚  Alertmanager   β”‚
          β”‚    Metrics      β”‚         β”‚   Dashboards    β”‚         β”‚     Alerts      β”‚
          β”‚   Port: 9090    β”‚         β”‚   Port: 3001    β”‚         β”‚   Port: 9093    β”‚
          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

⚑ Quick Start (5 Minutes)

For experienced users who want to get up and running quickly:

Prerequisites

  • Docker 20.10+ & Docker Compose 2.0+
  • Git
  • 4GB RAM minimum

Step 1: Install Docker (if not installed)

curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker $USER
# Log out and back in

Step 2: Clone and Configure

git clone https://github.com/dwin-gharibi/parvahan.git.git
cd parvahan
cp .env.example .env
# Edit .env - change SECRET_KEY and POSTGRES_PASSWORD at minimum

Step 3: Start Services

docker compose up -d
docker compose exec parvahan-admin python manage.py migrate
docker compose exec parvahan-admin python manage.py init_data
docker compose exec parvahan-admin python manage.py createsuperuser

Step 4: Access

Service URL
Web Dashboard http://localhost
HTTP Proxy localhost:8080
SOCKS5 Proxy localhost:1080
API Docs http://localhost/api/docs/
Grafana http://localhost:3001 (admin/admin)

Test Proxy

curl -x http://localhost:8080 -U username:password http://example.com

πŸ“¦ Complete Installation Guide

1. Server Preparation

Minimum Requirements:

Resource Development Production
CPU 2 cores 4+ cores
RAM 4 GB 8+ GB
Storage 20 GB 50+ GB SSD
OS Ubuntu 22.04 LTS Ubuntu 22.04 LTS

Prepare the server:

# Update system
sudo apt update && sudo apt upgrade -y

# Install essential tools
sudo apt install -y curl git make

# Open firewall ports (if using ufw)
sudo ufw allow 80,443,1080,8080/tcp

2. Install Docker and Docker Compose

# Install Docker using official script
curl -fsSL https://get.docker.com | sh

# Add current user to docker group
sudo usermod -aG docker $USER

# Log out and back in, then verify
docker --version
docker compose version

3. Clone Repository

# Clone the repository
git clone https://github.com/dwin-gharibi/parvahan.git.git
cd parvahan

# For a specific version
git checkout v1.3.9

4. Configure Environment

# Copy example config
cp .env.example .env

# Edit configuration
nano .env

Essential variables to change:

# Security - MUST change these!
SECRET_KEY=your-random-50-character-string-here
POSTGRES_PASSWORD=strong-database-password

# Your domain/IP
ALLOWED_HOSTS=parvahan.example.com,localhost
SITE_URL=https://parvahan.example.com

# Production mode
DEBUG=False

# Optional: Email for notifications
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_HOST_USER=your-email@gmail.com
EMAIL_HOST_PASSWORD=your-app-password

Generate a secure SECRET_KEY:

openssl rand -base64 50

5. Start Services

For Development:

docker compose up -d

For Production:

docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d

6. Initialize Database

# Run database migrations
docker compose exec parvahan-admin python manage.py migrate

# Load initial data (roles, default settings)
docker compose exec parvahan-admin python manage.py init_data

# Create admin user
docker compose exec parvahan-admin python manage.py createsuperuser

7. Verify Installation

# Check all services are running
docker compose ps

# All should show "Up" status
# View logs if any service has issues
docker compose logs SERVICE_NAME

Verification Checklist:

  • Web UI loads at http://SERVER_IP
  • Can login with admin credentials
  • Dashboard displays (may show zeros initially)
  • Proxy test: curl -x http://SERVER_IP:8080 -U admin:password http://example.com

πŸ”¨ Building from Source

Development Prerequisites

# Python 3.10+
sudo apt install -y python3.10 python3.10-venv python3.10-dev

# Node.js 18+
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs

# PostgreSQL and Redis (or use Docker)
docker run -d --name postgres -e POSTGRES_PASSWORD=devpass -p 5432:5432 postgres:16
docker run -d --name redis -p 6379:6379 redis:7

Build Parvahan Core

cd parvahan-core

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Run directly
python main.py

# Or build Docker image
docker build -t parvahan-core:custom .

Build Parvahan Admin

cd parvahan-admin

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Set environment variables
export DATABASE_URL=postgresql://user:pass@localhost:5432/parvahan
export REDIS_URL=redis://localhost:6379/0

# Run migrations
cd proxy_manager
python manage.py migrate

# Run development server
python manage.py runserver 0.0.0.0:8099

# Run Celery worker (separate terminal)
celery -A config worker -l INFO

# Or build Docker image
cd ..
docker build -t parvahan-admin:custom .

Build Frontend (UI)

cd frontend

# Install dependencies
npm install

# Run development server
npm run dev

# Build for production
npm run build

# Or build Docker image
docker build -t parvahan-ui:custom .

Using Makefile

# Build all images
make build

# Build with Iranian mirrors
make build-iran

# Build specific service
make build-core
make build-admin
make build-ui

# Run tests
make test

# Run linting
make lint

# Clean up
make clean

# See all commands
make help

πŸš€ Deployment Methods

1. Docker Compose (Recommended for Small-Medium)

# Development
docker compose up -d

# Production
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d

# Scale proxy instances
docker compose up -d --scale parvahan-core=3

# View logs
docker compose logs -f

# Stop all
docker compose down

2. Kubernetes (Recommended for Large Scale)

# Using kubectl
kubectl apply -k kubernetes/base/

# Using Helm (if available)
helm install parvahan ./charts/parvahan -f values.yaml

# Check status
kubectl get pods -n parvahan

# Scale
kubectl scale deployment parvahan-core --replicas=5 -n parvahan

Kubernetes Features:

  • HorizontalPodAutoscaler for automatic scaling
  • PodDisruptionBudget for high availability
  • NetworkPolicy for security
  • ServiceMonitor for Prometheus integration

3. Bare Metal / VM

# Install systemd services
sudo cp scripts/systemd/*.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable parvahan-core parvahan-admin
sudo systemctl start parvahan-core parvahan-admin

4. Cloud Platforms

ArvanCloud (Iran):

# Push images to ArvanCloud registry
docker tag parvahan-core:latest cr.arvancloud.ir/your-repo/parvahan-core:latest
docker push cr.arvancloud.ir/your-repo/parvahan-core:latest

# Deploy using ArvanCloud Container Platform

Other Clouds: AWS ECS/EKS, Azure ACI/AKS, Google Cloud Run/GKE

5. Air-Gapped / Offline Installation

# On internet-connected machine: create bundle
./scripts/offline-bundle.sh create

# Transfer bundle to air-gapped server
# On air-gapped server: install
./scripts/offline-bundle.sh install

βš™οΈ Configuration Reference

Environment Variables

Variable Required Default Description
SECRET_KEY βœ… - Django secret key (50+ chars)
POSTGRES_PASSWORD βœ… - PostgreSQL password
POSTGRES_DB ❌ parvahan Database name
POSTGRES_USER ❌ parvahan Database user
REDIS_URL ❌ redis://redis:6379/0 Redis connection URL
ALLOWED_HOSTS βœ… - Comma-separated allowed hosts
SITE_URL βœ… - Full site URL
DEBUG ❌ False Debug mode (never True in production)
PARVAHAN_WORKERS ❌ 4 Number of async workers
PARVAHAN_PORT ❌ 1080 SOCKS5 proxy port
PARVAHAN_HTTP_PORT ❌ 8080 HTTP proxy port
PARVAHAN_CACHE_SIZE ❌ 100MB Response cache size
PARVAHAN_MAX_CONNECTIONS ❌ 10000 Max concurrent connections
PARVAHAN_TIMEOUT ❌ 30 Request timeout (seconds)
EMAIL_HOST ❌ - SMTP server
EMAIL_PORT ❌ 587 SMTP port
EMAIL_HOST_USER ❌ - SMTP username
EMAIL_HOST_PASSWORD ❌ - SMTP password

Parvahan Core Configuration

Additional settings in config.yaml:

proxy:
  http_port: 8080
  socks5_port: 1080
  https_port: 8442
  max_connections: 10000
  timeout: 30
  buffer_size: 65536

security:
  auth_required: true
  rate_limit_enabled: true
  rate_limit_requests: 1000
  rate_limit_window: 60
  geoip_enabled: true
  blocked_countries: []

cache:
  enabled: true
  size: 100MB
  ttl_default: 3600

dns:
  servers:
    - 1.1.1.1
    - 8.8.8.8
  doh_enabled: true
  cache_ttl: 300

logging:
  level: INFO
  format: json

⚑ Parvahan Core

The core proxy engine written in Python with asyncio for maximum performance.

Modules

Module Description
main.py Application entry point
proxy_server.py HTTP/HTTPS proxy implementation
socks5.py SOCKS5 protocol implementation
websocket.py WebSocket tunneling
security.py Security checks and filtering
security_monitor.py Threat detection and monitoring
content_filter.py Ad blocking, content filtering
honeypot.py Honeypot traps for attackers
traffic_intelligence.py AI-powered traffic analysis
smart_router.py ML-based routing decisions
dns_resolver.py DNS-over-HTTPS/TLS resolver
geo_routing.py Geographic-based routing
metrics_exporter.py Prometheus metrics
alerting.py Alert generation
realtime.py Real-time event streaming

Protocol Support

Protocol Port Features
HTTP Proxy 8080 Full HTTP/1.1, CONNECT method
HTTPS Proxy 8442 SSL termination, inspection (optional)
SOCKS5 1080 TCP/UDP, authentication, DNS
WebSocket 8080 Bidirectional tunneling

Metrics Exported

# Request metrics
parvahan_requests_total{method, status, protocol}
parvahan_request_duration_seconds{method, protocol}

# Connection metrics  
parvahan_active_connections{protocol}
parvahan_connections_total{protocol}

# Bandwidth
parvahan_bytes_total{direction}

# Cache
parvahan_cache_hits_total
parvahan_cache_hit_rate

# Security
parvahan_blocked_requests{reason}
parvahan_threats_detected{type}

🏒 Parvahan Admin

Django REST Framework backend providing the management API.

Django Apps

App Description
users User management, organizations, RBAC, MFA
proxy Access rules, blocklists, webhooks
monitoring Metrics, alerts, dashboards
logs Proxy logs, security events, exports

User Management

Roles:

  • Super Admin - Full system access
  • Organization Admin - Manage own organization
  • Operator - View dashboards, manage alerts
  • Viewer - Read-only access
  • User - Use proxy only

Features:

  • Multi-tenant organizations
  • Invitation system with email
  • Two-factor authentication (TOTP)
  • Session management
  • API keys for automation
  • Subscription and usage limits

Access Rules

Define granular control over traffic:

{
  "name": "Block Social Media",
  "pattern": "*.facebook.com,*.instagram.com,*.twitter.com",
  "pattern_type": "domain",
  "action": "block",
  "target_groups": ["employees"],
  "schedule": {
    "days": ["monday", "tuesday", "wednesday", "thursday", "friday"],
    "start_time": "09:00",
    "end_time": "17:00"
  },
  "priority": 10
}

Celery Tasks

Background tasks for:

  • Sending notification emails
  • Log cleanup and archival
  • Blocklist synchronization
  • Report generation
  • Usage alerts

πŸ’» Parvahan CLI

Command-line interface for automation and scripting.

Installation

# From PyPI
pip install parvahan-cli

# From source
cd cli
pip install -e .

# With Iranian mirror
pip install -i https://mirror.arvancloud.ir/pypi/simple parvahan-cli

Configuration

# Interactive setup
parvahan config init

# Manual configuration
parvahan config set server https://parvahan.example.com
parvahan config set username admin
parvahan config set token YOUR_API_TOKEN

Commands

# Server status
parvahan status

# User management
parvahan user list
parvahan user create --email user@example.com --name "John Doe"
parvahan user delete USER_ID

# Rules management
parvahan rule list
parvahan rule create --name "Block Ads" --pattern "*.doubleclick.net"
parvahan rule test --url "https://ads.google.com/banner"

# Logs
parvahan log proxy --since 1h --user john
parvahan log security --level critical
parvahan log export --format csv --output report.csv

# Monitoring
parvahan monitor dashboard    # Terminal dashboard
parvahan monitor top          # Top URLs
parvahan monitor live         # Live request stream

# Configuration
parvahan config show
parvahan config set KEY VALUE

Automation Examples

# Daily report cron job
0 8 * * * parvahan log export --since yesterday --format csv | mail -s "Daily Report" admin@example.com

# Bulk user import
parvahan user import --file users.csv

# CI/CD integration
parvahan rule sync --file rules.yaml
parvahan cache clear

πŸ”Œ API Documentation

Authentication

JWT Authentication:

# Get tokens
curl -X POST http://localhost/api/v1/auth/token/ \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "password"}'

# Use access token
curl http://localhost/api/v1/users/ \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

# Refresh token
curl -X POST http://localhost/api/v1/auth/token/refresh/ \
  -d '{"refresh": "YOUR_REFRESH_TOKEN"}'

API Key:

curl http://localhost/api/v1/users/ \
  -H "X-API-Key: YOUR_API_KEY"

Key Endpoints

Method Endpoint Description
GET /api/v1/users/ List users
POST /api/v1/users/ Create user
GET /api/v1/organizations/ List organizations
GET /api/v1/proxy/rules/ List access rules
POST /api/v1/proxy/rules/ Create access rule
POST /api/v1/proxy/rules/test/ Test URL against rules
GET /api/v1/monitoring/dashboard/ Dashboard metrics
GET /api/v1/logs/proxy/ Proxy logs
GET /api/v1/logs/security/ Security events
POST /api/v1/logs/export/ Create log export job

Interactive Documentation


πŸ”’ Security Features

Security Layers

  1. Network Firewall - IP filtering, GeoIP blocking
  2. Rate Limiting - Request throttling per IP/user
  3. Authentication - Multi-method auth with MFA
  4. Authorization - RBAC with fine-grained permissions
  5. Encryption - TLS 1.2/1.3, AES-256 at rest
  6. Monitoring - IDS/IPS with automated response

Threat Detection

Threat Type Detection Method Response
DDoS Traffic pattern analysis Rate limit + challenge
Brute Force Failed login tracking Account lock + CAPTCHA
SQL Injection Payload analysis Block + alert
XSS Content inspection Sanitize + block
Bot Traffic Fingerprinting CAPTCHA + rate limit
Credential Stuffing Login pattern analysis 2FA enforcement

Honeypot System

Trap attackers with fake vulnerable services:

  • /admin/ fake admin panel
  • /wp-admin/ WordPress trap
  • Fake API endpoints
  • Database interface traps

🧠 AI & Machine Learning

Models

Model Algorithm Purpose
Anomaly Detection Isolation Forest Detect unusual patterns
Threat Classification Neural Network Classify threat types
Risk Scoring Ensemble Calculate request risk
Load Prediction Time Series Forecast traffic
Smart Routing Reinforcement Learning Optimize path selection

User Behavior Analytics (UBA)

Creates behavioral baselines for each user:

  • Activity time patterns
  • Geographic locations
  • Traffic volume patterns
  • Content preferences
  • Device fingerprints

Detects deviations indicating compromise or abuse.

Continuous Learning

Models improve automatically:

  • Online learning with each request
  • Batch retraining on accumulated data
  • Admin feedback loop for false positives

πŸ“Š Monitoring & Alerting

Prometheus Metrics

All metrics available at /metrics:

parvahan_requests_total
parvahan_request_duration_seconds
parvahan_active_connections
parvahan_bytes_total
parvahan_cache_hits_total
parvahan_blocked_requests
parvahan_threats_detected
parvahan_auth_failures

Grafana Dashboards

Pre-configured dashboards:

  • Overview - Key metrics at a glance
  • Performance - Latency, throughput, errors
  • Security - Threats, blocks, attacks
  • Users - Active users, top consumers
  • Infrastructure - CPU, memory, disk

Alert Channels

Channel Configuration
Email SMTP settings
Slack Webhook URL
MS Teams Connector URL
PagerDuty Integration key
Webhook Custom HTTP endpoint
SMS SMS gateway API

Alert Rules Examples

# High error rate
- name: HighErrorRate
  condition: error_rate > 5%
  duration: 5m
  severity: critical
  
# DDoS detection
- name: PossibleDDoS
  condition: requests_per_second > 10000 AND unique_ips < 100
  duration: 1m
  severity: critical

πŸ”§ Troubleshooting Guide

Installation Issues

Problem Cause Solution
Images won't download No Docker Hub access Configure Iranian mirrors
Service crashes on start Insufficient memory Increase RAM or reduce limits
Port already in use Conflict with other service Change port or stop conflicting service
Database connection failed Wrong credentials or DB not ready Check DATABASE_URL, wait for postgres

Proxy Issues

Problem Cause Solution
Can't connect to proxy Service not running docker compose ps, restart if needed
407 Authentication error Wrong credentials Verify username/password
Some sites blocked Access rules Check rules in admin panel
Slow performance Resource constraints Scale horizontally, enable caching

UI Issues

Problem Cause Solution
Login fails API connection issue Check NEXT_PUBLIC_API_URL
Dashboard shows zeros No traffic yet Generate some proxy traffic
CORS errors Misconfigured CORS Add domain to CORS_ALLOWED_ORIGINS

Debug Commands

# Check service status
docker compose ps

# View logs
docker compose logs -f SERVICE_NAME

# Enter container shell
docker compose exec parvahan-admin bash

# Check database connection
docker compose exec parvahan-admin python manage.py dbshell

# Check Redis connection
docker compose exec redis redis-cli ping

# Test proxy connectivity
curl -v -x http://localhost:8080 http://example.com

🀝 Contributing

We welcome contributions! Please see our contributing guidelines.

Development Setup

# Clone repo
git clone https://github.com/dwin-gharibi/parvahan.git.git
cd parvahan

# Create branches
git checkout -b feature/your-feature

# Make changes, then
git add .
git commit -m "Add your feature"
git push origin feature/your-feature

Code Standards

  • Python: Follow PEP 8, use Black formatter
  • JavaScript: ESLint + Prettier
  • Commits: Conventional Commits format
  • Tests: Required for new features

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


🏠 Home β€’ πŸ“– Docs β€’ πŸ› Issues β€’ πŸ’¬ Discussions


Made with ❀️ by the Dwin Gharibi

ΩΎΩŽΨ±ΩˆΩŽΩ‡Ψ§Ω† - Ω†Ϊ―Ω‡Ψ¨Ψ§Ω† Ω‡ΩˆΨ΄Ω…Ω†Ψ― Ψ΄Ψ¨Ϊ©Ω‡ Ψ΄Ω…Ψ§

Parvahan - Your Network's Intelligent Guardian

About

Parvahan is a comprehensive, enterprise-grade proxy management platform designed to provide organizations with complete control over their network traffic. Built entirely from scratch using Python's asyncio framework, Parvahan offers unmatched performance, security, and flexibility.

Topics

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors