mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-02 20:59:56 -05:00
repos: never fetch submodules from WROLPi's own network
A repo's .gitmodules is chosen by whoever controls the repo, so a submodule URL could make WROLPi fetch https://localhost:8443/..., https://10.0.0.1/..., etc. (SSRF), and show the response's error. Every submodule URL is now checked before git fetches it: relative URLs, the repo's own host, and hosts whose addresses are all public are allowed; anything else defers the download with the reason. Nested submodules are checked out one level at a time (instead of git's --recursive) so each level is checked, at most 5 levels deep. Submodule fetches do not follow HTTP redirects, so a checked host cannot redirect git into the network. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
03e3476631
commit
3b6e962dfc
4 changed files with 153 additions and 13 deletions
|
|
@ -44,11 +44,11 @@ class GitRemote:
|
|||
def head(self) -> str:
|
||||
return self.git('rev-parse', 'HEAD')
|
||||
|
||||
def add_submodule(self, path: str, submodule: 'GitRemote') -> str:
|
||||
"""Add `submodule` (at its current commit) at `path`, and commit it."""
|
||||
def add_submodule(self, path: str, submodule: 'GitRemote', url: str = None) -> str:
|
||||
"""Add `submodule` (at its current commit) at `path`, and commit it. `url` overrides the submodule's URL."""
|
||||
gitmodules = self.path / '.gitmodules'
|
||||
existing = gitmodules.read_text() if gitmodules.exists() else ''
|
||||
gitmodules.write_text(f'{existing}[submodule "{path}"]\n\tpath = {path}\n\turl = {submodule.url}\n')
|
||||
gitmodules.write_text(f'{existing}[submodule "{path}"]\n\tpath = {path}\n\turl = {url or submodule.url}\n')
|
||||
self.git('update-index', '--add', '--cacheinfo', f'160000,{submodule.head},{path}')
|
||||
self.git('add', '.gitmodules')
|
||||
self.git('commit', '--quiet', '-m', f'Add submodule {path}')
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import re
|
|||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
|
@ -11,7 +12,8 @@ from wrolpi.common import logger
|
|||
from wrolpi.dates import now
|
||||
from wrolpi.downloader import Downloader, Download, DownloadContext, DownloadResult, make_progress_callback
|
||||
from wrolpi.errors import DownloadError
|
||||
from .lib import git_command, git_env, find_readme, get_repo_size, is_valid_branch, read_readme_text
|
||||
from .lib import git_command, git_env, find_readme, get_repo_size, is_valid_branch, read_readme_text, \
|
||||
submodule_url_error
|
||||
from .models import Repository
|
||||
|
||||
__all__ = ['GitDownloader', 'git_downloader', 'PreparedRepo', 'ExecutedRepo', 'parse_git_progress']
|
||||
|
|
@ -21,6 +23,9 @@ logger = logger.getChild(__name__)
|
|||
# e.g. "Receiving objects: 45% (123/456), 1.20 MiB | 1.00 MiB/s"
|
||||
GIT_PROGRESS_RE = re.compile(r'^(?:remote: )?(?P<stage>[A-Za-z ]+):\s+(?P<percent>\d+)%')
|
||||
|
||||
# Submodules of submodules are checked out this many levels deep.
|
||||
MAXIMUM_SUBMODULE_DEPTH = 5
|
||||
|
||||
# Full mode keeps every branch of the remote as `origin/<branch>`.
|
||||
FULL_REFSPEC = '+refs/heads/*:refs/remotes/origin/*'
|
||||
|
||||
|
|
@ -165,17 +170,48 @@ class GitDownloader(Downloader):
|
|||
if not (directory / '.gitmodules').is_file():
|
||||
return None
|
||||
|
||||
args = ['submodule', 'update', '--init', '--recursive', '--force', '--progress']
|
||||
if prepared.mode == 'snapshot':
|
||||
args.extend(['--depth', '1'])
|
||||
try:
|
||||
await git('submodule', 'sync', '--recursive')
|
||||
await git(*args, progress=True)
|
||||
await self._check_out_submodules(download, ctx, directory, prepared)
|
||||
except DownloadError as e:
|
||||
logger.warning(f'Failed to update submodules of {prepared.url}', exc_info=e)
|
||||
return str(e)
|
||||
return None
|
||||
|
||||
async def _check_out_submodules(self, download: Download, ctx: DownloadContext, directory: pathlib.Path,
|
||||
prepared: PreparedRepo, depth: int = 0):
|
||||
"""Check out the submodules of the repo in `directory`, then theirs, one level at a time.
|
||||
|
||||
Each level's URLs are checked before git fetches them (git's `--recursive` would fetch nested submodules
|
||||
unchecked)."""
|
||||
if not (directory / '.gitmodules').is_file():
|
||||
return
|
||||
if depth >= MAXIMUM_SUBMODULE_DEPTH:
|
||||
raise DownloadError(f'Submodules are nested more than {MAXIMUM_SUBMODULE_DEPTH} levels deep')
|
||||
git = lambda *args, **kwargs: self._git(download, ctx, directory, *args, **kwargs) # noqa: E731
|
||||
|
||||
output = await git('config', '--file', '.gitmodules', '--get-regexp', r'^submodule\..*\.(url|path)$',
|
||||
check=False)
|
||||
urls, paths = [], []
|
||||
for line in output.splitlines():
|
||||
key, _, value = line.partition(' ')
|
||||
(urls if key.endswith('.url') else paths).append(value)
|
||||
repo_host = (urlparse(prepared.url).hostname or '').lower()
|
||||
for url in urls:
|
||||
if error := await asyncio.to_thread(submodule_url_error, url, repo_host):
|
||||
raise DownloadError(f'Refusing to download submodule {url}: {error}')
|
||||
|
||||
await git('submodule', 'sync')
|
||||
args = ['submodule', 'update', '--init', '--force', '--progress']
|
||||
if prepared.mode == 'snapshot':
|
||||
args.extend(['--depth', '1'])
|
||||
# A checked host could otherwise redirect git into WROLPi's network.
|
||||
await git(*args, progress=True, config=('http.followRedirects=false',))
|
||||
|
||||
for path in paths:
|
||||
submodule = (directory / path).resolve()
|
||||
if submodule.is_dir() and directory.resolve() in submodule.parents:
|
||||
await self._check_out_submodules(download, ctx, submodule, prepared, depth + 1)
|
||||
|
||||
async def _is_ancestor(self, download: Download, ctx: DownloadContext, directory: pathlib.Path,
|
||||
ancestor: str, descendant: str) -> bool:
|
||||
cmd = git_command('merge-base', '--is-ancestor', ancestor, descendant)
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import asyncio
|
||||
import html
|
||||
import ipaddress
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import stat
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List, Optional, Tuple
|
||||
|
|
@ -31,10 +33,10 @@ logger = logger.getChild(__name__)
|
|||
|
||||
__all__ = ['ParsedRepoURL', 'parse_repo_url', 'repo_url_key', 'git_command', 'git_env', 'create_repository',
|
||||
'update_repository', 'delete_repository', 'get_repositories', 'list_repo_tree', 'find_readme',
|
||||
'repo_destination_variables', 'is_valid_branch', 'read_readme_text', 'search_repos', 'count_repos',
|
||||
'search_repos_by_name', 'get_repo_log', 'get_repo_root', 'repo_archive_name', 'stream_repo_archive',
|
||||
'ReposConfig', 'repos_config', 'get_repos_config', 'save_repos_config', 'import_repos_config',
|
||||
'DEFAULT_REPO_FREQUENCY']
|
||||
'repo_destination_variables', 'is_valid_branch', 'submodule_url_error', 'read_readme_text',
|
||||
'search_repos', 'count_repos', 'search_repos_by_name', 'get_repo_log', 'get_repo_root',
|
||||
'repo_archive_name', 'stream_repo_archive', 'ReposConfig', 'repos_config', 'get_repos_config',
|
||||
'save_repos_config', 'import_repos_config', 'DEFAULT_REPO_FREQUENCY']
|
||||
|
||||
DEFAULT_REPO_FREQUENCY = DownloadFrequency.weekly.value
|
||||
|
||||
|
|
@ -121,6 +123,40 @@ def _validate_branch(branch: Optional[str]):
|
|||
raise ValidationError(f'Invalid branch name: {branch!r}')
|
||||
|
||||
|
||||
def resolve_host_addresses(host: str) -> List[str]:
|
||||
"""The IP addresses `host` resolves to."""
|
||||
return list({i[4][0] for i in socket.getaddrinfo(host, 443, type=socket.SOCK_STREAM)})
|
||||
|
||||
|
||||
def submodule_url_error(url: str, repo_host: str) -> Optional[str]:
|
||||
"""Why a submodule URL must not be fetched, or None when it may be.
|
||||
|
||||
A submodule's URL is chosen by whoever controls the repo, so it may not make WROLPi fetch from its own network
|
||||
(e.g. `https://localhost:8443/...` or `https://10.0.0.1/...`). Allowed: URLs relative to the repo's remote,
|
||||
the repo's own host (which the user chose), and hosts with only public addresses. (A host which resolves
|
||||
differently when git fetches it is not prevented.)"""
|
||||
if url.startswith(('./', '../')):
|
||||
return None
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme != 'https':
|
||||
return 'only https:// submodules can be downloaded'
|
||||
host = (parsed.hostname or '').lower()
|
||||
if not host:
|
||||
return 'the URL has no host'
|
||||
if host == repo_host:
|
||||
return None
|
||||
try:
|
||||
addresses = [ipaddress.ip_address(host)]
|
||||
except ValueError:
|
||||
try:
|
||||
addresses = [ipaddress.ip_address(i.split('%')[0]) for i in resolve_host_addresses(host)]
|
||||
except (OSError, ValueError):
|
||||
return f'could not resolve {host}'
|
||||
if not addresses or not all(i.is_global for i in addresses):
|
||||
return f'{host} is not a public address'
|
||||
return None
|
||||
|
||||
|
||||
def repo_url_key(url: str) -> str:
|
||||
"""Two URLs of the same repo have the same key (`.git` suffix and case of the host are ignored)."""
|
||||
parsed = urlparse(url.strip())
|
||||
|
|
|
|||
|
|
@ -184,3 +184,71 @@ async def test_archive_after_session_closes(test_session, async_client, git_remo
|
|||
assert response.status_code == HTTPStatus.OK
|
||||
with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
|
||||
assert any(i.endswith('/README.md') for i in archive.namelist())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url,resolved,allowed', [
|
||||
('../library.git', None, True), # Relative to the repo's own remote.
|
||||
('./library', None, True),
|
||||
('https://git.example.com/owner/library', None, True), # The repo's own host.
|
||||
('https://codeberg.org/owner/library', ['217.197.91.145'], True),
|
||||
('https://localhost/library', ['127.0.0.1'], False),
|
||||
('https://127.0.0.1/library', None, False),
|
||||
('https://10.0.0.5/library', None, False),
|
||||
('https://192.168.1.1:8443/library', None, False),
|
||||
('https://[::1]/library', None, False),
|
||||
('https://169.254.169.254/latest', None, False),
|
||||
('https://gitea.lan/library', ['192.168.1.20'], False),
|
||||
('https://mixed.example/library', ['93.184.215.14', '10.0.0.1'], False),
|
||||
('https://unresolvable.example/library', OSError('no such host'), False),
|
||||
('http://codeberg.org/owner/library', None, False),
|
||||
('ssh://git@codeberg.org/owner/library', None, False),
|
||||
('file:///etc', None, False),
|
||||
])
|
||||
def test_submodule_url_error(url, resolved, allowed):
|
||||
"""A submodule URL comes from the (untrusted) repo; it may not make WROLPi fetch from its own network."""
|
||||
side_effect = resolved if isinstance(resolved, Exception) else None
|
||||
with mock.patch('modules.repos.lib.resolve_host_addresses', side_effect=side_effect,
|
||||
return_value=resolved or []):
|
||||
error = lib.submodule_url_error(url, 'git.example.com')
|
||||
assert (error is None) is allowed, error
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submodule_to_private_address(test_session, git_remote_factory, repos_download_manager):
|
||||
"""A submodule which points into WROLPi's network is never fetched; the repo itself still updates."""
|
||||
library = git_remote_factory('library')
|
||||
remote = git_remote_factory()
|
||||
remote.add_submodule('vendor/library', library, url='https://10.0.0.5/admin/library')
|
||||
|
||||
repo = lib.create_repository(test_session, remote.url, submodules=True)
|
||||
with mock.patch('modules.repos.lib.resolve_host_addresses') as resolve:
|
||||
await repos_download_manager.wait_for_all_downloads()
|
||||
test_session.expire_all()
|
||||
|
||||
download = test_session.query(Download).one()
|
||||
assert download.status == DownloadStatus.deferred
|
||||
assert 'not a public address' in download.error
|
||||
assert repo.head_sha == remote.head
|
||||
assert not (repo.directory / 'vendor/library/README.md').exists()
|
||||
resolve.assert_not_called() # An IP address is checked without DNS.
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nested_submodule_to_private_address(test_session, git_remote_factory, repos_download_manager):
|
||||
"""Each level of submodules is checked before it is fetched."""
|
||||
evil = git_remote_factory('evil')
|
||||
library = git_remote_factory('library')
|
||||
library.add_submodule('nested', evil, url='https://127.0.0.1/evil')
|
||||
remote = git_remote_factory()
|
||||
remote.add_submodule('vendor/library', library)
|
||||
|
||||
repo = lib.create_repository(test_session, remote.url, submodules=True)
|
||||
await repos_download_manager.wait_for_all_downloads()
|
||||
test_session.expire_all()
|
||||
|
||||
download = test_session.query(Download).one()
|
||||
assert download.status == DownloadStatus.deferred
|
||||
assert 'not a public address' in download.error
|
||||
# The first level (the repo's own host) was fetched; the nested submodule was not.
|
||||
assert (repo.directory / 'vendor/library/README.md').is_file()
|
||||
assert not (repo.directory / 'vendor/library/nested/README.md').exists()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue