Skip to content

CWE-511: Logic/Time Bomb

Overview

Logic bombs are malicious code that triggers based on conditions (date, user action, event), causing data deletion, system corruption, or service disruption. Time bombs activate after specific dates, often used by disgruntled developers for sabotage or as malicious dependency payload.

Risk

Critical: Logic bombs enable delayed sabotage (data deletion after developer leaves), ransomware deployment, service disruption, data corruption, competitive sabotage, and are difficult to detect until triggered, causing catastrophic damage.

Remediation Steps

Core principle: Reject logic/time bombs: forbid hidden triggers and require transparent, reviewable control flow for critical behavior.

Locate Logic Bombs and Time-Based Triggers

When reviewing security scan results:

  • Search for time-based conditions: Date comparisons, datetime checks with future dates
  • Find conditional destructive actions: Delete, drop, destroy operations behind conditions
  • Check for user-specific triggers: Username checks, email-based conditions
  • Look for counter-based logic: Execution counts, request thresholds
  • Identify obfuscated code: Base64 strings, eval/exec, encoded conditions

Search patterns:

# Find time-based conditions
grep -r "datetime\.now()" . | grep ">"
grep -r "date\.today()" . | grep ">"

# Find destructive operations
grep -r "rmtree\|delete_all\|drop.*table\|rm -rf" .

# Find suspicious conditionals
grep -r "if.*username.*==" .
grep -r "eval\|exec" .

Code Review for Suspicious Patterns (Primary Defense)

RED FLAG patterns to identify and remove:

# TIME BOMB - triggers on specific date
import datetime
if datetime.datetime.now() > datetime.datetime(2024, 12, 31):
    delete_all_data()  # MALICIOUS!
    os.system('rm -rf /data/*')  # DELETE THIS CODE!

if date.today() >= date(2025, 1, 1):
    database.drop_all_tables()  # REMOVE THIS!

# USER-BASED LOGIC BOMB - triggers for specific user
if username == 'ex_employee@company.com':
    corrupt_database()  # MALICIOUS!

if current_user.email == 'fired_dev' and action == 'delete':
    shutil.rmtree('/critical/data')  # DELETE THIS!

# COUNTER-BASED LOGIC BOMB - triggers after threshold
if request_count > 1000000:
    shutdown_service()  # MALICIOUS!
    sys.exit(1)

if sys.modules['__main__'].execution_count > 500:
    corrupt_critical_files()  # REMOVE THIS!

# OBFUSCATED LOGIC BOMB - hidden condition
if eval(base64.b64decode('aWYgVHJ1ZTog...')): # Hidden condition
    malicious_action()  # DELETE THIS!

exec(__import__('base64').b64decode('cm0gLXJmIC8='))  # rm -rf / - REMOVE!

Why this is critical: Logic bombs can cause catastrophic damage when triggered. They must be completely removed, not just disabled. Any time-based or conditional destructive code without legitimate business purpose is suspicious.

Use Static Analysis to Detect Malicious Patterns

# Semgrep - pattern-based scanning
semgrep --config=p/security-audit .
semgrep --config=p/python .

# Custom Semgrep rules for logic bombs
# semgrep-rules.yaml:
rules:

  - id: time-bomb-detection
    pattern: |
      if datetime.datetime.now() > datetime.datetime(...):
        ...
    message: "Potential time bomb detected"
    severity: ERROR
    languages: [python]

# Bandit (Python)
bandit -r . --severity-level medium
bandit -r . -f json -o bandit-report.json

# FindSecBugs (Java)
findbugs -textui -effort:max -low

# PMD (Java) - custom rules
pmd -d src -R rulesets/java/controversial.xml

Pattern detection:

# Search for time comparisons
grep -rn "datetime.*>\|<" . --include="*.py"
grep -rn "Date.*after\|before" . --include="*.java"

# Search for destructive operations
grep -rn "shutil\.rmtree\|os\.remove\|DROP TABLE" .

# Search for suspicious conditionals
grep -rn "if.*==.*'.*@.*'" .  # Email-based triggers

Monitor for Suspicious Code Changes with Git Hooks

# .git/hooks/pre-commit
#!/bin/bash

# Detect dangerous patterns in commits
if git diff --cached --diff-filter=ACM | grep -iE "time.?bomb|logic.?bomb"; then
    echo "ERROR: Suspicious code comment detected!"
    exit 1
fi

if git diff --cached --diff-filter=ACM | grep -E "(rmtree|drop.*table|rm -rf|delete.*all)"; then
    echo "WARNING: Destructive operation detected - requires security review"
    echo "Please add justification in commit message"
    exit 1
fi

if git diff --cached --diff-filter=ACM | grep -E "datetime.*>.*datetime\(2[0-9]{3}"; then
    echo "WARNING: Time-based condition detected - requires review"
    exit 1
fi

# Scan with bandit
if command -v bandit &> /dev/null; then
    bandit -r . -ll -i || exit 1
fi

CI/CD enforcement:

# .github/workflows/security.yml
name: Security Checks
on: [push, pull_request]
jobs:
  scan:
    runs-on: ubuntu-latest
    steps:

      - uses: actions/checkout@v3

      - name: Scan for logic bombs
        run: |
          if git log -1 --pretty=%B | grep -iE "time.?bomb|logic.?bomb"; then
            echo "Suspicious commit message"
            exit 1
          fi

      - name: Static analysis
        run: |
          pip install bandit semgrep
          bandit -r . -ll
          semgrep --config=auto .

Implement Code Signing and Integrity Checks

import hashlib
import json
import os

# Generate integrity manifest
def generate_integrity_manifest(source_dir):
    manifest = {}
    for root, dirs, files in os.walk(source_dir):
        for file in files:
            if file.endswith('.py'):
                path = os.path.join(root, file)
                with open(path, 'rb') as f:
                    file_hash = hashlib.sha256(f.read()).hexdigest()
                manifest[path] = file_hash

    with open('integrity.json', 'w') as f:
        json.dump(manifest, f, indent=2)

# Verify module integrity before execution
def verify_module_integrity(module_path, manifest_path='integrity.json'):
    with open(module_path, 'rb') as f:
        actual_hash = hashlib.sha256(f.read()).hexdigest()

    with open(manifest_path) as f:
        manifest = json.load(f)

    expected_hash = manifest.get(module_path)
    if not expected_hash:
        raise SecurityError(f"Module not in manifest: {module_path}")

    if actual_hash != expected_hash:
        raise SecurityError(
            f"Module integrity violation for {module_path}! "
            f"Expected {expected_hash}, got {actual_hash}"
        )

# Use before importing critical modules
verify_module_integrity('app/auth.py')
import app.auth

Monitor and Test for Logic Bomb Indicators

Runtime monitoring:

import logging
import datetime

# Log all destructive operations
def monitored_delete(path):
    logger.warning(
        f"Destructive operation: delete {path}",
        extra={
            'user': current_user(),
            'timestamp': datetime.datetime.now(),
            'stack_trace': traceback.format_stack()
        }
    )
    # Require confirmation for destructive ops
    if not confirm_destructive_operation():
        raise PermissionError("Operation cancelled")
    os.remove(path)

Testing strategies:

  • Run code in isolated environment (container, VM)
  • Set system clock to future dates and test
  • Test with different usernames, especially former employees
  • Monitor file system for unexpected deletions
  • Check for new cron jobs or scheduled tasks
  • Review all database schema changes

Detection Indicators

Time-based:

  • Date comparisons with future dates
  • Destructive actions after specific dates
  • Trial period expiration code in wrong context

Condition-based:

  • Hidden backdoor usernames
  • Counter thresholds triggering destruction
  • Unusual event listeners

Obfuscation:

  • Base64 encoded strings with exec/eval
  • Complex conditional logic hiding intent
  • Dead code branches with destructive actions

Example Logic Bombs

# Classic time bomb

if date.today() > date(2024, 1, 1):
    os.system('rm -rf /data/*')

# Counter-based

if sys.modules['__main__'].execution_count > 1000:
    corrupt_critical_files()

# User-based  

if current_user.email == 'ex-employee@company.com':
    if action == 'fire':
        database.drop_all_tables()

# Obfuscated

exec(__import__('base64').b64decode('cm0gLXJmIC8='))  # rm -rf /

Prevention Best Practices

  • Mandatory code review (2+ reviewers)
  • Automated pattern detection
  • Regular security audits
  • Least privilege principle
  • Monitor destructive operations
  • Integrity checking
  • Background checks for developers
  • Incident response planning

Security Checklist

  • No time-based conditions with destructive actions
  • No user-specific backdoors or triggers
  • No obfuscated code (base64, eval, exec)
  • All destructive operations are justified and logged
  • Code review by 2+ developers required
  • Static analysis passes (no high/critical findings)
  • Integrity checks in place

Additional Resources