LoginSignup
0
0

ワンタイムパスワード検証試行回数制限の実装

ワンタイムパスワードの検証試行回数制限は、ブルートフォース攻撃対策として有効な手段です。ここでは、PHPで特定のIPアドレスに対して10分間に10回までの試行に制限をかける実装例を紹介します。

実装方法

  1. データベースに試行回数管理テーブルを作成
CREATE TABLE otp_attempts (
  ip_address VARCHAR(255) NOT NULL,
  first_attempt_at TIMESTAMP NOT NULL,
  attempt_count INT NOT NULL DEFAULT 0
);
  1. ワンタイムパスワード検証処理に試行回数制限チェックを追加
<?php

$userId = 1; // ユーザーID
$otp = '123456'; // 入力されたワンタイムパスワード
$timestamp = time(); // 現在時刻を取得
$ipAddress = $_SERVER['REMOTE_ADDR']; // ユーザーのIPアドレス

$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');

// 過去10分以内の試行回数を取得
$stmt = $db->prepare('SELECT attempt_count FROM otp_attempts WHERE ip_address = :ip_address AND first_attempt_at >= :first_attempt_at');
$stmt->bindParam(':ip_address', $ipAddress);
$stmt->bindParam(':first_attempt_at', $timestamp - 600); // 10分前
$stmt->execute();
$attemptCount = $stmt->fetchColumn();

if ($attemptCount === false) {
  // 初めての試行
  $attemptCount = 0;
}

// 試行回数を制限
if ($attemptCount >= 10) {
  echo 'Too many attempts. Please try again later.';
  exit;
}

// ワンタイムパスワード検証処理 (上記の例を参照)

// 試行回数を更新
$stmt = $db->prepare('INSERT INTO otp_attempts (ip_address, first_attempt_at, attempt_count) VALUES (:ip_address, :first_attempt_at, 1)
                        ON DUPLICATE KEY UPDATE attempt_count = attempt_count + 1');
$stmt->bindParam(':ip_address', $ipAddress);
$stmt->bindParam(':first_attempt_at', $timestamp);
$stmt->execute();

?>

ポイント

  • 試行回数管理テーブルには、IPアドレス、最初の試行日時、試行回数などのカラムを定義します。
  • ワンタイムパスワード検証処理の前に、過去10分以内の試行回数をデータベースから取得します。
  • 試行回数が制限を超えている場合は、エラーメッセージを表示して処理を終了します。
  • ワンタイムパスワード検証処理が成功した場合、試行回数をデータベースに更新します。
  • 上記はあくまで一例であり、環境に合わせて調整する必要があります。

その他の対策

  • 試行回数制限に加えて、ログイン失敗時のIPアドレスブロックなどの対策も検討しましょう。
  • 試行回数制限の閾値や時間制限は、環境に合わせて調整する必要があります。
  • 試行回数制限を厳しく設定しすぎると、正当なユーザーがログインできなくなる可能性があるため、注意が必要です。
0
0
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
0