From bac641f5f934c95800e7446249428dae3ef0020e Mon Sep 17 00:00:00 2001 From: Wisnu Jaya Date: Thu, 22 Oct 2026 15:36:47 +0700 Subject: [PATCH 1/3] feat(security): port rate limiting login & OTP dari #1478 ke rilis-dev Memindahkan isi PR #1478 ke struktur Laravel 13 di rilis-dev: - RateLimiter 'login' dan 'otp' dipindah dari RouteServiceProvider (sudah tidak ada di rilis-dev) ke AppServiceProvider::configureRateLimiting() - routes/web.php: hanya menambah middleware throttle:login / throttle:otp pada rute login, OTP, dan 2FA. Rute Profile dan Data Sarana di rilis-dev tidak berubah (penyebab 85 tes gagal di #1478). - TrustProxies, helper IpAddress, .env.example, cast expiry OTP, dan RateLimitingTest diambil dari #1478. Tes: config/cache.php membaca CACHE_DRIVER, sedangkan phpunit.xml hanya mengatur CACHE_STORE, sehingga tes memakai cache file dan hitungan rate limit bocor antar-tes. Tambah CACHE_DRIVER=array di phpunit.xml(.dist). Refs #1410, #1478 Co-authored-by: Revanza Firdaus --- .env.example | 20 ++- app/Helpers/IpAddress.php | 230 +++++++++++++++++++++++++++ app/Http/Middleware/TrustProxies.php | 51 +++++- app/Mail/OtpMail.php | 2 +- app/Providers/AppServiceProvider.php | 82 ++++++++++ app/Services/OtpService.php | 2 +- phpunit.xml | 1 + phpunit.xml.dist | 1 + routes/web.php | 19 ++- tests/Feature/RateLimitingTest.php | 184 +++++++++++++++++++++ 10 files changed, 583 insertions(+), 9 deletions(-) create mode 100644 app/Helpers/IpAddress.php create mode 100644 tests/Feature/RateLimitingTest.php diff --git a/.env.example b/.env.example index dd29c90472..03390aebe4 100644 --- a/.env.example +++ b/.env.example @@ -81,4 +81,22 @@ TELEGRAM_BOT_TOKEN= # SCRIBE_AUTH_KEY=your-api-key-here # pengaturan cache untuk API, jika ingin menonaktifkan cache, ubah API_CACHE_ENABLED menjadi false API_CACHE_ENABLED=true -API_CACHE_DURATION=3600 # dalam detik (1 jam) \ No newline at end of file +API_CACHE_DURATION=3600 # dalam detik (1 jam) + +# Security Configuration +# Trusted Proxies: Kosongkan untuk tidak trust proxy apapun (default). +# Untuk production di belakang reverse proxy, set ke IP spesifik proxy. +# Contoh Cloudflare IP ranges: https://www.cloudflare.com/ips/ +# Contoh multiple proxies: 103.21.244.0/22,103.22.200.0/22 +# PERINGATAN: Jangan gunakan '*' di production karena risiko IP spoofing. +# TRUST_PROXIES= + +# Rate Limiting Configuration +# Maksimal percobaan login per menit per IP + Email +RATE_LIMIT_LOGIN_MAX=10 +# Waktu decay dalam menit sebelum limit di-reset +RATE_LIMIT_LOGIN_DECAY=1 + +# Rate Limiting untuk OTP (lebih strict dari login) +RATE_LIMIT_OTP_MAX=3 +RATE_LIMIT_OTP_DECAY=1 diff --git a/app/Helpers/IpAddress.php b/app/Helpers/IpAddress.php new file mode 100644 index 0000000000..62f821baa9 --- /dev/null +++ b/app/Helpers/IpAddress.php @@ -0,0 +1,230 @@ +ip() ?? $request->server('REMOTE_ADDR', '127.0.0.1'); + } + + /** + * Ekstrak IP dari header proxy yang tersedia. + */ + private static function extractIpFromProxyHeaders(Request $request): ?string + { + foreach (self::PROXY_HEADERS as $header) { + $headerValue = $request->server->get('HTTP_'.$header); + + if ($headerValue === null || $headerValue === '') { + continue; + } + + // X-Forwarded-For bisa berisi multiple IP, ambil yang pertama (client IP) + if ($header === 'X_FORWARDED_FOR') { + $firstIp = self::parseFirstIp($headerValue); + + if ($firstIp !== null && $firstIp !== '') { + return $firstIp; + } + + continue; + } + + // CF-Connecting-IP dan X-Real-IP berisi single IP + $cleaned = trim($headerValue); + + if ($cleaned !== '') { + return $cleaned; + } + } + + return null; + } + + /** + * Parse IP pertama dari daftar comma-separated (X-Forwarded-For). + */ + private static function parseFirstIp(string $ipList): ?string + { + if (str_contains($ipList, ',')) { + $ips = explode(',', $ipList); + $first = trim($ips[0]); + + return $first !== '' ? $first : null; + } + + return trim($ipList); + } + + /** + * Validasi format alamat IP (IPv4 atau IPv6). + */ + private static function isValidIpAddress(string $ip): bool + { + return filter_var($ip, FILTER_VALIDATE_IP) !== false; + } + + /** + * Bersihkan alamat IP dari port atau karakter tidak valid. + * + * Menangani kasus: + * - IPv4 dengan port (contoh: 192.168.1.1:8080) + * - IPv6 dengan port (contoh: [::1]:8080) + * - Header injection attempts (newline characters) + * - IPv4-mapped IPv6 addresses (contoh: ::ffff:192.168.1.1) + */ + private static function cleanIpAddress(string $ip): string + { + // Hapus karakter newline dan control characters untuk mencegah header injection + $cleaned = preg_replace('/[\r\n\t\x00-\x1F\x7F]/', '', $ip); + + if ($cleaned === null) { + return $ip; + } + + $cleaned = trim($cleaned); + + // Handle IPv6 dengan port: [::1]:8080 + if (str_starts_with($cleaned, '[')) { + $bracketPos = strpos($cleaned, ']'); + + if ($bracketPos !== false) { + return substr($cleaned, 1, $bracketPos - 1); + } + } + + // Handle IPv4 dengan port: 192.168.1.1:8080 + // Hanya jika ada tepat satu colon dan valid IPv4 + if (substr_count($cleaned, ':') === 1) { + $colonPos = strrpos($cleaned, ':'); + $possibleIp = substr($cleaned, 0, $colonPos); + + if (filter_var($possibleIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) { + return $possibleIp; + } + } + + // Handle IPv4-mapped IPv6: ::ffff:192.168.1.1 + // Jangan split colon untuk pure IPv6 addresses + if (filter_var($cleaned, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) { + return $cleaned; + } + + return $cleaned; + } + + /** + * Generate rate limit key dengan sanitasi ketat. + * + * Key format: "rate_limit:{ip}|{identifier}" atau "rate_limit:{ip}" + */ + public static function getRateLimitKey(Request $request, ?string $identifier = null): string + { + $ip = self::getRealIp($request); + + if ($identifier !== null && $identifier !== '') { + // Sanitasi identifier - batasi panjang dan karakter + $identifier = self::sanitizeIdentifier($identifier); + + return "rate_limit:{$ip}|{$identifier}"; + } + + return "rate_limit:{$ip}"; + } + + /** + * Sanitasi identifier untuk rate limiting. + * + * - Hapus null bytes dan control characters + * - Batasi panjang maksimal 320 karakter (RFC 5321) + * - Hanya izinkan karakter alphanumeric dan @._- + */ + private static function sanitizeIdentifier(string $identifier): string + { + // Batasi panjang maksimal + if (strlen($identifier) > 320) { + $identifier = substr($identifier, 0, 320); + } + + // Hapus null bytes dan control characters + $sanitized = preg_replace('/[\x00-\x1F\x7F]/', '', $identifier); + + if ($sanitized === null) { + return ''; + } + + // Hanya izinkan karakter yang aman + $sanitized = preg_replace('/[^a-z0-9@._-]/i', '', $sanitized); + + return $sanitized !== null ? $sanitized : ''; + } +} diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 6bc386d8b9..93ea0da22a 100644 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -34,11 +34,25 @@ use Illuminate\Http\Middleware\TrustProxies as Middleware; use Illuminate\Http\Request; +/** + * Middleware untuk mengatur proxy yang dipercaya + * + * Konfigurasi ini penting ketika aplikasi berada di belakang reverse proxy + * seperti Nginx, Cloudflare, atau load balancer. + * + * Secure by default: tidak mempercayai proxy apapun kecuali dikonfigurasi eksplisit. + * + * @see https://laravel.com/docs/10.x/requests#configuring-trusted-proxies + */ class TrustProxies extends Middleware { /** * The trusted proxies for this application. * + * Secure by default: null berarti tidak trust proxy manapun. + * Untuk production di belakang reverse proxy, set TRUST_PROXIES + * ke IP spesifik proxy (comma-separated) atau gunakan Cloudflare IP ranges. + * * @var array|string|null */ protected $proxies; @@ -46,12 +60,45 @@ class TrustProxies extends Middleware /** * The headers that should be used to detect proxies. * + * Header standar yang dipakai Laravel untuk membaca original client IP + * dari trusted proxy. + * * @var int */ - protected $headers = - Request::HEADER_X_FORWARDED_FOR | + protected $headers = Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO | Request::HEADER_X_FORWARDED_AWS_ELB; + + /** + * Override untuk mendapatkan proxy dari environment variable + * + * PENTING: TRUST_PROXIES=* TIDAK diizinkan karena risiko IP spoofing. + * Jika developer set '*' di environment, akan diabaikan dan return null. + * + * @return array|string|null + */ + protected function proxies() + { + $envProxies = env('TRUST_PROXIES'); + + if ($envProxies === null || $envProxies === '' || $envProxies === '*') { + // Return null: tidak trust proxy headers dari manapun + return null; + } + + // Validasi format IP/CIDR sebelum trust + $proxies = array_map('trim', explode(',', $envProxies)); + $validProxies = []; + + foreach ($proxies as $proxy) { + // Validasi IPv4, IPv6, atau CIDR range + if (filter_var($proxy, FILTER_VALIDATE_IP) || preg_match('/^[\da-fA-F.:]+\/\d+$/', $proxy)) { + $validProxies[] = $proxy; + } + } + + return empty($validProxies) ? null : array_values($validProxies); + } } diff --git a/app/Mail/OtpMail.php b/app/Mail/OtpMail.php index 84e41d6591..8000171def 100644 --- a/app/Mail/OtpMail.php +++ b/app/Mail/OtpMail.php @@ -54,7 +54,7 @@ public function __construct(int $otp, string $purpose = 'login') { $this->otp = $otp; $this->purpose = $purpose; - $this->expiryMinutes = config('otp.expiry_minutes', 5); + $this->expiryMinutes = max(1, (int) config('otp.expiry_minutes', 5)); } /** diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index c77edb3db7..3a335a9eaf 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -31,6 +31,7 @@ namespace App\Providers; +use App\Helpers\IpAddress; use App\Rules\SafeFileContent; use App\Services\ActivityLogService; use App\Services\CacheService; @@ -38,13 +39,16 @@ use Illuminate\Auth\Events\Failed; use Illuminate\Auth\Events\Login; use Illuminate\Auth\Events\Logout; +use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Foundation\AliasLoader; +use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\Paginator; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; +use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Validator; use Illuminate\Support\ServiceProvider; @@ -88,6 +92,8 @@ public function boot(): void Paginator::useBootstrap(); $this->paginate(); + $this->configureRateLimiting(); + if (sudahInstal()) { $this->penduduk(); $this->config(); @@ -137,6 +143,82 @@ public function boot(): void }); } + /** + * Rate limiter untuk login dan OTP (issue #1410). + * (Sebelumnya di RouteServiceProvider::configureRateLimiting()) + */ + protected function configureRateLimiting(): void + { + RateLimiter::for('login', function (Request $request) { + $maxAttempts = max(1, (int) env('RATE_LIMIT_LOGIN_MAX', 10)); + $decayMinutes = max(1, (int) env('RATE_LIMIT_LOGIN_DECAY', 1)); + + $identifier = $this->extractAndValidateIdentifier($request); + + return Limit::perMinute($maxAttempts, $decayMinutes) + ->by(IpAddress::getRateLimitKey($request, $identifier)); + }); + + RateLimiter::for('otp', function (Request $request) { + $maxAttempts = max(1, (int) env('RATE_LIMIT_OTP_MAX', 3)); + $decayMinutes = max(1, (int) env('RATE_LIMIT_OTP_DECAY', 1)); + + $identifier = $this->extractAndValidateIdentifier($request); + + return Limit::perMinute($maxAttempts, $decayMinutes) + ->by(IpAddress::getRateLimitKey($request, $identifier)); + }); + } + + /** + * Extract dan validasi identifier (email/username) dari request. + * + * Validasi: + * - Harus string, bukan array atau tipe lain + * - Batasi panjang maksimal 320 karakter (RFC 5321) + * - Hapus null bytes dan control characters + * - Validasi format email jika terdeteksi sebagai email + */ + protected function extractAndValidateIdentifier(Request $request): ?string + { + $identifier = $request->input('email') + ?? $request->input('username') + ?? $request->input('identity') + ?? $request->input('identifier') + ?? data_get($request->session()->get('two-factor:auth'), 'email') + ?? data_get($request->session()->get('two-factor:auth'), 'id') + ?? data_get($request->session()->get('otp_login'), 'user_id'); + + // Return null jika tidak ada + if ($identifier === null) { + return null; + } + + // Validasi tipe data - harus string + if (! is_string($identifier)) { + return null; + } + + // Batasi panjang maksimal (RFC 5321: 320 characters) + if (strlen($identifier) > 320) { + $identifier = substr($identifier, 0, 320); + } + + // Hapus null bytes dan control characters + $identifier = preg_replace('/[\x00-\x1F\x7F]/', '', $identifier); + + if ($identifier === null) { + return null; + } + + $identifier = mb_strtolower(trim($identifier)); + + // Hanya izinkan karakter yang aman untuk rate limit key + $result = preg_replace('/[^a-z0-9@._-]/', '', $identifier); + + return ($result !== null && $result !== '') ? $result : null; + } + /** * Konfigurasi custom validator untuk data penduduk. */ diff --git a/app/Services/OtpService.php b/app/Services/OtpService.php index 00ff583d47..3c50e5710d 100644 --- a/app/Services/OtpService.php +++ b/app/Services/OtpService.php @@ -75,7 +75,7 @@ public function generateAndSave(User $user, string $channel, string $identifier, ->delete(); // Create new token - $expiryMinutes = config('otp.expiry_minutes', 5); + $expiryMinutes = max(1, (int) config('otp.expiry_minutes', 5)); $token = OtpToken::create([ 'user_id' => $user->id, 'token_hash' => $tokenHash, diff --git a/phpunit.xml b/phpunit.xml index 4cc02de2dd..ec87f3a820 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -52,6 +52,7 @@ + diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 70bdf5b632..1aff4324ad 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -77,6 +77,7 @@ + diff --git a/routes/web.php b/routes/web.php index fcde690df4..9c68233483 100644 --- a/routes/web.php +++ b/routes/web.php @@ -109,6 +109,11 @@ 'register' => false, ]); + Route::namespace('\App\Http\Controllers\Auth')->middleware('guest')->group(function () { + Route::post('/login', 'LoginController@login') + ->middleware('throttle:login'); + }); + // OTP Routes Route::namespace('\App\Http\Controllers\Auth')->middleware('otp.enabled')->group(function () { // OTP Activation (requires auth) @@ -126,13 +131,18 @@ // OTP Login (guest only) Route::middleware('guest')->group(function () { Route::get('/otp/login', 'OtpController@showLoginForm')->name('otp.login'); - Route::post('/otp/request-login', 'OtpController@requestLoginOtp')->name('otp.request-login'); + Route::post('/otp/request-login', 'OtpController@requestLoginOtp') + ->middleware('throttle:otp') + ->name('otp.request-login'); Route::get('/otp/verify-login', 'OtpController@showVerifyLoginForm')->name('otp.verify-login'); - Route::post('/otp/verify-login', 'OtpController@loginWithOtp'); + Route::post('/otp/verify-login', 'OtpController@loginWithOtp') + ->middleware('throttle:login'); }); // OTP Resend (both auth and guest) - Route::post('/otp/resend', 'OtpController@resendOtp')->name('otp.resend'); + Route::post('/otp/resend', 'OtpController@resendOtp') + ->middleware('throttle:otp') + ->name('otp.resend'); }); // 2FA Routes @@ -166,7 +176,8 @@ // 2FA Login Routes (guest access) Route::namespace('\App\Http\Controllers\Auth')->middleware('guest')->group(function () { Route::get('/2fa/verify-login', 'TwoFactorController@showVerifyLoginForm')->name('2fa.verify-login'); - Route::post('/2fa/verify-login', 'TwoFactorController@verifyLogin'); + Route::post('/2fa/verify-login', 'TwoFactorController@verifyLogin') + ->middleware('throttle:login'); }); Route::group(['prefix' => 'filemanager', 'middleware' => ['auth:web', 'action_permission:access.setting']], function () { diff --git a/tests/Feature/RateLimitingTest.php b/tests/Feature/RateLimitingTest.php new file mode 100644 index 0000000000..fd9b6f8cde --- /dev/null +++ b/tests/Feature/RateLimitingTest.php @@ -0,0 +1,184 @@ +logout(); + Mail::fake(); +}); + +test('login is throttled after too many failed attempts for the same email', function () { + $user = User::factory()->create([ + 'email' => 'login-throttle@example.com', + 'password' => Hash::make('password'), + 'status' => 1, + ]); + + for ($attempt = 0; $attempt < 10; $attempt++) { + $response = $this->from(route('login'))->post(route('login'), [ + 'email' => $user->email, + 'password' => 'wrong-password', + ]); + + $response->assertRedirect(route('login')); + } + + $this->post(route('login'), [ + 'email' => $user->email, + 'password' => 'wrong-password', + ])->assertStatus(429); +}); + +test('login rate limit keeps separate buckets for different emails on the same ip', function () { + $throttledUser = User::factory()->create([ + 'email' => 'login-throttle-a@example.com', + 'password' => Hash::make('password'), + 'status' => 1, + ]); + + $otherUser = User::factory()->create([ + 'email' => 'login-throttle-b@example.com', + 'password' => Hash::make('password'), + 'status' => 1, + ]); + + for ($attempt = 0; $attempt < 10; $attempt++) { + $this->from(route('login'))->post(route('login'), [ + 'email' => $throttledUser->email, + 'password' => 'wrong-password', + ])->assertRedirect(route('login')); + } + + $this->post(route('login'), [ + 'email' => $throttledUser->email, + 'password' => 'wrong-password', + ])->assertStatus(429); + + $this->from(route('login'))->post(route('login'), [ + 'email' => $otherUser->email, + 'password' => 'wrong-password', + ])->assertRedirect(route('login')); +}); + +test('otp request is throttled after too many attempts for the same identifier', function () { + $user = User::factory()->create([ + 'email' => 'otp-throttle@example.com', + 'name' => 'otp-throttle', + 'password' => Hash::make('password'), + 'status' => 1, + 'otp_enabled' => true, + 'otp_verified' => true, + 'otp_channel' => 'email', + ]); + + for ($attempt = 0; $attempt < 3; $attempt++) { + $this->post(route('otp.request-login'), [ + 'identifier' => $user->email, + ])->assertRedirect(route('otp.verify-login')); + } + + $this->post(route('otp.request-login'), [ + 'identifier' => $user->email, + ])->assertStatus(429); +}); + +test('otp request rate limit keeps separate buckets for different identifiers on the same ip', function () { + $throttledUser = User::factory()->create([ + 'email' => 'otp-throttle-a@example.com', + 'name' => 'otp-throttle-a', + 'password' => Hash::make('password'), + 'status' => 1, + 'otp_enabled' => true, + 'otp_verified' => true, + 'otp_channel' => 'email', + ]); + + $otherUser = User::factory()->create([ + 'email' => 'otp-throttle-b@example.com', + 'name' => 'otp-throttle-b', + 'password' => Hash::make('password'), + 'status' => 1, + 'otp_enabled' => true, + 'otp_verified' => true, + 'otp_channel' => 'email', + ]); + + for ($attempt = 0; $attempt < 3; $attempt++) { + $this->post(route('otp.request-login'), [ + 'identifier' => $throttledUser->email, + ])->assertRedirect(route('otp.verify-login')); + } + + $this->post(route('otp.request-login'), [ + 'identifier' => $throttledUser->email, + ])->assertStatus(429); + + $this->post(route('otp.request-login'), [ + 'identifier' => $otherUser->email, + ])->assertRedirect(route('otp.verify-login')); +}); + +test('2fa verification is throttled using the pending authentication session', function () { + $user = User::factory()->create([ + 'email' => '2fa-throttle@example.com', + 'password' => Hash::make('password'), + 'status' => 1, + 'two_fa_enabled' => true, + 'otp_verified' => true, + 'otp_channel' => 'email', + ]); + + app(OtpService::class)->generateAndSave($user, 'email', $user->email, '2fa_login'); + + session([ + 'two-factor:auth' => [ + 'id' => $user->id, + 'email' => $user->email, + ], + ]); + + for ($attempt = 0; $attempt < 10; $attempt++) { + $this->from(route('2fa.verify-login'))->post(route('2fa.verify-login'), [ + 'otp' => '000000', + ])->assertRedirect(); + } + + $this->post(route('2fa.verify-login'), [ + 'otp' => '000000', + ])->assertStatus(429); +}); From c83bda8f275719c7eb9177e9a668bd708d0f561c Mon Sep 17 00:00:00 2001 From: Wisnu Jaya Date: Thu, 22 Oct 2026 15:39:25 +0700 Subject: [PATCH 2/3] fix(security): cegah bypass rate limit lewat header proxy palsu Helper IpAddress membaca CF-Connecting-IP, X-Real-IP, dan X-Forwarded-For langsung dari $request->server, sehingga tidak melewati TrustProxies. Klien yang tidak di belakang proxy bisa mengisi header itu dengan nilai acak di setiap request untuk mendapat bucket baru, misalnya meminta OTP tanpa batas ke email/Telegram korban. Dibuktikan oleh tes baru yang gagal sebelum perbaikan (permintaan ke-4 mendapat 302, bukan 429). - Kunci rate limit memakai $request->ip(), yang hanya membaca X-Forwarded-For dari proxy yang dipercaya. Helper IpAddress dihapus. - TRUST_PROXIES dan RATE_LIMIT_* dibaca lewat config/security.php, bukan env() langsung, agar tetap berlaku setelah `config:cache`. - Tes: bypass dengan 3 header palsu, IP klien asli di balik proxy tepercaya, dan penolakan TRUST_PROXIES='*'. Refs #1410, #1478 Co-authored-by: Revanza Firdaus --- app/Helpers/IpAddress.php | 230 --------------------------- app/Http/Middleware/TrustProxies.php | 8 +- app/Providers/AppServiceProvider.php | 28 +++- config/security.php | 40 +++++ tests/Feature/RateLimitingTest.php | 78 +++++++++ 5 files changed, 142 insertions(+), 242 deletions(-) delete mode 100644 app/Helpers/IpAddress.php create mode 100644 config/security.php diff --git a/app/Helpers/IpAddress.php b/app/Helpers/IpAddress.php deleted file mode 100644 index 62f821baa9..0000000000 --- a/app/Helpers/IpAddress.php +++ /dev/null @@ -1,230 +0,0 @@ -ip() ?? $request->server('REMOTE_ADDR', '127.0.0.1'); - } - - /** - * Ekstrak IP dari header proxy yang tersedia. - */ - private static function extractIpFromProxyHeaders(Request $request): ?string - { - foreach (self::PROXY_HEADERS as $header) { - $headerValue = $request->server->get('HTTP_'.$header); - - if ($headerValue === null || $headerValue === '') { - continue; - } - - // X-Forwarded-For bisa berisi multiple IP, ambil yang pertama (client IP) - if ($header === 'X_FORWARDED_FOR') { - $firstIp = self::parseFirstIp($headerValue); - - if ($firstIp !== null && $firstIp !== '') { - return $firstIp; - } - - continue; - } - - // CF-Connecting-IP dan X-Real-IP berisi single IP - $cleaned = trim($headerValue); - - if ($cleaned !== '') { - return $cleaned; - } - } - - return null; - } - - /** - * Parse IP pertama dari daftar comma-separated (X-Forwarded-For). - */ - private static function parseFirstIp(string $ipList): ?string - { - if (str_contains($ipList, ',')) { - $ips = explode(',', $ipList); - $first = trim($ips[0]); - - return $first !== '' ? $first : null; - } - - return trim($ipList); - } - - /** - * Validasi format alamat IP (IPv4 atau IPv6). - */ - private static function isValidIpAddress(string $ip): bool - { - return filter_var($ip, FILTER_VALIDATE_IP) !== false; - } - - /** - * Bersihkan alamat IP dari port atau karakter tidak valid. - * - * Menangani kasus: - * - IPv4 dengan port (contoh: 192.168.1.1:8080) - * - IPv6 dengan port (contoh: [::1]:8080) - * - Header injection attempts (newline characters) - * - IPv4-mapped IPv6 addresses (contoh: ::ffff:192.168.1.1) - */ - private static function cleanIpAddress(string $ip): string - { - // Hapus karakter newline dan control characters untuk mencegah header injection - $cleaned = preg_replace('/[\r\n\t\x00-\x1F\x7F]/', '', $ip); - - if ($cleaned === null) { - return $ip; - } - - $cleaned = trim($cleaned); - - // Handle IPv6 dengan port: [::1]:8080 - if (str_starts_with($cleaned, '[')) { - $bracketPos = strpos($cleaned, ']'); - - if ($bracketPos !== false) { - return substr($cleaned, 1, $bracketPos - 1); - } - } - - // Handle IPv4 dengan port: 192.168.1.1:8080 - // Hanya jika ada tepat satu colon dan valid IPv4 - if (substr_count($cleaned, ':') === 1) { - $colonPos = strrpos($cleaned, ':'); - $possibleIp = substr($cleaned, 0, $colonPos); - - if (filter_var($possibleIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) { - return $possibleIp; - } - } - - // Handle IPv4-mapped IPv6: ::ffff:192.168.1.1 - // Jangan split colon untuk pure IPv6 addresses - if (filter_var($cleaned, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) { - return $cleaned; - } - - return $cleaned; - } - - /** - * Generate rate limit key dengan sanitasi ketat. - * - * Key format: "rate_limit:{ip}|{identifier}" atau "rate_limit:{ip}" - */ - public static function getRateLimitKey(Request $request, ?string $identifier = null): string - { - $ip = self::getRealIp($request); - - if ($identifier !== null && $identifier !== '') { - // Sanitasi identifier - batasi panjang dan karakter - $identifier = self::sanitizeIdentifier($identifier); - - return "rate_limit:{$ip}|{$identifier}"; - } - - return "rate_limit:{$ip}"; - } - - /** - * Sanitasi identifier untuk rate limiting. - * - * - Hapus null bytes dan control characters - * - Batasi panjang maksimal 320 karakter (RFC 5321) - * - Hanya izinkan karakter alphanumeric dan @._- - */ - private static function sanitizeIdentifier(string $identifier): string - { - // Batasi panjang maksimal - if (strlen($identifier) > 320) { - $identifier = substr($identifier, 0, 320); - } - - // Hapus null bytes dan control characters - $sanitized = preg_replace('/[\x00-\x1F\x7F]/', '', $identifier); - - if ($sanitized === null) { - return ''; - } - - // Hanya izinkan karakter yang aman - $sanitized = preg_replace('/[^a-z0-9@._-]/i', '', $sanitized); - - return $sanitized !== null ? $sanitized : ''; - } -} diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 93ea0da22a..92647b42d4 100644 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -35,7 +35,7 @@ use Illuminate\Http\Request; /** - * Middleware untuk mengatur proxy yang dipercaya + * Middleware untuk mengatur proxy yang dipercaya. * * Konfigurasi ini penting ketika aplikasi berada di belakang reverse proxy * seperti Nginx, Cloudflare, atau load balancer. @@ -72,16 +72,16 @@ class TrustProxies extends Middleware Request::HEADER_X_FORWARDED_AWS_ELB; /** - * Override untuk mendapatkan proxy dari environment variable + * Override untuk mendapatkan proxy dari environment variable. * * PENTING: TRUST_PROXIES=* TIDAK diizinkan karena risiko IP spoofing. - * Jika developer set '*' di environment, akan diabaikan dan return null. + * Jika TRUST_PROXIES diisi '*', akan diabaikan dan return null. * * @return array|string|null */ protected function proxies() { - $envProxies = env('TRUST_PROXIES'); + $envProxies = config('security.trusted_proxies'); if ($envProxies === null || $envProxies === '' || $envProxies === '*') { // Return null: tidak trust proxy headers dari manapun diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 3a335a9eaf..42e70c6db4 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -31,7 +31,6 @@ namespace App\Providers; -use App\Helpers\IpAddress; use App\Rules\SafeFileContent; use App\Services\ActivityLogService; use App\Services\CacheService; @@ -145,31 +144,44 @@ public function boot(): void /** * Rate limiter untuk login dan OTP (issue #1410). - * (Sebelumnya di RouteServiceProvider::configureRateLimiting()) + * (Sebelumnya di RouteServiceProvider::configureRateLimiting()). */ protected function configureRateLimiting(): void { RateLimiter::for('login', function (Request $request) { - $maxAttempts = max(1, (int) env('RATE_LIMIT_LOGIN_MAX', 10)); - $decayMinutes = max(1, (int) env('RATE_LIMIT_LOGIN_DECAY', 1)); + $maxAttempts = max(1, (int) config('security.rate_limit.login.max_attempts')); + $decayMinutes = max(1, (int) config('security.rate_limit.login.decay_minutes')); $identifier = $this->extractAndValidateIdentifier($request); return Limit::perMinute($maxAttempts, $decayMinutes) - ->by(IpAddress::getRateLimitKey($request, $identifier)); + ->by($this->rateLimitKey('login', $request, $identifier)); }); RateLimiter::for('otp', function (Request $request) { - $maxAttempts = max(1, (int) env('RATE_LIMIT_OTP_MAX', 3)); - $decayMinutes = max(1, (int) env('RATE_LIMIT_OTP_DECAY', 1)); + $maxAttempts = max(1, (int) config('security.rate_limit.otp.max_attempts')); + $decayMinutes = max(1, (int) config('security.rate_limit.otp.decay_minutes')); $identifier = $this->extractAndValidateIdentifier($request); return Limit::perMinute($maxAttempts, $decayMinutes) - ->by(IpAddress::getRateLimitKey($request, $identifier)); + ->by($this->rateLimitKey('otp', $request, $identifier)); }); } + /** + * Kunci rate limit: nama limiter + IP klien + identifier. + * + * $request->ip() hanya memakai X-Forwarded-For bila request datang dari + * proxy yang dipercaya (TrustProxies). Jangan membaca header proxy secara + * langsung: klien bisa mengisinya dengan nilai acak di setiap request + * untuk mendapat bucket baru dan melewati batas. + */ + protected function rateLimitKey(string $limiter, Request $request, ?string $identifier): string + { + return $limiter.'|'.$request->ip().'|'.($identifier ?? ''); + } + /** * Extract dan validasi identifier (email/username) dari request. * diff --git a/config/security.php b/config/security.php new file mode 100644 index 0000000000..bca6e984b2 --- /dev/null +++ b/config/security.php @@ -0,0 +1,40 @@ + env('TRUST_PROXIES'), + + /* + |-------------------------------------------------------------------------- + | Rate Limiting Login & OTP + |-------------------------------------------------------------------------- + | + | Batas percobaan per menit untuk tiap kombinasi IP klien + identitas + | (email/username). Dibaca di AppServiceProvider::configureRateLimiting(). + | + */ + + 'rate_limit' => [ + 'login' => [ + 'max_attempts' => (int) env('RATE_LIMIT_LOGIN_MAX', 10), + 'decay_minutes' => (int) env('RATE_LIMIT_LOGIN_DECAY', 1), + ], + 'otp' => [ + 'max_attempts' => (int) env('RATE_LIMIT_OTP_MAX', 3), + 'decay_minutes' => (int) env('RATE_LIMIT_OTP_DECAY', 1), + ], + ], + +]; diff --git a/tests/Feature/RateLimitingTest.php b/tests/Feature/RateLimitingTest.php index fd9b6f8cde..74be6477b7 100644 --- a/tests/Feature/RateLimitingTest.php +++ b/tests/Feature/RateLimitingTest.php @@ -182,3 +182,81 @@ 'otp' => '000000', ])->assertStatus(429); }); + +test('otp request rate limit cannot be bypassed with spoofed proxy headers', function (string $header) { + $user = User::factory()->create([ + 'email' => 'otp-spoof@example.com', + 'name' => 'otp-spoof', + 'password' => Hash::make('password'), + 'status' => 1, + 'otp_enabled' => true, + 'otp_verified' => true, + 'otp_channel' => 'email', + ]); + + // Tanpa TRUST_PROXIES, header proxy dari klien tidak boleh dipercaya: + // mengganti nilainya di setiap request tidak boleh membuat bucket baru. + for ($attempt = 0; $attempt < 3; $attempt++) { + $this->withHeader($header, "203.0.113.{$attempt}") + ->post(route('otp.request-login'), ['identifier' => $user->email]) + ->assertRedirect(route('otp.verify-login')); + } + + $this->withHeader($header, '203.0.113.99') + ->post(route('otp.request-login'), ['identifier' => $user->email]) + ->assertStatus(429); +})->with(['X-Forwarded-For', 'X-Real-IP', 'CF-Connecting-IP']); + +test('otp request rate limit uses the real client ip behind a trusted proxy', function () { + // Request di tes berasal dari 127.0.0.1; anggap itu reverse proxy kita. + config(['security.trusted_proxies' => '127.0.0.1']); + + $user = User::factory()->create([ + 'email' => 'otp-proxy@example.com', + 'name' => 'otp-proxy', + 'password' => Hash::make('password'), + 'status' => 1, + 'otp_enabled' => true, + 'otp_verified' => true, + 'otp_channel' => 'email', + ]); + + for ($attempt = 0; $attempt < 3; $attempt++) { + $this->withHeader('X-Forwarded-For', '198.51.100.1') + ->post(route('otp.request-login'), ['identifier' => $user->email]) + ->assertRedirect(route('otp.verify-login')); + } + + $this->withHeader('X-Forwarded-For', '198.51.100.1') + ->post(route('otp.request-login'), ['identifier' => $user->email]) + ->assertStatus(429); + + // Klien lain di balik proxy yang sama punya bucket sendiri. + $this->withHeader('X-Forwarded-For', '198.51.100.2') + ->post(route('otp.request-login'), ['identifier' => $user->email]) + ->assertRedirect(route('otp.verify-login')); +}); + +test('trusted proxies wildcard is rejected so forwarded headers stay ignored', function () { + config(['security.trusted_proxies' => '*']); + + $user = User::factory()->create([ + 'email' => 'otp-wildcard@example.com', + 'name' => 'otp-wildcard', + 'password' => Hash::make('password'), + 'status' => 1, + 'otp_enabled' => true, + 'otp_verified' => true, + 'otp_channel' => 'email', + ]); + + for ($attempt = 0; $attempt < 3; $attempt++) { + $this->withHeader('X-Forwarded-For', "203.0.113.{$attempt}") + ->post(route('otp.request-login'), ['identifier' => $user->email]) + ->assertRedirect(route('otp.verify-login')); + } + + $this->withHeader('X-Forwarded-For', '203.0.113.99') + ->post(route('otp.request-login'), ['identifier' => $user->email]) + ->assertStatus(429); +}); From bb0dc05dd04c2be33e436e15c8b596912ef4607c Mon Sep 17 00:00:00 2001 From: Wisnu Jaya Date: Thu, 22 Oct 2026 15:49:55 +0700 Subject: [PATCH 3/3] test: buat tes Lembaga mode gabungan tidak bergantung urutan Dua tes create/update Lembaga mode gabungan mengaktifkan database gabungan tanpa Http::fake. Tes itu lulus hanya karena tes sebelumnya di file yang sama menyimpan 'listDesa' di cache file. Dengan cache array per-tes (CACHE_DRIVER=array), keduanya memanggil API sungguhan dan gagal. Di rilis-dev pun keduanya gagal jika dijalankan sendiri. Co-Authored-By: Claude Opus 5.5 --- tests/Feature/LembagaControllerTest.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/Feature/LembagaControllerTest.php b/tests/Feature/LembagaControllerTest.php index 0141b78cb0..1ae9b878c9 100644 --- a/tests/Feature/LembagaControllerTest.php +++ b/tests/Feature/LembagaControllerTest.php @@ -189,6 +189,9 @@ function getLembagaKategori() ['value' => '1'] ); + // Jangan bergantung pada cache 'listDesa' dari tes sebelumnya. + Http::fake(['*' => Http::response(['data' => []], 200)]); + $penduduk = getLembagaPenduduk(); $kategori = getLembagaKategori(); @@ -213,6 +216,9 @@ function getLembagaKategori() ['value' => '1'] ); + // Jangan bergantung pada cache 'listDesa' dari tes sebelumnya. + Http::fake(['*' => Http::response(['data' => []], 200)]); + $penduduk = getLembagaPenduduk(); $kategori = getLembagaKategori(); $lembaga = Lembaga::factory()->create([