generated from oracle/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 28
feat(heuristics): add two analyzers to detect dependency confusion and distinguish from stub packages #1117
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
AmineRaouane
wants to merge
2
commits into
oracle:main
Choose a base branch
from
AmineRaouane:dependency-confusion
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+323
−9
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
54 changes: 54 additions & 0 deletions
54
src/macaron/malware_analyzer/pypi_heuristics/metadata/minimal_content.py
This file contains hidden or 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,54 @@ | ||
# Copyright (c) 2024 - 2025, 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/. | ||
|
||
"""This analyzer checks if a PyPI package has minimal content.""" | ||
|
||
import logging | ||
import os | ||
|
||
from macaron.errors import SourceCodeError | ||
from macaron.json_tools import JsonType | ||
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 MinimalContentAnalyzer(BaseHeuristicAnalyzer): | ||
"""Check whether the package has minimal content.""" | ||
|
||
FILES_THRESHOLD = 50 | ||
|
||
def __init__(self) -> None: | ||
super().__init__( | ||
name="minimal_content_analyzer", | ||
heuristic=Heuristics.MINIMAL_CONTENT, | ||
depends_on=None, | ||
) | ||
|
||
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. | ||
""" | ||
result = pypi_package_json.download_sourcecode() | ||
if not result: | ||
error_msg = "No source code files have been downloaded" | ||
logger.debug(error_msg) | ||
raise SourceCodeError(error_msg) | ||
|
||
file_count = sum(len(files) for _, _, files in os.walk(pypi_package_json.package_sourcecode_path)) | ||
|
||
if file_count >= self.FILES_THRESHOLD: | ||
return HeuristicResult.PASS, {"message": "Package has sufficient content"} | ||
|
||
return HeuristicResult.FAIL, {"message": "Not enough files found"} |
56 changes: 56 additions & 0 deletions
56
src/macaron/malware_analyzer/pypi_heuristics/metadata/unsecure_description.py
This file contains hidden or 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,56 @@ | ||
# Copyright (c) 2024 - 2025, 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/. | ||
|
||
"""This analyzer checks if a PyPI package has unsecure description.""" | ||
|
||
import logging | ||
import re | ||
|
||
from macaron.errors import HeuristicAnalyzerValueError | ||
from macaron.json_tools import JsonType, json_extract | ||
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 UnsecureDescriptionAnalyzer(BaseHeuristicAnalyzer): | ||
"""Check whether the package's description is unsecure.""" | ||
|
||
SECURE_DESCRIPTION_REGEX = re.compile( | ||
r"\b(?:internal|private|stub|placeholder|dependency confusion|security|namespace protection|reserved|harmless|prevent)\b", | ||
re.IGNORECASE, | ||
) | ||
|
||
def __init__(self) -> None: | ||
super().__init__( | ||
name="unsecure_description_analyzer", heuristic=Heuristics.UNSECURE_DESCRIPTION, depends_on=None | ||
) | ||
|
||
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. | ||
""" | ||
package_json = pypi_package_json.package_json | ||
info = package_json.get("info", {}) | ||
if not info: | ||
error_msg = "No package info found in metadata" | ||
logger.debug(error_msg) | ||
raise HeuristicAnalyzerValueError(error_msg) | ||
|
||
description = json_extract(package_json, ["info", "description"], str) | ||
summary = json_extract(package_json, ["info", "summary"], str) | ||
data = f"{description} {summary}" | ||
if self.SECURE_DESCRIPTION_REGEX.search(data): | ||
return HeuristicResult.PASS, {"message": "Package description is secure"} | ||
return HeuristicResult.FAIL, {"message": "Package description is unsecure"} |
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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,107 @@ | ||
# Copyright (c) 2024 - 2025, 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/. | ||
|
||
"""Tests for the MinimalContentAnalyzer heuristic.""" | ||
|
||
from unittest.mock import MagicMock, patch | ||
|
||
import pytest | ||
|
||
from macaron.errors import SourceCodeError | ||
from macaron.malware_analyzer.pypi_heuristics.heuristics import HeuristicResult | ||
from macaron.malware_analyzer.pypi_heuristics.metadata.minimal_content import MinimalContentAnalyzer | ||
|
||
|
||
@pytest.fixture(name="analyzer") | ||
def analyzer_() -> MinimalContentAnalyzer: | ||
"""Pytest fixture to create a MinimalContentAnalyzer instance.""" | ||
return MinimalContentAnalyzer() | ||
|
||
|
||
def test_analyze_sufficient_files_pass(analyzer: MinimalContentAnalyzer, pypi_package_json: MagicMock) -> None: | ||
"""Test the analyzer passes when the package has sufficient files.""" | ||
pypi_package_json.download_sourcecode.return_value = True | ||
pypi_package_json.package_sourcecode_path = "/fake/path" | ||
with patch("os.walk") as mock_walk: | ||
mock_walk.return_value = [("root", [], [f"file{i}.py" for i in range(60)])] | ||
result, info = analyzer.analyze(pypi_package_json) | ||
|
||
assert result == HeuristicResult.PASS | ||
assert info == {"message": "Package has sufficient content"} | ||
pypi_package_json.download_sourcecode.assert_called_once() | ||
|
||
|
||
def test_analyze_exactly_threshold_files_pass(analyzer: MinimalContentAnalyzer, pypi_package_json: MagicMock) -> None: | ||
"""Test the analyzer passes when the package has exactly the threshold number of files.""" | ||
pypi_package_json.download_sourcecode.return_value = True | ||
pypi_package_json.package_sourcecode_path = "/fake/path" | ||
with patch("os.walk") as mock_walk: | ||
mock_walk.return_value = [("root", [], [f"file{i}.py" for i in range(50)])] | ||
result, info = analyzer.analyze(pypi_package_json) | ||
|
||
assert result == HeuristicResult.PASS | ||
assert info == {"message": "Package has sufficient content"} | ||
|
||
|
||
def test_analyze_insufficient_files_fail(analyzer: MinimalContentAnalyzer, pypi_package_json: MagicMock) -> None: | ||
"""Test the analyzer fails when the package has insufficient files.""" | ||
pypi_package_json.download_sourcecode.return_value = True | ||
pypi_package_json.package_sourcecode_path = "/fake/path" | ||
with patch("os.walk") as mock_walk: | ||
mock_walk.return_value = [("root", [], ["file1.py"])] | ||
result, info = analyzer.analyze(pypi_package_json) | ||
|
||
assert result == HeuristicResult.FAIL | ||
assert info == {"message": "Not enough files found"} | ||
|
||
|
||
def test_analyze_no_files_fail(analyzer: MinimalContentAnalyzer, pypi_package_json: MagicMock) -> None: | ||
"""Test the analyzer fails when the package has no files.""" | ||
pypi_package_json.download_sourcecode.return_value = True | ||
pypi_package_json.package_sourcecode_path = "/fake/path" | ||
with patch("os.walk") as mock_walk: | ||
mock_walk.return_value = [("root", [], [])] | ||
result, info = analyzer.analyze(pypi_package_json) | ||
|
||
assert result == HeuristicResult.FAIL | ||
assert info == {"message": "Not enough files found"} | ||
|
||
|
||
def test_analyze_download_failed_raises_error(analyzer: MinimalContentAnalyzer, pypi_package_json: MagicMock) -> None: | ||
"""Test the analyzer raises SourceCodeError when source code download fails.""" | ||
pypi_package_json.download_sourcecode.return_value = False | ||
|
||
with pytest.raises(SourceCodeError) as exc_info: | ||
analyzer.analyze(pypi_package_json) | ||
|
||
assert "No source code files have been downloaded" in str(exc_info.value) | ||
pypi_package_json.download_sourcecode.assert_called_once() | ||
|
||
|
||
@pytest.mark.parametrize( | ||
("file_count", "expected_result"), | ||
[ | ||
(0, HeuristicResult.FAIL), | ||
(1, HeuristicResult.FAIL), | ||
(2, HeuristicResult.FAIL), | ||
(55, HeuristicResult.PASS), | ||
(70, HeuristicResult.PASS), | ||
], | ||
) | ||
def test_analyze_various_file_counts( | ||
analyzer: MinimalContentAnalyzer, | ||
pypi_package_json: MagicMock, | ||
file_count: int, | ||
expected_result: HeuristicResult, | ||
monkeypatch: pytest.MonkeyPatch, | ||
) -> None: | ||
"""Test the analyzer with various file counts.""" | ||
pypi_package_json.download_sourcecode.return_value = True | ||
pypi_package_json.package_sourcecode_path = "/fake/path" | ||
files = [f"file{i}.py" for i in range(file_count)] | ||
mock_walk = MagicMock(return_value=[("root", [], files)]) | ||
monkeypatch.setattr("os.walk", mock_walk) | ||
|
||
result, _ = analyzer.analyze(pypi_package_json) | ||
|
||
assert result == expected_result |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm worried this rule may generate false positives. This is a package with more than 50 files, an anomalous version, and does not include a stub package keyword. Are there any other heuristics or properties we can add on to this rule to be more restrictive?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
maybe forceSetup can be added