Skip to main content
Version: 4.2

Recipe: Learning IP reputation

Nauthilus can learn which client addresses behave well and which do not. This recipe uses the bundled reputation plugin to do that, and combines it with a small Lua script:

  • Every login teaches the plugin something. A wrong password adds risk to the client address, a successful login adds trust.
  • Before the password is checked, the plugin reports the band of the client address: unknown, positive, trusted, suspicious, or blocked.
  • A Lua environment source marks privileged accounts, such as administrators.
  • Policy rules protect privileged accounts from suspicious addresses, while ordinary users behind the same shared network keep working. An administrator can override the learned band of an address or a network at any time.

This is the most advanced recipe of the cookbook. Read Country rules per account first; it introduces native plugins with a much smaller configuration.

Shown: native Go plugin (learning obligation, assessment provider, management API), Lua environment source, policy record predicates, built-in identity provider with the client credentials grant.
Download: reputation.tar.gz

What happens​

  1. At pre_auth the plugin reads what it knows about the client address and reports its band. The Lua script reports whether the account is privileged.
  2. A rule refuses privileged accounts from suspicious addresses and everybody from blocked ones.
  3. Otherwise the password is checked. A rule at auth_decision decides as usual and carries the obligation learn_outcome: Nauthilus hands the backend result to the plugin, which updates the address in the background. Learning never delays or changes the login.

Start and test​

setup.sh creates the key material once: two HMAC keys for the plugin and a signing key for the identity provider.

./setup.sh
docker compose up -d --wait
./test.sh

The test picks addresses without history for every run, because the plugin keeps its model in Valkey: do not empty Valkey with FLUSHALL while Nauthilus runs. To start over, use docker compose down -v.

Try it by hand. Mark alice as privileged, then send four wrong passwords for bob from one address:

docker compose exec valkey valkey-cli SADD cookbook:privileged alice

for i in 1 2 3 4; do
curl -s -o /dev/null -u mailserver:mailserver-backchannel-secret -H 'Content-Type: application/json' \
-d "{\"username\":\"bob\",\"password\":\"wrong-$i\",\"protocol\":\"imap\",\"client_ip\":\"198.51.100.7\"}" \
http://127.0.0.1:28088/api/v1/auth/json
done

curl -i -u mailserver:mailserver-backchannel-secret -H 'Content-Type: application/json' \
-d '{"username":"alice","password":"alice-secret","protocol":"imap","client_ip":"198.51.100.7"}' \
http://127.0.0.1:28088/api/v1/auth/json

alice is refused with Login from a suspicious address is not allowed for this account; bob still logs in from the same address with his correct password.

The management API​

The plugin adds administrator endpoints below /api/v1/custom/reputation/. They accept only a Bearer token with the scope nauthilus:admin. The built-in identity provider issues it to the client reputation-admin:

TOKEN=$(curl -s -u reputation-admin:reputation-admin-secret \
-d grant_type=client_credentials -d scope=nauthilus:admin \
http://127.0.0.1:28088/oidc/token | sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p')

# What does the plugin know about an address?
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"kind": "ip", "subject": "198.51.100.7"}' \
http://127.0.0.1:28088/api/v1/custom/reputation/lookup

# Mark the address as trusted for one hour.
curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"kind": "ip", "subject": "198.51.100.7", "band": "trusted", "ttl_seconds": 3600,
"reason": "known_office", "origin": "operator", "audit_id": "ticket-1", "previous_audit": ""}' \
http://127.0.0.1:28088/api/v1/custom/reputation/override

# Block a whole network.
curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"kind": "network", "subject": "203.0.113.0/24", "band": "blocked", "ttl_seconds": 3600,
"reason": "incident", "origin": "operator", "audit_id": "ticket-2", "previous_audit": ""}' \
http://127.0.0.1:28088/api/v1/custom/reputation/override

