HIGH container escapefeathersjs

Container Escape in Feathersjs

How Container Escape Manifests in Feathersjs

Container escape in Feathersjs applications typically occurs when services interact with the host filesystem or network in ways that bypass Docker's isolation boundaries. Feathersjs's flexible service architecture can inadvertently expose escape vectors through improper file path handling, unsafe process execution, and misconfigured mount points.

The most common manifestation involves path traversal vulnerabilities in Feathersjs services that accept file paths from users. Consider a Feathersjs service that processes user-uploaded documents:

const fs = require('fs');
const path = require('path');

class DocumentService {
  async processDocument(filePath) {
    // Vulnerable: no path validation
    const fullPath = path.join('/uploads', filePath);
    const content = fs.readFileSync(fullPath, 'utf8');
    return { processed: true, content };
  }
}

An attacker can exploit this by providing paths like ../../../../etc/passwd, escaping the intended directory. When this container runs on a host with sensitive mounts (like Docker socket or host volumes), the consequences escalate dramatically.

Another critical vector involves Feathersjs services that execute shell commands. Services using child_process.exec or similar APIs can enable container escape when combined with Docker's default capabilities:

class SystemService {
  async runDiagnostics(command) {
    // Vulnerable: arbitrary command execution
    const { exec } = require('child_process');
    return new Promise((resolve, reject) => {
      exec(command, (error, stdout, stderr) => {
        if (error) reject(error);
        else resolve({ stdout, stderr });
      });
    });
  }
}

With Docker's default seccomp profile, even seemingly benign commands can access host resources. An attacker might execute docker exec or nsenter to access the host filesystem directly.

Feathersjs's hook system can also introduce escape vectors when hooks perform filesystem operations without proper validation. A before-hook that processes file uploads might inadvertently allow path traversal:

const { Hook } = require('feathers');

const validateFilePath = Hook((context, next) => {
  const { filePath } = context.data;
  // Vulnerable: no validation
  context.data.validatedPath = path.join('/data', filePath);
  next();
});

The most severe container escape scenarios occur when Feathersjs services run with elevated privileges or have access to Docker's control socket. A compromised Feathersjs API could then execute docker run --privileged or mount the host filesystem, achieving full host compromise.

Feathersjs-Specific Detection

Detecting container escape vulnerabilities in Feathersjs requires both static code analysis and runtime scanning. middleBrick's API security scanner includes specialized checks for Feathersjs applications that examine common escape patterns.

middleBrick scans Feathersjs endpoints for path traversal vulnerabilities by testing parameter handling with crafted payloads. For a Feathersjs service endpoint like:

app.service('documents').create({ filePath: 'user-doc.txt' });

middleBrick automatically tests variations like ../../etc/passwd, ./.././../, and other traversal patterns to identify unsafe path concatenation.

The scanner also examines Feathersjs hooks for dangerous patterns. middleBrick's analysis engine detects hooks that:

  • Use path.join() with user-controlled inputs without validation
  • Call filesystem APIs (fs.readFile, fs.writeFile) with dynamic paths
  • Execute shell commands via child_process APIs
  • Access environment variables that might expose host information

For LLM/AI security, middleBrick specifically tests Feathersjs applications that integrate AI services. The scanner checks for:

# Testing for system prompt leakage
POST /api/ai/chat
Content-Type: application/json

{"role":"system","content":"Company secrets: API_KEY=..."}

middleBrick's runtime scanning also tests for excessive agency in Feathersjs services that might interact with external tools or APIs. Services using LangChain or similar frameworks are checked for dangerous tool execution patterns.

The scanner provides specific Feathersjs findings with severity levels and remediation guidance. A typical report might identify:

Risk: HIGH - Path Traversal in DocumentService.processDocument
Location: src/services/document.service.js:12
Remediation: Validate and sanitize file paths using path.normalize() and whitelist checking

