generated from oracle/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 23
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: new metadata-based heuristic analyzing version numbers for sing…
…le releases that are too high
- Loading branch information
Showing
4 changed files
with
804 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
167 changes: 167 additions & 0 deletions
167
src/macaron/malware_analyzer/pypi_heuristics/metadata/anomalistic_version.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
# Copyright (c) 2024 - 2024, Oracle and/or its affiliates. All rights reserved. | ||
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/. | ||
|
||
"""The heuristic analyzer to check for an anomalistic package version.""" | ||
|
||
import logging | ||
from enum import Enum | ||
|
||
from packaging.version import InvalidVersion, parse | ||
|
||
from macaron.errors import HeuristicAnalyzerValueError | ||
from macaron.json_tools import JsonType, json_extract | ||
from macaron.malware_analyzer.datetime_parser import parse_datetime | ||
from macaron.malware_analyzer.pypi_heuristics.base_analyzer import BaseHeuristicAnalyzer | ||
from macaron.malware_analyzer.pypi_heuristics.heuristics import HeuristicResult, Heuristics | ||
from macaron.slsa_analyzer.package_registry.pypi_registry import PyPIPackageJsonAsset | ||
|
||
logger: logging.Logger = logging.getLogger(__name__) | ||
|
||
|
||
class AnomalisticVersionAnalyzer(BaseHeuristicAnalyzer): | ||
""" | ||
Analyze the version number (if there is only a single release) to detect if it is anomalistic. | ||
A version number is anomalistic if it is above the thresholds for an epoch, major, or minor value. | ||
If the version does not adhere to PyPI standards (PEP 440, as per the 'packaging' module), this heuristic | ||
cannot analyze it. | ||
Calendar versioning is detected as version numbers with the major value as the year (either yyyy or yy), | ||
the minor as the month, and the micro as the day (+/- 2 days), with no further values. | ||
Calendar-semantic versioning is detected as version numbers with the major value as the year (either yyyy or yy), | ||
and any other series of numbers following it. | ||
All other versionings are detected as semantic versioning. | ||
""" | ||
|
||
DATETIME_FORMAT: str = "%Y-%m-%dT%H:%M:%S" | ||
|
||
MAJOR_THRESHOLD: int = 20 | ||
MINOR_THRESHOLD: int = 40 | ||
EPOCH_THRESHOLD: int = 5 | ||
|
||
DETAIL_INFO_KEY: str = "versioning" | ||
|
||
def __init__(self) -> None: | ||
super().__init__( | ||
name="anomalistic_version_analyzer", | ||
heuristic=Heuristics.ANOMALISTIC_VERSION, | ||
depends_on=[(Heuristics.ONE_RELEASE, HeuristicResult.FAIL)], | ||
) | ||
|
||
def analyze(self, pypi_package_json: PyPIPackageJsonAsset) -> tuple[HeuristicResult, dict[str, JsonType]]: | ||
"""Analyze the package. | ||
Parameters | ||
---------- | ||
pypi_package_json: PyPIPackageJsonAsset | ||
The PyPI package JSON asset object. | ||
Returns | ||
------- | ||
tuple[HeuristicResult, dict[str, JsonType]]: | ||
The result and related information collected during the analysis. | ||
Raises | ||
------ | ||
HeuristicAnalyzerValueError | ||
if there is no release information available. | ||
""" | ||
releases = pypi_package_json.get_releases() | ||
if releases is None: # no release information | ||
error_msg = "There is no information for any release of this package." | ||
logger.debug(error_msg) | ||
raise HeuristicAnalyzerValueError(error_msg) | ||
|
||
if len(releases) != 1: | ||
error_msg = ( | ||
"This heuristic depends on a single release, but somehow there are multiple when the one release" | ||
+ " heuristic failed." | ||
) | ||
logger.debug(error_msg) | ||
raise HeuristicAnalyzerValueError(error_msg) | ||
|
||
# Since there is only one release, the latest version should be that release | ||
release = pypi_package_json.get_latest_version() | ||
if release is None: | ||
error_msg = "No latest version information available" | ||
logger.debug(error_msg) | ||
raise HeuristicAnalyzerValueError(error_msg) | ||
|
||
try: | ||
release_metadata = releases[release] | ||
except KeyError as release_error: | ||
error_msg = "The latest release is not available in the list of releases" | ||
logger.debug(error_msg) | ||
raise HeuristicAnalyzerValueError(error_msg) from release_error | ||
|
||
try: | ||
version = parse(release) | ||
except InvalidVersion: | ||
return HeuristicResult.SKIP, {self.DETAIL_INFO_KEY: Versioning.INVALID.value} | ||
|
||
calendar_semantic = False | ||
|
||
if len(str(version.major)) == 4 or len(str(version.major)) == 2: | ||
# possible this version number refers to a date | ||
|
||
for distribution in release_metadata: | ||
upload_time = json_extract(distribution, ["upload_time"], str) | ||
if upload_time is None: | ||
error_msg = "Missing upload time from release information" | ||
logger.debug(error_msg) | ||
raise HeuristicAnalyzerValueError(error_msg) | ||
|
||
parsed_time = parse_datetime(upload_time, self.DATETIME_FORMAT) | ||
if parsed_time is None: | ||
error_msg = "Upload time is not of the expected PyPI format" | ||
logger.debug(error_msg) | ||
raise HeuristicAnalyzerValueError(error_msg) | ||
|
||
if version.major in (parsed_time.year, parsed_time.year % 100): | ||
# the major of the version refers to the year published | ||
if ( | ||
parsed_time.month == version.minor | ||
and parsed_time.day + 2 >= version.micro >= parsed_time.day - 2 | ||
and len(version.release) == 3 | ||
): | ||
# In the format of full_year.month.day or year.month.day, with a 48-hour buffer for timezone differences | ||
detail_info: dict[str, JsonType] = {self.DETAIL_INFO_KEY: Versioning.CALENDAR.value} | ||
if version.epoch > self.EPOCH_THRESHOLD: | ||
return HeuristicResult.FAIL, detail_info | ||
|
||
return HeuristicResult.PASS, detail_info | ||
|
||
calendar_semantic = True | ||
|
||
if calendar_semantic: | ||
detail_info = {self.DETAIL_INFO_KEY: Versioning.CALENDAR_SEMANTIC.value} | ||
# analyze starting from the minor instead | ||
if version.epoch > self.EPOCH_THRESHOLD: | ||
return HeuristicResult.FAIL, detail_info | ||
if version.minor > self.MAJOR_THRESHOLD: | ||
return HeuristicResult.FAIL, detail_info | ||
|
||
return HeuristicResult.PASS, detail_info | ||
|
||
# semantic versioning | ||
detail_info = {self.DETAIL_INFO_KEY: Versioning.SEMANTIC.value} | ||
|
||
if version.epoch > self.EPOCH_THRESHOLD: | ||
return HeuristicResult.FAIL, detail_info | ||
if version.major > self.MAJOR_THRESHOLD: | ||
return HeuristicResult.FAIL, detail_info | ||
if version.minor > self.MINOR_THRESHOLD: | ||
return HeuristicResult.FAIL, detail_info | ||
|
||
return HeuristicResult.PASS, detail_info | ||
|
||
|
||
class Versioning(Enum): | ||
"""Enum used to assign different versioning methods.""" | ||
|
||
INVALID = "invalid" | ||
CALENDAR = "calendar" | ||
CALENDAR_SEMANTIC = "calendar_semantic" | ||
SEMANTIC = "semantic" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.