ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
fix(security): close git argument injection in repo_url/app_path/branch (GHSA-8vx6-432p-h62q)
Juan Denis9fb0a6cab5ca
diff --git a/VERSION b/VERSIONindex 3d82b493..e7dd4c3f 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.7.85+1.7.86diff --git a/backend/app/api/deploy.py b/backend/app/api/deploy.pyindex 05168764..1551d236 100644--- a/backend/app/api/deploy.py+++ b/backend/app/api/deploy.py@@ -1,8 +1,11 @@# Bucket: PER-APP (plan 29 #9). Deploy config reads/writes gate on the shared# app-access seam (can_access_app / can_edit_app); the public inbound webhook is# token/signature-verified (ALLOWLISTed — no per-app user session).+import os+from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_required, get_jwt_identity+from app import pathsfrom app.middleware.rbac import admin_required, app_access_tierfrom app.models import User, Applicationfrom app.services.git_service import GitService@@ -189,8 +192,16 @@ def clone_repository():if missing:return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400+ # GHSA-8vx6-432p-h62q: app_path is attacker-controlled here (unlike+ # /apps/from-repository, which derives it server-side). Confine clones to+ # the managed apps root, mirroring _assert_managed_app_path.+ base_dir = os.path.abspath(paths.APPS_DIR)+ app_path = os.path.abspath(data['app_path'])+ if app_path == base_dir or not app_path.startswith(base_dir + os.sep):+ return jsonify({'error': 'app_path must be inside the managed apps directory'}), 400+result = GitService.clone_repository(- app_path=data['app_path'],+ app_path=app_path,repo_url=data['repo_url'],branch=data.get('branch', 'main'))diff --git a/backend/app/services/git_deploy_service.py b/backend/app/services/git_deploy_service.pyindex f90f1b2b..e2fdeb66 100644--- a/backend/app/services/git_deploy_service.py+++ b/backend/app/services/git_deploy_service.py@@ -8,6 +8,8 @@ import loggingfrom datetime import datetimefrom typing import Dict, Optional+from app.utils.git_security import git_argv, git_env, validate_ref_name+logger = logging.getLogger(__name__)@@ -337,11 +339,18 @@ class GitDeployService:if not os.path.exists(git_dir):return {'success': False, 'error': 'Not a git repository'}+ # The branch flows in from API bodies and webhook configs; validate it+ # and terminate options with '--' so it cannot be parsed as a git flag+ # (GHSA-8vx6-432p-h62q).+ ref_error = validate_ref_name(branch, 'branch')+ if ref_error:+ return {'success': False, 'error': ref_error}+try:# Fetch and reset to remote branchcommands = [- ['git', 'fetch', 'origin', branch],- ['git', 'reset', '--hard', f'origin/{branch}']+ git_argv('fetch', 'origin', '--', branch),+ git_argv('reset', '--hard', f'origin/{branch}')]output = []@@ -351,7 +360,8 @@ class GitDeployService:cwd=path,capture_output=True,text=True,- timeout=120+ timeout=120,+ env=git_env())output.append(f"$ {' '.join(cmd)}")output.append(result.stdout)diff --git a/backend/app/services/git_service.py b/backend/app/services/git_service.pyindex f788d277..4b0e6db3 100644--- a/backend/app/services/git_service.py+++ b/backend/app/services/git_service.py@@ -9,6 +9,13 @@ from typing import Dict, List, Optionalfrom pathlib import Pathfrom app import paths+from app.utils.git_security import (+ git_argv,+ git_env,+ validate_clone_path,+ validate_ref_name,+ validate_repo_url,+)class GitService:@@ -104,16 +111,31 @@ class GitService:@classmethoddef clone_repository(cls, app_path: str, repo_url: str, branch: str = 'main') -> Dict:"""Clone a Git repository."""+ # GHSA-8vx6-432p-h62q: repo_url and app_path are user-controlled on+ # several routes. Validate both and terminate options with '--' — the+ # terminator is load-bearing: protocol pinning alone does not stop+ # option injection such as app_path='--upload-pack=<cmd>'.+ url_error = validate_repo_url(repo_url)+ if url_error:+ return {'success': False, 'error': url_error}+ path_error = validate_clone_path(app_path)+ if path_error:+ return {'success': False, 'error': path_error}+ ref_error = validate_ref_name(branch, 'branch')+ if ref_error:+ return {'success': False, 'error': ref_error}+try:# Remove existing directory if existsif os.path.exists(app_path):return {'success': False, 'error': 'Directory already exists'}- cmd = ['git', 'clone']+ cmd = git_argv('clone')if branch:cmd.extend(['--branch', branch, '--single-branch'])- cmd.extend([repo_url, app_path])- result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)+ cmd.extend(['--', repo_url, app_path])+ result = subprocess.run(cmd, capture_output=True, text=True,+ timeout=300, env=git_env())if result.returncode == 0:return {@@ -134,10 +156,15 @@ class GitService:if not os.path.exists(os.path.join(app_path, '.git')):return {'success': False, 'error': 'Not a Git repository'}+ ref_error = validate_ref_name(branch, 'branch')+ if ref_error:+ return {'success': False, 'error': ref_error}+try:# Fetch first- fetch_cmd = ['git', '-C', app_path, 'fetch', '--all']- subprocess.run(fetch_cmd, capture_output=True, text=True, timeout=60)+ fetch_cmd = git_argv('-C', app_path, 'fetch', '--all')+ subprocess.run(fetch_cmd, capture_output=True, text=True, timeout=60,+ env=git_env())# Get current branch if not specifiedif not branch:@@ -146,8 +173,9 @@ class GitService:branch = result.stdout.strip() if result.returncode == 0 else 'main'# Reset to remote branch (force pull)- reset_cmd = ['git', '-C', app_path, 'reset', '--hard', f'origin/{branch}']- result = subprocess.run(reset_cmd, capture_output=True, text=True, timeout=60)+ reset_cmd = git_argv('-C', app_path, 'reset', '--hard', f'origin/{branch}')+ result = subprocess.run(reset_cmd, capture_output=True, text=True, timeout=60,+ env=git_env())if result.returncode == 0:# Get new commit info@@ -390,9 +418,17 @@ class GitService:@classmethoddef get_remote_branches_from_url(cls, repo_url: str) -> Dict:"""Get list of branches from a remote repository URL without cloning."""+ # GHSA-8vx6-432p-h62q: reachable by any authenticated role via+ # POST /deploy/branches. Validate the URL (blocks ext::/file:// and+ # option injection) and pin protocols regardless of host git version.+ url_error = validate_repo_url(repo_url)+ if url_error:+ return {'success': False, 'error': url_error}+try:- cmd = ['git', 'ls-remote', '--heads', repo_url]- result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)+ cmd = git_argv('ls-remote', '--heads', '--', repo_url)+ result = subprocess.run(cmd, capture_output=True, text=True,+ timeout=30, env=git_env())if result.returncode != 0:return {'success': False, 'error': result.stderr or 'Failed to fetch branches'}diff --git a/backend/app/utils/git_security.py b/backend/app/utils/git_security.pynew file mode 100644index 00000000..f5c71586--- /dev/null+++ b/backend/app/utils/git_security.py@@ -0,0 +1,169 @@+"""Shared validation and hardening helpers for git subprocess invocations.++All git calls that interpolate user-influenced values (repository URLs, branch+names, destination paths) must go through these helpers. They defend against+argument/option injection (CWE-88), which list-form ``subprocess.run`` does+NOT prevent: git interprets its own arguments, so an attacker-controlled value+such as ``ext::sh -c <cmd>``, ``file:///etc/repo`` or ``--upload-pack=<cmd>``+is otherwise executed by git itself.++Defences applied here (GHSA-8vx6-432p-h62q):++1. Scheme allowlist for repository URLs (https/http/git/ssh + scp-like SSH).+ Rejects the ``ext::`` transport, ``file://`` and bare local paths.+2. Rejection of values beginning with ``-`` (option injection).+3. ``-c protocol.ext.allow=never -c protocol.file.allow=never`` pinned on+ every network-touching git invocation, plus a restrictive+ ``GIT_ALLOW_PROTOCOL`` in the subprocess environment. This closes the+ transport-selection tiers regardless of the host's git version (the+ ``protocol.ext.allow=user`` default only changed in git 2.52).+4. ``--`` positional terminator before URL/path/refspec arguments. This is+ co-load-bearing with protocol pinning: pinning restricts transports only+ and does NOT stop option injection such as ``--upload-pack=<cmd>``; only+ the terminator does.+5. Branch/ref name validation (leading ``-``, whitespace, ref-format+ metacharacters) for values used as fetch refspecs or ``--branch``.+"""++import os+import re+from typing import List, Optional++# Schemes allowed for user-supplied repository URLs. Local paths, file:// and+# ext:: are deliberately excluded: the panel has no legitimate need to clone+# from the local filesystem, and ext:: executes arbitrary commands.+ALLOWED_REPO_SCHEMES = ('https', 'http', 'git', 'ssh')++# Config pinned on every git invocation that talks to a remote. Belt-and-+# braces alongside URL validation; also protects repositories whose stored+# origin URL was configured before validation existed.+GIT_PROTOCOL_PIN = [+ '-c', 'protocol.ext.allow=never',+ '-c', 'protocol.file.allow=never',+]++# scp-like SSH syntax: [user@]host:path (single colon, no "://" prefix).+_SCP_LIKE_RE = re.compile(r'^[A-Za-z0-9_.-]+@[A-Za-z0-9_.-]+:[^-\s].*$')++# Characters never legal in a git ref/branch component (see git-check-ref-format).+_REF_ILLEGAL_CHARS = (' ', '\t', '\n', '\r', '~', '^', ':', '?', '*', '[', '\\', '..', '@{')++_SCHEME_RE = re.compile(r'^([A-Za-z][A-Za-z0-9+.-]*)://')+++def validate_repo_url(repo_url: str) -> Optional[str]:+ """Validate a user-supplied git repository URL.++ Returns None when valid, otherwise a human-readable error string.+ Accepts only http(s)://, git://, ssh:// URLs and scp-like SSH syntax+ (user@host:path). Rejects local paths, file://, ext:: and anything that+ could be parsed as a git option or transport specifier.+ """+ if not repo_url or not isinstance(repo_url, str):+ return 'Repository URL is required'++ url = repo_url.strip()+ if not url or len(url) > 2048:+ return 'Invalid repository URL'++ # Option injection guard: a leading '-' makes git parse the value as a flag.+ if url.startswith('-'):+ return 'Invalid repository URL'++ # Transport injection guard: 'ext::cmd' / '<proto>::<cmd>' syntax.+ if '::' in url:+ return 'Invalid repository URL'++ # No whitespace or control characters in any accepted form.+ if any(c.isspace() or ord(c) < 0x20 for c in url):+ return 'Invalid repository URL'++ scheme_match = _SCHEME_RE.match(url)+ if scheme_match:+ if scheme_match.group(1).lower() not in ALLOWED_REPO_SCHEMES:+ return (f'Repository URL scheme "{scheme_match.group(1)}" is not allowed '+ f'(allowed: {", ".join(ALLOWED_REPO_SCHEMES)})')+ return None++ # No scheme: only scp-like SSH syntax (user@host:path) is acceptable.+ if _SCP_LIKE_RE.match(url):+ return None++ return ('Invalid repository URL: use an http(s)://, git:// or ssh:// URL, '+ 'or SSH syntax (user@host:path)')+++def validate_ref_name(ref: str, what: str = 'branch') -> Optional[str]:+ """Validate a branch/tag/ref name used in a git invocation.++ Returns None when valid, otherwise an error string. Guards both option+ injection (leading '-') and ref-format metacharacters.+ """+ if not ref or not isinstance(ref, str):+ return None # Absent ref is fine; callers default it.++ name = ref.strip()+ if not name or len(name) > 255:+ return f'Invalid {what} name'++ if name.startswith('-'):+ return f'Invalid {what} name'++ if any(c in name for c in _REF_ILLEGAL_CHARS):+ return f'Invalid {what} name'++ if any(ord(c) < 0x20 or ord(c) == 0x7F for c in name):+ return f'Invalid {what} name'++ if name.startswith('/') or name.endswith('/') or '//' in name:+ return f'Invalid {what} name'++ if name.endswith('.') or name.endswith('.lock') or '.lock/' in name:+ return f'Invalid {what} name'++ return None+++def validate_clone_path(path: str) -> Optional[str]:+ """Validate a clone destination path used as a git positional argument.++ Returns None when valid, otherwise an error string. The path must be+ absolute, must not begin with '-', and must not be a URL/transport+ specifier. Callers that manage a dedicated apps root should additionally+ confine the path to that root (see the /deploy/clone route).+ """+ if not path or not isinstance(path, str):+ return 'Destination path is required'++ candidate = path.strip()+ if not candidate or candidate.startswith('-'):+ return 'Invalid destination path'++ if not os.path.isabs(candidate):+ return 'Destination path must be absolute'++ if '::' in candidate or any(ord(c) < 0x20 for c in candidate):+ return 'Invalid destination path'++ return None+++def git_argv(*args: str) -> List[str]:+ """Build a git argv with protocol pinning pre-applied.++ Example: ``git_argv('ls-remote', '--heads', '--', url)`` ->+ ``['git', '-c', 'protocol.ext.allow=never', '-c',+ 'protocol.file.allow=never', 'ls-remote', '--heads', '--', url]``+ """+ return ['git', *GIT_PROTOCOL_PIN, *args]+++def git_env() -> dict:+ """Subprocess environment with a restrictive GIT_ALLOW_PROTOCOL.++ Complements the per-invocation config pinning: any transport helper git+ might spawn is additionally limited to the allowlisted protocols.+ """+ env = dict(os.environ)+ env['GIT_ALLOW_PROTOCOL'] = ':'.join(ALLOWED_REPO_SCHEMES)+ return envdiff --git a/backend/tests/BASELINE_COUNT b/backend/tests/BASELINE_COUNTindex e0f118c0..2f09edac 100644--- a/backend/tests/BASELINE_COUNT+++ b/backend/tests/BASELINE_COUNT@@ -1 +1 @@-3175\ No newline at end of file+3234diff --git a/backend/tests/test_git_security.py b/backend/tests/test_git_security.pynew file mode 100644index 00000000..83d5ffa8--- /dev/null+++ b/backend/tests/test_git_security.py@@ -0,0 +1,238 @@+"""Regression tests for GHSA-8vx6-432p-h62q — authenticated argument injection+into git subprocesses (repo_url transport selection, --upload-pack option+injection via app_path, branch refspec injection).++Pure unit tests: validators are exercised directly, and the git services are+tested with subprocess.run mocked so no git binary or network is needed.+"""++from unittest import mock++from app.utils.git_security import (+ ALLOWED_REPO_SCHEMES,+ git_argv,+ git_env,+ validate_clone_path,+ validate_ref_name,+ validate_repo_url,+)+from app.services.git_service import GitService+from app.services.git_deploy_service import GitDeployService+++# --------------------------------------------------------------------------- #+# validate_repo_url+# --------------------------------------------------------------------------- #+class TestValidateRepoUrl:+ def test_accepts_https(self):+ assert validate_repo_url('https://github.com/org/repo.git') is None++ def test_accepts_http_git_ssh_schemes(self):+ assert validate_repo_url('http://git.example.com/org/repo.git') is None+ assert validate_repo_url('git://git.example.com/org/repo.git') is None+ assert validate_repo_url('ssh://[email protected]/org/repo.git') is None++ def test_accepts_scp_like_ssh(self):+ assert validate_repo_url('[email protected]:org/repo.git') is None++ def test_rejects_ext_transport(self):+ assert validate_repo_url('ext::sh -c id>&2') is not None+ assert validate_repo_url('fd::17/foo') is not None++ def test_rejects_file_scheme(self):+ assert validate_repo_url('file:///etc/secret-repo') is not None++ def test_rejects_local_paths(self):+ assert validate_repo_url('/var/serverkit/apps/seed') is not None+ assert validate_repo_url('../outside') is not None+ assert validate_repo_url('relative/path') is not None++ def test_rejects_leading_dash(self):+ assert validate_repo_url('--upload-pack=evil') is not None++ def test_rejects_whitespace_and_control_chars(self):+ assert validate_repo_url('https://example.com/a b.git') is not None+ assert validate_repo_url('https://example.com/a\nb.git') is not None++ def test_rejects_empty(self):+ assert validate_repo_url('') is not None+ assert validate_repo_url(None) is not None+ assert validate_repo_url(' ') is not None+++# --------------------------------------------------------------------------- #+# validate_ref_name+# --------------------------------------------------------------------------- #+class TestValidateRefName:+ def test_accepts_common_branch_names(self):+ assert validate_ref_name('main') is None+ assert validate_ref_name('feature/login-page') is None+ assert validate_ref_name('release-1.2.3') is None++ def test_absent_ref_is_allowed(self):+ assert validate_ref_name(None) is None+ assert validate_ref_name('') is None++ def test_rejects_option_injection(self):+ assert validate_ref_name('--upload-pack=sh -c id') is not None+ assert validate_ref_name('-oFoo') is not None++ def test_rejects_ref_metacharacters(self):+ assert validate_ref_name('foo..bar') is not None+ assert validate_ref_name('foo bar') is not None+ assert validate_ref_name('foo:bar') is not None+ assert validate_ref_name('foo@{bar') is not None+++# --------------------------------------------------------------------------- #+# validate_clone_path+# --------------------------------------------------------------------------- #+class TestValidateClonePath:+ def test_accepts_absolute_path(self):+ assert validate_clone_path('/var/serverkit/apps/myapp') is None++ def test_rejects_option_injection(self):+ assert validate_clone_path('--upload-pack=sh -c "id>&2"') is not None++ def test_rejects_relative_path(self):+ assert validate_clone_path('apps/myapp') is not None++ def test_rejects_empty(self):+ assert validate_clone_path('') is not None+ assert validate_clone_path(None) is not None+++# --------------------------------------------------------------------------- #+# argv/env helpers+# --------------------------------------------------------------------------- #+class TestHelpers:+ def test_git_argv_pins_protocols(self):+ argv = git_argv('ls-remote', '--heads', '--', 'https://x/y.git')+ assert argv[:5] == [+ 'git',+ '-c', 'protocol.ext.allow=never',+ '-c', 'protocol.file.allow=never',+ ]+ assert argv[-4:] == ['ls-remote', '--heads', '--', 'https://x/y.git']++ def test_git_env_restricts_protocols(self):+ env = git_env()+ assert env['GIT_ALLOW_PROTOCOL'] == ':'.join(ALLOWED_REPO_SCHEMES)+ assert 'ext' not in env['GIT_ALLOW_PROTOCOL'].split(':')+ assert 'file' not in env['GIT_ALLOW_PROTOCOL'].split(':')+++# --------------------------------------------------------------------------- #+# GitService.clone_repository+# --------------------------------------------------------------------------- #+class TestCloneRepository:+ def _run_clone(self, app_path='/tmp/sk-clone-target', repo_url='https://x/y.git',+ branch='main'):+ completed = mock.Mock(returncode=0, stdout='', stderr='')+ with mock.patch('app.services.git_service.subprocess.run',+ return_value=completed) as run_mock, \+ mock.patch('app.services.git_service.os.path.exists', return_value=False):+ result = GitService.clone_repository(app_path, repo_url, branch)+ return result, run_mock++ def test_valid_clone_invocation_is_hardened(self):+ result, run_mock = self._run_clone()+ assert result['success'] is True+ argv = run_mock.call_args[0][0]+ # Protocol pinning present.+ assert 'protocol.ext.allow=never' in argv+ assert 'protocol.file.allow=never' in argv+ # '--' terminator separates options from positionals.+ terminator = argv.index('--')+ assert argv[terminator + 1] == 'https://x/y.git'+ assert argv[terminator + 2] == '/tmp/sk-clone-target'+ # Restrictive protocol env.+ assert run_mock.call_args[1]['env']['GIT_ALLOW_PROTOCOL'] == 'https:http:git:ssh'++ def test_ext_transport_rejected_without_subprocess(self):+ result, run_mock = self._run_clone(repo_url='ext::sh -c id>&2')+ assert result['success'] is False+ run_mock.assert_not_called()++ def test_file_scheme_rejected_without_subprocess(self):+ result, run_mock = self._run_clone(repo_url='file:///etc/repo')+ assert result['success'] is False+ run_mock.assert_not_called()++ def test_local_path_repo_rejected_without_subprocess(self):+ result, run_mock = self._run_clone(repo_url='/var/serverkit/apps/seed')+ assert result['success'] is False+ run_mock.assert_not_called()++ def test_upload_pack_option_in_app_path_rejected_without_subprocess(self):+ result, run_mock = self._run_clone(+ app_path='--upload-pack=sh -c "id>&2"')+ assert result['success'] is False+ run_mock.assert_not_called()++ def test_malicious_branch_rejected_without_subprocess(self):+ result, run_mock = self._run_clone(branch='--upload-pack=evil')+ assert result['success'] is False+ run_mock.assert_not_called()+++# --------------------------------------------------------------------------- #+# GitService.get_remote_branches_from_url+# --------------------------------------------------------------------------- #+class TestGetRemoteBranchesFromUrl:+ def _run_ls_remote(self, repo_url):+ completed = mock.Mock(returncode=0, stdout='abc123\trefs/heads/main\n',+ stderr='')+ with mock.patch('app.services.git_service.subprocess.run',+ return_value=completed) as run_mock:+ result = GitService.get_remote_branches_from_url(repo_url)+ return result, run_mock++ def test_valid_url_uses_terminator_and_pinning(self):+ result, run_mock = self._run_ls_remote('https://github.com/org/repo.git')+ assert result['success'] is True+ assert result['branches'] == ['main']+ argv = run_mock.call_args[0][0]+ assert 'protocol.ext.allow=never' in argv+ assert argv[-2:] == ['--', 'https://github.com/org/repo.git']++ def test_ext_transport_rejected_without_subprocess(self):+ result, run_mock = self._run_ls_remote('ext::sh -c id>&2')+ assert result['success'] is False+ run_mock.assert_not_called()++ def test_file_scheme_rejected_without_subprocess(self):+ result, run_mock = self._run_ls_remote('file:///etc/repo')+ assert result['success'] is False+ run_mock.assert_not_called()++ def test_leading_dash_rejected_without_subprocess(self):+ result, run_mock = self._run_ls_remote('--upload-pack=evil')+ assert result['success'] is False+ run_mock.assert_not_called()+++# --------------------------------------------------------------------------- #+# GitDeployService._git_pull+# --------------------------------------------------------------------------- #+class TestGitPull:+ def _run_pull(self, branch='main'):+ completed = mock.Mock(returncode=0, stdout='', stderr='')+ with mock.patch('app.services.git_deploy_service.subprocess.run',+ return_value=completed) as run_mock, \+ mock.patch('app.services.git_deploy_service.os.path.exists',+ return_value=True):+ result = GitDeployService._git_pull('/srv/app', branch)+ return result, run_mock++ def test_fetch_uses_terminator(self):+ result, run_mock = self._run_pull('main')+ assert result['success'] is True+ fetch_argv = run_mock.call_args_list[0][0][0]+ assert fetch_argv[-3:] == ['origin', '--', 'main']+ assert 'protocol.ext.allow=never' in fetch_argv++ def test_malicious_branch_rejected_without_subprocess(self):+ result, run_mock = self._run_pull('--upload-pack=evil')+ assert result['success'] is False+ run_mock.assert_not_called()