-
Notifications
You must be signed in to change notification settings - Fork 112
Improve typosquatting top-packages sources for npm and PyPI #799
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
sobregosodd
wants to merge
4
commits into
v3
Choose a base branch
from
s.obregoso/improve_npm_toplist
base: v3
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.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
a5edddb
change npm top packages list to use npm.io
sobregosodd 9c11331
change the sources used to retrieve top packages list
sobregosodd 759cfa8
fix formatting and update stale test case for new package data
sobregosodd a00f386
fix docstring
sobregosodd 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,48 +1,81 @@ | ||
| import json | ||
| import os | ||
| import time | ||
| from typing import Optional | ||
|
|
||
| import requests | ||
|
|
||
| from guarddog.analyzer.metadata.typosquatting import TyposquatDetector | ||
| from guarddog.utils.config import TOP_PACKAGES_CACHE_LOCATION | ||
|
|
||
| _NPMS_URL = "https://api.npms.io/v2/search?q=not:unstable&size=250&from={offset}" | ||
| _TOP_N = 10000 | ||
| _PAGE_SIZE = 250 | ||
| _CACHE_FILE = "top_npm_packages.json" | ||
| _REFRESH_DAYS = 30 | ||
|
|
||
|
|
||
| class NPMTyposquatDetector(TyposquatDetector): | ||
| """Detector for typosquatting attacks. Detects if a package name is a typosquat of one of the top 5000 packages. | ||
| """Detector for typosquatting attacks. Detects if a package name is a typosquat of one of the top 10000 packages. | ||
| Checks for distance one Levenshtein, one-off character swaps, permutations | ||
| around hyphens, and substrings. | ||
|
|
||
| Attributes: | ||
| popular_packages (set): set of top 5000 most popular packages from npm | ||
| popular_packages (set): set of top 10k most popular packages from npm | ||
| """ | ||
|
|
||
| def _get_top_packages(self) -> set: | ||
| """ | ||
| Gets the top 8000 most popular NPM packages. | ||
| Uses the base class implementation with NPM-specific parameters. | ||
| """ | ||
| return self._get_top_packages_with_refresh( | ||
| packages_filename="top_npm_packages.json", | ||
| popular_packages_url="https://github.com/LeoDog896/npm-rank/releases/download/latest/raw.json", | ||
| refresh_days=30, | ||
| resources_dir = TOP_PACKAGES_CACHE_LOCATION or os.path.abspath( | ||
| os.path.join(os.path.dirname(__file__), "../resources") | ||
| ) | ||
| cache_path = os.path.join(resources_dir, _CACHE_FILE) | ||
| cache = self._load_cache_file(cache_path) | ||
|
|
||
| if not self._cache_is_expired(cache, days=_REFRESH_DAYS): | ||
| packages = (cache or {}).get("packages") or [] | ||
| return set(packages) | ||
|
|
||
| packages = self._fetch_from_npms() | ||
| if packages: | ||
| with open(cache_path, "w+") as f: | ||
| json.dump( | ||
| {"downloaded_timestamp": int(time.time()), "packages": packages}, | ||
| f, | ||
| ensure_ascii=False, | ||
| indent=4, | ||
| ) | ||
| return set(packages) | ||
|
|
||
| # Fall back to stale cache rather than returning empty | ||
| packages = (cache or {}).get("packages") or [] | ||
| return set(packages) | ||
|
|
||
| def _fetch_from_npms(self) -> list: | ||
| packages = [] | ||
| for offset in range(0, _TOP_N, _PAGE_SIZE): | ||
| try: | ||
| resp = requests.get( | ||
| _NPMS_URL.format(offset=offset), | ||
| headers={"User-Agent": "guarddog/1.0"}, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. should probably be guarddog 3.0? or just a dynamic version number? |
||
| timeout=30, | ||
| ) | ||
| resp.raise_for_status() | ||
| data = resp.json() | ||
| except Exception: | ||
| break | ||
| batch = [obj["package"]["name"] for obj in data.get("results", [])] | ||
| packages.extend(batch) | ||
| if len(batch) < _PAGE_SIZE: | ||
| break | ||
| return packages[:_TOP_N] | ||
|
|
||
| def _extract_package_names(self, data: dict | list | None) -> list | None: | ||
| """ | ||
| Extract package names from NPM data structure. | ||
|
|
||
| Network response format: [{"name": "package-name", ...}, ...] | ||
| Local file format: ["package-name", "package-name", ...] | ||
|
|
||
| This method handles both formats and limits to top 8000 packages. | ||
| """ | ||
| if data is None: | ||
| return None | ||
|
|
||
| # If data is already a list of strings (local file format) | ||
| if isinstance(data, list) and len(data) > 0: | ||
| if isinstance(data[0], str): | ||
| return data | ||
|
|
||
| # If data is list of dicts (network response format) | ||
| if isinstance(data[0], dict) and "name" in data[0]: | ||
| return [item["name"] for item in data[0:8000]] | ||
| # Local cache format: list of strings | ||
| if isinstance(data, list) and len(data) > 0 and isinstance(data[0], str): | ||
| return data | ||
|
|
||
| return None | ||
|
|
||
|
|
||
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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.