Files
pterodactyl-panel/app/Http/Middleware/VerifyReCaptcha.php
T
Sandip Ghimire bb4e89826e fix(security): harden path validation, session revocation, and request handling (#7255)
# Security, Validation & Session Improvements

## Changes

* **Hardened IP/CIDR validation**
* Properly handles invalid IP addresses and CIDR ranges during API key
creation.
* Invalid IP/CIDR data now fails safely instead of causing a 500 error.

* **Improved reCAPTCHA error handling**
  * Handles network and verification failures gracefully.
  * Fixed undefined result notices and removed duplicate checks.

* **Added file permission activity logging**
* File permission (`chmod`) changes are now recorded in the activity
log.

* **Removed duplicate 2FA middleware**
* Cleaned up duplicate `RequireTwoFactorAuthentication` registration
from API routes.

* **Improved session revocation on password changes**
  * Password changes now invalidate other active sessions.
* Rotates the `remember_token` and removes stale database sessions where
applicable.
* Applies consistently across password resets and user password changes.

* **Reduced unnecessary public storage access**
* Disabled automatic public storage routes for the local filesystem disk
to reduce the attack surface.

* **Hardened file manager request validation**
  * Added strict validation for file permission modes.
  * Fixed optional `root` validation rules.
  * Added length limits for file paths, roots, and file/folder names.

* **Hardened mount source and target path validation**
* Prevents path traversal and subpath-based bypasses in mount source and
target validation.
  * Handles trailing slashes and normalized paths correctly.
* Prevents mounts from targeting protected subdirectories, such as
another server's volume directory.
2026-10-07 12:39:12 -04:00

118 lines
3.5 KiB
PHP

<?php
declare(strict_types=1);
namespace Pterodactyl\Http\Middleware;
use Closure;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Pterodactyl\Events\Auth\FailedCaptcha;
use Pterodactyl\Support\JsonValueGuard;
use Symfony\Component\HttpKernel\Exception\HttpException;
class VerifyReCaptcha
{
/**
* VerifyReCaptcha constructor.
*/
public function __construct(private readonly Dispatcher $dispatcher, private readonly Repository $config) {}
/**
* Handle an incoming request.
*/
/**
* @param Closure(Request): \Symfony\Component\HttpFoundation\Response $next
* @return \Symfony\Component\HttpFoundation\Response
*/
public function handle(Request $request, Closure $next): mixed
{
if (! $this->config->get('recaptcha.enabled')) {
return $next($request);
}
$result = $this->verifyCaptcha($request);
$domainValid = ! $this->config->get('recaptcha.verify_domain') || $this->isResponseVerified($result, $request);
if ($result['success'] && $domainValid) {
return $next($request);
}
$this->dispatcher->dispatch(
new FailedCaptcha(
$request->ip() ?? 'unknown',
$result['hostname'] ?? 'unknown'
)
);
throw new HttpException(Response::HTTP_BAD_REQUEST, 'Failed to validate reCAPTCHA data.');
}
/**
* @return array{success: bool, hostname: string|null}
*/
private function verifyCaptcha(Request $request): array
{
if (! $request->filled('g-recaptcha-response')) {
return ['success' => false, 'hostname' => null];
}
try {
$client = new Client(['timeout' => 5, 'connect_timeout' => 2]);
$res = $client->post(JsonValueGuard::string($this->config->get('recaptcha.domain')), [
'form_params' => [
'secret' => $this->config->get('recaptcha.secret_key'),
'response' => $request->input('g-recaptcha-response'),
],
]);
if ($res->getStatusCode() === 200) {
return $this->decodeResponse($res->getBody()->__toString());
}
} catch (GuzzleException $exception) {
// Ignore the error entirely, we will just return a failed response below.
}
return ['success' => false, 'hostname' => null];
}
/**
* Determine if the response from the recaptcha servers was valid.
*/
/**
* @param array{success: bool, hostname: string|null} $result
*/
private function isResponseVerified(array $result, Request $request): bool
{
$url = parse_url($request->url());
return $url !== false && $result['hostname'] === Arr::get($url, 'host');
}
/**
* @return array{success: bool, hostname: string|null}
*/
private function decodeResponse(string $response): array
{
$decoded = json_decode($response, true);
if (! is_array($decoded)) {
return ['success' => false, 'hostname' => null];
}
$success = $decoded['success'] ?? false;
$hostname = $decoded['hostname'] ?? null;
return [
'success' => is_bool($success) && $success,
'hostname' => is_string($hostname) ? $hostname : null,
];
}
}