Skip to content

Repository files navigation

Simple C2C Server

A educational Command and Control (C2C) server implementation written in Python 3.12, designed for cybersecurity learning and research purposes.

⚠️ Educational Disclaimer

This project is for educational and research purposes only. It should only be used in controlled environments with proper authorization. The authors are not responsible for any misuse of this software.

Features

Core Features

  • Web-based Dashboard: Real-time monitoring of active sessions
  • RESTful API: Easy integration with various clients
  • Multiple Client Examples: Bash, PowerShell, and Python implementations
  • Docker Support: Easy deployment and isolation
  • Session Management: Track and manage multiple client connections
  • Real-time Updates: WebSocket-based live updates in the dashboard
  • Cross-platform: Works on Linux, macOS, and Windows

Production Features

  • Authentication & Authorization: JWT-based authentication with role-based access
  • HTTPS/TLS Support: End-to-end encryption for all communications
  • Database Persistence: PostgreSQL backend for reliable data storage
  • Redis Caching: High-performance session and command caching
  • Rate Limiting: Protection against abuse and DoS attacks
  • API Versioning: Backward compatibility and API evolution
  • Comprehensive Logging: Structured logging with multiple levels
  • Health Monitoring: Prometheus metrics and health checks
  • Input Validation: Comprehensive input sanitization and validation
  • CORS Configuration: Secure cross-origin resource sharing
  • Environment Configuration: Flexible configuration management
  • Docker Production Setup: Multi-stage builds and security hardening

Architecture

graph TB
    subgraph "Client Side"
        C1[Client Agent 1]
        C2[Client Agent 2]
        CN[Client Agent N]
    end
    
    subgraph "Server Side"
        LB[Load Balancer/Nginx]
        API[Flask API Server]
        WS[WebSocket Handler]
        DB[(Database)]
        REDIS[(Redis Cache)]
    end
    
    subgraph "Admin Interface"
        WEB[Web Dashboard]
        ADMIN[Admin Panel]
    end
    
    C1 -->|HTTPS REST API| LB
    C2 -->|HTTPS REST API| LB
    CN -->|HTTPS REST API| LB
    
    LB --> API
    API --> DB
    API --> REDIS
    
    WEB -->|WebSocket| WS
    ADMIN -->|WebSocket| WS
    WS --> API
    
    API -->|Real-time updates| WS
Loading

Sequence Diagram

sequenceDiagram
    participant C as Client Agent
    participant API as C2C Server API
    participant DB as Database
    participant WS as WebSocket
    participant DASH as Dashboard
    
    Note over C,DASH: Session Registration
    C->>+API: POST /api/register
    API->>+DB: Store session data
    DB-->>-API: Session created
    API-->>-C: Session ID + Auth token
    API->>WS: New session event
    WS->>DASH: Update session list
    
    Note over C,DASH: Heartbeat Loop
    loop Every 30 seconds
        C->>API: POST /api/heartbeat/{session_id}
        API->>DB: Update last_seen
        API->>WS: Session update
        WS->>DASH: Update session status
    end
    
    Note over C,DASH: Command Execution
    DASH->>+API: POST /api/command/{session_id}
    API->>+DB: Store command
    DB-->>-API: Command queued
    API->>WS: Command sent event
    WS->>DASH: Show command sent
    API-->>-DASH: Command queued
    
    C->>+API: GET /api/commands/{session_id}
    API->>+DB: Get pending commands
    DB-->>-API: Command list
    API-->>-C: Pending commands
    
    C->>C: Execute command
    C->>+API: POST /api/response/{session_id}
    API->>+DB: Store response
    DB-->>-API: Response saved
    API->>WS: Response received event
    WS->>DASH: Show command output
    API-->>-C: Response acknowledged
    
    Note over C,DASH: Session Cleanup
    DASH->>+API: DELETE /api/session/{session_id}
    API->>+DB: Delete session
    DB-->>-API: Session deleted
    API->>WS: Session deleted event
    WS->>DASH: Remove from session list
    API-->>-DASH: Session deleted
Loading

Quick Start

Development Environment

Using Docker (Recommended)

  1. Clone the repository:

    git clone <your-repo-url>
    cd simple-c2c
  2. Build and run with Docker Compose:

    docker-compose up --build
  3. Access the dashboard: Open your browser and navigate to http://localhost:8080

