VAITP Dataset

← Back to the dataset

CVE-2019-15795

MD5 sum validation missing in python-apt 1.9.0ubuntu1 and earlier

  • CVSS 4.7
  • CWE-327 Use of a Broken or Risky Cryptographic Algorithm
  • Cryptographic
  • Remote

python-apt only checks the MD5 sums of downloaded files in `Version.fetch_binary()` and `Version.fetch_source()` of apt/package.py in version 1.9.0ubuntu1 and earlier. This allows a man-in-the-middle attack which could potentially be used to install altered packages and has been fixed in versions 1.9.0ubuntu1.2, 1.6.5ubuntu0.1, 1.1.0~beta1ubuntu0.16.04.7, 0.9.3.5ubuntu3+esm2, and 0.8.3ubuntu7.5.

CVSS base score
4.7
Published
2020-03-26
OWASP
A08 Software and Data Integrity Failures
Orthogonal defect classification
Checking
Code defect classification
Incorrect Check
Category
Cryptographic
Subcategory
Unencrypted communication
Accessibility scope
Remote
Impact
Arbitrary Code Execution
Fixed by upgrading
Yes

Solution

Update python-apt to version 1.9.0ubuntu1.2 or higher.

Vulnerable code sample

import requests

class Version:
    def __init__(self, package_name, version):
        self.package_name = package_name
        self.version = version
        self.url = f"http://example.com/packages/{package_name}_{version}.deb"

    def fetch_binary(self):
        response = requests.get(self.url)
        if response.status_code == 200:
            md5_hash = self.calculate_md5(response.content)
            self.save_file(response.content)
        else:
            raise Exception("Failed to download the package.")

    def calculate_md5(self, content):
        import hashlib
        return hashlib.md5(content).hexdigest()

    def save_file(self, content):
        with open(f"{self.package_name}_{self.version}.deb", "wb") as f:
            f.write(content)

Patched code sample

"""
Module for secure package download verification.
"""
import os
import re
import hashlib
import tempfile
from typing import Dict, Optional, Set, Tuple
from urllib.parse import urlparse
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

class PackageError(Exception):
    pass

class Version:
    
    TRUSTED_SCHEMES = {'https'}
    TRUSTED_HOSTS = {'example.com'}
    MAX_SIZE = 100 * 1024 * 1024
    CHUNK_SIZE = 8192
    TIMEOUT = 30
    
    PACKAGE_PATTERN = r'^[a-zA-Z0-9][a-zA-Z0-9_.-]*$'
    
    def __init__(
        self,
        package_name: str,
        version: str,
        expected_hash: str,
        hash_type: str = 'sha256'
    ):
        
        try:

            if not re.match(self.PACKAGE_PATTERN, package_name):
                raise PackageError("Invalid package name")
                
            if not re.match(r'^[\w.-]+$', version):
                raise PackageError("Invalid version")
                
            if hash_type not in {'sha256', 'sha512'}:
                raise PackageError("Invalid hash type")
                
            hash_len = 64 if hash_type == 'sha256' else 128
            if not re.match(f'^[a-f0-9]{{{hash_len}}}$', expected_hash):
                raise PackageError("Invalid hash format")
                
            self.package_name = package_name
            self.version = version
            self.expected_hash = expected_hash
            self.hash_type = hash_type
            self.url = f"https://example.com/packages/{package_name}_{version}.deb"
            
            self.session = self._create_session()
            
        except Exception as e:
            raise PackageError(f"Initialization failed: {str(e)}")
            
    def _create_session(self) -> requests.Session:
        session = requests.Session()
        
        retry = Retry(
            total=3,
            backoff_factor=0.5,
            status_forcelist=[500, 502, 503, 504]
        )
        
        adapter = HTTPAdapter(
            max_retries=retry,
            pool_connections=10,
            pool_maxsize=10
        )
        
        session.mount('https://', adapter)
        
        return session
        
    def _validate_url(self) -> None:
        
        try:
            parsed = urlparse(self.url)
            
            if parsed.scheme not in self.TRUSTED_SCHEMES:
                raise PackageError("HTTPS required")
                
            if parsed.hostname not in self.TRUSTED_HOSTS:
                raise PackageError("Untrusted host")
                
        except Exception as e:
            if isinstance(e, PackageError):
                raise
            raise PackageError(f"URL validation failed: {str(e)}")
            
    def _verify_hash(self, file_path: str) -> None:
        
        try:
            hasher = hashlib.new(self.hash_type)
            
            with open(file_path, 'rb') as f:
                for chunk in iter(lambda: f.read(self.CHUNK_SIZE), b''):
                    hasher.update(chunk)
                    
            if hasher.hexdigest() != self.expected_hash:
                raise PackageError("Hash verification failed")
                
        except Exception as e:
            if isinstance(e, PackageError):
                raise
            raise PackageError(f"Hash verification failed: {str(e)}")
            
    def fetch_binary(self, output_dir: str) -> str:
        
        try:
            self._validate_url()
            
            with tempfile.NamedTemporaryFile(delete=False) as temp_file:
                try:
                    response = self.session.get(
                        self.url,
                        stream=True,
                        timeout=self.TIMEOUT
                    )
                    response.raise_for_status()
                    
                    content_length = response.headers.get('content-length')
                    if content_length and int(content_length) > self.MAX_SIZE:
                        raise PackageError("Package too large")
                        
                    size = 0
                    for chunk in response.iter_content(chunk_size=self.CHUNK_SIZE):
                        size += len(chunk)
                        if size > self.MAX_SIZE:
                            raise PackageError("Package too large")
                        temp_file.write(chunk)
                        
                    self._verify_hash(temp_file.name)
                    
                    output_path = os.path.join(
                        output_dir,
                        f"{self.package_name}_{self.version}.deb"
                    )
                    
                    os.replace(temp_file.name, output_path)
                    return output_path
                    
                except Exception:
                    try:
                        os.unlink(temp_file.name)
                    except OSError:
                        pass
                    raise
                    
        except requests.exceptions.RequestException as e:
            raise PackageError(f"Download failed: {str(e)}")
        except Exception as e:
            raise PackageError(f"Error fetching binary: {str(e)}")

Cite this entry

@misc{vaitp:cve201915795,
  title        = {{MD5 sum validation missing in python-apt 1.9.0ubuntu1 and earlier}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2020},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2019-15795},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2019-15795/}}
}
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 ::