CVE-2019-15796
Python-apt versions 1.9.3ubuntu2 and earlier don't check for signed hashes in certain functions, allowing downloads from unsigned repositories
- CVSS 4.7
- CWE-347
- Input Validation and Sanitization
- Remote
Python-apt doesn't check if hashes are signed in `Version.fetch_binary()` and `Version.fetch_source()` of apt/package.py or in `_fetch_archives()` of apt/cache.py in version 1.9.3ubuntu2 and earlier. This allows downloads from unsigned repositories which shouldn't be allowed and has been fixed in verisions 1.9.5, 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.
- CWE
- CWE-347
- CVSS base score
- 4.7
- Published
- 2020-03-26
- OWASP
- A08 Software and Data Integrity Failures
- Orthogonal defect classification
- Checking
- Code defect classification
- Missing Check
- Category
- Input Validation and Sanitization
- Subcategory
- Insecure Parsing or Deserialization
- Accessibility scope
- Remote
- Impact
- Unauthorized Access
- Fixed by upgrading
- Yes
Solution
Update Python-apt to version 1.9.5 or higher.
Vulnerable code sample
import urllib.request
import hashlib
import os
class Version:
def __init__(self, origin, uri, hash_value, hash_type, filename):
self.origin = origin
self.uri = uri
self.hash_value = hash_value
self.hash_type = hash_type
self.filename = filename
def _download_file(self):
try:
urllib.request.urlretrieve(self.uri, self.filename)
except Exception as e:
print(f"Error downloading {self.uri}: {e}")
return False
return True
def _verify_hash(self):
if not os.path.exists(self.filename):
print(f"Error: file {self.filename} does not exist, cannot verify hash.")
return False
if self.hash_type == 'sha256':
hasher = hashlib.sha256()
elif self.hash_type == 'md5':
hasher = hashlib.md5()
else:
print(f"Unsupported hash type: {self.hash_type}")
return False
with open(self.filename, 'rb') as f:
while True:
chunk = f.read(4096)
if not chunk:
break
hasher.update(chunk)
calculated_hash = hasher.hexdigest()
if calculated_hash == self.hash_value:
return True
else:
print(f"Error: Hash mismatch. Expected {self.hash_value}, got {calculated_hash}")
return False
def fetch_binary(self):
if not self._download_file():
return False
print("Hash verification skipped in vulnerable version. Proceeding despite lack of check")
return True
def fetch_source(self):
if not self._download_file():
return False
return True
class Cache:
def __init__(self):
self.archives = []
def _fetch_archives(self):
for archive in self.archives:
if not archive.fetch_binary():
print(f"Failed to fetch archive from {archive.uri}")
return False
return TruePatched code sample
import os
import re
import hashlib
import tempfile
from typing import List, Optional
from urllib.parse import urlparse
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
class DownloadError(Exception):
pass
class Version:
MAX_SIZE = 100 * 1024 * 1024
CHUNK_SIZE = 8192
TIMEOUT = 30
def __init__(self, url: str, expected_sha256: str):
if not url or not isinstance(url, str):
raise ValueError("Invalid URL")
if not expected_sha256 or not re.match(r'^[a-f0-9]{64}$', expected_sha256):
raise ValueError("Invalid SHA256 hash")
self.url = url
self.expected_sha256 = expected_sha256
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)
session.mount('https://', adapter)
return session
def _validate_url(self) -> None:
try:
parsed = urlparse(self.url)
if parsed.scheme != 'https':
raise DownloadError("HTTPS required")
if not parsed.netloc:
raise DownloadError("Invalid domain")
except Exception as e:
raise DownloadError(f"URL validation failed: {str(e)}")
def fetch_binary(self) -> bytes:
try:
self._validate_url()
session = self._create_session()
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
try:
response = 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 DownloadError("File too large")
sha256 = hashlib.sha256()
size = 0
for chunk in response.iter_content(chunk_size=self.CHUNK_SIZE):
size += len(chunk)
if size > self.MAX_SIZE:
raise DownloadError("File too large")
sha256.update(chunk)
temp_file.write(chunk)
if sha256.hexdigest() != self.expected_sha256:
raise DownloadError("Hash mismatch")
temp_file.seek(0)
return temp_file.read()
finally:
try:
os.unlink(temp_file.name)
except OSError:
pass
except requests.exceptions.RequestException as e:
raise DownloadError(f"Download failed: {str(e)}")
except Exception as e:
raise DownloadError(f"Error downloading file: {str(e)}")
class Package:
def __init__(self, binary_url: str, binary_sha256: str):
self.binary_version = Version(binary_url, binary_sha256)
def install(self) -> None:
try:
binary_data = self.binary_version.fetch_binary()
print("Binary installed successfully")
except Exception as e:
raise DownloadError(f"Installation failed: {str(e)}")
def fetch_archives(packages: List[Package]) -> None:
try:
for package in packages:
package.install()
except Exception as e:
raise DownloadError(f"Archive fetch failed: {str(e)}")Cite this entry
@misc{vaitp:cve201915796,
title = {{Python-apt versions 1.9.3ubuntu2 and earlier don't check for signed hashes in certain functions, allowing downloads from unsigned repositories}},
author = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
year = {2020},
note = {VAITP Python Vulnerability Dataset, entry CVE-2019-15796},
howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2019-15796/}}
}
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 ::
