HIGH log injectiondocker

Log Injection on Docker

How Log Injection Manifests in Docker

Detecting log injection in Docker requires examining both container runtime behavior and log content patterns. Docker's built-in logging mechanisms provide several detection vectors. The docker logs command reveals suspicious patterns, but requires careful analysis to distinguish injection attempts from legitimate log noise.

Automated scanning tools like middleBrick excel at Docker-specific log injection detection. When scanning a Dockerized API endpoint, middleBrick analyzes the unauthenticated attack surface for log injection vulnerabilities by testing how the application handles special characters in log messages. The scanner examines whether log outputs can be manipulated to create false security events or bypass log filtering rules.

# Scanning a Dockerized API with middleBrick
middlebrick scan https://api.example.com --docker --output json

The --docker flag enables Docker-specific checks, including analysis of environment variable logging, JSON log structure validation, and detection of unsafe log formatting patterns commonly found in containerized applications.

Log aggregation systems like ELK Stack or Prometheus require custom detection rules for Docker log injection. Monitor for these indicators:

# Logstash filter for Docker log injection detection
filter {
  if [docker][image] {
    grok {
      match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:level} %{GREEDYDATA:message}" }
    }
    
    # Detect ANSI escape sequences
    if [message] =~ /\[.*?m/ {
      mutate { add_tag => [ "ansi_escape" ] }
    }
    
    # Detect JSON injection attempts
    if [message] =~ /\{.*\}/ {
      json {
        source => "message"
        skip_on_invalid_json => true
        add_tag => [ "json_injection_attempt" ]
      }
    }
  }
}

Container runtime monitoring complements log analysis. Watch for containers that spawn unusual processes or modify log files unexpectedly. Docker's built-in security features like seccomp profiles and AppArmor can restrict log-related file system access, but require proper configuration.

Network-based detection works for distributed Docker setups. Monitor log shipping traffic for anomalies: unexpected destinations, unusual payload sizes, or traffic patterns that correlate with known injection attempts. Docker Swarm and Kubernetes environments need additional monitoring since logs traverse multiple nodes.

Docker-Specific Remediation

Remediating log injection in Docker environments requires defense-in-depth across the container lifecycle. Start with application-level fixes that sanitize log inputs before they reach any logging mechanism.

// Node.js application with Docker log injection protection
const express = require('express');
const app = express();
const logger = require('./secure-logger');

// Secure logger implementation
class SecureLogger {
  constructor() {
    this.ansiEscapePattern = /\u001b\[?\d{0,2}[a-zA-Z]/g;
    this.jsonInjectionPattern = /\{.*\}/;
    this.controlCharPattern = /[\x00-\x1F\x7F]/g;
  }

  sanitize(message) {
    if (typeof message !== 'string') return message;
    
    // Remove ANSI escape sequences
    let sanitized = message.replace(this.ansiEscapePattern, '');
    
    // Escape JSON special characters
    if (this.jsonInjectionPattern.test(sanitized)) {
      sanitized = sanitized.replace(/["{}]/g, (char) => `\${char}`);
    }
    
    // Remove control characters
    sanitized = sanitized.replace(this.controlCharPattern, '?');
    
    return sanitized;
  }

  info(message) {
    console.log(`INFO: ${this.sanitize(message)}`);
  }

  error(message) {
    console.log(`ERROR: ${this.sanitize(message)}`);
  }
}

const secureLogger = new SecureLogger();

app.get('/api/data', (req, res) => {
  const userInput = req.query.input || 'default';
  
  // Sanitize before logging
  secureLogger.info(`Processing request with input: ${secureLogger.sanitize(userInput)}`);
  
  res.json({ status: 'success' });
});

app.listen(3000, () => {
  secureLogger.info('Docker container started on port 3000');
});

Docker's logging configuration provides another remediation layer. Use structured logging with strict schemas to prevent injection through malformed log entries:

# docker-compose.yml with secure logging configuration
version: '3.8'
services:
  app:
    build: .
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
        env: "LOG_LEVEL,NODE_ENV"
    environment:
      - LOG_LEVEL=INFO
      - NODE_ENV=production
    security_opt:
      - no-new-privileges:true
    read_only: true
    tmpfs:
      - /tmp:rw,noexec,nosuid,size=100m

The read_only filesystem prevents log tampering, while tmpfs limits where temporary log files can be written. The security_opt flag prevents privilege escalation that could bypass log controls.

For Docker Swarm or Kubernetes deployments, implement log shipping with validation. Use Fluentd or Logstash filters that reject suspicious log entries before they reach centralized systems:

# Fluentd configuration with Docker log injection protection
<source>
  @type forward
  port 24224
</source>n
<filter docker.**>
  @type parser
  format json
  time_key time
  time_format %Y-%m-%dT%H:%M:%S.%L%z
  hash_value_field message
  inject_key true
  time_type string
</filter>

<match docker.**>
  @type stdout
  
  # Block logs containing suspicious patterns
  <filter>
    @type grep
    exclude1 message /\u001b\[.*?m/ # ANSI escape sequences
    exclude2 message /\{.*\}/ # Potential JSON injection
    exclude3 message /[\x00-\x1F]/ # Control characters
  </filter>
</match>

Container image scanning tools should verify that base images don't include vulnerable logging libraries. Use minimal base images and regularly update logging dependencies to patch known injection vulnerabilities.

Frequently Asked Questions

How does Docker's logging driver architecture affect log injection risks?
Docker's logging drivers create multiple injection points across the logging pipeline. The JSON-file driver stores raw log data that may contain malicious content, while the journald driver integrates with system logs where injection can affect system-wide logging. The gelf and fluentd drivers ship logs to external systems, creating network-based injection opportunities. Each driver requires specific sanitization approaches, and the default JSON-file driver is particularly vulnerable to structured injection attacks.
Can log injection in Docker containers lead to remote code execution?
Yes, in specific configurations. If log files are processed by applications that execute embedded commands, injection can lead to RCE. For example, if log monitoring tools interpret log content as shell commands, or if log rotation scripts execute filenames containing malicious commands. The risk increases when containers run with elevated privileges or when log files are accessible to processes with execution permissions. Proper file system isolation and input sanitization are critical mitigations.