Files
ping_service/manager/SECURITY.md
2026-01-08 12:11:26 +02:00

11 KiB

Security Checklist for Internet-Exposed Deployment

This manager application is hardened for direct internet exposure without a reverse proxy. This document summarizes the security measures implemented and provides a deployment checklist.

Built-in Security Features

Application-Level Security

Feature Implementation Status
Two-Factor Authentication TOTP (RFC 6238) with QR code enrollment Active
Encrypted Storage AES-256-GCM double encryption (Server Key + User Key) Active
Secure Sessions Encrypted session IDs, HttpOnly, Secure, SameSite=Strict cookies Active
Session Expiration 1 hour for authenticated sessions, 5 minutes for temp sessions Active
Rate Limiting 10/min auth endpoints, 100/min API endpoints (per IP) Active
Input Validation Length checks, null byte protection, sanitization Active
Security Headers HSTS, CSP, X-Frame-Options, X-Content-Type-Options, etc. Active
TLS 1.2+ Only Strong cipher suites (ECDHE + AES-GCM/ChaCha20) Active
DoS Protection Timeouts, size limits, slowloris protection Active
Security Logging AUTH_FAILURE and RATE_LIMIT_EXCEEDED with source IP Active
Gateway API Keys 256-bit keys, encrypted storage, Bearer token auth (optional) ⚙️ Optional

🔒 Encryption Details

User Data Encryption (Double Layer):

  1. Server Key: 32-byte AES key encrypts entire user database file
  2. User Key: Derived from User ID + Server Key via PBKDF2, encrypts individual TOTP secrets

Session Security:

  • Session IDs generated with nanosecond timestamp
  • Encrypted with Server Key before storing in cookie
  • Cookie flags: HttpOnly, Secure, SameSite=Strict

TLS Configuration:

  • Minimum: TLS 1.2
  • Cipher suites: ECDHE_ECDSA/RSA with AES_GCM and ChaCha20_Poly1305
  • Perfect Forward Secrecy (PFS) guaranteed

API Key Security (Gateway Mode):

  • 256-bit cryptographically secure random keys
  • Encrypted storage with Server Key (AES-256-GCM)
  • Bearer token authentication (OAuth 2.0 standard)
  • Usage tracking (request count, last used timestamp)
  • Instant revocation capability

🛡️ Attack Protection

Attack Type Protection Mechanism
Brute Force Rate limiting (10/min) + fail2ban integration
Slowloris ReadHeaderTimeout (5s), ReadTimeout (15s)
Large Payloads Request body limit (10MB), MaxHeaderBytes (1MB)
XSS Content-Security-Policy header, input validation
CSRF SameSite=Strict cookies
Clickjacking X-Frame-Options: DENY
MIME Sniffing X-Content-Type-Options: nosniff
SQL Injection N/A (no SQL database, uses encrypted file storage)
Command Injection Input validation, no shell execution of user input
Null Byte Injection Explicit null byte checking in validation

Production Deployment Checklist

Before First Run

  • Generate SERVER_KEY: On first run, save the generated key to environment

    export SERVER_KEY="base64-encoded-32-byte-key"
    
  • Create Admin User: Add initial user with TOTP

    ./manager --add-user=admin
    # Scan QR code with authenticator app
    
  • Configure Environment Variables:

    export SERVER_KEY="your-key-here"
    export DYFI_DOMAIN="example.dy.fi"
    export DYFI_USER="your-email@example.com"
    export DYFI_PASS="your-password"
    export ACME_EMAIL="admin@example.com"
    export LOG_FILE="/var/log/twostepauth.log"
    

Firewall Configuration

  • Open Ports:

    • Port 443 (HTTPS)
    • Port 80 (Let's Encrypt HTTP-01 challenge only)
  • Install fail2ban:

    apt-get install fail2ban
    
  • Configure fail2ban Filter (/etc/fail2ban/filter.d/twostepauth.conf):

    [Definition]
    failregex = AUTH_FAILURE: .* from IP <HOST>
                RATE_LIMIT_EXCEEDED: .* from IP <HOST>
                API_KEY_INVALID: .* from IP <HOST>
                API_KEY_MISSING: .* from IP <HOST>
    ignoreregex =
    
  • Configure fail2ban Jail (/etc/fail2ban/jail.d/twostepauth.local):

    [twostepauth]
    enabled  = true
    port     = 80,443
    filter   = twostepauth
    logpath  = /var/log/twostepauth.log
    maxretry = 5
    bantime  = 3600
    findtime = 600
    
  • Restart fail2ban:

    systemctl restart fail2ban
    systemctl status fail2ban
    

DNS Configuration (dy.fi)

  • Register domain at https://www.dy.fi/
  • Note your dy.fi credentials
  • Configure environment variables (DYFI_DOMAIN, DYFI_USER, DYFI_PASS)
  • Manager will automatically update DNS every 20 hours

TLS Certificate

Option A: Let's Encrypt (Production)

  • Ensure ports 80 and 443 are open
  • Run with domain flag:
    sudo ./manager --port=443 --domain=example.dy.fi
    
  • Certificates will be automatically obtained and renewed

Option B: Self-Signed (Development/Internal)

  • Run without domain flag:
    ./manager --port=8080
    
  • Accept self-signed certificate warning in browser

Gateway Mode (Optional)

If you need to support external ping workers outside your network:

  • Enable Gateway: Add --enable-gateway flag when starting manager
    sudo ./manager --port=443 --domain=example.dy.fi --enable-gateway
    
  • Register Internal Workers: Add input/output services to dashboard
  • Generate API Keys: Create keys for each external ping worker
  • Secure API Keys: Store keys in environment variables, not in code
  • Monitor Usage: Regularly check /api/apikeys/list for unusual activity
  • Rotate Keys: Rotate API keys periodically (recommended: every 90 days)
  • Revoke Unused: Remove keys for decommissioned workers

See GATEWAY.md for detailed setup instructions.

Running as Systemd Service

Create /etc/systemd/system/ping-manager.service:

[Unit]
Description=Ping Service Manager
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/ping_service/manager
Environment="SERVER_KEY=your-key-here"
Environment="DYFI_DOMAIN=example.dy.fi"
Environment="DYFI_USER=your-email@example.com"
Environment="DYFI_PASS=your-password"
Environment="ACME_EMAIL=admin@example.com"
Environment="LOG_FILE=/var/log/twostepauth.log"
ExecStart=/opt/ping_service/manager/manager --port=443 --domain=example.dy.fi --enable-gateway
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Enable and start:

systemctl daemon-reload
systemctl enable ping-manager
systemctl start ping-manager
systemctl status ping-manager

Monitoring

  • Check Logs:

    tail -f /var/log/twostepauth.log
    
  • Monitor fail2ban:

    fail2ban-client status twostepauth
    
  • Health Endpoint: Verify /health responds:

    curl https://example.dy.fi/health
    # Should return: {"status":"healthy"}
    
  • dy.fi Failover: Check logs for DNS pointer status (ACTIVE/STANDBY/FAILOVER)

Security Best Practices

User Management

  • Use strong, unique User IDs (avoid common names like "admin", "root")
  • Backup TOTP secret or print QR code in case device is lost
  • Regularly rotate SERVER_KEY and regenerate user TOTP secrets
  • Remove unused user accounts promptly

Server Hardening

  • Keep Go and system packages up to date
  • Run as non-root user when possible (except for port 443 binding)
  • Use dedicated server/VM for the manager (isolation)
  • Enable automatic security updates
  • Regular backups of users_data and workers_data.json

Network Security

  • Use fail2ban to block repeat offenders
  • Consider additional firewall rules (e.g., geographic restrictions)
  • Monitor logs for unusual patterns
  • Set up alerts for AUTH_FAILURE spikes

Application Updates

  • Monitor this repository for security updates
  • Test updates in staging environment first
  • Have rollback plan ready
  • Review CHANGELOG for security-related changes

Security Audit Results

Common Vulnerabilities (OWASP Top 10)

Vulnerability Risk Mitigation
A01: Broken Access Control Low TOTP 2FA, encrypted sessions, auth checks on all endpoints
A02: Cryptographic Failures Low TLS 1.2+, AES-256-GCM, strong ciphers, HSTS enabled
A03: Injection Low Input validation, no SQL/command execution of user input
A04: Insecure Design Low Defense in depth: rate limiting + fail2ban + input validation
A05: Security Misconfiguration Low Secure defaults, security headers, minimal attack surface
A06: Vulnerable Components ⚠️ Medium Keep dependencies updated (Go, autocert, otp libraries)
A07: Authentication Failures Low TOTP 2FA, rate limiting, fail2ban, secure session management
A08: Software/Data Integrity Low TLS for all communication, encrypted storage
A09: Logging/Monitoring Failures Low Comprehensive security logging, fail2ban integration
A10: SSRF Low No user-controlled URL fetching (REST client is admin-only)

Optional Enhancements (not required, but can improve security):

  1. Geographic Restrictions: Use iptables or ufw to block regions you don't operate in
  2. Port Knocking: Hide port 443 behind port knocking sequence
  3. VPN Access: Require VPN connection for dashboard access
  4. IP Whitelist: Restrict admin access to known IPs only
  5. Alert System: Set up email/Telegram alerts for AUTH_FAILURE events
  6. Backup Encryption: Encrypt backup files of users_data
  7. Audit Logging: Log all worker registration/removal events
  8. Multi-User Support: Add role-based access control (RBAC) for team access

Incident Response

If you suspect a security breach:

  1. Immediate Actions:

    • Check fail2ban status: fail2ban-client status twostepauth
    • Review logs: grep AUTH_FAILURE /var/log/twostepauth.log
    • Check active sessions: Restart service to clear all sessions
    • Review worker list for unauthorized additions
  2. Containment:

    • Rotate SERVER_KEY immediately
    • Regenerate all user TOTP secrets
    • Review and remove any suspicious workers
    • Check worker health logs for unusual access patterns
  3. Recovery:

    • Update to latest version
    • Review fail2ban rules
    • Audit all configuration files
    • Restore from known-good backup if necessary
  4. Prevention:

    • Analyze attack vector
    • Implement additional controls if needed
    • Update this document with lessons learned

Support and Reporting

  • Security Issues: Report privately to maintainer before public disclosure
  • Questions: Open GitHub issue (do not include sensitive info)
  • Updates: Watch repository for security announcements

Last Updated: 2026-01-07 Version: 1.0 Security Review Status: Self-audited, production-ready for small-to-medium deployments