BRUTE FORCE ATTACKS
Thwart brute force attacks
To thwart brute force attacks, you can implement a mechanism to lock user accounts after a certain number of failed login attempts. Here’s an example in PHP .
// Function to log a failed login attempt
function logFailedLoginAttempt($username) {
// Implement your logging mechanism, such as storing in a database
// For simplicity, let's just echo a message here
echo "Login failed for user: $username\n";
}
// Function to check and lock user account after multiple failed attempts
function handleFailedLoginAttempts($username, $maxAttempts = 3) {
// Check if the user has exceeded the maximum allowed login attempts
$loginAttempts = isset($_SESSION['login_attempts']) ? $_SESSION['login_attempts'] : 0;
if ($loginAttempts >= $maxAttempts) {
// Lock the account or implement other actions (e.g., notify the user, log the event)
echo "Account locked due to multiple failed login attempts. Please contact support.\n";
return false;
}
// Increment the login attempts
$_SESSION['login_attempts'] = $loginAttempts + 1;
// Log the failed login attempt
logFailedLoginAttempt($username);
// Return true to indicate that the login attempt is unsuccessful
return true;
}
// Example usage during the login process
function login($username, $password) {
// Your authentication logic here
// Check if the login credentials are correct
if (/* Authentication successful */) {
// Reset the login attempts on successful login
$_SESSION['login_attempts'] = 0;
// Continue with the login process
echo "Login successful!\n";
} else {
// Handle failed login attempts
if (handleFailedLoginAttempts($username)) {
// Display an error message to the user (e.g., wrong password)
echo "Invalid username or password. Please try again.\n";
}
}
}
// Example usage
login("example_user", "wrong_password");
login("example_user", "wrong_password");
login("example_user", "correct_password");
this example uses a session variable to keep track of the number of failed login attempts. If the maximum allowed attempts ($maxAttempts
) are reached, you can take actions like locking the account or implementing a delay before allowing further login attempts. Adjust the $maxAttempts
variable based on your security requirements.