# Remove the block; previous_audit must name the audit ID of the override you replace.
curl -s -X DELETE -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"kind": "network", "subject": "203.0.113.0/24", "previous_audit": "ticket-2",
"audit_id": "ticket-3", "reason": "resolved", "origin": "operator"}' \
http://127.0.0.1:28088/api/v1/custom/reputation/override
  • The lookup shows the band, the scores, and the evidence of all three profiles. It never shows the stored key or the HMAC tag.
  • An override wins over learned evidence. Among overrides, an exact address wins over its network, so a trusted office address stays usable while the rest of its network is blocked.
  • previous_audit protects against lost updates: replacing or deleting an override needs the audit ID of the current one.
  • A network override applies to the addresses inside it only for networks listed in ip_override_networks.

See Operating the reputation subsystem for the complete API.

The stack​

docker-compose.yml
# Lua Cookbook recipe "Learning IP reputation".
# Start with: ./setup.sh && docker compose up -d --wait Test with: ./test.sh Stop with: docker compose down
name: cookbook-reputation

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

nauthilus:
image: ${NAUTHILUS_IMAGE:-ghcr.io/croessner/nauthilus:v4.2.0}
depends_on:
valkey:
condition: service_healthy
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}
ports:
- "127.0.0.1:28088:8080"
volumes:
- ./nauthilus/nauthilus.yml:/etc/nauthilus/nauthilus.yml:ro
- ./nauthilus/lua:/etc/nauthilus/lua:ro
- ./secrets:/run/secrets:ro
healthcheck:
test: ["CMD", "/usr/app/healthcheck", "--url", "http://127.0.0.1:8080/healthz"]
interval: 5s
timeout: 3s
retries: 30
setup.sh
#!/usr/bin/env sh
# Creates the key material of the "Learning IP reputation" recipe in ./secrets. Run once before docker compose up.
# reputation-subject.key, reputation-manifest.key 32 random bytes each; the reputation plugin stores subjects
# (IP addresses, networks, accounts) only as HMAC tags of them
# oidc-signing.key RSA key the built-in identity provider signs tokens with
set -eu
cd "$(dirname "$0")"
mkdir -p secrets

for name in reputation-subject reputation-manifest; do
[ -f "secrets/$name.key" ] || openssl rand -out "secrets/$name.key" 32
done

[ -f secrets/oidc-signing.key ] || openssl genrsa -out secrets/oidc-signing.key 2048 2>/dev/null

