0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Laravel】IP制限+ブラウザ指紋でログイン画面すら見せず「404」で隠蔽するミドルウェア設計

0
Posted at

はじめに

Webシステムの管理画面を公開していると、海外IPなどから /admin/login に対するブルートフォース攻撃(総当たり試行)や脆弱性スキャンのアクセスが毎日大量に発生します。

一般的な対策として「IPアドレス制限」が挙げられますが、実務では次のような課題に直面しがちです。

  1. 自宅やモバイル回線が動的IPのため、プロバイダのIPが変わるたびに自分が締め出される
  2. 一般的な 403 Forbidden を返すと、「そこに管理画面が存在すること」自体は攻撃者に知られてしまう

本記事では、これらを解決するために設計した**「IPアドレス + ブラウザ識別子(フィンガープリント)」による自動追従型ホワイトリスト認証**と、未許可アクセスに対してログイン画面の存在自体を隠蔽する 404 Not Found 応答ミドルウェアの実装パターンを紹介します。


設計の全体像(2段階防御の「第1の壁」)

Laravel標準のID・パスワード認証(第2の壁)の手前に、以下のルールで判定する専用ミドルウェア(第1の壁)を配置します。

アクセス元の状態 判定結果 システムの挙動
許可リストに存在する固定IP 許可 ログイン画面・管理画面へ通過
IPは変わったが、許可済みのブラウザ識別子(FP)と一致 許可 DB内の許可IPを新しいIPへ自動上書き更新して通過
IPもブラウザ識別子も未登録(または無効化済み) 遮断 abort(404) を即時返却(ログイン画面を見せない)

なぜ 403 ではなく 404 を返すのか?

403 Forbidden は「ページは存在するが権限がない」ことを攻撃者に教えてしまいます。存在しないURLと同じ 404 Not Found を返すことで、自動スキャンツールに対して「このパスには何もない」と認識させ、継続的な攻撃対象から外す効果が期待できます。


1. データベース設計(許可デバイス管理テーブル)

許可された管理者デバイスのIPとブラウザ識別子を保持する allowed_devices テーブルを作成します。

// database/migrations/xxxx_xx_xx_create_allowed_devices_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('allowed_devices', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->boolean('is_allowed')->default(true)->comment('許可フラグ');
            $table->string('allowed_ip')->nullable()->comment('許可IPアドレス');
            $table->string('browser_fingerprint')->nullable()->index()->comment('端末識別子');
            $table->timestamp('last_accessed_at')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('allowed_devices');
    }
};

2. フロントエンド側:端末識別子の生成と送信

ブラウザの localStorage に一意の識別子を生成・保存し、フォーム送信時や非同期通信(htmx / fetch 等)のリクエストへ自動的に付与します。HTTP/2やプロキシ経由でのヘッダー小文字正規化を考慮し、カスタムヘッダー名はすべて小文字の x-device-fingerprint に統一します。

// public/js/device-fingerprint.js
function getDeviceFingerprint() {
    const storageKey = 'app_device_fp';
    let fp = localStorage.getItem(storageKey);

    if (!fp || !fp.startsWith('fp_')) {
        fp = 'fp_' + Math.random().toString(36).substring(2, 15) + Date.now().toString(36);
        localStorage.setItem(storageKey, fp);
    }
    return fp;
}

document.addEventListener('DOMContentLoaded', () => {
    const fp = getDeviceFingerprint();

    // 1. 通常のHTMLフォーム送信時に hidden フィールドを自動注入
    document.addEventListener('submit', (event) => {
        const form = event.target;
        if (!form.querySelector('input[name="device_fingerprint"]')) {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'device_fingerprint';
            input.value = fp;
            form.appendChild(input);
        }
    });

    // 2. htmx や fetch 等の非同期リクエストヘッダーにも付与する例(すべて小文字で指定)
    document.addEventListener('htmx:configRequest', (event) => {
        event.detail.headers['x-device-fingerprint'] = fp;
    });
});

3. ミドルウェア実装(IP+指紋の照合と自動IP更新)

管理画面ルート(/admin/*)およびログインルートの手前に適用するミドルウェアです。

<?php

namespace App\Http\Middleware;

use App\Models\AllowedDevice;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AdminGatekeeperMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $clientIp = $request->ip();
        // ヘッダー(すべて小文字)またはフォーム入力から端末識別子を取得
        $fingerprint = $request->header('x-device-fingerprint')
            ?? $request->input('device_fingerprint');

        // 1. 固定IPホワイトリストで一致する有効デバイスを検索
        $device = AllowedDevice::where('is_allowed', true)
            ->where('allowed_ip', $clientIp)
            ->first();

        // 2. IPが一致しない場合、端末識別子(動的IP追従)で検索
        if (!$device && !empty($fingerprint)) {
            $device = AllowedDevice::where('is_allowed', true)
                ->where('browser_fingerprint', $fingerprint)
                ->first();

            // 端末識別子が一致したら、最新の動的IPアドレスへ自動更新
            if ($device) {
                $device->update([
                    'allowed_ip' => $clientIp,
                ]);
            }
        }

        // 3. どちらも不一致の場合は存在自体を隠蔽するため 404 を返す
        if (!$device) {
            abort(404);
        }

        $device->update(['last_accessed_at' => now()]);

        return $next($request);
    }
}

ルーティングへの適用(Laravel 11〜13 構成)

bootstrap/app.php でミドルウェアエイリアスを登録し、routes/web.php の管理画面グループとログインルートに適用します。

// routes/web.php
Route::middleware(['admin.gatekeeper'])->group(function () {
    Route::get('/admin/login', [LoginController::class, 'showLoginForm'])->name('login');
    Route::post('/admin/login', [LoginController::class, 'login']);

    Route::middleware(['auth'])->prefix('admin')->group(function () {
        Route::get('/dashboard', [DashboardController::class, 'index'])->name('admin.dashboard');
    });
});

運用上のセキュリティポイント

  • 初期デバイスの登録フロー: 最初に管理者自身がアクセスする際はまだDBにIP・指紋が登録されていないため、環境変数(.env)に初期セットアップ用トークンや初期許可IPを一時設定するか、CLI(Artisanコマンド)から初回レコードを投入する仕組みを用意しておくと安全です。
  • 端末紛失時の即時遮断: DB上の is_allowed を false に切り替えるだけで、そのブラウザからは次回リクエスト時から即座に 404 となりアクセス不能になります。
  • 多層防御との併用: 実運用ではこれに加えて、ログインフォームへのハニーポット(ボット対策の隠しフィールド)や Cloudflare Turnstile などを組み合わせることで、さらに強固な防御が可能になります。

おわりに

今回ご紹介したIPアドレスとブラウザ指紋による404隠蔽ミドルウェアの設計は、自社専用のVPSサーバーとAmazon SESを直結させた完全隔離型のメール配信・API中継システム「ESMA」の多層防御基盤をベースに汎用化したものです。

興味のある方は、こちらもぜひご覧ください。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?