Local Development

  1. Install dependencies:

    pip install -r requirements.txt
  2. Run the server:

    python app.py
  3. Access the dashboard: Open your browser and navigate to http://localhost:8080

Production Environment

Prerequisites

  • Docker and Docker Compose
  • SSL certificates (or use self-signed for testing)
  • Proper firewall configuration
  • Backup strategy for data

Production Deployment

  1. Clone and configure:

    git clone <your-repo-url>
    cd simple-c2c
    cp .env.example .env
  2. Edit environment variables:

    nano .env

    Update the following critical values:

    • POSTGRES_PASSWORD: Strong database password
    • REDIS_PASSWORD: Strong Redis password
    • SECRET_KEY: Long random secret key
    • JWT_SECRET_KEY: JWT signing secret
    • CORS_ORIGINS: Your domain(s)
  3. Deploy with production script:

    ./deploy-prod.sh
  4. Access services:

    • Dashboard: https://localhost
    • Prometheus: http://localhost:9090
    • Grafana: http://localhost:3000

Manual Production Deployment

# Start infrastructure
docker-compose -f docker-compose.prod.yml up -d postgres redis

# Wait for services and run migrations
docker-compose -f docker-compose.prod.yml run --rm c2c-app python migrate.py upgrade

# Create admin user
docker-compose -f docker-compose.prod.yml run --rm c2c-app python migrate.py create-admin

# Start all services
docker-compose -f docker-compose.prod.yml up -d

Client Usage

Bash Client (Linux/macOS)

# Make the script executable
chmod +x examples/client.sh

# Run with default server (localhost:8080)
./examples/client.sh

# Run with custom server
./examples/client.sh http://192.168.1.100:8080

PowerShell Client (Windows)

# Run with default server
.\examples\client.ps1

# Run with custom server
.\examples\client.ps1 -ServerUrl "http://192.168.1.100:8080"

Python Client (Cross-platform)

# Install requirements first
pip install requests

# Run with default server
python examples/client.py

# Run with custom server
python examples/client.py http://192.168.1.100:8080

Manual Testing with curl

Register a new session:

curl -X POST http://localhost:8080/api/register \
  -H "Content-Type: application/json" \
  -d '{"hostname":"test-host","username":"testuser","os":"Linux","arch":"x86_64"}'

Send heartbeat:

curl -X POST http://localhost:8080/api/heartbeat/YOUR_SESSION_ID

Get commands:

curl http://localhost:8080/api/commands/YOUR_SESSION_ID

Submit response:

curl -X POST http://localhost:8080/api/response/YOUR_SESSION_ID \
  -H "Content-Type: application/json" \
  -d '{"command":"ls","response":"file1.txt\nfile2.txt"}'

API Endpoints

Method Endpoint Description
GET / Web dashboard
POST /api/register Register new client session
POST /api/heartbeat/<session_id> Update session activity
GET /api/commands/<session_id> Get pending commands
POST /api/command/<session_id> Send command to session
POST /api/response/<session_id> Submit command response
GET /api/sessions List all active sessions
GET /api/session/<session_id> Get session details
DELETE /api/session/<session_id> Delete session
GET /health Health check

Configuration

Environment Variables

  • SECRET_KEY: Flask secret key (change in production)
  • FLASK_ENV: Flask environment (development/production)
  • C2C_SERVER_URL: Default server URL for clients

Docker Configuration

Edit docker-compose.yml to customize:

  • Port mapping
  • Environment variables
  • Volume mounts

Security Considerations

⚠️ Production Security Requirements:

Authentication & Authorization

  • JWT-based authentication with configurable token expiration
  • Role-based access control (admin, operator, viewer)
  • Password hashing using bcrypt
  • Session management with secure cookies

Network Security

  • HTTPS/TLS encryption for all communications
  • Rate limiting to prevent abuse and DoS attacks
  • CORS configuration for secure cross-origin requests
  • Nginx reverse proxy with security headers
  • IP-based session limits to prevent session flooding

Input Validation & Sanitization

  • Schema validation using Marshmallow
  • Command length limits to prevent large payloads
  • SQL injection protection via SQLAlchemy ORM
  • XSS protection with secure templating

Monitoring & Auditing

  • Comprehensive audit logging of all actions
  • Structured logging with configurable levels
  • Prometheus metrics for monitoring
  • Health checks for service monitoring
  • Database persistence for audit trails

