SoFunction
Updated on 2025-04-06

Implement IP locking function based on Java and Lua

LuaIt is a lightweight scripting language designed to be embedded in applications. It has simple and easy-to-understand syntax and high execution efficiency, so it is often used in the fields of game development, configuration scripts, data processing, etc.LuaScripts are usually integrated into other programs to implement specific functions or logic.

Introduction to Lua

Lua is a small scripting language developed by a research team at the Catholic University of Rio de Janeiro, Brazil in 1993.

Lua is written in standard C and open in source code, and can be compiled and run on almost all operating systems and platforms. Lua scripts can call C/C++ functions or be called by C/C++ code, so Lua can be widely used in applications.

Lua does not provide a powerful library, which is determined by its positioning. So Lua is not suitable as a language for developing standalone applications. It is designed to provide flexible extension and customization functions for applications by flexibly embedding into applications.

Lua is small in size and fast initiation. A complete Lua interpreter is only 200k. Among all scripting engines, Lua's speed can be said to be the fastest. So Lua is the best choice for embedded scripts. This is why we need to learn the language Lua.

So what can Lua language do? In fact, it is mainly used as a scripting language, used to develop scripts, such as writing game assistive scripts, using Lua scripts in Redis, etc.

Lua official website address:/

Lua Features

  • Lightweight:Lua is written in standard C language. The official version of Lua language only includes a streamlined core and the most basic library. It is small in size and fast in startup speed. A complete Lua interpreter is only 200k, suitable for embedded in other programs.

  • Scalable:Lua provides very easy-to-use extension interfaces and mechanisms, which are provided by the host language (usually C or C++) and can be used by Lua just like it is built-in.

  • Other features

    • Supports procedure-oriented programming and functional programming;
    • Automatic memory management;
    • Only a table of common types is provided, but it can be used to implement arrays, hash tables, collections, and objects;
    • Closures (closures), through closures and tables, can easily support some key mechanisms required for object-oriented programming, such as data abstraction, virtual functions, inheritance and overloading. ;
    • Provide multi-threading (co-process, not threads supported by the operating system);

Application scenarios

  • Game development, such as game assistive scripts.
  • Apply scripts, such as Redis, using Lua scripts.
  • Database plugins such as MySQL Proxy and MySQL WorkBench.
  • Security systems, such as intrusion detection systems.

Basic syntax of Lua scripts

LuaThe syntax is simple and intuitive. Here are some commonly used syntaxes:

  • variable:uselocalKeywords declare local variables, for example:local a = 10
  • Conditional statements:useifthenelseifelseendImplement conditional judgment, for example:
if x > 0 then
    print("x is positive")
elseif x == 0 then
    print("x is zero")
else
    print("x is negative")
end
  • cycle:supportforandwhileLoop, for example:
for i = 1, 10 do
    print(i)
end
  • function:usefunctionDefine a function, for example:
function add(a, b)
    return a + b
end

Use Redis + Lua script to implement limiting IP multiple times of incorrect password entry

RedisIt is a high-performance key-value database that supportsLuaScripts to implement atomic operations. The following is passedRedisandLuaScript restrictionIPImplementation of entering the wrong password multiple times.

Application scenarios

Suppose we want to limit the sameIPEnter the wrong password no more than 5 times in a short period of time (for example, 10 minutes), otherwise theIPFor a while.

Lua script example

-- limitIPEnter the wrong password multiple timesLuascript
local ip = KEYS[1]
local current_time = tonumber(ARGV[1])
local expire_time = 600  -- 10minute
local max_attempts = 5
local lock_duration = 3600  -- Lock time1Hour

-- Get the current error count and last error time
local attempts = tonumber(('get', ip) or '0')
local lock_time = tonumber(('get', ip .. ':lock') or '0')

-- Check if it has been locked
if current_time < lock_time then
    return -1  -- -1expressIPLocked
end

-- Update Error Count
attempts = attempts + 1
if attempts >= max_attempts then
    -- Exceeded maximum attempts,Make lock
    ('set', ip .. ':lock', current_time + lock_duration)
    return -1
else
    -- Maximum number of times not reached,Update Error Count
    ('set', ip, attempts)
    ('expire', ip, expire_time)
    return attempts
end

Of course, the following is the aboveLuaExplanation of each parameter and variable in the script:

  • KEYS[1] (ip):

    • This is the first key parameter passed to the Lua script, indicating the IP address that needs to be restricted. With this parameter, Redis can operate on a specific IP.
  • ARGV[1] (current_time):

    • This is the first parameter passed to the Lua script, representing the current Unix timestamp in seconds. This timestamp is used to check whether the IP has been locked and to update the lock time.
  • expire_time:

    • Indicates the validity period of the Error Attempt Count, which is set to 600 seconds (10 minutes). During this time, if the maximum limit is not reached, the count will automatically fail.
  • max_attempts:

    • Maximum number of allowed error attempts. Set to 5 times here, which means that within 10 minutes, if an IP enters the wrong password for 5 times, the locking mechanism will be triggered.
  • lock_duration:

    • Locking time, unit in seconds. This is set to 3600 seconds (1 hour). If the IP is locked, it will not be able to make any new attempts within 1 hour.
  • attempts:

    • Current error attempt count, obtained from Redis. use('get', ip)to get the number of errors for the specified IP, and if it does not exist, the default is 0.
  • lock_time:

    • The IP lock deadline is obtained from Redis. use('get', ip .. ':lock')Gets the lock timestamp of the current IP, which defaults to 0 if it does not exist.

