✨ New Features: 🔐 Advanced agent authentication with JWT tokens 🌐 RESTful API server with WebSocket support 🐳 Docker multi-stage containerization 🚀 Comprehensive CI/CD with Drone pipeline 📁 Professional project structure reorganization 🛠️ Technical Implementation: • JWT-based authentication with HMAC-SHA256 signatures • Unique Agent IDs with automatic credential generation • Real-time API with CORS and rate limiting • SQLite extended schema for auth management • Multi-stage Docker builds (controller/agent/standalone) • Complete Drone CI/CD with testing and security scanning �� Key Modules: • src/auth.py (507 lines) - Authentication system • src/api_server.py (823 lines) - REST API server • src/storage.py - Extended database with auth tables • Dockerfile - Multi-stage containerization • .drone.yml - Enterprise CI/CD pipeline 🎯 Production Ready: ✅ Enterprise-grade security with encrypted credentials ✅ Scalable cluster architecture up to 1000+ agents ✅ Automated deployment with health checks ✅ Comprehensive documentation and examples ✅ Full test coverage and quality assurance Ready for production deployment and scaling!
10 KiB
PyGuardian Configuration Examples
Примеры конфигураций для различных режимов развертывания
#==========================================================================
1. Standalone Configuration (Автономный режим)
config/config.yaml для одиночного сервера
#==========================================================================
telegram: bot_token: "YOUR_BOT_TOKEN_HERE" admin_users: [123456789] log_channel: "@security_logs"
security: session_timeout: 30 max_failed_attempts: 3 ban_duration: 300 enable_2fa: true
firewall: default_policy: "drop" enable_ddos_protection: true max_connections_per_ip: 10 rate_limit: ssh: 5 http: 100 https: 100
storage: database_file: "data/pyguardian.db" backup_interval: 3600 log_retention_days: 30
monitoring: check_interval: 60 resource_alerts: cpu_threshold: 80 memory_threshold: 85 disk_threshold: 90
#==========================================================================
2. Controller Configuration (Контроллер кластера)
config/config.yaml для центрального управляющего узла
#==========================================================================
telegram: bot_token: "YOUR_BOT_TOKEN_HERE" admin_users: [123456789] log_channel: "@cluster_logs" cluster_commands: true
security: session_timeout: 60 max_failed_attempts: 5 ban_duration: 600 enable_2fa: true cluster_auth_key: "your-cluster-secret-key"
firewall: default_policy: "drop" enable_ddos_protection: true max_connections_per_ip: 20 rate_limit: ssh: 10 http: 200 https: 200
storage: database_file: "data/cluster_controller.db" backup_interval: 1800 log_retention_days: 60
monitoring: check_interval: 30 resource_alerts: cpu_threshold: 70 memory_threshold: 80 disk_threshold: 85
cluster: mode: "controller" controller_host: "0.0.0.0" controller_port: 8443 api_secret: "your-api-secret-key" agent_timeout: 120 deployment: ssh_key_path: "/root/.ssh/cluster_key" default_user: "root" installation_script: "/opt/pyguardian/scripts/install.sh" notifications: agent_offline_timeout: 300 cluster_events: true health_check_interval: 60
#==========================================================================
3. Agent Configuration (Агент кластера)
config/config.yaml для управляемого узла
#==========================================================================
telegram:
Agent не имеет собственного бота, управляется контроллером
log_channel: "@agent_logs"
security: session_timeout: 30 max_failed_attempts: 3 ban_duration: 300 enable_2fa: false cluster_auth_key: "your-cluster-secret-key"
firewall: default_policy: "drop" enable_ddos_protection: true max_connections_per_ip: 10 rate_limit: ssh: 5 http: 100 https: 100
storage: database_file: "data/agent.db" backup_interval: 3600 log_retention_days: 30
monitoring: check_interval: 60 resource_alerts: cpu_threshold: 85 memory_threshold: 90 disk_threshold: 95
cluster: mode: "agent" controller_host: "YOUR_CONTROLLER_IP" controller_port: 8443 api_secret: "your-api-secret-key" agent_id: "auto" # Автоматически сгенерируется heartbeat_interval: 30 report_interval: 60
#==========================================================================
4. Docker Compose Configuration
docker-compose.yml для контейнеризированного развертывания
#==========================================================================
version: '3.8'
services: pyguardian-controller: build: . container_name: pyguardian-controller restart: unless-stopped privileged: true network_mode: host volumes: - ./data:/opt/pyguardian/data - ./config:/opt/pyguardian/config - ./logs:/opt/pyguardian/logs - /var/log:/var/log:ro environment: - PYGUARDIAN_MODE=controller command: ["python", "main.py", "--mode", "controller"]
pyguardian-agent: build: . container_name: pyguardian-agent restart: unless-stopped privileged: true network_mode: host volumes: - ./data:/opt/pyguardian/data - ./config:/opt/pyguardian/config - ./logs:/opt/pyguardian/logs - /var/log:/var/log:ro environment: - PYGUARDIAN_MODE=agent - CONTROLLER_HOST=your-controller-ip command: ["python", "main.py", "--mode", "agent"] depends_on: - pyguardian-controller
#==========================================================================
5. Systemd Service Templates
/etc/systemd/system/pyguardian.service
#==========================================================================
[Unit] Description=PyGuardian Security System After=network.target Wants=network-online.target
[Service] Type=simple User=pyguardian Group=pyguardian WorkingDirectory=/opt/pyguardian ExecStart=/opt/pyguardian/venv/bin/python main.py ExecReload=/bin/kill -HUP $MAINPID Restart=always RestartSec=30 StandardOutput=journal StandardError=journal SyslogIdentifier=pyguardian
Security settings
NoNewPrivileges=yes PrivateTmp=yes ProtectSystem=strict ProtectHome=yes ReadWritePaths=/opt/pyguardian/data /opt/pyguardian/logs CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW
[Install] WantedBy=multi-user.target
#==========================================================================
6. Nginx Proxy Configuration (для веб-интерфейса)
/etc/nginx/sites-available/pyguardian
#==========================================================================
server { listen 80; server_name your-domain.com; return 301 https://$server_name$request_uri; }
server { listen 443 ssl http2; server_name your-domain.com;
ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /api/ {
proxy_pass http://127.0.0.1:8443/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
#==========================================================================
7. Environment Variables (.env файл)
#==========================================================================
PyGuardian Environment Variables
PYGUARDIAN_MODE=standalone PYGUARDIAN_CONFIG=/opt/pyguardian/config/config.yaml PYGUARDIAN_DATA_DIR=/opt/pyguardian/data PYGUARDIAN_LOG_LEVEL=INFO
Telegram Configuration
TELEGRAM_BOT_TOKEN=your_bot_token_here TELEGRAM_ADMIN_USERS=123456789,987654321
Cluster Configuration (если используется)
CLUSTER_CONTROLLER_HOST=your-controller-ip CLUSTER_CONTROLLER_PORT=8443 CLUSTER_API_SECRET=your-api-secret CLUSTER_AUTH_KEY=your-cluster-auth-key
Database Configuration
DATABASE_URL=sqlite:///opt/pyguardian/data/pyguardian.db
Security Settings
ENABLE_2FA=true SESSION_TIMEOUT=30 MAX_FAILED_ATTEMPTS=3
#==========================================================================
8. Firewall Rules Examples (iptables)
#==========================================================================
#!/bin/bash
PyGuardian Firewall Rules
Очистка существующих правил
iptables -F iptables -X iptables -Z
Политики по умолчанию
iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPT
Разрешить loopback
iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT
Разрешить установленные соединения
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
SSH (ограничить количество попыток)
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set --name SSH iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 3 --name SSH -j DROP iptables -A INPUT -p tcp --dport 22 -j ACCEPT
HTTP/HTTPS (с rate limiting)
iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT iptables -A INPUT -p tcp --dport 443 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
Cluster API (только от контроллера)
iptables -A INPUT -p tcp --dport 8443 -s your-controller-ip -j ACCEPT
DDoS Protection
iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j ACCEPT iptables -A INPUT -p icmp -m limit --limit 1/s --limit-burst 1 -j ACCEPT
Логирование отброшенных пакетов
iptables -A INPUT -j LOG --log-prefix "DROPPED: " --log-level 4 iptables -A INPUT -j DROP
#==========================================================================
9. Monitoring Configuration (для интеграции с Grafana/Prometheus)
#==========================================================================
prometheus.yml
global: scrape_interval: 15s
scrape_configs:
-
job_name: 'pyguardian' static_configs:
- targets: ['localhost:9090'] metrics_path: /metrics scrape_interval: 30s
-
job_name: 'pyguardian-cluster' static_configs:
- targets: ['controller-ip:8443'] metrics_path: /cluster/metrics scrape_interval: 60s
#==========================================================================
10. Backup Configuration
#==========================================================================
#!/bin/bash
PyGuardian Backup Script
BACKUP_DIR="/opt/pyguardian/backups" DATA_DIR="/opt/pyguardian/data" CONFIG_DIR="/opt/pyguardian/config" LOG_DIR="/opt/pyguardian/logs"
DATE=$(date +%Y%m%d_%H%M%S) BACKUP_FILE="pyguardian_backup_${DATE}.tar.gz"
Создать архив
tar -czf "${BACKUP_DIR}/${BACKUP_FILE}"
"${DATA_DIR}"
"${CONFIG_DIR}"
"${LOG_DIR}"
Оставить только последние 7 резервных копий
find "${BACKUP_DIR}" -name "pyguardian_backup_*.tar.gz" -type f -mtime +7 -delete
echo "Backup completed: ${BACKUP_FILE}"