# Security Hardening Guide

## Overview

This guide covers security hardening for Torrent Gateway deployments, including authentication, authorization, network security, and operational security practices.

## Application Security

### Authentication & Authorization

**API Key Management:**
- Generate strong API keys with sufficient entropy
- Rotate API keys regularly (recommended: every 90 days)
- Store API keys securely (avoid environment variables in production)
- Implement API key scope limitations

**Session Security:**
```bash
# Verify session configuration
sqlite3 data/metadata.db "SELECT * FROM sessions WHERE expires_at > datetime('now');"

# Clean expired sessions
./scripts/migrate.sh  # Includes session cleanup
```

**Access Control:**
- Implement role-based access control (RBAC)
- Separate admin and user permissions
- Use principle of least privilege
- Regular access audits

### Input Validation

**File Upload Security:**
- File type validation (whitelist approach)
- File size limits (configurable per user/role)
- Filename sanitization
- Virus scanning integration (recommended)

**API Input Validation:**
- Validate all JSON inputs
- Sanitize file paths
- Validate authentication tokens
- Rate limiting per endpoint

### Cryptographic Security

**Hashing:**
- Use strong hashing algorithms (SHA-256 minimum)
- Implement salt for password hashing
- Verify file integrity with checksums

**Data Encryption:**
```bash
# Encrypt sensitive data at rest
# Configure in environment variables
export ENCRYPTION_KEY=$(openssl rand -hex 32)
export DB_ENCRYPTION=true
```

## Network Security

### Firewall Configuration

**UFW Setup:**
```bash
# Reset firewall rules
sudo ufw --force reset

# Default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow essential services
sudo ufw allow ssh
sudo ufw allow 80/tcp    # HTTP
sudo ufw allow 443/tcp   # HTTPS

# Monitoring (localhost only)
sudo ufw allow from 127.0.0.1 to any port 9090  # Prometheus
sudo ufw allow from 127.0.0.1 to any port 3000  # Grafana

# Enable firewall
sudo ufw enable
```

**iptables Rules (advanced):**
```bash
# Block common attack patterns
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

# Block brute force attempts
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
```

### SSL/TLS Configuration

**Nginx SSL Setup:**
```nginx
server {
    listen 443 ssl http2;
    server_name yourdomain.com;
    
    # SSL certificates
    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    
    # SSL configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # Security headers
    add_header Strict-Transport-Security "max-age=63072000" always;
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options DENY;
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy "strict-origin-when-cross-origin";
    
    # CSP header
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'";
    
    location / {
        proxy_pass http://127.0.0.1:9876;
        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;
    }
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    server_name yourdomain.com;
    return 301 https://$server_name$request_uri;
}
```

### Rate Limiting

**Nginx Rate Limiting:**
```nginx
http {
    # Define rate limiting zones
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=upload:10m rate=1r/s;
    limit_req_zone $binary_remote_addr zone=download:10m rate=5r/s;
    
    server {
        # Apply rate limits
        location /api/upload {
            limit_req zone=upload burst=5 nodelay;
            proxy_pass http://torrent_gateway;
        }
        
        location /api/download {
            limit_req zone=download burst=10 nodelay;
            proxy_pass http://torrent_gateway;
        }
        
        location /api/ {
            limit_req zone=api burst=20 nodelay;
            proxy_pass http://torrent_gateway;
        }
    }
}
```

**Application-Level Rate Limiting:**
Configure in gateway environment:
```bash
export RATE_LIMIT_UPLOAD=10/minute
export RATE_LIMIT_DOWNLOAD=100/minute
export RATE_LIMIT_API=1000/minute
```

## System Security

### User and Permission Security

**Service Account Security:**
```bash
# Verify service user configuration
id torrent-gateway
groups torrent-gateway

# Check file permissions
ls -la /opt/torrent-gateway/
ls -la /opt/torrent-gateway/data/

# Verify no shell access
grep torrent-gateway /etc/passwd
```

**File System Permissions:**
```bash
# Secure sensitive files
chmod 600 /opt/torrent-gateway/configs/*.yml
chmod 700 /opt/torrent-gateway/data/
chmod 755 /opt/torrent-gateway/scripts/*.sh

# Regular permission audit
find /opt/torrent-gateway/ -type f -perm /o+w -ls
```

### Log Security

**Secure Log Configuration:**
```bash
# Configure logrotate for security
cat > /etc/logrotate.d/torrent-gateway << 'EOF'
/opt/torrent-gateway/logs/*.log {
    daily
    missingok
    rotate 90
    compress
    delaycompress
    notifempty
    copytruncate
    su torrent-gateway torrent-gateway
    create 640 torrent-gateway torrent-gateway
}
EOF
```

**Log Monitoring:**
```bash
# Monitor for security events
journalctl -u torrent-gateway | grep -E "(failed|error|denied|unauthorized)"

# Setup log monitoring alerts
# Add to monitoring configuration
```

### System Hardening

**SSH Security:**
```bash
# Disable root login
sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config

# Disable password authentication (use keys only)
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config

# Change default SSH port
sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config

systemctl restart ssh
```

**Kernel Security:**
```bash
# Enable kernel security features
cat >> /etc/sysctl.conf << 'EOF'
# Network security
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.log_martians = 1

# Memory protection
kernel.exec-shield = 1
kernel.randomize_va_space = 2
EOF

sysctl -p
```

## Monitoring and Alerting

### Security Monitoring

**Failed Authentication Attempts:**
```bash
# Monitor auth failures
journalctl -u torrent-gateway | grep "authentication failed"

# Setup alert for repeated failures
# Add to Prometheus alerting rules
```