middleBrick's OpenAPI analysis also validates that Feathersjs service schemas properly restrict path parameters and don't allow dangerous characters in file path fields.

Feathersjs-Specific Remediation

Securing Feathersjs applications against container escape requires defense-in-depth. The most effective approach combines input validation, principle of least privilege, and secure coding practices specific to Feathersjs's architecture.

Start with robust path validation in Feathersjs services. Instead of naive path joining, implement strict validation:

const fs = require('fs');
const path = require('path');

class SecureDocumentService {
  async processDocument(filePath) {
    // Validate against allowed patterns
    const normalized = path.normalize(filePath);
    const resolved = path.resolve('/uploads', normalized);
    
    // Ensure path stays within allowed directory
    if (!resolved.startsWith('/uploads')) {
      throw new Error('Invalid file path');
    }
    
    // Check if file exists and is accessible
    try {
      await fs.promises.access(resolved, fs.constants.R_OK);
      const content = await fs.promises.readFile(resolved, 'utf8');
      return { processed: true, content };
    } catch (error) {
      throw new Error('File access denied');
    }
  }
}

For command execution, replace dangerous APIs with safe alternatives. Feathersjs services should never use child_process.exec with user input:

class SafeSystemService {
  async runDiagnostics(command) {
    // Whitelist allowed commands
    const allowedCommands = ['ls', 'ps', 'df'];
    if (!allowedCommands.includes(command)) {
      throw new Error('Command not allowed');
    }
    
    // Use execFile instead of exec for better security
    const { execFile } = require('child_process');
    return new Promise((resolve, reject) => {
      execFile(command, ['-la'], (error, stdout, stderr) => {
        if (error) reject(error);
        else resolve({ stdout, stderr });
      });
    });
  }
}

Implement secure hooks in Feathersjs that validate all inputs before processing:

const { Hook } = require('feathers');

const validateFilePathHook = Hook((context, next) => {
  const { filePath } = context.data;
  
  // Reject dangerous patterns
  if (filePath.includes('..') || filePath.startsWith('/')) {
    return next(new Error('Invalid file path'));
  }
  
  // Additional validation based on file extension
  const allowedExtensions = ['.txt', '.pdf', '.docx'];
  const ext = path.extname(filePath);
  if (!allowedExtensions.includes(ext)) {
    return next(new Error('File type not allowed'));
  }
  
  next();
});

Configure Docker containers running Feathersjs with minimal capabilities:

# docker-compose.yml
version: '3.8'
services:
  app:
    build: .
    security_opt:
      - no-new-privileges:true
    read_only: true
    tmpfs:
      - /tmp
    volumes:
      - ./uploads:/uploads:ro  # Read-only if possible
    cap_drop:
      - ALL
    cap_add:
      - CHOWN
      - SETGID
      - SETUID

Finally, implement comprehensive logging in Feathersjs services to detect escape attempts:

const logger = require('winston');

class AuditedDocumentService {
  async processDocument(filePath) {
    logger.info('Processing document', { filePath, user: context.params.user });
    
    try {
      // ... validation logic ...
      const content = await fs.promises.readFile(resolved, 'utf8');
      logger.info('Document processed successfully');
      return { processed: true, content };
    } catch (error) {
      logger.error('Document processing failed', { error: error.message });
      throw error;
    }
  }
}

Frequently Asked Questions

How can I test my Feathersjs application for container escape vulnerabilities?
Use middleBrick's API security scanner which specifically tests Feathersjs applications for path traversal, command injection, and other container escape patterns. The scanner automatically tests your endpoints with crafted payloads and provides detailed findings with severity levels and remediation guidance.
What's the difference between container escape and privilege escalation in Feathersjs?
Container escape allows an attacker to break out of the container's isolation and access the host system, while privilege escalation occurs within the container itself. In Feathersjs, escape often involves path traversal or command injection that leverages Docker's mount points or control socket, whereas privilege escalation might involve bypassing Feathersjs's authentication to access admin functionality.