Skip to content
Tutorials

Never Trust the Client: Securing FiveM Server Events in Lua

ATY Development
·
·Updated ·
25 views
QBCoreESXQbox
Never Trust the Client: Securing FiveM Server Events in Lua

Most money and item exploits on FiveM servers do not need a clever cheat. They need one server event that accepts an amount, an item name or a coordinate from the client and acts on it. This article shows how to write server events that stay safe even when the person calling them is running an executor.

The threat model: every client message is a suggestion

Anything that runs on the client can be read, modified or replayed. That includes your client Lua, your NUI JavaScript and every TriggerServerEvent call. A cheater does not need your source code to find your events. They can watch what fires while they play your job normally, then call the same event with different arguments, a thousand times, from anywhere on the map.

So the rule is simple: the client may ask for something to happen. The server decides whether it happens and how much it is worth. Event names do not protect you either. Renaming job:pay to something random only slows down someone who is already watching traffic.

The classic exploit: a payout event with an amount

This pattern still shows up in free and paid resources:

-- client
TriggerServerEvent('garbage:pay', 5000)

-- server
RegisterNetEvent('garbage:pay', function(amount)
    local Player = QBCore.Functions.GetPlayer(source)
    Player.Functions.AddMoney('cash', amount)
end)

Three problems in four lines. The client chooses the amount. Nothing checks whether the player is doing the job, is near a bin, or has already been paid for this bin. And nothing limits how often the event can be called. Fix any one of these and the exploit gets harder; fix all of them and it stops being worth the effort.

Move the state to the server

The most effective change is not a check, it is a design change. The server should know what the player is doing, so the client never has to tell it. When a player starts a job, the server creates the run, picks the route from config and sends the client only what it needs to display.

local activeRuns = {}

RegisterNetEvent('garbage:server:startRun', function()
    local src = source
    if activeRuns[src] then return end
    if not hasJob(src, 'garbage') then return end

    local route = {}
    for i, coords in ipairs(Config.Bins) do
        route[i] = { coords = coords, done = false }
    end

    activeRuns[src] = { route = route, startedAt = os.time() }
    TriggerClientEvent('garbage:client:setRoute', src, Config.Bins)
end)

AddEventHandler('playerDropped', function()
    activeRuns[source] = nil
end)

Now the client reports progress with an index into a list the server owns, not with money or coordinates. The server can look up the real bin position and the real reward itself. Always clean up on playerDropped, or your tables leak memory and a reconnecting player may inherit stale state.

Validate who, where, when and what

With state on the server, the completion handler can run four cheap checks before paying anything.

local PAY_PER_BAG = 150
local MAX_DISTANCE = 10.0
local COOLDOWN_MS = 8000
local lastDrop = {}

RegisterNetEvent('garbage:server:dropBag', function(binIndex)
    local src = source

    -- who: is this player actually on a run?
    local run = activeRuns[src]
    if not run then return end

    -- what: is the argument the type and range we expect?
    if type(binIndex) ~= 'number' or binIndex % 1 ~= 0 then return end
    local bin = run.route[binIndex]
    if not bin or bin.done then return end

    -- when: rate limit per player
    local now = GetGameTimer()
    if lastDrop[src] and now - lastDrop[src] < COOLDOWN_MS then return end

    -- where: is the ped near the bin the server knows about?
    local ped = GetPlayerPed(src)
    local dist = #(GetEntityCoords(ped) - bin.coords)
    if dist > MAX_DISTANCE then
        print(('[garbage] %s (%d) dropped bag %.1fm from bin %d'):format(
            GetPlayerName(src), src, dist, binIndex))
        return
    end

    bin.done = true
    lastDrop[src] = now
    addMoney(src, PAY_PER_BAG)
end)

Who

Check the job and the active task, not just the job. A player with the garbage job who never started a run should get nothing. For police or EMS actions, check the job and duty status every time, because players can be fired or go off duty between two events.

What

Check types and ranges for every argument. Lua will happily index a table with a string, a negative number or a huge float. If you expect an integer between 1 and the route length, test exactly that. For strings such as item names, look them up in a server-side whitelist instead of passing them straight to your inventory.

When

A per-player cooldown kills replay spam. Choose a value just below the fastest legitimate time to complete the action. Server-side GetGameTimer is fine for this; use os.time when you need wall-clock values for logs or database rows.

Where

With OneSync enabled, the server can read a player's ped position with GetPlayerPed and GetEntityCoords. Use the coordinates you stored, never coordinates the client sent. Give a generous tolerance; network latency and animations mean a strict 2 metre check will punish honest players.

Capture source before anything async

source is a global that changes as other events fire. If your handler waits on a database query, a Wait or a callback, source may point to a different player when it resumes. Always assign local src = source on the first line and use src everywhere after that. This bug is subtle because it only shows up under load, which is exactly when you are least able to debug it.

Keep the money call in one place

Wrap framework calls in a single helper so every payout goes through the same path, and so you can add logging later without touching every job.

local function addMoney(src, amount)
    -- QBCore
    local Player = QBCore.Functions.GetPlayer(src)
    if Player then
        Player.Functions.AddMoney('cash', amount, 'garbage-job')
    end

    -- ESX equivalent:
    -- local xPlayer = ESX.GetPlayerFromId(src)
    -- if xPlayer then xPlayer.addMoney(amount) end
end

On Qbox, use the equivalent function from your core. The point is that amount comes from your config, never from an event argument.

State bags are input too

State bags are a clean way to share data like duty status or a carried object. But a client can set replicated values on its own player state, for example through LocalPlayer.state. That means a value like onDuty or isCuffed that the client can write is just another message from the client.

Treat it accordingly. Set authoritative values from the server with Player(src).state:set(key, value, true), and when the server reads a state bag to make a decision, make sure that key is only ever written by server code. If you need a client to report something, use an event you validate, then let the server write the state.

NUI callbacks follow the same rule

Your NUI posts to a client-side callback, which then usually triggers a server event. A player can open devtools on the NUI page or call the client callback directly, so prices, quantities and item names shown in your UI mean nothing on the server. Re-read them from config, recompute totals and check stock on the server before charging or giving anything.

Log first, punish carefully

It is tempting to call DropPlayer the moment a check fails. Do not do that for distance or timing checks. Desync, lag spikes and teleporting admins will trigger them on honest players. A better approach:

  • Silently reject the request and return.
  • Log the player, the check that failed and the values involved.
  • Count failures per player and only alert staff after a threshold.
  • Reserve automatic kicks for impossible inputs, such as a negative quantity or a bin index that does not exist.

Logs also tell you when your tolerances are wrong. If half your legitimate players fail the distance check at one bin, the config coordinates are off, not the players.

Checklist for every server event

  1. Is source captured into a local on the first line?
  2. Does the server already know what this player is doing, or is it taking the client's word?
  3. Are all arguments type-checked and range-checked?
  4. Are amounts, prices and rewards read from server config?
  5. Is the player's job, duty or ownership checked on every call?
  6. Is the position checked against server-known coordinates?
  7. Is there a cooldown or a one-time flag preventing replay?
  8. Is per-player state cleared on playerDropped?
  9. Are failures logged with enough detail to tune thresholds?

Takeaway

Secure events are mostly about where the data lives. Keep tasks, routes, rewards and permissions on the server, let the client send only intents and indexes, and validate who, what, when and where before touching money or items. Read the FiveM events documentation for the details on net events, then run the checklist above against every RegisterNetEvent in your resources. If a handler fails two or more items, fix it before you ship it.