**Suspicious Activity Detection:**
```promql
# High error rates
rate(http_requests_total{status=~"4.."}[5m]) > 0.1

# Unusual upload patterns
rate(upload_requests_total[1h]) > 100

# Large file downloads
rate(download_bytes_total[5m]) > 100000000  # 100MB/s
```

### Security Alerts

**Critical Security Events:**
- Multiple authentication failures
- Unusual traffic patterns
- File system permission changes
- Service account login attempts
- Database integrity check failures

**AlertManager Configuration:**
```yaml
# In configs/alertmanager.yml
route:
  routes:
  - match:
      severity: critical
      team: security
    receiver: 'security-team'

receivers:
- name: 'security-team'
  slack_configs:
  - api_url: 'YOUR_SLACK_WEBHOOK'
    channel: '#security-alerts'
    title: 'Security Alert'
    text: '{{ range .Alerts }}{{ .Annotations.summary }}{{ end }}'
```

## Vulnerability Management

### Regular Security Updates

**System Updates:**
```bash
# Automated security updates
apt-get install unattended-upgrades
dpkg-reconfigure unattended-upgrades

# Manual update process
apt-get update
apt-get upgrade
apt-get autoremove
```

**Application Dependencies:**
```bash
# Go module security scanning
go list -m all | nancy sleuth

# Check for known vulnerabilities
go mod download
govulncheck ./...
```

### Security Scanning

**Static Analysis:**
```bash
# Run security scanner
gosec ./...

# Check for hardcoded secrets
git secrets --scan

# Dependency vulnerability scan
snyk test
```

**Container Security (if using Docker):**
```bash
# Scan Docker images
docker scan torrent-gateway:latest

# Check container configuration
docker-bench-security
```

## Incident Response

### Security Incident Procedures

**Immediate Response:**
1. **Isolate affected systems**
2. **Preserve evidence**
3. **Assess damage scope**
4. **Implement containment**
5. **Begin recovery**

**Evidence Collection:**
```bash
# Collect system state
ps aux > incident_processes.txt
netstat -tulpn > incident_network.txt
ls -la /opt/torrent-gateway/ > incident_files.txt

# Collect logs
journalctl -u torrent-gateway --since "1 hour ago" > incident_app_logs.txt
tail -1000 /var/log/auth.log > incident_auth_logs.txt
tail -1000 /var/log/nginx/access.log > incident_access_logs.txt
```

### Forensic Analysis

**Database Forensics:**
```bash
# Check for unauthorized data access
sqlite3 data/metadata.db "
SELECT * FROM files 
WHERE last_access > datetime('now', '-1 hour')
ORDER BY last_access DESC;
"

# Check for unauthorized user creation
sqlite3 data/metadata.db "
SELECT * FROM users 
WHERE created_at > datetime('now', '-1 day')
ORDER BY created_at DESC;
"
```

**File System Analysis:**
```bash
# Check for recently modified files
find /opt/torrent-gateway/ -type f -mtime -1 -ls

# Check for unauthorized executables
find /opt/torrent-gateway/ -type f -executable -ls
```

## Compliance and Auditing

### Audit Logging

**Enable comprehensive logging:**
```bash
# Application audit logs
export AUDIT_LOG_ENABLED=true
export AUDIT_LOG_LEVEL=detailed

# System audit logs (auditd)
apt-get install auditd
systemctl enable auditd
systemctl start auditd
```

**Log Analysis:**
```bash
# Search for security events
journalctl -u torrent-gateway | grep -E "(authentication|authorization|failed|denied)"

# Generate audit reports
./scripts/generate_audit_report.sh
```

### Security Checklist

**Daily:**
- [ ] Review security alerts
- [ ] Check authentication logs
- [ ] Verify backup completion
- [ ] Monitor resource usage

**Weekly:**
- [ ] Review access logs
- [ ] Check for failed login attempts
- [ ] Verify firewall rules
- [ ] Update security patches

**Monthly:**
- [ ] Rotate API keys
- [ ] Review user access
- [ ] Security scan
- [ ] Backup restoration test
- [ ] Vulnerability assessment

**Quarterly:**
- [ ] Security architecture review
- [ ] Penetration testing
- [ ] Incident response drill
- [ ] Security training update

## Emergency Security Procedures

### Suspected Breach

**Immediate Actions:**
```bash
# 1. Isolate system
sudo ufw deny incoming

# 2. Stop services
sudo systemctl stop torrent-gateway
sudo systemctl stop nginx

# 3. Create forensic backup
sudo ./scripts/backup.sh forensic_$(date +%Y%m%d_%H%M%S)

# 4. Preserve logs
sudo cp -r /var/log /tmp/incident_logs_$(date +%Y%m%d_%H%M%S)
```

### Compromised Credentials

**API Key Compromise:**
```bash
# 1. Revoke compromised keys
# (Implement key revocation in application)

# 2. Force re-authentication
sqlite3 data/metadata.db "DELETE FROM sessions;"

# 3. Generate new keys
# (Application-specific procedure)

# 4. Notify affected users
# (Implement notification system)
```

### System Recovery After Incident

**Clean Recovery Process:**
1. **Verify threat elimination**
2. **Restore from clean backup**
3. **Apply security patches**
4. **Implement additional controls**
5. **Monitor for recurring issues**

```bash
# Recovery script
sudo ./scripts/restore.sh <pre_incident_backup>
sudo ./scripts/install_native.sh --skip-build
sudo ./scripts/health_check.sh
```