How to Create a Security Plugin That Blocks Login Attempts

Contents

How to Create a Security Plugin That Blocks Login Attempts

In an age where automated attacks and credential stuffing are rampant, it’s critical to implement robust mechanisms that protect user accounts. This article walks you through designing and building a security plugin (for WordPress) that tracks and blocks suspicious login attempts. We’ll cover threat modeling, architecture, coding, configuration, and testing in depth.

1. Understanding the Threat

  • Brute-Force Attacks: Automated tools systematically try username/password combinations.
  • Credential Stuffing: Reusing leaked credentials from other breaches.
  • Distributed Attacks: Multiple IPs hitting your login endpoint to evade simple rate limits.

Key Metrics

Metric Description
Threshold Max failed attempts before lockout
Lockout Duration Time (in minutes) an IP/user remains blocked
Logging Records of attempts for audit

2. Requirements and Tools

  • WordPress ≥ 5.x
  • PHP ≥ 7.2
  • MySQL (or MariaDB)
  • Access to wp-login.php hooks
  • Familiarity with WP Plugin Handbook

3. Architectural Overview

The plugin consists of:

  1. Hooks Filters: Capture login failures and successes.
  2. Data Storage: Use either WordPress options/transients or a custom DB table to track IPs and timestamps.
  3. Lockout Logic: Calculate if an IP/user has exceeded the threshold within the time window.
  4. Admin Interface: Settings page for threshold, lockout duration, allowlist/blocklist.
  5. Notifications Logging: Email admin on lockouts, store logs for compliance.

4. Implementation Steps

4.1. Boilerplate Plugin File


ltphp
/
Plugin Name: Secure Login Guard
Description: Blocks excessive login attempts to defend against brute-force attacks.
Version: 1.0
Author: Your Name
/
defined(ABSPATH) or die(No direct access)
class Secure_Login_Guard {
    // initialization
    public function __construct() {
        add_action(wp_login_failed, [this, track_failed_attempt])
        add_action(wp_login, [this, reset_attempts], 10, 2)
        add_filter(authenticate, [this, block_if_needed], 30, 3)
        add_action(admin_menu, [this, add_settings_page])
    }
    // ...
}
new Secure_Login_Guard()

4.2. Tracking Failed Attempts


public function track_failed_attempt(username) {
    ip = _SERVER[REMOTE_ADDR]
    key = slg_ . md5(ip)
    data = get_transient(key) : [count=>0,first_time=>time()]
    data[count]  
    set_transient(key, data, DAY_IN_SECONDS)
}

4.3. Blocking Logic Before Authentication


public function block_if_needed(user, username, password) {
    ip = _SERVER[REMOTE_ADDR]
    key = slg_ . md5(ip)
    data = get_transient(key)
    threshold = get_option(slg_threshold, 5)
    lockout = get_option(slg_lockout, 15)  60 // seconds
    if(data  data[count] >= threshold) {
        if((time() - data[first_time]) lt lockout) {
            wp_die(Too many login attempts. Try again later., 403)
        } else {
            delete_transient(key)
        }
    }
    return user
}

4.4. Resetting on Successful Login


public function reset_attempts(user_login, user) {
    ip = _SERVER[REMOTE_ADDR]
    delete_transient(slg_ . md5(ip))
}

4.5. Admin Settings Page

Provide an options page under Settings gt Secure Login Guard to configure:

  • Attempt threshold
  • Lockout duration (minutes)
  • IP allowlist / blocklist

Use add_options_page, register_setting, and the Settings API. For details, see the WP Settings API guide.

5. Advanced Features

  • Custom Database Table: For high-scale sites, store attempt logs in a table rather than transients.
  • Geo-IP Blocking: Integrate with services like MaxMind.
  • Two-Factor Integration: Add 2FA prompts after threshold is reached instead of a full lockout.
  • reCAPTCHA: Insert a challenge for suspicious IPs. Refer to Google reCAPTCHA docs.

6. Testing Deployment

  1. Simulate failed logins via script or automation (e.g., curl loops).
  2. Verify that legitimate logins reset counters.
  3. Check edge cases: IP rotation, long-lived sessions, caching layers.
  4. Monitor performance impact use caching layers responsibly.
  5. Deploy to staging, then to production behind a CDN or WAF.

7. Security Best Practices

  • Sanitize Validate: Always sanitize input data use sanitize_text_field and WP nonces.
  • Least Privilege: Hook only where necessary don’t expose admin APIs.
  • Error Messages: Avoid leaking whether the username or password was wrong.
  • Audit Logs: Retain logs for compliance rotate or purge data periodically.
  • Stay Updated: Follow OWASP Top Ten guidance.

Conclusion

By following this guide, you’ll have a professional-grade security plugin that significantly reduces the risk of automated login attacks. Always continuously monitor, refine thresholds, and keep up with the evolving threat landscape. For further reading, consider the WordPress Security Developer Resources.



Acepto donaciones de BAT's mediante el navegador Brave 🙂



Leave a Reply

Your email address will not be published. Required fields are marked *