Skip to content

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.

fix(php): guard pool paths and stop fabricating unreadable pool configs

Juan Denis452a2d43aebf
diff --git a/backend/app/services/php_service.py b/backend/app/services/php_service.py
index 899ac80b..3b62f856 100644
--- a/backend/app/services/php_service.py
+++ b/backend/app/services/php_service.py
@@ -229,7 +229,9 @@ env[TEMP] = /tmp
def get_pools(cls, version: str) -> List[Dict]:
"""Get FPM pools for a PHP version."""
pools = []
- pool_dir = cls.PHP_FPM_CONF_DIR.format(version=version)
+ pool_dir, error = cls._pool_dir(version)
+ if error:
+ return pools
if not os.path.exists(pool_dir):
return pools
@@ -240,6 +242,14 @@ env[TEMP] = /tmp
pool_name = filename[:-5] # Remove .conf
filepath = os.path.join(pool_dir, filename)
config = cls._parse_pool_config(filepath)
+ if config is None:
+ # Unreadable file: report the honest unknown, not
+ # fabricated www-data/dynamic defaults.
+ pools.append({'name': pool_name, 'file': filepath,
+ 'user': None, 'listen': None,
+ 'pm': None, 'max_children': None,
+ 'unreadable': True})
+ continue
pools.append({
'name': pool_name,
'file': filepath,
@@ -253,9 +263,31 @@ env[TEMP] = /tmp
return pools
+ # Version/pool-name guards: both land in a filesystem path handed to
+ # privileged write/rm, so they must never carry separators or dot-dot.
+ _VERSION_RE = re.compile(r'^\d+\.\d+$')
+ _POOL_NAME_RE = re.compile(r'^[A-Za-z0-9_][A-Za-z0-9_.-]*$')
+
+ @classmethod
+ def _pool_dir(cls, version):
+ """(pool_dir, None) for a well-formed version, else (None, error)."""
+ if not cls._VERSION_RE.match(str(version or '')):
+ return None, f'invalid PHP version: {version!r}'
+ return cls.PHP_FPM_CONF_DIR.format(version=version), None
+
@classmethod
- def _parse_pool_config(cls, filepath: str) -> Dict:
- """Parse a pool configuration file."""
+ def _pool_file(cls, version, pool_name):
+ """(pool_file, None) for well-formed inputs, else (None, error)."""
+ pool_dir, error = cls._pool_dir(version)
+ if error:
+ return None, error
+ if not cls._POOL_NAME_RE.match(str(pool_name or '')):
+ return None, f'invalid pool name: {pool_name!r}'
+ return os.path.join(pool_dir, f'{pool_name}.conf'), None
+
+ @classmethod
+ def _parse_pool_config(cls, filepath: str) -> Optional[Dict]:
+ """Parse a pool configuration file; None when it cannot be read."""
config = {}
try:
with open(filepath, 'r') as f:
@@ -265,14 +297,15 @@ env[TEMP] = /tmp
key, value = line.split('=', 1)
config[key.strip()] = value.strip()
except Exception:
- pass
+ return None
return config
@classmethod
def create_pool(cls, version: str, pool_name: str, config: Dict = None) -> Dict:
"""Create a new FPM pool."""
- pool_dir = cls.PHP_FPM_CONF_DIR.format(version=version)
- pool_file = os.path.join(pool_dir, f'{pool_name}.conf')
+ pool_file, error = cls._pool_file(version, pool_name)
+ if error:
+ return {'success': False, 'error': error}
if os.path.exists(pool_file):
return {'success': False, 'error': f'Pool {pool_name} already exists'}
@@ -321,8 +354,9 @@ env[TEMP] = /tmp
@classmethod
def delete_pool(cls, version: str, pool_name: str) -> Dict:
"""Delete an FPM pool."""
- pool_dir = cls.PHP_FPM_CONF_DIR.format(version=version)
- pool_file = os.path.join(pool_dir, f'{pool_name}.conf')
+ pool_file, error = cls._pool_file(version, pool_name)
+ if error:
+ return {'success': False, 'error': error}
if not os.path.exists(pool_file):
return {'success': False, 'error': f'Pool {pool_name} not found'}
diff --git a/backend/tests/test_php_pool_guards.py b/backend/tests/test_php_pool_guards.py
new file mode 100644
index 00000000..13409c78
--- /dev/null
+++ b/backend/tests/test_php_pool_guards.py
@@ -0,0 +1,71 @@
+"""PHP-FPM pool name/version guards + honest unreadable pools (plan 82 §F.3).
+
+version and pool_name both come straight from the URL into a filesystem path
+handed to privileged write/rm — a traversal pool_name reached
+``run_privileged(['rm', <escaped path>])``. And an unreadable pool file used
+to list as ``user: www-data, pm: dynamic`` — fabricated defaults, not the
+honest unknown (the probe-honesty house rule).
+"""
+import pytest
+
+from app.services.php_service import PHPService
+
+
+class TestPathGuards:
+ def test_create_rejects_traversal_pool_name(self):
+ res = PHPService.create_pool('8.2', '../../etc/cron.d/evil', {})
+ assert res['success'] is False
+ assert 'invalid pool name' in res['error']
+
+ def test_delete_rejects_traversal_pool_name(self):
+ res = PHPService.delete_pool('8.2', '../www')
+ assert res['success'] is False
+ assert 'invalid pool name' in res['error']
+
+ def test_rejects_traversal_version(self):
+ res = PHPService.delete_pool('8.2/../..', 'www2')
+ assert res['success'] is False
+ assert 'invalid PHP version' in res['error']
+
+ @pytest.mark.parametrize('bad', ['', 'a/b', 'a\\b', '.hidden', '..',
+ 'name with space', 'a;b'])
+ def test_rejects_malformed_pool_names(self, bad):
+ path, error = PHPService._pool_file('8.2', bad)
+ assert path is None and 'invalid pool name' in error
+
+ @pytest.mark.parametrize('good', ['www2', 'my-app', 'my_app', 'my.site',
+ 'App9'])
+ def test_accepts_conventional_pool_names(self, good):
+ path, error = PHPService._pool_file('8.2', good)
+ assert error is None
+ assert path == f'/etc/php/8.2/fpm/pool.d/{good}.conf'
+
+
+class TestHonestParsing:
+ def test_unreadable_pool_lists_as_unknown_not_defaults(self, tmp_path, monkeypatch):
+ pool_dir = tmp_path / 'pool.d'
+ pool_dir.mkdir()
+ (pool_dir / 'ok.conf').write_text('[ok]\nuser = deploy\npm = static\n')
+ monkeypatch.setattr(PHPService, '_parse_pool_config',
+ classmethod(lambda cls, p:
+ None if p.endswith('broken.conf')
+ else {'user': 'deploy', 'pm': 'static'}))
+ (pool_dir / 'broken.conf').write_text('')
+
+ monkeypatch.setattr(PHPService, '_pool_dir',
+ classmethod(lambda cls, v: (str(pool_dir), None)))
+ pools = {p['name']: p for p in PHPService.get_pools('8.2')}
+
+ assert pools['ok']['user'] == 'deploy'
+ assert pools['broken']['unreadable'] is True
+ assert pools['broken']['user'] is None # not 'www-data'
+ assert pools['broken']['pm'] is None # not 'dynamic'
+
+ def test_parse_returns_none_for_missing_file(self, tmp_path):
+ assert PHPService._parse_pool_config(str(tmp_path / 'nope.conf')) is None
+
+ def test_parse_reads_real_file(self, tmp_path):
+ f = tmp_path / 'p.conf'
+ f.write_text('[p]\n; comment\nuser = deploy\npm.max_children = 12\n')
+ cfg = PHPService._parse_pool_config(str(f))
+ assert cfg == {'user': 'deploy', 'pm.max_children': '12'}