Recipe: Login journal
Two questions that reach every helpdesk:
- "When did this user last log in, and from where?" The journal answers it from Valkey in a second.
- "Are we under attack?" Nauthilus mails the administrator when its brute-force protection blocks a network, once per network and hour.
Interfaces: POST-action, synchronous action (action_type: brute_force).
Download: login-journal.tar.gz
What happens
- Every answered login request ends with the POST-action
last_login.lua. It runs after the answer was sent, so it never slows down or changes a login. For successful logins it writes the latest login and a short history. - The built-in brute-force check counts wrong passwords per network. After 5 distinct wrong passwords within 5
minutes it blocks the
/24network for 10 minutes. - A policy rule denies blocked requests and carries the brute-force action
brute_force_alert.luaas an obligation. The action mails the administrator through Mailpit, at most once per network and hour.
Start and test
docker compose up -d --wait
./test.sh
Open Mailpit at http://127.0.0.1:28185 to see the alert mail. Read the journal of an account:
docker compose exec valkey valkey-cli HGETALL cookbook:last_login:alice
docker compose exec valkey valkey-cli LRANGE cookbook:logins:alice 0 -1
The stack
docker-compose.yml
# Lua Cookbook recipe "Login journal".
# Start with: docker compose up -d --wait Test with: ./test.sh Stop with: docker compose down
name: cookbook-login-journal
services:
valkey:
image: valkey/valkey:8-alpine
command: ["valkey-server", "--save", "", "--appendonly", "no"]
healthcheck:
test: ["CMD", "valkey-cli", "ping"]
interval: 5s
timeout: 3s
retries: 20
# Mailpit accepts every mail on port 1025 and shows it at http://127.0.0.1:28185.
mailpit:
image: axllent/mailpit:v1.27
ports:
- "127.0.0.1:28185:8025"
nauthilus:
image: ${NAUTHILUS_IMAGE:-ghcr.io/croessner/nauthilus:v4.2.0}
depends_on:
valkey:
condition: service_healthy
mailpit:
condition: service_started
environment:
# Optional switch for the Lua JIT (Nauthilus 4.2 and later; earlier releases ignore it).
NAUTHILUS_AUTH_BACKENDS_LUA_BACKEND_DEFAULT_JIT: ${NAUTHILUS_LUA_JIT:-true}
# Read by actions/brute_force_alert.lua.
COOKBOOK_ALERT_TO: "admin@example.test"
COOKBOOK_SMTP_SERVER: "mailpit"
COOKBOOK_SMTP_PORT: "1025"
ports:
- "127.0.0.1:28085:8080"
volumes:
- ./nauthilus/nauthilus.yml:/etc/nauthilus/nauthilus.yml:ro
- ./nauthilus/lua:/etc/nauthilus/lua:ro
healthcheck:
test: ["CMD", "/usr/app/healthcheck", "--url", "http://127.0.0.1:8080/healthz"]
interval: 5s
timeout: 3s
retries: 30
Mailpit is a mail catcher: it accepts every mail on port 1025 and shows it in a web interface. Replace it with your
real mail relay through COOKBOOK_SMTP_SERVER and COOKBOOK_SMTP_PORT.
The configuration
nauthilus/nauthilus.yml
# Nauthilus configuration of the "Login journal" Lua Cookbook recipe.
# Interfaces shown: a POST-action and a synchronous brute-force action.
runtime:
instance_name: "cookbook-login-journal"
servers:
http:
address: "0.0.0.0:8080"
observability:
log:
level: "info"
json: false
storage:
redis:
primary:
address: "valkey:6379"
database_number: 0
prefix: "nt:"
positive_cache_ttl: "1h"
negative_cache_ttl: "5m"
# Demo values only. Generate your own random strings for a real installation.
password_nonce: "cookbookPasswordNonce05"
encryption_secret: "cookbookEncryption05"
auth:
backchannel:
basic_auth:
enabled: true
# Scoped credentials: each caller holds only the scopes it needs. Demo passwords only.
users:
# The mail server (or curl in test.sh) checks logins.
- username: "mailserver"
password: "mailserver-backchannel-secret"
scopes:
- "nauthilus:authenticate"
backends:
order:
- "cache"
- "lua"
lua:
backend:
default:
backend_script_path: "/etc/nauthilus/lua/backend.lua"
# require() finds the bundled helpers and files in /etc/nauthilus/lua.
package_path: "/usr/app/lua-plugins.d/share/?.lua;/etc/nauthilus/lua/?.lua"
backend_number_of_workers: 2
action_number_of_workers: 2
search:
- protocol:
- "imap"
- "smtp"
cache_name: "demo"
controls:
enabled:
- "brute_force"
# Block a /24 network for 10 minutes after 5 distinct wrong passwords within 5 minutes.
brute_force:
protocols:
- "imap"
- "smtp"
buckets:
- name: "cookbook_rule"
period: 5m
ban_time: 10m
cidr: 24
ipv4: true
ipv6: false
failed_requests: 5
policy:
namespaces:
authn:
# Effects name the Lua actions. The policy decides when they run.
effects:
# Runs after the answer was sent; see terminal_post_actions below.
lua_action_last_login:
kind: lua_action
action_type: post
script_path: "/etc/nauthilus/lua/actions/last_login.lua"
targets: [{action: authenticate}]
execution: host_post_action
# Runs while the request waits, when the brute-force rule below selects it.
lua_action_brute_force_alert:
kind: lua_action
action_type: brute_force
script_path: "/etc/nauthilus/lua/actions/brute_force_alert.lua"
targets: [{action: authenticate}]
execution: host_sync
domain_plans:
journal:
checkpoints:
# The built-in brute-force check runs first and can stop a request before the password is checked.
pre_auth:
providers:
- name: brute_force
use: authn/builtin/brute_force
actions: [authenticate]
auth_backend:
providers:
- name: backend_order
use: authn/auth_backend
actions: [authenticate]
auth_decision:
providers: []
policy_sets:
journal:
visibility: private
rules:
# A blocked client is denied, and the decision carries the alert action as an obligation.
- name: brute_force_alert
checkpoint: pre_auth
actions: [authenticate]
require_providers: [brute_force]
if:
attribute: nauthilus.auth.brute_force.triggered
is: true
then:
decision: deny
reason: brute_force
obligations:
- id: authn/lua_action_brute_force_alert
targets:
- namespace: authn
action: authenticate
schema: authn/authenticate/v1
mode: enforce
default_policy: authn/standard_auth
domain_plan: authn/journal
plans:
pre_auth:
policy_sets: [authn/journal]
# Run the journal once for every answered request, whichever rule answered it.
terminal_post_actions:
- id: authn/lua_action_last_login
action_number_of_workersis the number of Lua action workers. Actions and POST-actions run on these workers, not on the request's own goroutine.auth.controls.brute_forceswitches on the built-in brute-force protection. The bucketcookbook_rulecounts failed logins per/24network over 5 minutes and blocks for 10 minutes after 5 failures. See Brute-force protection.effectsname the two Lua actions:lua_action_last_loginwithaction_type: postandexecution: host_post_actionruns after the answer.lua_action_brute_force_alertwithaction_type: brute_forceandexecution: host_syncruns while the request waits.
domain_plans.journalschedules the built-in brute-force provider atpre_authand the backends atauth_backend.- The rule
brute_force_alertdenies a request whennauthilus.auth.brute_force.triggeredis true, and itsobligationsselect the alert action. An effect only runs when a selected rule asks for it. terminal_post_actionsruns the journal exactly once for every answered request, whichever rule answered it, including the built-in rules. A POST-action listed only on one rule would miss every other answer.
The login journal (POST-action)
nauthilus/lua/actions/last_login.lua
-- actions/last_login.lua
-- POST-action of the "Login journal" recipe. Nauthilus runs it after the answer has been sent, once for every
-- authentication request, so it cannot slow down or change a login. For every successful login it records:
-- cookbook:last_login:<account> hash with time, client_ip, protocol of the latest login
-- cookbook:logins:<account> list of the last 10 logins, newest first
-- Helpdesk question "when did bob last log in, and from where?" -> valkey-cli HGETALL cookbook:last_login:bob
local nauthilus_redis = require("nauthilus_redis")
local HISTORY_LENGTH = 10
function nauthilus_call_action(request)
if not request.authenticated then
return nauthilus_builtin.ACTION_RESULT_OK
end
local account = request.account
if account == nil or account == "" then
account = request.username
end
local now = os.date("!%Y-%m-%dT%H:%M:%SZ")
local protocol = request.protocol or "unknown"
local client_ip = request.client_ip or "unknown"
local last_key = "cookbook:last_login:" .. account
local history_key = "cookbook:logins:" .. account
nauthilus_redis.redis_hset("default", last_key, "time", now)
nauthilus_redis.redis_hset("default", last_key, "client_ip", client_ip)
nauthilus_redis.redis_hset("default", last_key, "protocol", protocol)
local length = nauthilus_redis.redis_lpush("default", history_key, table.concat({ now, client_ip, protocol }, " "))
-- Keep only the newest entries: drop the oldest ones from the end of the list.
while length ~= nil and length > HISTORY_LENGTH do
nauthilus_redis.redis_rpop("default", history_key)
length = length - 1
end
return nauthilus_builtin.ACTION_RESULT_OK
end
An action defines nauthilus_call_action(request) and returns ACTION_RESULT_OK or ACTION_RESULT_FAIL.
- A POST-action sees the final result:
request.authenticatedis true only for a successful login, andrequest.accountholds the canonical account name. os.date("!%Y-%m-%dT%H:%M:%SZ")writes the time in UTC; the!selects UTC.- The history is a Valkey list.
redis_lpushadds the newest entry in front and returns the new length; the loop removes the oldest entries from the end until 10 remain. - Because it runs after the answer, the test waits a moment before it reads the journal.
The brute-force alert (synchronous action)
nauthilus/lua/actions/brute_force_alert.lua
-- actions/brute_force_alert.lua
-- Brute-force action of the "Login journal" recipe. A policy rule in nauthilus.yml runs it when the brute-force
-- check blocks a client. It mails the administrator once per blocked network and hour; further blocked attempts in
-- that hour only increase a counter, so an attack does not flood the mailbox.
local nauthilus_mail = require("nauthilus_mail")
local nauthilus_redis = require("nauthilus_redis")
local MAIL_TO = os.getenv("COOKBOOK_ALERT_TO") or "admin@example.test"
local SMTP_SERVER = os.getenv("COOKBOOK_SMTP_SERVER") or "mailpit"
local SMTP_PORT = tonumber(os.getenv("COOKBOOK_SMTP_PORT") or "1025")
local QUIET_SECONDS = 3600
-- describe formats the request fields that help the administrator, one "name: value" per line.
local function describe(request)
local lines = {}
for _, field in ipairs({ "client_ip", "client_net", "username", "protocol", "brute_force_bucket" }) do
lines[#lines + 1] = string.format("%-20s %s", field .. ":", tostring(request[field] or "-"))
end
return table.concat(lines, "\n")
end
function nauthilus_call_action(request)
local network = request.client_net
if network == nil or network == "" then
network = request.client_ip or "unknown"
end
local key = "cookbook:bf_alert:" .. network
local first, err = nauthilus_redis.redis_set("default", key, "1", { nx = true, ex = QUIET_SECONDS })
if err ~= nil then
return nauthilus_builtin.ACTION_RESULT_FAIL
end
nauthilus_redis.redis_incr("default", key .. ":count")
-- redis_set with nx answers "OK" only for the first attempt of the hour.
if first ~= "OK" then
return nauthilus_builtin.ACTION_RESULT_OK
end
local err_mail = nauthilus_mail.send_mail({
server = SMTP_SERVER,
port = SMTP_PORT,
helo_name = "nauthilus.example.test",
from = '"Nauthilus" <nauthilus@example.test>',
to = { MAIL_TO },
subject = "Brute-force block for " .. network,
body = "Nauthilus blocked a client because of too many failed logins.\n\n" .. describe(request) .. "\n",
})
if err_mail ~= nil then
nauthilus_builtin.custom_log_add("brute_force_alert_error", err_mail)
return nauthilus_builtin.ACTION_RESULT_FAIL
end
nauthilus_builtin.custom_log_add("brute_force_alert", MAIL_TO)
return nauthilus_builtin.ACTION_RESULT_OK
end
- In a brute-force action,
request.client_netis the blocked network andrequest.brute_force_bucketthe bucket that triggered. - One mail per network and hour.
redis_setwithnx = truecreates the key only if it does not exist yet, andexlets it expire after an hour. Only the request that created the key sends a mail; later ones only count. Without this, an attack with thousands of attempts would send thousands of mails. nauthilus_mail.send_mailspeaks SMTP or LMTP, optionally with TLS or STARTTLS and authentication, see Mail.- The action runs while the blocked request waits and occupies one action worker. Keep it short; the once-per-hour key also keeps slow SMTP sessions rare.
What the test checks
test.sh
#!/usr/bin/env bash
# Checks the "Login journal" recipe. Start the stack first: docker compose up -d --wait
cd "$(dirname "$0")" || exit 1
. ../lib/cookbook.sh
NAUTHILUS_URL="${NAUTHILUS_URL:-http://127.0.0.1:28085}"
MAILPIT_URL="${MAILPIT_URL:-http://127.0.0.1:28185}"
# mail_count prints how many mails Mailpit holds with the given subject.
mail_count() {
curl -sS "${MAILPIT_URL}/api/v1/messages" | grep -o "\"Subject\":\"$1\"" | wc -l | tr -d ' '
}
# Start from a clean state: no journal, no brute-force counters, no mails.
valkey FLUSHALL >/dev/null
curl -sS -X DELETE "${MAILPIT_URL}/api/v1/messages" >/dev/null
section "POST-action: login journal"
auth alice alice-secret imap 192.0.2.10
expect_auth_status "OK" "alice logs in"
# The POST-action runs after the answer, so wait for it.
wait_until '[ "$(valkey HGET cookbook:last_login:alice client_ip)" = "192.0.2.10" ]'
expect_equal "192.0.2.10" "$(valkey HGET cookbook:last_login:alice client_ip)" "the journal records the client address"
expect_equal "imap" "$(valkey HGET cookbook:last_login:alice protocol)" "the journal records the protocol"
auth alice wrong-password smtp 192.0.2.10
sleep 1
expect_equal "imap" "$(valkey HGET cookbook:last_login:alice protocol)" "a failed login does not change the journal"
for i in $(seq 1 12); do auth alice alice-secret smtp "192.0.2.$((i + 20))"; done
wait_until '[ "$(valkey HGET cookbook:last_login:alice client_ip)" = "192.0.2.32" ]'
expect_equal "10" "$(valkey LLEN cookbook:logins:alice)" "the history keeps the newest 10 logins"
printf ' newest entry: %s\n' "$(valkey LINDEX cookbook:logins:alice 0)"
section "Brute-force action: mail alert"
for i in $(seq 1 6); do auth bob "wrong-password-$i" imap "203.0.113.$i"; done
auth bob bob-secret imap 203.0.113.99
expect_auth_status "Invalid login or password" "after 5 wrong passwords the network 203.0.113.0/24 is blocked"
wait_until '[ "$(mail_count "Brute-force block for 203.0.113.0/24")" -ge 1 ]'
expect_equal "1" "$(mail_count 'Brute-force block for 203.0.113.0/24')" "the administrator got exactly one mail"
for i in $(seq 1 5); do auth bob bob-secret imap "203.0.113.$((i + 100))"; done
sleep 1
expect_equal "1" "$(mail_count 'Brute-force block for 203.0.113.0/24')" "further blocked attempts send no more mails"
blocked="$(valkey GET 'cookbook:bf_alert:203.0.113.0/24:count')"
[ "${blocked:-0}" -ge 5 ] && pass "the action counted $blocked blocked attempts" || fail "the action counted ${blocked:-0} blocked attempts"
auth bob bob-secret imap 198.51.100.7
expect_auth_status "OK" "bob still logs in from another network"
finish
Ideas for your own changes
- Send the alert to a chat instead of mail with the bundled
httpmodule. The bundledactions/telegram.luashows how. - Record failed logins in the journal as well, with a separate list per account.
- Add a custom hook
GET /api/v1/custom/last-loginfor the helpdesk, as the Admin toolkit shows for other data.