# Nauthilus runs as user 65532 in the container and must be able to read the demo keys.
chmod 0644 secrets/*.key
echo "Key material: $(pwd)/secrets"

The stack mounts secrets/ as /run/secrets. The keys stay on your machine: the files are excluded from Git and from the download archive.

The configuration​

nauthilus/nauthilus.yml
# Nauthilus configuration of the "Learning IP reputation" Lua Cookbook recipe.
# Shown: the bundled native reputation plugin (learning, assessment, management API) together with a Lua environment
# source, combined by policy rules; the built-in identity provider issues the administrator's API token.

runtime:
instance_name: "cookbook-reputation"

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: "cookbookPasswordNonce08"
encryption_secret: "cookbookEncryption08"

# Native Go plugins. The Nauthilus image ships reputation.so below /usr/local/lib/nauthilus/plugins.
plugins:
# The plugin stores IP addresses, networks, and accounts only as HMAC tags. The host computes them with these keys
# (32 random bytes each, created by setup.sh). Every Nauthilus instance that shares the Redis data needs the same keys.
opaque_identifier_tagger:
scopes:
- scope: reputation-subject
active: {version: current, secret_ref: {file: /run/secrets/reputation-subject.key}}
- scope: reputation-manifest
active: {version: allocation, secret_ref: {file: /run/secrets/reputation-manifest.key}}

# A checksum or signature is verified when one is configured. This recipe configures none, so it runs with every
# image; in production pin the artifact with checksum (sha256:...) or a minisign signature.
verification_policy: when_present
allowed_dirs:
- /usr/local/lib/nauthilus/plugins
modules:
- name: reputation
type: go
path: /usr/local/lib/nauthilus/plugins/reputation.so
optional: false
config:
# The model: how evidence is stored and how fast it fades. Changing these values needs a new model_id.
state_schema: reputation-state.v1
model_id: cookbook-v1
allocation_maintenance: false
allocation_drain_generation: 0
subject_scope: reputation-subject
manifest_scope: reputation-manifest
retention: 168h
event_manifest_ttl: 49h
subject_seen_ttl: 49h
maximum_retry_horizon: 24h
maximum_source_classes: 4
maximum_new_subjects_per_source_hour: 1000
maximum_event_manifests_per_source: 10000
maximum_seen_events_per_subject: 10000
# Evidence fades with these half-lives. "fast" reacts to the last hour, "operational" to the last days.
profiles:
fast: {half_life: 1h}
operational: {half_life: 24h}
baseline: {half_life: 168h}
# score = tanh(ln((risk + alpha) / (trust + alpha)) / temperature) * confidence,
# confidence = 1 - exp(-(risk + trust) / saturation). Small values react to few events, as a demo should.
score: {alpha: 1, saturation: 3, temperature: 1}
# Bands turn scores into words. With these demo thresholds three wrong passwords make an address
# "suspicious", and five successful logins make it "trusted". Learned evidence never blocks on its own.
bands:
learned_blocked: false
minimum_confidence: 0.2
minimum_samples: 1
diversity_mass_floor: 0.5
minimum_block_source_classes: 2
authoritative_risk_max_age: 24h
severe_risk_max_age: 24h
severe_risk_score: 0.65
trusted: {score: 0.65, confidence: 0.70, samples: 5}
positive: {score: 0.35, confidence: 0.35, samples: 2}
suspicious_fast: {score: 0.5, confidence: 0.5, samples: 3}
suspicious_operational: {score: 0.5, confidence: 0.5, samples: 3}
blocked: {score: 0.9, confidence: 0.9, samples: 50}
network_subjects: {ipv4_prefix: 24, ipv6_prefix: 64}
account_normalization: exact
services: []

# Learning from logins: the host hands every backend result to the plugin after the password check.
auth_learning_queue: {capacity: 1024, max_age: 30s, timeout: 5s}
auth_learning:
success_signal: auth.success
bad_credentials_signal: auth.bad_credentials
source_class_caps:
authentication: {risk: 20, trust: 20, samples: 100}
sources:
authentication:
source_policy_id: authentication-backend-v1
binding:
kind: host_execution
module: reputation
component: learn_outcome
extension_point: obligation
operation: execute
targets: [authn/authenticate]
source_class: authentication
allowed_signals: [auth.success, auth.bad_credentials]
allowed_subjects: {auth_client: [ip], auth_account: [account]}
derived_subjects: {auth_client: [network]}
maximum_subjects: 2
maximum_lateness: 10m
future_clock_skew: 0s
allow_magnitude: false
requests_per_second: 50
max_concurrency: 4
# A successful login adds trust to the client address, its network, and the account. A wrong password adds
# risk to the address and its network only, so an attacker cannot ruin an account's reputation.
signals:
auth.success:
direction: trust
weight: 1.0
magnitude: forbidden
subject_roles: {auth_client: {ip: 1.0, network: 0.25}, auth_account: {account: 1.0}}
source_classes: [authentication]
evidence_origin: host_backend_outcome
authoritative: false
max_event_age: 10m
profiles: [fast, operational, baseline]
auth.bad_credentials:
direction: risk
weight: 1.0
magnitude: forbidden
subject_roles: {auth_client: {ip: 1.0, network: 0.25}}
source_classes: [authentication]
evidence_origin: host_backend_outcome
authoritative: false
max_event_age: 10m
profiles: [fast, operational, baseline]

# Assessment: before the password check, the plugin reports the band of the client address.
target_bindings:
- target: authn/authenticate
component: authentication
output_fact: auth_subjects
decision_profile: fast
subjects:
- {attribute: nauthilus.request.client.ip, category: environment, role: auth_client, kind: ip}
# An operator override on one of these networks also applies to every address inside it.
ip_override_networks:
- 203.0.113.0/24

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"
# The management API of the reputation plugin accepts only Bearer tokens. Nauthilus validates the tokens that
# its own identity provider issues.
oidc_bearer:
enabled: true

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
environment_vm_pool_size: 2

search:
- protocol:
- "imap"
- "smtp"
cache_name: "demo"

# The built-in identity provider. It only serves one machine client here: the administrator's tool, which gets a
# token with the client credentials grant. The frontend and WebAuthn blocks are the minimum the provider needs to
# start; this recipe uses no browser login.
identity:
frontend:
enabled: true
# Demo value only; at least 32 bytes.
encryption_secret: "cookbook-frontend-secret-08-at-least-32-bytes"
assets:
html_static_content_path: "/usr/app/static/templates"
language_resources: "/usr/app/server/resources"
localization:
languages: [en]
default_language: "en"
mfa:
webauthn:
rp_display_name: "Nauthilus Cookbook"
rp_id: "localhost"
rp_origins:
- "http://localhost:28088"
oidc:
enabled: true
issuer: "http://localhost:28088"
access_token_type: "opaque"
token_endpoint_auth_methods_supported: [client_secret_basic]
signing_keys:
- id: "cookbook-rs256"
key_file: "/run/secrets/oidc-signing.key"
algorithm: "RS256"
active: true
clients:
- name: "Reputation administrator"
client_id: "reputation-admin"
# Demo value only.
client_secret: "reputation-admin-secret"
grant_types:
- client_credentials
token_endpoint_auth_method: "client_secret_basic"
access_token_lifetime: 5m
scopes:
- nauthilus:admin

policy:
namespaces:
authn:
# The registry script declares the attribute that environment/privileged_account.lua emits.
schema_contributions:
lua:
registry_scripts:
- "/etc/nauthilus/lua/policy/registry.lua"

providers:
# The reputation plugin's assessment provider (component "authentication" of its target binding), so its
# identity is authn/plugin.reputation.authentication. It returns one record per subject with the band.
authentication:
kind: native
module: reputation
targets: [{action: authenticate}]
produced_facts:
- plugin.reputation.auth_subjects
- plugin.reputation.auth_subjects_fast
- plugin.reputation.auth_subjects_operational
- plugin.reputation.auth_subjects_baseline
failure: indeterminate
timeout: 500ms
# The Lua environment source.
lua_environment_privileged_account:
kind: lua_environment
script_path: "/etc/nauthilus/lua/environment/privileged_account.lua"
targets: [{action: authenticate}]
executions: [host_sync]

domain_plans:
reputation:
checkpoints:
# Both providers run before the password is checked.
pre_auth:
providers:
- name: reputation
use: authn/plugin.reputation.authentication
actions: [authenticate]
- name: privileged_account
use: authn/lua_environment_privileged_account
actions: [authenticate]
auth_backend:
providers:
- name: backend_order
use: authn/auth_backend
actions: [authenticate]
auth_decision:
providers: []

policy_sets:
reputation:
visibility: private
rules:
# An operator blocked the address or its network: nobody logs in from there.
- name: blocked_by_operator
checkpoint: pre_auth
actions: [authenticate]
require_providers: [reputation]
if:
records:
attribute: plugin.reputation.auth_subjects
quantifier: any
where: {field: band, eq: blocked}
then:
decision: deny
reason: reputation_blocked
response_message:
from: literal
text: "Access from your network is blocked"
# A suspicious address may not log in to a privileged account. Other accounts may: a shared office or
# mobile network can look suspicious because of one user's typos.
- name: privileged_account_from_suspicious_address
checkpoint: pre_auth
actions: [authenticate]
require_providers: [reputation, privileged_account]
if:
all:
- attribute: lua.plugin.cookbook.account.privileged
is: true
- records:
attribute: plugin.reputation.auth_subjects
quantifier: any
where: {field: band, eq: suspicious}
then:
decision: deny
reason: reputation_suspicious
response_message:
from: literal
text: "Login from a suspicious address is not allowed for this account"

# Learning. The rules decide like the built-in rules and also hand the backend result to the plugin.
# Never attach learn_outcome to a rule that denies because of reputation: the plugin would learn from its
# own verdict.
- name: learn_success
checkpoint: auth_decision
actions: [authenticate]
if:
attribute: backend.authenticated
is: true
then:
decision: permit
obligations:
- id: authn/plugin.reputation.learn_outcome
- name: learn_failure
checkpoint: auth_decision
actions: [authenticate]
if:
attribute: backend.authenticated
is: false
then:
decision: deny
obligations:
- id: authn/plugin.reputation.learn_outcome

targets:
- namespace: authn
action: authenticate
schema: authn/authenticate/v1
mode: enforce
default_policy: authn/standard_auth
domain_plan: authn/reputation
plans:
pre_auth:
policy_sets: [authn/reputation]
auth_decision:
policy_sets: [authn/reputation]

The plugin​

  • plugins.opaque_identifier_tagger gives the host two HMAC keys. The plugin never stores an address, network, or account in clear text, only its HMAC tag. Every Nauthilus instance that shares the Valkey data needs the same keys.
  • The model block (model_id to bands) defines how evidence is stored, how fast it fades, and how it turns into bands. The values are chosen for a demo: three to four wrong passwords make an address suspicious, five successful logins make it trusted. Production values are far more patient; see the calibration example in the plugin reference. A change to the model needs a new model_id.
  • learned_blocked: false means learned evidence never blocks an address by itself. Only an administrator does, with an override.
  • auth_learning, sources, and signals define the learning from logins. A success adds trust to the address, its /24 network, and the account; a wrong password adds risk to the address and its network only, so an attacker cannot damage the reputation of an account.
  • target_bindings registers the assessment provider authn/plugin.reputation.authentication. It reads the client address from nauthilus.request.client.ip and publishes the record facts plugin.reputation.auth_subjects (the profile named by decision_profile, here fast) and ..._fast, ..._operational, ..._baseline.

The identity provider​

The management API needs a Bearer token, so the recipe turns on the built-in identity provider with one machine client. auth.backchannel.oidc_bearer.enabled lets Nauthilus accept the tokens it issued itself. The frontend and mfa.webauthn blocks are the minimum the provider needs to start; the recipe does not use a browser login. The frontend encryption_secret must be at least 32 bytes long.

The rules​

  • blocked_by_operator uses a record predicate: records with quantifier: any matches when at least one record of plugin.reputation.auth_subjects has band: blocked. Everybody is refused.
  • privileged_account_from_suspicious_address combines the Lua fact with the plugin's records.
  • learn_success and learn_failure decide at auth_decision like the built-in rules and attach the obligation authn/plugin.reputation.learn_outcome. Never attach it to a rule that denies because of reputation: the plugin would then learn from its own verdict.
  • The target binds the set at both checkpoints with plans.pre_auth and plans.auth_decision.

The Lua environment source​

nauthilus/lua/environment/privileged_account.lua
-- environment/privileged_account.lua
-- Environment source of the "Learning IP reputation" recipe. It marks privileged accounts, such as administrators or
-- service accounts, that an administrator listed in a Valkey set:
-- valkey-cli SADD cookbook:privileged alice
-- It emits the policy attribute lua.plugin.cookbook.account.privileged. The script knows nothing about the client's
-- reputation; the native reputation plugin provides that, and the policy rules in nauthilus.yml combine both.

local nauthilus_redis = require("nauthilus_redis")
local nauthilus_policy = require("nauthilus_policy")

function nauthilus_call_environment(request)
local member, err = nauthilus_redis.redis_sismember("default", "cookbook:privileged", request.username or "")

if err ~= nil then
return nauthilus_builtin.ENVIRONMENT_TRIGGER_NO,
nauthilus_builtin.ENVIRONMENT_ABORT_NO,
nauthilus_builtin.ENVIRONMENT_RESULT_FAIL
end

local privileged = member == 1 or member == true

if privileged then
nauthilus_builtin.custom_log_add("privileged_account", "yes")
end

nauthilus_policy.emit_attribute({ id = "lua.plugin.cookbook.account.privileged", value = privileged })

return nauthilus_builtin.ENVIRONMENT_TRIGGER_NO,
nauthilus_builtin.ENVIRONMENT_ABORT_NO,
nauthilus_builtin.ENVIRONMENT_RESULT_OK
end

The script asks Valkey whether the username is a member of the set cookbook:privileged and always emits the attribute, true or false. It does not decide anything and it cannot see the reputation: the policy combines both.

nauthilus/lua/policy/registry.lua
-- policy/registry.lua
-- Policy registry script of the "Learning IP reputation" recipe. It declares the attribute that
-- environment/privileged_account.lua emits, so that the rules in nauthilus.yml can test it.

nauthilus_policy.register_attribute({
id = "lua.plugin.cookbook.account.privileged",
stage = "pre_auth",
operations = { "authenticate" },
category = "environment",
type = "bool",
description = "Whether the account is listed as privileged.",
})

What the test checks​

test.sh
#!/usr/bin/env bash
# Checks the "Learning IP reputation" recipe. Start the stack first: ./setup.sh && docker compose up -d --wait
# The plugin keeps its model and allocation state in Valkey, so the test never empties Valkey. It picks addresses
# without history for every run and removes its own overrides.
cd "$(dirname "$0")" || exit 1
. ../lib/cookbook.sh

NAUTHILUS_URL="${NAUTHILUS_URL:-http://127.0.0.1:28088}"
SUSPICIOUS_TEXT="Login from a suspicious address is not allowed for this account"
BLOCKED_TEXT="Access from your network is blocked"

# admin_token asks the built-in identity provider for an administrator token (client credentials grant).
admin_token() {
curl -sS -u reputation-admin:reputation-admin-secret \
-d grant_type=client_credentials -d scope=nauthilus:admin \
"${NAUTHILUS_URL}/oidc/token" | sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p'
}

TOKEN="$(admin_token)"

# reputation calls the plugin's management API. Arguments: method path json
reputation() {
http "$1" "/api/v1/custom/reputation/$2" -H "Authorization: Bearer ${TOKEN}" \
-H 'Content-Type: application/json' -d "$3"
}

# band prints the learned or overridden band of an address in the "fast" profile that the rules use.
band() {
reputation POST lookup "{\"kind\": \"ip\", \"subject\": \"$1\"}"
printf '%s' "$last_body" | awk -F'"fast":' '{ print $2 }' | grep -o '"band":"[a-z]*"' | head -1 | cut -d'"' -f4
}

# fresh_ip prints an address of the given /24 prefix that has no history yet. Argument: prefix such as 198.51.100
fresh_ip() {
local candidate attempt

for attempt in $(seq 1 40); do
candidate="$1.$(( (RANDOM % 250) + 1 ))"

if [ "$(band "$candidate")" = "unknown" ]; then
printf '%s' "$candidate"
return 0
fi
done

return 1
}

# remove_network_block deletes the network override this test creates, if an earlier run left it behind.
remove_network_block() {
reputation DELETE override '{"kind": "network", "subject": "203.0.113.0/24", "previous_audit": "cookbook-test-block",
"audit_id": "cookbook-test-unblock", "reason": "test_cleanup", "origin": "operator"}'
}

section "Plugin and administrator token"
[ -n "$TOKEN" ] && pass "the identity provider issued an administrator token" || fail "no administrator token"
reputation POST lookup '{"kind": "ip", "subject": "192.0.2.1"}'
expect_body_contains '"model_id":"cookbook-v1"' "the plugin answers a lookup with the configured model"

remove_network_block >/dev/null
valkey SADD cookbook:privileged alice >/dev/null
valkey SREM cookbook:privileged bob >/dev/null

section "Learning from wrong passwords"
ATTACKER="$(fresh_ip 198.51.100)" || fail "no address without history found"
expect_equal "unknown" "$(band "$ATTACKER")" "a new address has no reputation"

auth alice alice-secret imap "$ATTACKER"
expect_auth_status "OK" "alice (privileged) logs in from the new address"

for i in 1 2 3 4; do auth bob "wrong-password-$i" imap "$ATTACKER"; done
wait_until "[ \"\$(band $ATTACKER)\" = suspicious ]"
expect_equal "suspicious" "$(band "$ATTACKER")" "four wrong passwords make the address suspicious"

auth alice alice-secret imap "$ATTACKER"
expect_auth_status "$SUSPICIOUS_TEXT" "alice (privileged) is refused from the suspicious address"

auth bob bob-secret imap "$ATTACKER"
expect_auth_status "OK" "bob (not privileged) still logs in from there"

section "Learning from successful logins"
OFFICE="$(fresh_ip 192.0.2)" || fail "no address without history found"
for i in 1 2 3 4 5 6; do auth bob bob-secret imap "$OFFICE"; done
wait_until "[ \"\$(band $OFFICE)\" = trusted ]"
expect_equal "trusted" "$(band "$OFFICE")" "six successful logins make the address trusted"

section "Operator overrides"
reputation PUT override "{\"kind\": \"ip\", \"subject\": \"$ATTACKER\", \"band\": \"trusted\", \"ttl_seconds\": 600,
\"reason\": \"known_office\", \"origin\": \"operator\", \"audit_id\": \"cookbook-test-trust\", \"previous_audit\": \"\"}"
expect_status 200 "the administrator marks the suspicious address as trusted"
auth alice alice-secret imap "$ATTACKER"
expect_auth_status "OK" "alice logs in from the trusted address again"

reputation PUT override '{"kind": "network", "subject": "203.0.113.0/24", "band": "blocked", "ttl_seconds": 600,
"reason": "incident", "origin": "operator", "audit_id": "cookbook-test-block", "previous_audit": ""}'
expect_status 200 "the administrator blocks the network 203.0.113.0/24"
auth bob bob-secret imap 203.0.113.99
expect_auth_status "$BLOCKED_TEXT" "everybody is refused from the blocked network"

remove_network_block
expect_status 200 "the administrator removes the block"
auth bob bob-secret imap 203.0.113.99
expect_auth_status "OK" "logins from the network work again"

reputation DELETE override "{\"kind\": \"ip\", \"subject\": \"$ATTACKER\", \"previous_audit\": \"cookbook-test-trust\",
\"audit_id\": \"cookbook-test-untrust\", \"reason\": \"test_cleanup\", \"origin\": \"operator\"}"

section "Access control of the management API"
http POST /api/v1/custom/reputation/lookup -u mailserver:mailserver-backchannel-secret \
-H 'Content-Type: application/json' -d '{"kind": "ip", "subject": "192.0.2.1"}'
[ "$last_status" = 401 ] || [ "$last_status" = 403 ] && pass "a Basic credential cannot use the management API" ||
fail "a Basic credential reached the management API"

section "Many requests"
wrong=0
for i in $(seq 1 100); do
auth bob bob-secret imap "$OFFICE"
[ "$(header Auth-Status)" = "OK" ] || wrong=$((wrong + 1))
auth alice alice-secret imap "$OFFICE"
[ "$(header Auth-Status)" = "OK" ] || wrong=$((wrong + 1))
done
expect_equal 0 "$wrong" "200 logins from the trusted office address got the expected answer"

valkey SREM cookbook:privileged alice >/dev/null

finish

Ideas for your own changes​

  • Refuse every login from suspicious addresses with a tempfail instead of a deny, so mail clients retry later.
  • Learn from more sources, for example your mail filter, through the reputation/observe target of the Policy API.
  • Run several Nauthilus instances with the same keys and Valkey, so they share what they learned.
  • Look at the plugin's metrics: curl -s http://127.0.0.1:28088/metrics | grep nauthilus_plugin_reputation.