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/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 6bc386d8b9..92647b42d4 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 TRUST_PROXIES diisi '*', akan diabaikan dan return null. + * + * @return array|string|null + */ + protected function proxies() + { + $envProxies = config('security.trusted_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..42e70c6db4 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -38,13 +38,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 +91,8 @@ public function boot(): void Paginator::useBootstrap(); $this->paginate(); + $this->configureRateLimiting(); + if (sudahInstal()) { $this->penduduk(); $this->config(); @@ -137,6 +142,95 @@ 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) 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($this->rateLimitKey('login', $request, $identifier)); + }); + + RateLimiter::for('otp', function (Request $request) { + $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($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. + * + * 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/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/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/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([ diff --git a/tests/Feature/RateLimitingTest.php b/tests/Feature/RateLimitingTest.php new file mode 100644 index 0000000000..74be6477b7 --- /dev/null +++ b/tests/Feature/RateLimitingTest.php @@ -0,0 +1,262 @@ +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); +}); + +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); +});