IntelOwl icon indicating copy to clipboard operation
IntelOwl copied to clipboard

Race Condition in S3 Storage File Retrieval Causes Concurrent Downloads and File Corruption

Open gks281263 opened this issue 10 months ago • 0 comments

Problem Description

The S3 storage implementation in intel_owl/settings/storage.py contains critical race conditions that manifest when multiple file analyzers execute concurrently via Celery workers. The current implementation uses a non-atomic check-then-act pattern that allows multiple processes to simultaneously download and write the same file, leading to potential data corruption, redundant S3 API calls, and performance degradation.

Current Behavior

When a job executes multiple file analyzers in parallel (which is the default behavior via Celery's group() execution), each analyzer independently calls storage.retrieve() to obtain a local file path. The current implementation checks for file existence and then downloads from S3 if the file doesn't exist locally. However, this check-then-act sequence is not atomic, allowing multiple processes to pass the existence check before any process completes the download.

Impact

  • Data Integrity Risk: Concurrent file writes can result in corrupted files, causing analyzer failures
  • Resource Waste: The same file is downloaded multiple times from S3 (once per analyzer) instead of being shared
  • Performance Degradation: Redundant S3 API calls and network transfers slow down job execution
  • Cost Implications: Increased AWS S3 data transfer costs due to redundant downloads
  • Scalability Issues: The problem compounds with the number of concurrent analyzers per job

Example Scenario

A job analyzing a 10 MB file with 5 analyzers (YaraScan, ClamAV, PE_Info, Capa_Info, Strings_Info) currently results in:

  • 50 MB total downloaded from S3 (5 × 10 MB)
  • 5 separate S3 API calls
  • 5 separate local file copies
  • Potential file corruption if writes overlap

Expected behavior would be a single download shared across all analyzers.

Code Examples

Problematic Code Location

File: intel_owl/settings/storage.py
Lines: 36-55

class S3Boto3StorageWrapper(S3Boto3Storage):
    def retrieve(self, file, analyzer):
        # FIXME we can optimize this a lot.
        #  Right now we are doing an http request FOR analyzer. We can have a
        #  proxy that will store the content and then save it locally

        # The idea is to download the file in MEDIA_ROOT/analyzer/namefile
        # if it does not exist
        path_dir = os.path.join(MEDIA_ROOT, analyzer)
        name = file.name
        _path = os.path.join(path_dir, name)
        if not os.path.exists(_path):  # ⚠️ Race condition: check
            os.makedirs(path_dir, exist_ok=True)
            if not self.exists(name):
                raise AssertionError
            with self.open(name) as s3_file_object:
                content = s3_file_object.read()
                s3_file_object.seek(0)
                with open(_path, "wb") as local_file_object:
                    local_file_object.write(content)  # ⚠️ Race condition: concurrent write
        return _path

Race Condition Sequence

Time    Analyzer A (Worker 1)              Analyzer B (Worker 2)
----    --------------------               --------------------
T1      Check: os.path.exists(_path)       
        → Returns False
T2                              Check: os.path.exists(_path)
                                → Returns False (file not created yet)
T3      Start downloading from S3          
T4                              Start downloading from S3 (redundant)
T5      Writing to _path                   
T6                              Writing to _path (concurrent write!)
T7      File created                       File corrupted/overwritten

Execution Flow

The concurrent execution is triggered through the following call chain:

  1. Job Pipeline (intel_owl/tasks.py:254): job_pipeline task executes job.execute()
  2. Pipeline Creation (api_app/models.py:671-695): _get_pipeline() creates Celery signatures
  3. Concurrent Execution (api_app/models.py:628): group(signatures) executes analyzers in parallel
  4. File Retrieval (api_app/analyzers_manager/classes.py:251): Each analyzer calls storage.retrieve()
# api_app/models.py:628
return (
    config_class.signature_pipeline_running(self)
    | group(signatures)  # ⚠️ Executes all analyzers concurrently
    | config_class.signature_pipeline_completed(self)
)

Additional Issues Identified

  1. Directory Creation Race: os.makedirs(path_dir, exist_ok=True) can raise FileExistsError if another process creates the directory between check and creation
  2. Poor Error Handling: Generic AssertionError without descriptive message makes debugging difficult
  3. Unnecessary Operation: s3_file_object.seek(0) is called but never used

Test Cases

Test Case 1: Concurrent Download Prevention

Objective: Verify that multiple concurrent calls to retrieve() for the same file do not result in redundant downloads.

def test_concurrent_retrieve_same_file():
    """Test that multiple analyzers don't download the same file multiple times"""
    storage = S3Boto3StorageWrapper()
    file = MockFile(name="test.exe")
    
    # Simulate 5 concurrent retrievals (typical job scenario)
    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = [
            executor.submit(storage.retrieve, file, f"analyzer_{i}")
            for i in range(5)
        ]
        paths = [f.result() for f in futures]
    
    # Verify only one download occurred
    assert len(set(paths)) == 1  # All should return same path
    # Verify S3 API was called only once (via mock verification)
    assert s3_mock.open.call_count == 1

Test Case 2: File Corruption Prevention

Objective: Ensure concurrent writes do not corrupt file content.

def test_no_file_corruption_on_concurrent_write():
    """Test that concurrent writes don't corrupt the file"""
    storage = S3Boto3StorageWrapper()
    file = MockFile(name="test.exe", content=b"test content" * 1000)
    expected_content = file.content
    
    # Concurrent writes from 10 analyzers
    with ThreadPoolExecutor(max_workers=10) as executor:
        futures = [
            executor.submit(storage.retrieve, file, f"analyzer_{i}")
            for i in range(10)
        ]
        paths = [f.result() for f in futures]
    
    # Verify file integrity for all returned paths
    for path in paths:
        with open(path, 'rb') as f:
            assert f.read() == expected_content, f"File {path} is corrupted"

Test Case 3: Directory Creation Race Condition

Objective: Verify directory creation doesn't fail under concurrent access.

def test_concurrent_directory_creation():
    """Test that concurrent directory creation doesn't raise FileExistsError"""
    storage = S3Boto3StorageWrapper()
    file = MockFile(name="test.exe")
    
    # Multiple analyzers creating directories simultaneously
    with ThreadPoolExecutor(max_workers=10) as executor:
        futures = [
            executor.submit(storage.retrieve, file, f"analyzer_{i}")
            for i in range(10)
        ]
        # Should not raise FileExistsError
        paths = [f.result() for f in futures]
    
    assert all(os.path.exists(p) for p in paths)

Test Case 4: Error Handling

Objective: Verify proper error messages when S3 file doesn't exist.

def test_error_handling_missing_s3_file():
    """Test that missing S3 file raises descriptive error"""
    storage = S3Boto3StorageWrapper()
    file = MockFile(name="nonexistent.exe")
    
    # Mock S3 to return False for exists()
    with patch.object(storage, 'exists', return_value=False):
        with pytest.raises(Exception) as exc_info:
            storage.retrieve(file, "test_analyzer")
        
        # Verify error message is descriptive
        assert "nonexistent.exe" in str(exc_info.value)
        assert "S3" in str(exc_info.value) or "bucket" in str(exc_info.value)

Related Code Locations

  • Main Issue: intel_owl/settings/storage.py:36-55 - S3Boto3StorageWrapper.retrieve()
  • File Retrieval Call: api_app/analyzers_manager/classes.py:251 - FileAnalyzer.filepath property
  • Concurrent Execution: api_app/models.py:628 - group(signatures) in _get_signatures()
  • Pipeline Creation: api_app/models.py:671-695 - Job._get_pipeline()
  • Job Execution: intel_owl/tasks.py:254 - job_pipeline task
  • File Cleanup: api_app/analyzers_manager/classes.py:268-274 - FileAnalyzer.after_run() file deletion

Environment

  • Repository: intelowlproject/IntelOwl
  • Python: 3.x
  • Django: 4.2.27
  • Celery: 5.4.0
  • Storage Backend: S3 (boto3)
  • Deployment: Multi-worker Celery setup

Additional Context

The FIXME comment in the code (line 37) acknowledges the optimization opportunity: "we can optimize this a lot. Right now we are doing an http request FOR analyzer. We can have a proxy that will store the content and then save it locally."

This issue affects all deployments using S3 storage with concurrent analyzer execution, which is the default behavior in production environments.

gks281263 avatar Jan 14 '26 12:01 gks281263