Script logic flow

  • First, fromRedisGet the current oneIPnumber of error attempts and lock time.
  • Check whether the current time is less than the lock time. If so, it meansIPLocked, return-1
  • If not locked, increase the number of error attempts.
  • Check if the maximum number of attempts is reached or exceeded (max_attempts)。
    • If it is reached or exceeded, lockIP, set the lock time and return-1
    • If not reached, update the number of attempts and set the expiration time of attempts toexpire_time

Execute Lua scripts with Redis

You can use Redis providedEVALThe command executes the above Lua script. Here is an example:

redis-cli --eval limit_login_attempts.lua 192.168.1.1 , 1620000000

Here,192.168.1.1It's an IP address,1620000000is the current Unix timestamp.

In this way, it can effectively limit an IP to enter the wrong password multiple times in a short period of time to prevent brute-force cracking attacks. This mechanism can be integrated into the login system to enhance security.

To more specifically combine project application scenarios, we can consider an example scenario: In a user login system, a certain number of cases need to be restricted.IPThe address enters the wrong password multiple times in a short time to prevent brute force attacks. Here is a complete oneJavaApplication example, demonstrate how to use itRedisandLuaScripts to implement this function.

Project background

In the user login system, we want to restrict a certainIPThe address can enter the wrong password up to 5 times within 10 minutes. If this number exceeds, login attempts for the IP will be disabled for the next 1 hour.

Java code examples

import ;
import ;

public class LoginAttemptLimiter {

    private static final String LUA_SCRIPT =
        "local ip = KEYS[1] " +
        "local current_time = tonumber(ARGV[1]) " +
        "local expire_time = 600 " +  // 10 minutes in seconds
        "local max_attempts = 5 " +
        "local lock_duration = 3600 " +  // 1 hour in seconds
        "local attempts = tonumber(('get', ip) or '0') " +
        "local lock_time = tonumber(('get', ip .. ':lock') or '0') " +
        "if current_time < lock_time then " +
        "    return -1 " +  // IP is locked
        "end " +
        "attempts = attempts + 1 " +
        "if attempts >= max_attempts then " +
        "    ('set', ip .. ':lock', current_time + lock_duration) " +
        "    return -1 " +  // Lock the IP
        "else " +
        "    ('set', ip, attempts) " +
        "    ('expire', ip, expire_time) " +
        "    return attempts " +  // Return current attempt count
        "end";

    private final JedisPool jedisPool;

    public LoginAttemptLimiter(JedisPool jedisPool) {
         = jedisPool;
    }

    public int checkLoginAttempts(String ip) {
        try (Jedis jedis = ()) {
            long currentTime = () / 1000;  // Get current time in seconds
            Object result = (LUA_SCRIPT, 1, ip, (currentTime));
            return ((Long) result).intValue();
        }
    }

    public static void main(String[] args) {
        // Create a connection pool to the Redis server
        try (JedisPool jedisPool = new JedisPool("localhost", 6379)) {
            LoginAttemptLimiter limiter = new LoginAttemptLimiter(jedisPool);

            String ip = "192.168.1.1";
            int attemptResult = (ip);

            if (attemptResult == -1) {
                ("IP is locked due to too many failed attempts.");
            } else {
                ("Failed attempt count for IP: " + attemptResult);
            }
        }
    }
}

Code explanation

  • Lua Script: Defined aLuaScript that checks and updates the number of error login attempts and locks when limit is exceededIP
  • JedisPool: For managementRedisConnection ensures connection security in multi-threaded environments.
  • checkLoginAttempts method: implementLuaThe script and returns the result, indicating the current number of error attempts or whether it is locked.
  • Main method: In the example, a specific IP address is used for testing, a login attempt is performed and the result is output.

In the aboveJavaIn the code,evalMethods are used for executionLuaScript and pass parameters to the script.evalThe parameter list of the method is as follows:

Object result = (LUA_SCRIPT, 1, ip, (currentTime));

Details of passing the sect

  • LUA_SCRIPT

    • This is to be executedLuaA string of the script. Logic is defined in the script to limit the number of login attempts for IP.
  • 1

    • This isevalThe second parameter of the method indicates how many keys are passed toLuascript. In this example, we only pass one key (IP address), so the value is1
  • ip

    • This is passed toLuaKey parameters of scripts (KEYS[1]). Passed in Lua scriptKEYS[1]Come to access this value.
  • (currentTime)

    • This is passed toLuaAdditional parameters for scripts (ARGV[1]). Passed in Lua scriptARGV[1]Come to access this value. Here it represents the current oneUnixTimestamp, in seconds.

Use of parameters in Lua scripts

  • KEYS[1]Corresponding to incomingip, that is, the IP address that needs to be restricted.
  • ARGV[1]Corresponding to incomingcurrentTime, that is, the current time, is used to determine whether the IP needs to be locked.

This structure allows operations on the specified IP address, judging its login attempt, and making corresponding processing based on the current time. passevalThe parameters passed by the method can dynamically affect the execution logic of the script.

Application scenarios

This code can be integrated into the actual login verification logic, such as calling each time the user enters a passwordcheckLoginAttemptsMethod, determine whether to allow continued login attempts. In this way, brute-force cracking attacks can be effectively prevented and user accounts can be protected.

The above is the detailed content of implementing IP locking functions based on Java and Lua. For more information about Java Lua's implementation of IP locking, please pay attention to my other related articles!