VAITP Dataset

← Back to the dataset

CVE-2021-29539

Segfault in TensorFlow tf.raw_ops.ImmutableConst for tf.resource and tf.variant dtype

  • CVSS 5.5
  • CWE-681 Incorrect Conversion between Numeric Types
  • Input Validation and Sanitization
  • Local

TensorFlow is an end-to-end open source platform for machine learning. Calling `tf.raw_ops.ImmutableConst`(https://www.tensorflow.org/api_docs/python/tf/raw_ops/ImmutableConst) with a `dtype` of `tf.resource` or `tf.variant` results in a segfault in the implementation as code assumes that the tensor contents are pure scalars. We have patched the issue in 4f663d4b8f0bec1b48da6fa091a7d29609980fa4 and will release TensorFlow 2.5.0 containing the patch. TensorFlow nightly packages after this commit will also have the issue resolved. If using `tf.raw_ops.ImmutableConst` in code, you can prevent the segfault by inserting a filter for the `dtype` argument.

CVSS base score
5.5
Published
2021-05-14
OWASP
A06 Vulnerable and Outdated Components
Orthogonal defect classification
Function
Code defect classification
Incorrect Functionality
Category
Input Validation and Sanitization
Subcategory
Insecure Parsing or Deserialization
Accessibility scope
Local
Impact
Denial of Service (DoS)
Affected component
TensorFlow
Fixed by upgrading
Yes

Solution

Update to TensorFlow version 2.5.0 or higher.

Vulnerable code sample

import subprocess
import os

def process_user_command(user_input):
    """Process user command - VULNERABLE to code injection"""
    # Dangerous: Direct execution without validation
    command = f"echo 'Processing: {user_input}'"
    
    # Vulnerable: os.system allows command injection
    os.system(command)
    
    return "Command executed"

def run_script(script_name):
    """Run user script - VULNERABLE"""
    # Dangerous: No path validation
    subprocess.call([f"python3 {script_name}"], shell=True)

# Vulnerable examples:
# process_user_command("test'; rm -rf /; echo '")
# run_script("../../../etc/passwd")

Patched code sample

import subprocess
import shlex
import re
from pathlib import Path
from typing import Optional, List

class SecureCommandProcessor:
    """Secure command processor with validation"""
    
    def __init__(self, allowed_commands: List[str] = None):
        # Whitelist of allowed commands
        self.allowed_commands = allowed_commands or ['echo', 'ls', 'cat', 'grep']
        self.allowed_script_dir = Path('./safe_scripts').resolve()
    
    def process_user_command(self, user_input: str) -> Optional[str]:
        """Securely process user command with validation"""
        try:
            # Input validation
            if not user_input or len(user_input) > 100:
                raise ValueError("Invalid input length")
            
            # Sanitize input - only allow alphanumeric and safe chars
            if not re.match(r'^[a-zA-Z0-9\s._-]+$', user_input):
                raise ValueError("Input contains invalid characters")
            
            # Use subprocess with explicit arguments (no shell)
            result = subprocess.run(
                ['echo', f'Processing: {user_input}'],
                capture_output=True,
                text=True,
                timeout=5
            )
            
            if result.returncode == 0:
                return result.stdout.strip()
            else:
                return None
                
        except Exception as e:
            print(f"Command processing error: {e}")
            return None
    
    def run_safe_script(self, script_name: str) -> bool:
        """Run script from safe directory with validation"""
        try:
            # Input validation
            if not script_name or not isinstance(script_name, str):
                raise ValueError("Invalid script name")
            
            # Sanitize filename
            if not re.match(r'^[a-zA-Z0-9._-]+\.py$', script_name):
                raise ValueError("Invalid script filename")
            
            # Resolve script path
            script_path = (self.allowed_script_dir / script_name).resolve()
            
            # Security checks
            if not script_path.exists() or not script_path.is_file():
                raise FileNotFoundError("Script not found")
            
            # Ensure script is within allowed directory
            if not str(script_path).startswith(str(self.allowed_script_dir)):
                raise ValueError("Script outside allowed directory")
            
            # Run with explicit arguments (no shell)
            result = subprocess.run(
                ['python3', str(script_path)],
                capture_output=True,
                timeout=30,
                cwd=self.allowed_script_dir
            )
            
            return result.returncode == 0
            
        except Exception as e:
            print(f"Script execution error: {e}")
            return False

# Secure usage
processor = SecureCommandProcessor()
result = processor.process_user_command("hello world")
success = processor.run_safe_script("safe_script.py")

Cite this entry

@misc{vaitp:cve202129539,
  title        = {{Segfault in TensorFlow tf.raw_ops.ImmutableConst for tf.resource and tf.variant dtype}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2021},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2021-29539},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2021-29539/}}
}
Introducing the "VAITP dataset": a specialized repository of Python vulnerabilities and patches, meticulously compiled for the use of the security research community. As Python's prominence grows, understanding and addressing potential security vulnerabilities become crucial. Crafted by and for the cybersecurity community, this dataset offers a valuable resource for researchers, analysts, and developers to analyze and mitigate the security risks associated with Python. Through the comprehensive exploration of vulnerabilities and corresponding patches, the VAITP dataset fosters a safer and more resilient Python ecosystem, encouraging collaborative advancements in programming security.

The supreme art of war is to subdue the enemy without fighting.

Sun Tzu – “The Art of War”

:: Shaping the future through research and ingenuity ::