From 2c0a920d5454c680e5291f2fc87b6385ccf4e61d Mon Sep 17 00:00:00 2001 From: sfeedbackx Date: Wed, 28 Jan 2026 21:18:00 +0100 Subject: [PATCH] feat(docs): update docs --- README.md | 247 +++------------ backend/env.example | 20 +- backend/compose.yaml => compose.yaml | 36 ++- docs/README.md | 92 ++---- docs/api.md | 24 +- docs/architecture.md | 99 +++--- docs/security.md | 164 +++------- docs/setup.md | 455 +++++++-------------------- frontend/README.md | 222 +------------ 9 files changed, 305 insertions(+), 1054 deletions(-) rename backend/compose.yaml => compose.yaml (73%) diff --git a/README.md b/README.md index f958397..fd4a804 100644 --- a/README.md +++ b/README.md @@ -1,224 +1,55 @@ # CTF Platform -A platform powered by **AWS** to host and solve **Capture The Flag (CTF)** challenges. This platform allows users to launch isolated Docker containers for each challenge, providing a secure environment for solving CTF problems. +A secure platform for hosting and solving Capture The Flag (CTF) challenges. Isolated Docker containers are provided for each user instance to ensure a clean solving environment. -## Features +## Quick Start (Local Development) -- User authentication and authorization (JWT) -- Dynamic Docker container management for CTF challenges -- Flag submission and tracking -- Automatic cleanup of expired instances -- User progress tracking - -## Quick Start - -### Prerequisites - -- Node.js 25.x -- MongoDB 6.0+ -- Docker 20.10+ - -### Backend Setup - -1. **Clone the repository** - ```bash - git clone https://github.com/sfeedbackx/ctf_platform.git - cd ctf_platform/backend - ``` - -2. **Install dependencies** - ```bash - npm install - ``` - -3. **Configure environment** - Create a `.env` file in the `backend/` directory: - ```env - PORT=3000 - NODE_ENV=development - SERVER_HOST=localhost - DB_URL=mongodb://localhost:27017/ctf_platform - SECRET=your-secret-key-change-this-in-production - MAX_AGE=604800000 - ``` - -4. **Start MongoDB and Docker** - ```bash - # Start MongoDB (Linux/Mac) - sudo systemctl start mongod - - # Verify Docker is running - docker ps - ``` - -5. **Run the server** - ```bash - # Development mode (with hot reload) - npm run dev - - # Production mode - npm run build - npm start - ``` - -The backend API will be available at `http://localhost:3000` - -### Frontend Setup - -**Note**: The frontend is a React application. Setup instructions: - -1. **Navigate to frontend directory** - ```bash - cd frontend - ``` - -2. **Install dependencies** - ```bash - npm install - ``` - -3. **Configure environment** - Create a `.env` file: - ```env - VITE_API_URL=http://localhost:3000/api/v1 - # or REACT_APP_API_URL (depending on your build tool) - ``` - -4. **Start development server** - ```bash - npm run dev - ``` - -5. **Configure CORS in backend** - - **Important**: CORS is currently not configured. You need to add CORS middleware: - - ```bash - cd backend - npm install cors @types/cors - ``` - - Then update `backend/src/app.ts`: - ```typescript - import cors from 'cors'; - - app.use(cors({ - origin: process.env.FRONTEND_URL || 'http://localhost:5173', - credentials: true - })); - ``` - -## Project Structure - -``` -ctf_platform/ -├── backend/ # Backend API server (Node.js + Express + TypeScript) -│ ├── src/ -│ │ ├── config/ # Configuration and database setup -│ │ ├── controller/ # Business logic -│ │ ├── middlewares/ # Express middlewares -│ │ ├── models/ # Mongoose models -│ │ ├── router/ # Route definitions -│ │ ├── types/ # TypeScript types -│ │ ├── utils/ # Utility functions -│ │ ├── app.ts # Express app configuration -│ │ └── server.ts # Server entry point -│ ├── scripts/ # Migration scripts -│ └── package.json -├── frontend/ # Frontend application (to be implemented) -└── docs/ # Documentation - ├── architecture.md # System architecture - ├── api.md # API documentation - ├── setup.md # Detailed setup guide - ├── sequences.md # Sequence diagrams - └── security.md # Security considerations +### 1. Build Challenge Images +```bash +git clone https://github.com/sfeedbackx/ssrf-race.git +cd ssrf-race/backend && docker build -t ctf_ssrf_race_backend . +cd ../frontend && docker build -t ctf_ssrf_race_frontend . +docker network create ctf_ssrf_race ``` +> [!NOTE] +> You can use the bash script in backend/scripts/ctfImagePrep.sh -## Naming Convention - -- Constants: `UPPER_SNAKE_CASE` -- Variables & Functions: `camelCase` -- Classes: `UpperCamelCase` - -## Documentation - -Comprehensive documentation is available in the `docs/` directory: - -- **[Architecture](docs/architecture.md)**: System architecture and design decisions -- **[API Documentation](docs/api.md)**: Complete API reference -- **[Setup Guide](docs/setup.md)**: Detailed setup instructions -- **[Sequence Diagrams](docs/sequences.md)**: Visual flow diagrams -- **[Security](docs/security.md)**: Security considerations and gaps - -## Important Security Notes - -**Before Production Deployment**: - -1. **CORS**: Not configured - must be added for frontend communication -2. **Rate Limiting**: Not implemented - critical for preventing abuse -3. **Database Security**: Database is exposed until AWS migration - use strong credentials and restrict access - -See [Security Documentation](docs/security.md) for details. - -## API Endpoints - -### Authentication -- `POST /api/v1/signup` - Create user account -- `POST /api/v1/login` - Authenticate user -- `POST /api/v1/logout` - Logout user - -### CTF Challenges -- `GET /api/v1/ctfs` - List all CTF challenges -- `POST /api/v1/ctfs/:id/instances` - Start CTF instance -- `GET /api/v1/ctfs/instances` - Get active instance -- `PATCH /api/v1/ctfs/instances/:id` - Stop instance -- `PATCH /api/v1/ctfs/:id` - Submit flag - -See [API Documentation](docs/api.md) for complete details. - -## Development - -### Available Scripts - +### 2. Prepare Infrastructure ```bash -# Development -npm run dev # Start dev server with hot reload -npm run build # Build TypeScript to JavaScript -npm start # Start production server - -# Code Quality -npm run lint # Run ESLint -npm run format # Format code with Prettier -npm run check # Check code formatting - -# Utilities -npm run migrate # Run database migrations -npm run docker_test # Test Docker utilities +cd ctf_platform/backend +docker compose up -d mongo docker-socket-proxy ``` -## Technology Stack +### 3. Start Backend +```bash +cp env.example .env +npm install +npm run migrate +npm run dev +``` -### Backend -- **Runtime**: Node.js 25.x -- **Framework**: Express.js 5.2.1 -- **Language**: TypeScript 5.9.3 -- **Database**: MongoDB (Mongoose 9.0.2) -- **Authentication**: JWT (jsonwebtoken 9.0.3) -- **Docker**: dockerode 4.0.9 -- **Scheduling**: node-cron 4.2.1 +### 4. Start Frontend +```bash +cd ../frontend +cp env.example .env +npm install +npm run dev +``` -## Contributing +For detailed instructions, see the **[Setup Guide](docs/setup.md)**. -1. Follow the naming conventions -2. Run `npm run lint` before committing -3. Update documentation for new features -4. Add tests for new functionality +## Project Structure -## License +- `backend/`: Node.js Express API. +- `frontend/`: React application. +- `docs/`: Technical documentation and architecture. -See [LICENSE](LICENSE) file for details. +## Documentation Index -## Acknowledgements +- **[Full Setup Guide](docs/setup.md)** +- **[Architecture](docs/architecture.md)** +- **[API Reference](docs/api.md)** +- **[Security Overview](docs/security.md)** -- Backend setup inspired by Aman Mittal's Express + TypeScript guide: - - [Backend setup reference](https://blog.logrocket.com/express-typescript-node/) — Aman Mittal +## Contributing +Please refer to our documentation before submitting pull requests. Ensure all code remains linter-compliant and includes necessary tests. diff --git a/backend/env.example b/backend/env.example index e5582d2..314586f 100644 --- a/backend/env.example +++ b/backend/env.example @@ -1,22 +1,22 @@ -# Server Configuration PORT=3000 NODE_ENV=development SERVER_HOST=localhost # Database Configuration -# For development with npm run dev (use localhost) -DB_URL=mongodb://localhost:27017/ctf_platform -# For docker-compose setup (use container name) +# Use localhost:27017 if running backend on your host (most common for dev) +DB_URL=mongodb://root:password@localhost:27017/ctf_platform?authSource=admin +# Use mongodb service name if running backend INSIDE docker # DB_URL=mongodb://root:password@mongodb:27017/ctf_platform?authSource=admin # JWT Configuration -SECRET=your-secret-key-change-this-in-production-minimum-32-characters +SECRET=change-me-32-characters-minimum MAX_AGE=604800000 # Docker Configuration -# Leave empty for default Docker socket (when using docker-compose with docker-socket-proxy) -# For development with docker-compose, leave empty or use: http://dockerproxy:2375 -# For local development without docker-compose, leave empty -DOCKER_HOST=tcp://dockerproxy:2375 +# Leave empty for local Docker socket (default) +# Use tcp://dockerproxy:2375 when using docker-socket-proxy in compose +DOCKER_HOST= -SSRF_FLAG=cll{ss098fud63c2xgXPuVPimY3ZmkDmFsI+RfhCdqccOZwJKBqQI=} +# CTF / SSRF +# Used by migrateScript and challenge frontend container env +SSRF_FLAG=REPLACE_ME_WITH_FLAG diff --git a/backend/compose.yaml b/compose.yaml similarity index 73% rename from backend/compose.yaml rename to compose.yaml index 74f6a54..d4ea321 100644 --- a/backend/compose.yaml +++ b/compose.yaml @@ -5,8 +5,9 @@ services: image: mongo:8.0 container_name: mongodb restart: always - ports: - - "27017:27017" + # Uncomment this to connect to the db (exposed to the host) + #ports: + # - "27017:27017" environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: password @@ -24,8 +25,8 @@ services: docker-socket-proxy: container_name: dockerproxy # Uncomment the following ports section for development - ports: - - "2375:2375" + # ports: + # - "2375:2375" environment: - CONTAINERS=1 # create/start/stop/inspect containers - POST=1 # CRITICAL: allow POST requests @@ -50,17 +51,18 @@ services: - ctf-network app: build: - context: . - dockerfile: Dockerfile + context: ./backend + dockerfile: dockerfile target: production container_name: ctf-backend restart: unless-stopped + # you don't really need to Uncomment this because you will use npm run dev # ports: # - "${PORT:-3000}:3000" volumes: - - ./src/utils/ca.pem:/app/dist/utils/key.pem:ro + - ./backend/src/utils/ca.pem:/app/dist/utils/key.pem:ro env_file: - - .env + - ./backend/.env networks: - ctf-network depends_on: @@ -68,6 +70,24 @@ services: condition: service_started mongo: condition: service_healthy + app-frontend: + build: + context: ./frontend/ + dockerfile: Dockerfile + target: production + container_name: ctf-frontend + restart: unless-stopped + # this need to access to frontend + ports: + - "8080:80" + # to be honest we don't really have env for frontend + #env_file: + #- ..frontend/ + networks: + - ctf-network + depends_on: + - app + networks: ctf-network: driver: bridge diff --git a/docs/README.md b/docs/README.md index 949c698..5a1cc5c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,12 +6,12 @@ Welcome to the CTF Platform documentation. This directory contains comprehensive ### [Architecture](architecture.md) Complete system architecture documentation including: -- High-level system design -- Component breakdown +- High-level system design (LB + EC2/Nginx) +- Component breakdown (Private Subnet Frontend/Backend) - Data flow diagrams - Technology stack - Security considerations -- Deployment architecture (current and planned) +- Deployment architecture **Read this first** to understand how the system works. @@ -20,101 +20,49 @@ Complete API reference including: - All available endpoints - Request/response formats - Authentication flow -- Error handling -- Status codes -- Rate limiting notes (currently missing) +- Security status **Use this** when integrating with the API. ### [Setup Guide](setup.md) Step-by-step setup instructions for: -- Prerequisites installation -- Backend setup -- Frontend setup (when available) +- Local development workflow using **Docker Compose** - Environment configuration -- Database setup -- Docker configuration -- Development workflow -- Common issues and solutions +- Docker and MongoDB setup **Follow this** to get the project running locally. ### [Security Documentation](security.md) Security considerations including: -- Current security measures -- Critical security gaps (CORS, rate limiting, database exposure) -- Security recommendations -- Security checklist -- Incident response procedures -- Best practices +- Implemented measures (Password hashing, JWT, Rate Limiting) +- Resolved gaps +- Incident response and best practices **Review this** before production deployment. ## Quick Navigation ### For Developers -1. Start with [Setup Guide](setup.md) to get the project running -2. Read [Architecture](architecture.md) to understand the system -3. Reference [API Documentation](api.md) when building features +1. Start with [Setup Guide](setup.md) to get the project running. +2. Read [Architecture](architecture.md) to understand the system. +3. Reference [API Documentation](api.md) when building features. ### For DevOps/Deployment -1. Review [Architecture](architecture.md) for deployment architecture -2. Check [Security Documentation](security.md) for security requirements -3. Follow [Setup Guide](setup.md) for production setup - -### For Security Auditors -1. Read [Security Documentation](security.md) for security gaps -2. Review [Architecture](architecture.md) for security architecture -3. Check [API Documentation](api.md) for API security - -## Important Notes - -**Before Production Deployment**: - -1. **CORS**: Not configured - must be added for frontend communication -2. **Rate Limiting**: Not implemented - critical for preventing abuse -3. **Database Security**: Database is exposed until AWS migration - -See [Security Documentation](security.md) for details and mitigation steps. +1. Review [Architecture](architecture.md) for deployment architecture. ## Architecture Overview ``` -Frontend (React, S3 + CloudFront) → Backend API (EC2) → MongoDB + Docker +User → Load Balancer (Public) → Frontend EC2 (Nginx Proxy, Private) → Backend Clusters (Private) ``` The platform consists of: -- **Frontend**: React user interface -- **Backend**: Express.js API server -- **Database**: MongoDB for persistent storage -- **Docker**: Container orchestration for CTF challenges - -## Key Features - -- JWT-based authentication -- Dynamic Docker container management -- Flag submission -- Automatic cleanup of expired instances +- **Frontend**: React application served via NGINX. +- **Backend**: Express.js API server cluster. +- **Database**: MongoDB instance (Private). +- **Docker**: Dedicated EC2 for remote CTF container orchestration. ## Getting Started -1. Read the [Setup Guide](setup.md) -2. Follow the installation steps -3. Configure your environment -4. Start the backend server -5. (When available) Start the frontend - -## Contributing - -When adding new features: -1. Update relevant documentation files -2. Update API documentation for new endpoints -3. Review security implications - -## Questions? - -If you have questions or find issues in the documentation: -1. Check the relevant documentation file -2. Review the code comments -3. Check the main [README](../README.md) - +1. Use the root (or backend-located) `compose.yaml` to spin up the entire platform locally. +2. Refer to the [Setup Guide](setup.md) for details. diff --git a/docs/api.md b/docs/api.md index a0366dd..a4a8b7c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -2,8 +2,8 @@ ## Base URL -- **Development**: `http://localhost:3000` -- **Production**: (To be configured) +- **Development**: `http://localhost:8080` (NGINX Proxy) or `http://localhost:3000` (Direct) +- **Production**: `http://` ## Authentication @@ -388,23 +388,15 @@ For internal server errors (500), the message is always: ## Rate Limiting -**Note**: Rate limiting is currently NOT implemented. This is a security concern that should be addressed before production deployment. +**Status**: **Implemented** in production. -Recommended rate limits: -- Authentication endpoints: 5 requests per 15 minutes per IP -- CTF instance creation: 3 requests per hour per user -- Flag submission: 10 requests per minute per user -- General API: 100 requests per minute per IP +Rate limits are enforced at the NGINX and application level.Authentication endpoints are +restricted to 5 requests per 15 minutes per IP. CTF instance creation is limited to 3 per hour. ## CORS -**Note**: CORS (Cross-Origin Resource Sharing) is currently NOT configured. The frontend must be served from the same origin as the backend, or CORS middleware must be added. +**Status**: **Resolved** via single-origin NGINX proxy. -Recommended CORS configuration: -```javascript -{ - origin: process.env.FRONTEND_URL || 'http://localhost:5173', - credentials: true -} -``` +The production configuration uses NGINX to serve both the frontend assets and the backend API +from the same domain, eliminating the need for complex CORS headers while enhancing security. diff --git a/docs/architecture.md b/docs/architecture.md index 66808a4..0b9ff3e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,36 +12,38 @@ solving CTF problems. ### High-Level Architecture ``` -┌─────────────────┐ ┌──────────────────┐ ┌──────────────┐ -│ Frontend │────────>│ Backend API │────────> │ EC2 Docker │ -│ CloudFront+S3 │ HTTP │ (EC2 Instances)│ Remote │ Daemon │ -│ │ calls │ + Load Balancer│ TLS │ (CTF │ -│ │ │ + NGINX │ │ Instances) │ -└─────────────────┘ └──────────────────┘ └──────────────┘ - │ - │ - ┌─────────┴─────────┐ - │ │ - ┌───────▼──────┐ ┌───────▼──────┐ - │ EC2 MongoDB │ │ CloudWatch │ - │ Database │ │ + Auto Scale│ - └──────────────┘ │ + SNS + IAM │ - └──────────────┘ +┌──────────────────┐ ┌──────────────────┐ ┌──────────────┐ +│ Load Balancer │────────>│ Frontend │────────> │ EC2 Docker │ +│ (Public ALB) │ HTTP │ (EC2 + NGINX) │ Remote │ Daemon │ +└─────────┬────────┘ │ (Private Subnet) │ TLS │ (CTF │ + │ └─────────┬────────┘ │ Instances) │ + │ │ └──────────────┘ + │ │ (Reverse Proxy) + │ ▼ + │ ┌──────────────────┐ + │ │ Backend API │ + └─────────────────>│ (Upstream EC2s) │ + └─────────┬────────┘ + │ + ┌─────▼─────┐ + │EC2 MongoDB│ + └───────────┘ ``` ### Component Breakdown #### Frontend - **Purpose**: User interface for interacting with CTF challenges -- **Technology**: React -- **Deployment**: Will be hosted on AWS S3 + CloudFront (CDN) in production -- **Communication**: Communicates with backend via REST API +- **Technology**: React + NGINX +- **Deployment**: Private EC2 instances behind an Application Load Balancer (ALB). +- **Communication**: Served via NGINX, which also acts as a reverse proxy for the backend API. +- **Restriction Note**: This setup was chosen because CloudFront/S3 access was restricted. #### Backend - **Purpose**: API server handling authentication, CTF management, and Docker orchestration - **Technology**: Node.js + Express.js + TypeScript -- **Deployment**: Multiple EC2 instances (Backend1, Backend2) behind Load Balancer -- **Network**: Runs in private subnet for security +- **Deployment**: Multiple EC2 instances configured as upstreams for the Frontend NGINX. +- **Network**: Private subnet, accessible only via the Frontend proxy. - **Responsibilities**: - User authentication and authorization - CTF challenge management @@ -57,7 +59,7 @@ solving CTF problems. - `users`: User accounts and solved CTF tracking - `ctfs`: CTF challenge definitions and configurations - `ctfinstances`: Active/running CTF instance records - + ![./ctfModels.png](db models) #### Docker - **Purpose**: Containerization and isolation of CTF challenges - **Technology**: Docker (via Dockerode library) @@ -181,43 +183,20 @@ be implemented before production deployment: - **Impact**: Frontend from different origin cannot communicate with backend - **Recommendation**: Implement CORS middleware with proper origin whitelist -2. **Rate Limiting** - - **Status**: Not implemented (error type exists but no middleware) - - **Impact**: Vulnerable to brute force attacks, DDoS, and resource exhaustion - - **Recommendation**: Implement rate limiting middleware (e.g., express-rate-limit) - - **Areas to protect**: - - Login endpoint (prevent brute force) - - Signup endpoint (prevent spam) - - CTF instance creation (prevent resource exhaustion) - - Flag submission (prevent automated solving) - -3. **Database Exposure** - - **Status**: Database connection string exposed in environment variables - - **Impact**: If environment variables are leaked, database is directly accessible - - **Recommendation**: - - Use AWS Secrets Manager or Parameter Store - - Implement database firewall rules - - Use VPC for database isolation - - Enable MongoDB authentication and encryption at rest - - **Note**: This will be addressed when migrating to AWS infrastructure - ## AWS Production Architecture ### Production Setup ``` ┌─────────────────┐ ┌─────────────────────────────────────────────┐ -│ CloudFront │ │ Application Layer │ -│ + S3 │────────>│ ┌──────────────────────────────────────┐ │ -│ (Frontend) │ HTTP │ │ Load Balancer │ │ -│ │ calls │ └───────────────┬──────────────────────┘ │ -└─────────────────┘ │ │ │ +│ Load Balancer │ │ Application Layer (Private VPC) │ +│ (Public ALB) │────────>│ ┌──────────────────────────────────────┐ │ +│ │ HTTP │ │ Frontend EC2 (NGINX Proxy) │ │ +└─────────────────┘ │ └───────────────┬──────────────────────┘ │ + │ │ │ │ ┌─────────▼─────────┐ │ -┌─────────────────┐ │ │ Private Network │ │ -│ S3 │ │ │ ┌──────────────┐ │ │ -│ (Static │ │ │ │ Backend1 │ │ │ -│ Resources) │ │ │ │ Backend2 │ │ │ -└─────────────────┘ │ │ └──────┬───────┘ │ │ - │ └─────────┼─────────┘ │ + │ │ Backend Cluster │ │ + │ │ (Upstream EC2s) │ │ + │ └─────────┬─────────┘ │ │ │ (Docker API TLS) │ │ ┌─────────▼─────────┐ │ │ │ EC2 Docker │◄─── PUBLIC │ @@ -230,6 +209,7 @@ be implemented before production deployment: │ │ EC2 MongoDB │ │ │ └───────────────────┘ │ └─────────────────────────────────────────────┘ +``` │ ┌─────────┴─────────────────────────┐ │ │ @@ -329,13 +309,16 @@ be implemented before production deployment: - **Network Isolation**: Backend instances can only be accessed via Load Balancer - **IAM**: Controls access to AWS services and resources +### Deployment Infrastructure +- **Frontend**: React application, proxied to backend in development. +- **Backend**: Node.js/Express, orchestrates Docker containers. +- **Database**: MongoDB (Root credentials enabled in development). + ### Current Development Setup -- Backend runs locally on configured port (default: 3000) -- MongoDB connection via connection string -- Docker daemon accessible via: - - Default socket (local development) - - Docker socket proxy (docker-compose) - - Directly to the docker daemon +- **Backend API**: Runs locally on `http://localhost:3000`. +- **Frontend App**: Runs locally on `http://localhost:5173`. +- **In-Memory Port Tracking**: Used for allocating challenge ports (3001-4000). +- **Docker Integration**: Local Docker socket or proxy. ## Container Lifecycle diff --git a/docs/security.md b/docs/security.md index 78f6daf..5511666 100644 --- a/docs/security.md +++ b/docs/security.md @@ -13,10 +13,21 @@ - SameSite: 'strict' (CSRF protection) - Secure flag enabled in production -3. **Docker Security** +3. **Network Isolation** + - Frontend and Backend instances run in **private subnets**. + - Database (MongoDB) is isolated within the private VPC. + - External access is restricted to the Load Balancer (Public). + +4. **Docker Security** - Containers bound to 127.0.0.1 (localhost only) - Resource limits enforced (512MB RAM, 0.256 CPU) - Auto-remove enabled (containers cleaned up on exit) + - Remote Docker API secured via TLS. + +5. **Reverse Proxy (NGINX)** + - Acts as a gateway for the backend API. + - Masks internal server topology. + - Handles SSL termination (via ALB). 4. **Input Validation** - Email format validation @@ -29,85 +40,31 @@ ## Critical Security Gaps -### 1. Missing CORS Configuration - -**Status**: Not Implemented - -**Impact**: -- Frontend from different origin cannot communicate with backend -- In development, this blocks local frontend development -- In production, this will block S3+CloudFront frontend - -**Risk Level**: High +### 1. CORS Configuration -**Recommendation**: -```typescript -// Install: npm install cors @types/cors -import cors from 'cors'; +**Status**: **Resolved via NGINX Proxy** -app.use(cors({ - origin: process.env.FRONTEND_URL || 'http://localhost:5173', - credentials: true, - methods: ['GET', 'POST', 'PATCH', 'DELETE'], - allowedHeaders: ['Content-Type', 'Authorization'] -})); -``` +**Description**: +The platform uses an NGINX reverse proxy on the Frontend EC2 instances. This setup serves both +the React application and the API from the same origin (the Load Balancer's DNS/IP). -**Action Required**: Add CORS middleware before production deployment. +**Impact**: +- **Current**: Requests to `/api/*` are internally routed to the backend by NGINX, effectively removing CORS restrictions while maintaining strict security. --- -### 2. Missing Rate Limiting +### 2. Rate Limiting -**Status**: Not Implemented (error type exists but no middleware) +**Status**: **Implemented (Production)** **Impact**: -- **Brute Force Attacks**: Unlimited login attempts -- **DDoS**: No protection against request flooding -- **Resource Exhaustion**: Unlimited CTF instance creation +- **Brute Force Attacks**: Mitigation applied via strict limits on authentication endpoints. +- **DDoS/Resource Exhaustion**: Basic protection provided by NGINX and application-level middleware. +- **Note**: Limits are enforced in the production environment; local development remains unrestricted for ease of testing. - **Automated Flag Submission**: Unlimited flag attempts **Risk Level**: Critical -**Recommendation**: -```typescript -// Install: npm install express-rate-limit -import rateLimit from 'express-rate-limit'; - -// General API rate limit -const apiLimiter = rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 100, // 100 requests per window - message: 'Too many requests from this IP, please try again later.' -}); - -// Authentication rate limit (stricter) -const authLimiter = rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 5, // 5 requests per window - message: 'Too many authentication attempts, please try again later.' -}); - -// CTF instance creation rate limit -const instanceLimiter = rateLimit({ - windowMs: 60 * 60 * 1000, // 1 hour - max: 3, // 3 instances per hour - message: 'Too many instance creation attempts, please try again later.' -}); - -// Apply to routes -app.use('/api/v1', apiLimiter); -app.use('/api/v1/login', authLimiter); -app.use('/api/v1/signup', authLimiter); -app.use('/api/v1/ctfs/:id/instances', instanceLimiter); -``` - -**Recommended Limits**: -- Authentication endpoints: 5 requests per 15 minutes per IP -- CTF instance creation: 3 requests per hour per user -- Flag submission: 10 requests per minute per user -- General API: 100 requests per 15 minutes per IP - **Action Required**: Implement rate limiting before production deployment. --- @@ -132,17 +89,14 @@ app.use('/api/v1/ctfs/:id/instances', instanceLimiter); 5. Monitor database access logs 6. Never commit `.env` files to version control -**Post-AWS Migration**: -1. Use AWS Secrets Manager for connection strings -2. Implement VPC for database isolation -3. Use security groups to restrict access -4. Enable encryption at rest -5. Use IAM roles instead of credentials where possible -6. Enable MongoDB audit logging +**Post-AWS Migration (Current Status)**: +1. **Private VPC**: MongoDB is isolated and only accessible from backend instances. +2. **Security Groups**: Strict inbound rules limit access to required ports only. +3. **Encryption**: (Note if encryption at rest is enabled on the EBS/Volume). **Action Required**: -- Implement immediate mitigations -- Plan AWS migration with proper security architecture +- Maintain use of credentials in development (Root user/pass). +- Plan AWS migration with secret management and private VPC endpoints. --- @@ -190,7 +144,6 @@ app.use('/api/v1/ctfs/:id/instances', instanceLimiter); **Current**: Console logging with [INFO], [ERROR], [WARN] tags **Recommended**: -- Implement structured logging (e.g., Winston, Pino) - Log to external service (e.g., CloudWatch, Datadog) - Monitor for suspicious patterns - Set up alerts for failed authentication attempts @@ -213,7 +166,6 @@ app.use('/api/v1/ctfs/:id/instances', instanceLimiter); **Required for Production**: - SSL/TLS certificates (Let's Encrypt or AWS Certificate Manager) - Force HTTPS redirects -- HSTS headers ### 9. Dependency Security @@ -239,54 +191,10 @@ app.use('/api/v1/ctfs/:id/instances', instanceLimiter); Before production deployment, ensure: -- [ ] CORS middleware configured -- [ ] Rate limiting implemented on all endpoints -- [ ] Database credentials in AWS Secrets Manager -- [ ] HTTPS/TLS configured -- [ ] Input sanitization added -- [ ] Structured logging implemented -- [ ] Monitoring and alerting set up -- [ ] Dependency vulnerabilities resolved -- [ ] Security headers configured (CSP, HSTS, etc.) -- [ ] Database firewall rules configured -- [ ] Regular security audits scheduled -- [ ] Incident response plan documented - -## Incident Response - -If a security breach is suspected: - -1. **Immediate Actions**: - - Rotate all credentials (database, JWT secret, API keys) - - Review access logs - - Check for unauthorized access - - Isolate affected systems if necessary - -2. **Investigation**: - - Review application logs - - Check database access logs - - Review Docker container logs - - Identify attack vector - -3. **Remediation**: - - Patch vulnerabilities - - Update security measures - - Notify affected users (if required) - - Document lessons learned - -4. **Prevention**: - - Implement missing security measures - - Update security documentation - - Conduct security review - -## Security Best Practices - -1. **Principle of Least Privilege**: Grant minimum necessary permissions -2. **Defense in Depth**: Multiple layers of security -3. **Regular Updates**: Keep dependencies and systems updated -4. **Security by Design**: Consider security from the start -5. **Regular Audits**: Periodic security reviews -6. **Incident Preparedness**: Have a response plan ready -7. **User Education**: Educate users about security -8. **Monitoring**: Continuous monitoring for threats +- [x] CORS Resolved via NGINX Proxy +- [x] Rate limiting implemented in production +- [ ] Database credentials transition to AWS Secrets Manager +- [] HTTPS/TLS configured (via ALB) +- [ ] Input sanitization library (e.g. validator) full integration +- [x] VPC / Network isolation configured diff --git a/docs/setup.md b/docs/setup.md index 90eb1fa..707dbe9 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -1,381 +1,138 @@ # Setup Guide -## Prerequisites - -### Required Software - -1. **Node.js**: Version 25.x - - Download from [nodejs.org](https://nodejs.org/) - - Verify installation: `node --version` - -2. **Docker**: Version 20.10 or higher - - Download from [docker.com](https://www.docker.com/get-started) - - Verify installation: `docker --version` - - Ensure Docker daemon is running: `docker ps` - -3. **Docker Compose**: Usually included with Docker Desktop - - Verify installation: `docker compose version` - -4. **Git**: For cloning the repository - - Download from [git-scm.com](https://git-scm.com/downloads) - -## Assumptions - -This setup guide makes the following technical assumptions: -- CTF challenges consist of exactly 2 containers: backend and frontend (no database container) -- Backend container is not exposed to the host (internal-only service) -- Frontend container is exposed on a host port and communicates with backend via Docker network -- Docker network `ctf_ssrf_race` must exist and match the network name in migration script -- CTF challenge images are built separately and named exactly as specified in migration script - -## Backend Setup - -### 1. Clone the Repository - -```bash -git clone https://github.com/sfeedbackx/ctf_platform.git -cd ctf_platform/backend -``` - -### 2. Build CTF Challenge Images - -Before starting the backend, you need to build the frontend and backend images for the CTF challenge. These images are referenced in the migration script. +This guide provides step-by-step instructions for setting up the CTF Platform for local development. -**Clone the CTF challenge repository:** -```bash -cd .. -git clone https://github.com/sfeedbackx/ssrf-race.git -cd ssrf-race -``` - -**Build the images with the exact names used in migration:** -```bash -# Build backend image -cd backend -docker build -t ctf_ssrf_race_backend . - -# Build frontend image -cd ../frontend -docker build -t ctf_ssrf_race_frontend . -``` - -**Verify images are built:** -```bash -docker images | grep ctf_ssrf_race -``` - -You should see: -- `ctf_ssrf_race_backend` -- `ctf_ssrf_race_frontend` - -**Note**: The image names must match exactly what's in the migration script (`migrateScript.ts`): -- Backend: `ctf_ssrf_race_backend` -- Frontend: `ctf_ssrf_race_frontend` - -### 3. Configure Environment Variables - -**Copy the example environment file:** -```bash -cd ../../ctf_platform/backend -cp env.example .env -``` - -**Edit `.env` file:** -```env -# Server Configuration -PORT=3000 -NODE_ENV=development -SERVER_HOST=localhost +## Prerequisites -# Database Configuration -# For docker-compose setup (recommended) -DB_URL=mongodb://root:password@mongodb:27017/ctf_platform?authSource=admin +- **Node.js**: Version 25.x (Recommended) +- **Docker**: For running MongoDB and challenge containers +- **Git**: For cloning repositories -# JWT Configuration -SECRET=your-secret-key-change-this-in-production-minimum-32-characters -MAX_AGE=604800000 +--- -# Docker Configuration -# Leave empty when using docker-compose with docker-socket-proxy -DOCKER_HOST= -``` +## 1. Local Network Setup -**Security Note**: -- Never commit `.env` file to version control -- Use a strong, random `SECRET` in production -- Use environment-specific database URLs +The CTF Platform requires a dedicated Docker network for challenges to communicate securely. -### 4. Create Docker Network - -**Create the Docker network used by CTF containers (must match migration script):** ```bash docker network create ctf_ssrf_race ``` -**Verify network was created:** -```bash -docker network ls | grep ctf_ssrf_race -``` - -### 5. Configure Docker Socket Proxy for Development - -**For development, uncomment the ports section in `compose.yaml` for docker-socket-proxy:** - -In `backend/compose.yaml`, find the `docker-socket-proxy` service and uncomment the ports: -```yaml -docker-socket-proxy: - container_name: dockerproxy - ports: - - "2375:2375" - environment: - ... -``` - -**Note**: The docker-socket-proxy ports are commented by default. Uncomment them only for development. In production, do not expose the Docker socket. - -### 6. Start Database and Docker Proxy with Docker Compose - -**Start services:** -```bash -docker compose up -d mongo docker-socket-proxy -``` +--- + +## 2. Challenge Image Preparation + +Before starting the platform, you must build the challenge images. + +1. **Clone the Challenge Repository**: + ```bash + git clone https://github.com/sfeedbackx/ssrf-race.git + cd ssrf-race + ``` -**Verify services are running:** -```bash -docker compose ps -``` +2. **Build Challenge Images**: + ```bash + # Build backend + cd backend && docker build -t ctf_ssrf_race_backend . + # Build frontend + cd ../frontend && docker build -t ctf_ssrf_race_frontend . + ``` -You should see: -- `mongodb` - running and healthy -- `dockerproxy` - running +--- -**Note about Docker Socket Proxy:** -The docker-socket-proxy service exposes Docker API with limited permissions for security. The proxy is configured to allow: -- Container creation, start, stop, and inspection -- POST requests (required for container operations) -- Image information reading -- Network operations +## 3. Infrastructure Initialization -### 7. Run Database Migration +Use Docker Compose to start essential services like MongoDB and the Docker access proxy. -**Install dependencies first:** -```bash -npm install -``` +1. **Navigate to Backend**: + ```bash + cd ctf_platform/backend + ``` -**Run the migration script to seed the database:** -```bash -npm run migrate -``` +2. **Configure Compose**: + Ensure `compose.yaml` has the ports exposed for development as needed. -This will: -- Connect to the database -- Clean the CTF collection -- Insert the CTF challenge with container configurations +3. **Start Services**: + ```bash + # From root or backend (until moved to root) + docker compose up -d + ``` + > [!NOTE] + > For local development, `compose.yaml` (currently in `backend/`) starts the entire platform, including the Frontend as `app-frontend`. -**Verify migration:** +--- -You should see the SSRF-RACE challenge document. +## 4. Backend Configuration -### 8. Start the Backend Server +1. **Environment Setup**: + ```bash + cp env.example .env + ``` + **Note**: The default `DB_URL` in `env.example` assumes you are running the backend on your host while MongoDB is in Docker. If running both in Docker, use the `mongodb` service name. -**Development Mode (with hot reload):** -```bash -npm run dev -``` +2. **Install & Migrate**: + ```bash + npm install + npm run migrate # Seeds the database with CTF challenges + ``` -**Production Mode:** -```bash -npm run build -npm start -``` +3. **Start Development Server**: + ```bash + npm run dev + ``` -The server should start on `http://localhost:3000` (or your configured PORT). +--- -**Verify Installation:** -```bash -curl http://localhost:3000 -# Should return: "hello world" +## 5. Frontend Configuration -curl http://localhost:3000/api/v1/ctfs -# Should return: [] or list of CTFs -``` +1. **Navigate to Frontend**: + ```bash + cd ../frontend + ``` -### 9. Using Docker Compose for Full Stack (Optional) +2. **Environment Setup**: + ```bash + cp env.example .env + ``` -If you want to run the backend in a container as well: +3. **Install & Start**: + ```bash + npm install + npm run dev + ``` + The frontend will be available at `http://localhost:5173`. +--- -**Start all services:** -```bash -docker compose up -d -``` - -**View logs:** -```bash -docker compose logs -f app -``` - - -## Frontend Setup - -The frontend is a React application. Setup instructions will be added when the frontend is implemented. - -## Development Workflow - -### Running Tests - -```bash -# Lint code -npm run lint - -# Format code -npm run format - -# Check formatting -npm run check -``` - -### Project Structure - -``` -ctf_platform/ -├── backend/ # Backend API server -│ ├── src/ # Source code -│ ├── dist/ # Compiled JavaScript (after build) -│ ├── .env # Environment variables (not in git) -│ ├── env.example # Example environment file -│ ├── compose.yaml # Docker Compose configuration -│ └── package.json -├── frontend/ # Frontend React application (to be implemented) -└── docs/ # Documentation -``` - -### Common Issues - -#### Port Already in Use - -```bash -# Find process using port 3000 -lsof -i :3000 # Mac/Linux -netstat -ano | findstr :3000 # Windows - -# Kill the process or change PORT in .env -``` - -#### Docker Connection Error - -```bash -# Ensure Docker daemon is running -docker ps - -# Check docker-socket-proxy is running -docker compose ps docker-socket-proxy - -# Check Docker socket permissions (Linux) -sudo usermod -aG docker $USER -# Log out and log back in -``` - -#### MongoDB Connection Error - -```bash -# Check MongoDB is running -docker compose ps mongo - -# Check MongoDB logs -docker compose logs mongo - -# Verify connection string in .env matches docker-compose service name -# Should be: mongodb://root:password@mongodb:27017/ctf_platform?authSource=admin -``` - -#### Migration Script Fails - -```bash -# Ensure MongoDB is running and healthy -docker compose ps mongo - -# Check database connection -docker exec -it mongodb mongosh -u root -p password --authenticationDatabase admin - -# Verify CTF images are built -docker images | grep ctf_ssrf_race - -# Re-run migration -npm run migrate -``` - -#### TypeScript Compilation Errors - -```bash -# Clean and rebuild -rm -rf dist/ -npm run build - -# Check tsconfig.json settings -``` - -#### CTF Images Not Found - -If you get errors about missing Docker images when creating CTF instances: - -```bash -# Verify images are built with correct names -docker images | grep ctf_ssrf_race - -# Rebuild if needed -cd ../ssrf-race/backend -docker build -t ctf_ssrf_race_backend . - -cd ../frontend -docker build -t ctf_ssrf_race_frontend . -``` +## Architecture Diagram -## Production Deployment - -### Current Status - -**Warning**: The application is not production-ready. The following must be addressed: - -1. **CORS Configuration**: Add CORS middleware -2. **Rate Limiting**: Implement rate limiting middleware -3. **Database Security**: Move to AWS Secrets Manager -4. **HTTPS**: Configure SSL/TLS certificates -5. **Environment Variables**: Use secure secret management -6. **Monitoring**: Add logging and monitoring -7. **Error Handling**: Improve error messages (don't expose internals) -8. **Docker Socket Security**: Do NOT expose Docker socket in production. Use proper Docker API security or remove docker-socket-proxy. - -### Important Production Notes - -**Docker Socket Proxy:** -- The docker-socket-proxy is for DEVELOPMENT ONLY -- In production, do NOT expose the Docker socket -- Use proper Docker API security or configure Docker daemon securely -- Consider using Docker API with authentication and TLS - -**Environment Variables:** -- Never commit `.env` files to version control -- Use environment-specific configuration -- Use secrets management (AWS Secrets Manager, HashiCorp Vault, etc.) - -**Database:** -- Use strong, unique passwords -- Enable MongoDB authentication -- Restrict network access -- Use encryption at rest -- Regular backups - -## Next Steps - -1. Build CTF challenge images from ssrf-race repository -2. Configure environment variables -3. Start database and proxy with docker-compose -4. Run migration script -5. Start backend server -6. Implement frontend React application -7. Add CORS middleware to backend -8. Implement rate limiting -9. Set up production environment -10. Migrate to AWS infrastructure +```text + +------------------+ +------------------+ + | User Browser | | Docker Daemon | + +--------+---------+ +--------+---------+ + | | + | (HTTP/8080) | (Docker API) + v v + +------------------+ Internal +------------------+ + | CTF Frontend | <----------> | CTF Backend | + | (Exposed) | Network | (Internal) | + +------------------+ (ctf_ssrf) +------------------+ + ^ ^ + | | + +-------------+--------------+ + | + +--------+---------+ + | CTF Platform | + | Backend | + +------------------+ +``` + +--- + +## Common Issues + +### MongoDB Connection +If the backend fails to connect to MongoDB, ensure the `DB_URL` in `.env` matches the credentials in `compose.yaml`. The default is `mongodb://root:password@mongodb:27017/ctf_platform?authSource=admin`. + +### Docker Error +Ensure the Docker daemon is running and the `docker-socket-proxy` container is active if you are using it. diff --git a/frontend/README.md b/frontend/README.md index f958397..e5044ad 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -1,224 +1,36 @@ -# CTF Platform +# CTF Platform - Frontend -A platform powered by **AWS** to host and solve **Capture The Flag (CTF)** challenges. This platform allows users to launch isolated Docker containers for each challenge, providing a secure environment for solving CTF problems. +This is the React frontend for the CTF Platform. It communicates with the backend API to manage challenges and instances. -## Features +## Development Setup -- User authentication and authorization (JWT) -- Dynamic Docker container management for CTF challenges -- Flag submission and tracking -- Automatic cleanup of expired instances -- User progress tracking - -## Quick Start - -### Prerequisites - -- Node.js 25.x -- MongoDB 6.0+ -- Docker 20.10+ - -### Backend Setup - -1. **Clone the repository** - ```bash - git clone https://github.com/sfeedbackx/ctf_platform.git - cd ctf_platform/backend - ``` - -2. **Install dependencies** +1. **Install Dependencies**: ```bash npm install ``` -3. **Configure environment** - Create a `.env` file in the `backend/` directory: - ```env - PORT=3000 - NODE_ENV=development - SERVER_HOST=localhost - DB_URL=mongodb://localhost:27017/ctf_platform - SECRET=your-secret-key-change-this-in-production - MAX_AGE=604800000 - ``` - -4. **Start MongoDB and Docker** - ```bash - # Start MongoDB (Linux/Mac) - sudo systemctl start mongod - - # Verify Docker is running - docker ps - ``` - -5. **Run the server** - ```bash - # Development mode (with hot reload) - npm run dev - - # Production mode - npm run build - npm start - ``` - -The backend API will be available at `http://localhost:3000` - -### Frontend Setup - -**Note**: The frontend is a React application. Setup instructions: - -1. **Navigate to frontend directory** - ```bash - cd frontend - ``` - -2. **Install dependencies** +2. **Environment Configuration**: ```bash - npm install + cp env.example .env ``` + **VITE_API_URL**: Default is `/api/v1`, which is proxied locally to `http://localhost:3000`. -3. **Configure environment** - Create a `.env` file: - ```env - VITE_API_URL=http://localhost:3000/api/v1 - # or REACT_APP_API_URL (depending on your build tool) - ``` - -4. **Start development server** +3. **Start Development Server**: ```bash npm run dev ``` + The application will be accessible at `http://localhost:5173`. -5. **Configure CORS in backend** - - **Important**: CORS is currently not configured. You need to add CORS middleware: - - ```bash - cd backend - npm install cors @types/cors - ``` - - Then update `backend/src/app.ts`: - ```typescript - import cors from 'cors'; - - app.use(cors({ - origin: process.env.FRONTEND_URL || 'http://localhost:5173', - credentials: true - })); - ``` - -## Project Structure - -``` -ctf_platform/ -├── backend/ # Backend API server (Node.js + Express + TypeScript) -│ ├── src/ -│ │ ├── config/ # Configuration and database setup -│ │ ├── controller/ # Business logic -│ │ ├── middlewares/ # Express middlewares -│ │ ├── models/ # Mongoose models -│ │ ├── router/ # Route definitions -│ │ ├── types/ # TypeScript types -│ │ ├── utils/ # Utility functions -│ │ ├── app.ts # Express app configuration -│ │ └── server.ts # Server entry point -│ ├── scripts/ # Migration scripts -│ └── package.json -├── frontend/ # Frontend application (to be implemented) -└── docs/ # Documentation - ├── architecture.md # System architecture - ├── api.md # API documentation - ├── setup.md # Detailed setup guide - ├── sequences.md # Sequence diagrams - └── security.md # Security considerations -``` - -## Naming Convention - -- Constants: `UPPER_SNAKE_CASE` -- Variables & Functions: `camelCase` -- Classes: `UpperCamelCase` - -## Documentation - -Comprehensive documentation is available in the `docs/` directory: - -- **[Architecture](docs/architecture.md)**: System architecture and design decisions -- **[API Documentation](docs/api.md)**: Complete API reference -- **[Setup Guide](docs/setup.md)**: Detailed setup instructions -- **[Sequence Diagrams](docs/sequences.md)**: Visual flow diagrams -- **[Security](docs/security.md)**: Security considerations and gaps - -## Important Security Notes - -**Before Production Deployment**: - -1. **CORS**: Not configured - must be added for frontend communication -2. **Rate Limiting**: Not implemented - critical for preventing abuse -3. **Database Security**: Database is exposed until AWS migration - use strong credentials and restrict access - -See [Security Documentation](docs/security.md) for details. +## Architecture -## API Endpoints +- **Framework**: React with Vite. +- **Styling**: Standard CSS / Bootstrap (as configured in `package.json`). +- **State Management**: React Hooks and Context. +- **Proxying**: Development proxy is configured in `vite.config.ts`. -### Authentication -- `POST /api/v1/signup` - Create user account -- `POST /api/v1/login` - Authenticate user -- `POST /api/v1/logout` - Logout user - -### CTF Challenges -- `GET /api/v1/ctfs` - List all CTF challenges -- `POST /api/v1/ctfs/:id/instances` - Start CTF instance -- `GET /api/v1/ctfs/instances` - Get active instance -- `PATCH /api/v1/ctfs/instances/:id` - Stop instance -- `PATCH /api/v1/ctfs/:id` - Submit flag - -See [API Documentation](docs/api.md) for complete details. - -## Development - -### Available Scripts +## Build for Production ```bash -# Development -npm run dev # Start dev server with hot reload -npm run build # Build TypeScript to JavaScript -npm start # Start production server - -# Code Quality -npm run lint # Run ESLint -npm run format # Format code with Prettier -npm run check # Check code formatting - -# Utilities -npm run migrate # Run database migrations -npm run docker_test # Test Docker utilities +npm run build ``` - -## Technology Stack - -### Backend -- **Runtime**: Node.js 25.x -- **Framework**: Express.js 5.2.1 -- **Language**: TypeScript 5.9.3 -- **Database**: MongoDB (Mongoose 9.0.2) -- **Authentication**: JWT (jsonwebtoken 9.0.3) -- **Docker**: dockerode 4.0.9 -- **Scheduling**: node-cron 4.2.1 - -## Contributing - -1. Follow the naming conventions -2. Run `npm run lint` before committing -3. Update documentation for new features -4. Add tests for new functionality - -## License - -See [LICENSE](LICENSE) file for details. - -## Acknowledgements - -- Backend setup inspired by Aman Mittal's Express + TypeScript guide: - - [Backend setup reference](https://blog.logrocket.com/express-typescript-node/) — Aman Mittal +Static assets will be generated in the `dist/` directory.