Infrastructure Security

  • Docker security with non-root user and minimal images
  • Environment-based configuration for secrets
  • Database isolation with dedicated users
  • Redis authentication for cache security

Deployment Security

  • Multi-stage Docker builds for smaller attack surface
  • Secret management via environment variables
  • SSL certificate configuration
  • Firewall recommendations for port restrictions

⚠️ Important Security Notes:

  1. Educational purposes only - Implement additional security measures for real production use
  2. Regular security updates - Keep all dependencies and base images updated
  3. Network isolation - Use proper network segmentation in production
  4. Backup security - Encrypt backups and store securely
  5. Access control - Implement proper user management and access controls
  6. Monitoring - Set up alerting for suspicious activities

Development

Project Structure

simple-c2c/
├── app.py                      # Development Flask application
├── app_prod.py                 # Production Flask application
├── config.py                   # Environment-based configuration
├── models.py                   # Database models
├── migrate.py                  # Database migration utilities
├── requirements.txt            # Development dependencies
├── requirements-prod.txt       # Production dependencies
├── Dockerfile                  # Development Docker configuration
├── Dockerfile.prod            # Production Docker configuration
├── docker-compose.yml         # Development Docker Compose
├── docker-compose.prod.yml    # Production Docker Compose
├── nginx.conf                 # Nginx reverse proxy configuration
├── prometheus.yml             # Prometheus monitoring configuration
├── deploy-prod.sh             # Production deployment script
├── .env.example               # Environment variables template
├── templates/
│   └── index.html            # Web dashboard
├── examples/
│   ├── client.sh             # Bash client
│   ├── client.ps1            # PowerShell client
│   └── client.py             # Python client
├── docs/
│   ├── API.md                # API documentation
│   └── TESTING.md            # Testing guide
├── ssl/                      # SSL certificates directory
├── logs/                     # Application logs
├── data/                     # Persistent data
└── README.md                 # This file

Adding New Features

  1. New API endpoints: Add routes in app.py
  2. Client functionality: Modify client scripts in examples/
  3. Dashboard features: Update templates/index.html
  4. Dependencies: Update requirements.txt

Troubleshooting

Common Issues

  1. Port already in use:

    # Change port in docker-compose.yml or kill existing process
    lsof -ti:8080 | xargs kill -9
  2. Client connection issues:

    • Verify server is running: curl http://localhost:8080/health
    • Check firewall settings
    • Verify correct server URL
  3. Permission denied on scripts:

    chmod +x examples/client.sh

Logs

  • Docker logs: docker-compose logs -f
  • Application logs: Check console output when running locally

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Legal Notice

This software is provided for educational and research purposes only. Users must:

  • Only use this software in authorized environments
  • Comply with all applicable laws and regulations
  • Not use this software for malicious purposes
  • Take full responsibility for their use of this software

License

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

Acknowledgments

  • Flask and Flask-SocketIO for the web framework
  • Bootstrap for the responsive UI
  • Font Awesome for icons

Roadmap

Version 1.0 - Educational Foundation ✅

  • Basic C2C server functionality
  • Web dashboard with real-time updates
  • Multiple client implementations
  • Docker support
  • Basic session management

Version 2.0 - Production Ready ✅

  • Authentication and authorization
  • Database persistence (PostgreSQL)
  • Redis caching and session management
  • Rate limiting and security headers
  • Comprehensive logging and monitoring
  • Docker production deployment
  • Nginx reverse proxy
  • SSL/TLS support
  • Input validation and sanitization
  • Audit logging

Version 3.0 - Enhanced Features (Planned)

  • File upload/download capabilities
  • Command scheduling and queuing
  • Plugin system for extensibility
  • Multi-user collaboration
  • Advanced client management
  • Encrypted client communications
  • Mobile-responsive dashboard
  • Backup and recovery tools

Version 4.0 - Enterprise Features (Future)

  • High availability setup
  • Load balancing support
  • Advanced threat detection
  • Integration with SIEM systems
  • Custom alerting rules
  • API versioning and documentation
  • Kubernetes deployment
  • Advanced analytics and reporting

About

A educational Command and Control (C2C) server implementation written in Python 3.12, designed for cybersecurity learning and research purposes.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages