OWASP Web Top 10 — A07

Brute Force Attacks

Brute force attacks are one of the most persistent and straightforward attack vectors in cybersecurity. By systematically trying all possible combinations of credentials or tokens, attackers can gain unauthorized access to systems, accounts, and sensitive data. While simple in concept, these attacks remain highly effective against systems that lack proper defensive measures.

What Are Brute Force Attacks?

A brute force attack is a trial-and-error method used to crack passwords, login credentials, encryption keys, or API tokens by systematically attempting every possible combination until the correct one is found. Unlike sophisticated exploits that leverage specific vulnerabilities, brute force attacks rely on computational power and persistence. The attacker makes repeated authentication attempts, either manually or through automated tools, until access is granted.

Modern brute force attacks often leverage existing credential databases from previous data breaches. In credential stuffing attacks, attackers use lists of millions of username-password pairs leaked from other services, exploiting the fact that many users reuse the same credentials across multiple platforms. Tools like Hydra, Burp Suite Intruder, and custom scripts can automate these attacks, making thousands of login attempts per second against vulnerable systems.

Despite being a well-known attack vector, brute force attacks continue to succeed because many systems lack basic rate limiting, account lockout mechanisms, or multi-factor authentication. According to security research, brute force and credential stuffing attacks account for a significant portion of unauthorized access incidents, particularly targeting cloud services, e-commerce platforms, and social media accounts.

How It Works

1
Target identification

The attacker identifies a login endpoint, API authentication mechanism, or any system that accepts credentials. This could be a web application login form, SSH service, FTP server, or API endpoint that requires a token or password. The attacker determines the authentication method and any visible security measures.

2
Credential list preparation

The attacker prepares a list of credentials to attempt. This might be a dictionary of common passwords (like password123, admin, qwerty), a leaked credential database from a previous breach, or a systematically generated list of all possible character combinations. Popular wordlists include rockyou.txt with over 14 million passwords.

3
Automated attack execution

Using tools like Hydra, Burp Suite, or custom scripts, the attacker configures an automated attack that submits login requests with each credential combination. The tool typically uses multiple threads or connections to maximize the speed of attempts, potentially making hundreds or thousands of requests per second if the target has no rate limiting.

4
Response analysis

The attack tool analyzes each response from the server to determine if authentication succeeded. It looks for HTTP status codes (200 vs 401), response body differences, redirect behavior, or response timing to distinguish successful logins from failures. Some tools can adapt to different response patterns automatically.

5
Successful credential extraction

When a valid credential is found, the attack tool records it and may continue testing to find additional valid accounts. The attacker can then use these credentials to access the system, exfiltrate data, create backdoor accounts, or launch further attacks. Without account lockout mechanisms, the attack can continue indefinitely until successful.

Vulnerable Code Example

Vulnerable — Java / Spring Boot
@RestController
public class AuthController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest req) {
        // VULNERABLE: No rate limiting whatsoever
        // An attacker can make unlimited login attempts
        // without any delay or throttling

        User user = userRepository.findByUsername(req.getUsername());

        if (user == null) {
            return ResponseEntity.status(401).body("Invalid credentials");
        }

        // No account lockout after failed attempts
        // No progressive delays
        // Immediate response allows timing attacks
        if (passwordEncoder.matches(req.getPassword(), user.getPassword())) {
            String token = generateToken(user);
            return ResponseEntity.ok(Map.of("token", token));
        }

        return ResponseEntity.status(401).body("Invalid credentials");
    }
}

// An attacker can use Hydra to make thousands of attempts:
// hydra -l admin -P rockyou.txt https-post-form
// "//login:username=^USER^&password=^PASS^:Invalid credentials"
//
// With no rate limiting, the attacker will eventually
// find the correct password from their wordlist.

Secure Code Example

Secure — Java / Spring Boot (Bucket4j + Account Lockout)
@RestController
public class AuthController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RateLimiterService rateLimiter;

    private static final int MAX_FAILED_ATTEMPTS = 5;
    private static final long LOCKOUT_DURATION_MS = 15 * 60 * 1000; // 15 min

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest req,
                                    HttpServletRequest request) {
        String clientIp = request.getRemoteAddr();

        // SECURE: Rate limiting using Bucket4j (token bucket algorithm)
        // Allow max 5 requests per minute per IP
        if (!rateLimiter.allowRequest(clientIp, 5, Duration.ofMinutes(1))) {
            return ResponseEntity.status(429)
                .body("Too many login attempts. Please try again later.");
        }

        User user = userRepository.findByUsername(req.getUsername());

        if (user == null) {
            // Add small delay to prevent timing attacks
            Thread.sleep(200);
            return ResponseEntity.status(401).body("Invalid credentials");
        }

        // Check if account is locked due to too many failed attempts
        if (user.isLocked() && user.getLockExpiry() > System.currentTimeMillis()) {
            long remainingMs = user.getLockExpiry() - System.currentTimeMillis();
            return ResponseEntity.status(423)
                .body("Account locked. Try again in " + (remainingMs/60000) + " minutes.");
        }

        if (passwordEncoder.matches(req.getPassword(), user.getPassword())) {
            // Success: reset failed attempt counter
            user.setFailedAttempts(0);
            user.setLocked(false);
            userRepository.save(user);

            String token = generateToken(user);
            return ResponseEntity.ok(Map.of("token", token));
        }

        // Failed attempt: increment counter
        int attempts = user.getFailedAttempts() + 1;
        user.setFailedAttempts(attempts);

        if (attempts >= MAX_FAILED_ATTEMPTS) {
            // Lock account after 5 failed attempts
            user.setLocked(true);
            user.setLockExpiry(System.currentTimeMillis() + LOCKOUT_DURATION_MS);
        }

        userRepository.save(user);

        // Progressive delay: wait longer with each failed attempt
        Thread.sleep(attempts * 1000); // 1s, 2s, 3s, etc.

        return ResponseEntity.status(401).body("Invalid credentials");
    }
}

// Additional layer: Implement CAPTCHA after 3 failed attempts
// and consider multi-factor authentication (MFA) for sensitive accounts.

Types of Brute Force Attacks

Simple Brute Force

The most straightforward approach where the attacker systematically tries every possible character combination. Starting from single characters (a, b, c), the attack progresses to longer combinations (aa, ab, abc123, etc.). This method is extremely time-consuming for long passwords but guaranteed to eventually succeed given enough time. It is most effective against short passwords or weak encryption keys with limited character sets.

Dictionary Attacks

Uses pre-compiled wordlists containing common passwords, words from dictionaries, and previously leaked passwords. Popular lists like rockyou.txt contain over 14 million real-world passwords collected from breaches. Attackers often augment these with common patterns like adding numbers or symbols (password1, password123!). This method is far more efficient than simple brute force because most users choose predictable passwords.

Credential Stuffing

Leverages username-password pairs leaked from previous data breaches on other services. Attackers obtain massive databases containing millions of credentials from breached sites and test them against your application. This attack succeeds because users frequently reuse the same credentials across multiple services. For example, credentials from a breached gaming forum might work on banking or email accounts. This is one of the most successful modern attack vectors.

Impact

A successful brute force attack can lead to complete account compromise and cascading security failures. The impact extends beyond the immediate breach, affecting both individuals and organizations.

Account takeover and identity theft

Attackers gain full access to user accounts, allowing them to impersonate victims, access personal information, view private communications, and make unauthorized transactions. In e-commerce systems, this can lead to fraudulent purchases. In social media, attackers can post malicious content or scam the victim's contacts.

Data exfiltration and privacy violation

Once inside an account, attackers can access and steal sensitive data including personal documents, financial records, health information, business communications, and intellectual property. This stolen data can be sold on dark web marketplaces, used for further attacks, or held for ransom.

Lateral movement and privilege escalation

Compromised credentials often provide a foothold for deeper infiltration. Attackers can use basic user accounts to explore the system, discover additional vulnerabilities, and escalate to administrative privileges. In enterprise environments, one compromised account can lead to domain-wide compromise.

Service disruption and resource exhaustion

Even unsuccessful brute force attacks can cause significant damage. High-volume automated attacks consume server resources, slow down legitimate user access, and may cause service outages. The traffic surge can overwhelm systems, leading to degraded performance or complete denial of service.

Prevention Checklist

Implement robust rate limiting

Apply rate limiting at multiple levels: per IP address, per username, and globally. Use proven algorithms like token bucket (Bucket4j) or sliding window counters. Start with conservative limits such as 5 login attempts per minute per IP, and adjust based on monitoring. Ensure rate limiting cannot be bypassed by changing IP addresses or user agents.

Account lockout with progressive delays

Temporarily lock accounts after a threshold of failed login attempts (typically 3-5 attempts). Implement progressive delays that increase with each failed attempt (1 second, 2 seconds, 4 seconds, etc.). Lock accounts for a reasonable duration (15-30 minutes) to slow down attackers without creating excessive user friction. Notify users of lockouts via email.

Deploy CAPTCHA challenges

Integrate CAPTCHA (Google reCAPTCHA v3, hCaptcha) after 2-3 failed login attempts to distinguish humans from automated bots. Modern CAPTCHA solutions can run invisibly for legitimate users while blocking automated attacks. Consider risk-based CAPTCHA that only challenges suspicious requests.

Enforce strong password policies

Require minimum password length (12+ characters), complexity requirements (mix of uppercase, lowercase, numbers, symbols), and check passwords against known breach databases using APIs like Have I Been Pwned. Prevent users from choosing common passwords or reusing previous passwords. Encourage use of password managers.

Multi-factor authentication (MFA)

Require MFA for all accounts, especially administrative and privileged accounts. Support multiple MFA methods: TOTP apps (Google Authenticator, Authy), SMS codes (though less secure), hardware tokens (YubiKey), or biometrics. Even if credentials are compromised, MFA provides an additional barrier against unauthorized access.

Monitor and alert on suspicious activity

Implement real-time monitoring for unusual login patterns: multiple failed attempts, logins from new locations or devices, rapid-fire requests, or credential stuffing patterns. Use SIEM systems to correlate events and detect distributed attacks. Alert security teams and affected users immediately when suspicious activity is detected.

Real-World Examples

2014

iCloud Celebrity Photo Leak

Attackers used brute force attacks against Apple's Find My iPhone service, which lacked rate limiting at the time. By systematically trying common passwords and security question answers, they gained access to hundreds of celebrity iCloud accounts, stealing and leaking private photos. The incident led to Apple implementing account lockouts and two-factor authentication.

2018-2019

Dunkin' Donuts

The coffee and donut chain suffered credential stuffing attacks affecting thousands of customer accounts. Attackers used credentials from previous third-party breaches to access Dunkin' accounts, stealing DD Perks rewards points and stored payment card information. The company was forced to reset affected accounts and implement additional security measures.

2020

Spotify

Security researchers discovered a database containing login credentials for over 300,000 Spotify accounts obtained through credential stuffing attacks. The compromised accounts were being sold or used to manipulate streaming numbers for financial gain. Spotify reset passwords for affected users and strengthened authentication mechanisms.

2021

MEGA Cloud Storage

The cloud storage provider faced massive credential stuffing campaigns using leaked credential lists from other services. Attackers successfully compromised numerous accounts to upload and distribute pirated content and malware. MEGA responded by implementing stricter rate limiting, CAPTCHA challenges, and encouraging users to enable two-factor authentication.

Ready to Test Your Knowledge?

Put what you have learned into practice. Try identifying and implementing brute force protection mechanisms in our interactive coding challenges, or explore more security guides to deepen your understanding.