Research context: All work was performed on infrastructure owned and operated by the author in a private homelab environment. Every hostname and address in this post has been replaced with a role or a placeholder. Techniques documented here are for defensive awareness. Do not test against systems you do not own or have explicit written authorization to assess.

Published by Oob Skulden™

Standing up Wazuh takes an afternoon. The installer is great, the docs are great, and there are a hundred tutorials. This isn’t one of them.

This is about everything the installer doesn’t do for you: who gets in, how you find out when something weird happens to your identity system, and whether you can get back in after you break it. (You will break it.)

I run Wazuh as a single node with Authentik as the identity provider, in a homelab I treat like a small production shop. Over about two months I rebuilt the single sign-on, piped Authentik’s event log into Wazuh, got alerts landing on my phone, and patched the whole stack from 4.14.7 to 4.14.10.

Most of this post is what went wrong, because that’s the useful part. After each story you’ll find the commands I actually ran for it, so you can read straight through or jump to the parts you need.

How to read the command blocks:

  • Every block starts with a comment saying which host it runs on. Read your prompt before you paste. (Seriously. Wrong host was my most common mistake.)
  • Placeholders are in angle brackets, like <ver>, <date> and <ntfy-host>. Swap them for your own.
  • Blocks marked not run as written are here for completeness and weren’t part of the logged work. Test them before you trust them.
  • Never paste the contents of a backup archive, a certificate key or a token into a ticket, a chat or a post.
  • The two long scripts (the event collector and the ntfy integration) live in the appendices so they don’t break the flow.

The shape of it

Four machines matter here:

  • The Wazuh host (indexer, manager, dashboard and Filebeat, all on one box)
  • The Authentik host (Docker Compose)
  • A control node that runs Ansible
  • A small notification host running ntfy (self-hosted push notifications)

It’s all on a private network, and every hostname and address in this post has been swapped for a role.

Here’s the alert path, start to finish:

Authentik Events API
  -> collector (systemd timer, 60s) -> events.json
  -> Wazuh agent -> Wazuh manager (custom rules 100700-100726)
  -> integratord -> custom script (with a deny list) -> ntfy -> phone

I also keep one hard rule: no change goes in if it removes the last working way back in. It comes up again below.

Part 1: What the installer leaves behind, and what you build on top

The tarball

The assisted installer generates certificates and every service password, then bundles them into one tarball. Mine was sitting in a home directory, owned by root. Inside: the root CA private key and the password file.

That’s the most valuable file on the machine. Whoever can read it can mint certificates your cluster will trust. So treat it that way: encrypt it, and keep a copy off the host.

SAML terminates at the indexer

This one fact clears up most of the confusion. Wazuh’s SAML login is handled by the indexer’s security plugin, not the dashboard. The dashboard just needs to know SAML exists and that its callback paths are exempt from XSRF checks. The real work happens in the indexer’s config.yml. Wazuh’s own authentik SSO guide covers the happy path; the rest of this section is where mine wasn’t.

Here’s the shape of it, with placeholders:

# indexer: opensearch-security/config.yml, under authc
basic_internal_auth_domain:
  order: 0
  http_authenticator:
    type: "basic"
    challenge: false      # stays enabled as a break-glass path, without taking over the browser login
saml_auth_domain:
  http_enabled: true
  transport_enabled: false
  order: 1
  http_authenticator:
    type: saml
    challenge: true
    config:
      idp:
        metadata_file: <path to the metadata XML exported from Authentik>
        entity_id: <the entityID inside that metadata file>
      sp:
        entity_id: <the Issuer/audience you set on the Authentik provider>
      kibana_url: https://<your-wazuh-dashboard>
      roles_key: Roles
      exchange_key: <generate with openssl rand -hex 32>
  authentication_backend:
    type: noop
# dashboard: opensearch_dashboards.yml
opensearch_security.auth.multiple_auth_enabled: true
opensearch_security.auth.type: ["basicauth","saml"]
opensearch_security.session.keepalive: false
server.xsrf.allowlist: ["/_opendistro/_security/saml/acs", "/_opendistro/_security/saml/logout", "/_opendistro/_security/saml/acs/idpinitiated"]

Two choices here were on purpose. The internal basic-auth domain stays on with its challenge turned off, so there’s still a login that doesn’t need Authentik to be alive, and it doesn’t hijack the browser flow. And session.keepalive goes to false, which Authentik’s own integration notes call out.

One more thing: editing the indexer’s config file doesn’t do anything by itself. You have to push it with securityadmin.sh. If you skip that, you’ll spend an evening debugging a config that was never loaded. Ask me how I know.

The commands: backing up and pushing indexer config

Editing the indexer’s security files doesn’t change anything by itself. It only takes effect when you push the file.

# on: wazuh host
# back up the live security configuration before touching it
sudo /usr/share/wazuh-indexer/bin/indexer-security-init.sh --options "-backup /etc/wazuh-indexer/opensearch-security -icl -nhnv"

# generate the exchange key used in config.yml (keep it out of chat and version control)
openssl rand -hex 32

After you edit config.yml (the saml_auth_domain block from earlier), push it. The same command pushes roles_mapping.yml if you change -f:

# on: wazuh host
sudo JAVA_HOME=/usr/share/wazuh-indexer/jdk/ bash /usr/share/wazuh-indexer/plugins/opensearch-security/tools/securityadmin.sh \
  -f /etc/wazuh-indexer/opensearch-security/config.yml \
  -icl -key /etc/wazuh-indexer/certs/admin-key.pem \
  -cert /etc/wazuh-indexer/certs/admin.pem \
  -cacert /etc/wazuh-indexer/certs/root-ca.pem \
  -h localhost -nhnv

You want Done with success at the end. In roles_mapping.yml, add your backend role under all_access as a new list entry. Don’t replace the existing ones:

all_access:
  reserved: false
  hidden: false
  backend_roles:
  - "admin"          # already there, keep it
  - "wazuh-admins"   # added

Then restart the dashboard after the dashboard config edits above:

# on: wazuh host
sudo systemctl restart wazuh-dashboard

To tell two logged-in users apart, open the dashboard’s /api/v1/auth/authinfo path in the same browser session while you’re logged in. It shows the hashed user name and backend roles.

The commands: the Authentik side of the SAML build

This is all done in the Authentik admin UI unless a command is shown. The names match the rest of this post, and the hosts are placeholders.

Group and mapping first, provider second, application third. That order means every step has something to point at.

  1. Groups: wazuh-administrators and wazuh-readonly.
  2. Property mapping (Customization, Property Mappings, SAML Provider Property Mapping). Name it Wazuh Roles, set the SAML attribute name to Roles (case-sensitive, and it has to match roles_key: Roles in the indexer config), and leave the friendly name blank:
if ak_is_group_member(request.user, name="wazuh-administrators"):
    return "wazuh-admins"
elif ak_is_group_member(request.user, name="wazuh-readonly"):
    return "wazuh-readonly"
return None
  1. SAML provider:
FieldValue
NameWazuh-provider
Authorization flowdefault-provider-authorization-implicit-consent
ACS URLhttps://<wazuh-host>/_opendistro/_security/saml/acs
Audiencewazuh-saml
Service Provider BindingPost
Signing certificatethe self-signed one, with Sign assertions on
EntityID/Issuer overrideleave blank (see below)
Property mappingsmove Wazuh Roles from Available to Selected

On the provider’s Preview tab, a user in wazuh-administrators should show Roles: wazuh-admins. This is the cheapest check in the whole build, and it would have caught the September failure before Wazuh was even involved.

  1. Application: name Wazuh, slug wazuh, provider Wazuh-provider, launch URL https://<wazuh-host>. Use the simple create form (the small arrow next to New Application). The wizard’s provider step likes to create a second provider instead of picking the existing one.

  2. Download the provider’s metadata and read the real entityID out of it:

# on: wazuh host
ls -l /tmp/*.xml && grep -o 'entityID="[^"]*"' /tmp/*.xml

Put that exact URL in idp.entity_id. In this build it was an HTTPS URL on the HTTPS port, not the plain-HTTP one from my first attempt. That’s why you read the value from the file instead of typing it.

Install the new metadata, and move the old file out of the scanned directory. The indexer scans its security directory, so a stale copy with the same name and the old certificate shouldn’t live there.

# on: wazuh host
sudo mv /etc/wazuh-indexer/opensearch-security/<metadata>.xml ~/<metadata>.xml.old
sudo mv /tmp/<metadata>.xml /etc/wazuh-indexer/opensearch-security/
sudo chown wazuh-indexer:wazuh-indexer /etc/wazuh-indexer/opensearch-security/<metadata>.xml
sudo chmod 640 /etc/wazuh-indexer/opensearch-security/<metadata>.xml
sudo ls -l /etc/wazuh-indexer/opensearch-security/<metadata>.xml
sudo grep -o 'entityID="[^"]*"' /etc/wazuh-indexer/opensearch-security/<metadata>.xml

Stage the config.yml change instead of editing it in place. This script inserts the SAML block at one exact anchor, refuses to run if the anchor isn’t unique or a SAML block already exists, and generates a fresh exchange_key inside the script so the key never shows up on screen. It writes a root-only staging file.

# on: wazuh host
sudo python3 - <<'EOF'
import os, secrets, sys
p = "/etc/wazuh-indexer/opensearch-security/config.yml"
out = "/root/config.yml.new"
src = open(p).read()
anchor = "      proxy_auth_domain:\n"
if src.count(anchor) != 1 or "saml_auth_domain" in src:
    sys.exit("ABORT: anchor not unique, or SAML block already present")
key = secrets.token_hex(32)
block = f"""      saml_auth_domain:
        http_enabled: true
        transport_enabled: false
        order: 1
        http_authenticator:
          type: saml
          challenge: true
          config:
            idp:
              metadata_file: '/etc/wazuh-indexer/opensearch-security/<metadata>.xml'
              entity_id: '<entityID read from the metadata file>'
            sp:
              entity_id: 'wazuh-saml'
            kibana_url: https://<wazuh-host>
            roles_key: Roles
            exchange_key: '{key}'
        authentication_backend:
          type: noop
"""
os.umask(0o077)
open(out, "w").write(src.replace(anchor, block + anchor))
print("staged:", out)
EOF
# show exactly what changed, key redacted
sudo diff /etc/wazuh-indexer/opensearch-security/config.yml /root/config.yml.new | sed "s/exchange_key: '.*'/exchange_key: 'REDACTED'/"

The diff should show only added lines, with authentication_backend sitting next to http_authenticator. Then install the staged file, push it with the securityadmin.sh command from the first commands section, and check the indexer log for the metadata load:

# on: wazuh host
sudo grep -iE 'saml|metadata' /var/log/wazuh-indexer/wazuh-cluster.log | tail -10

You want a line saying the new metadata loaded. A missing or unreadable metadata file gives you a dashboard HTTP 500 on /auth/saml/login, because the dashboard asks the indexer for the redirect and the indexer’s SAML domain can’t answer.

Check break-glass before you rely on SSO. Use the local admin through the indexer, and print the status code, because a wrong password returns an empty 401 body:

# on: wazuh host
curl -sk -u admin -w '\nHTTP %{http_code}\n' https://localhost:9200/_plugins/_security/authinfo

Five ways I got it wrong the first time

  1. YAML indentation. I nested authentication_backend one level too deep, under http_authenticator instead of next to it. The file stopped parsing.
  2. Replacing a role instead of adding one. While editing roles_mapping.yml, I overwrote the existing admin backend role instead of appending to it. That’s a great way to nearly lock yourself out of basic auth while building the thing that was supposed to be an addition.
  3. Two different entity IDs. I set idp.entity_id to the string I’d typed into Authentik’s Issuer field. It actually needs the entityID Authentik generates inside its metadata file, which is a URL. Two fields that look related and aren’t.
  4. A mapping that existed but was never selected. The custom Roles property mapping was fine. The expression was fine. The group it read was populated. I just never moved it from Available to Selected on the provider’s edit screen, so Authentik never sent a Roles attribute. This was the last blocker behind a bunch of identical-looking failures where the backend roles came back empty.
  5. Trusting “it should work.” What actually found each bug was reading raw state: grepping the real file, looking at the real attached list. Not believing a step had finished just because I’d done it.

The integration that quietly wasn’t there: HTTP 500 at /auth/saml/login

In early October, a cleanup removed both halves of the integration: the Authentik provider and application, and the SAML domain in the indexer config. Nothing replaced them. I found out in November when the login threw an HTTP 500, about five weeks later.

So I rebuilt it, and then almost fooled myself again. My first check “worked”, but the logs showed only the default admin account authorizing. The identity I thought was mine was really that account’s session.

The dashboard’s /api/v1/auth/authinfo endpoint shows the hashed user name and backend roles, which is how you tell two users apart when both look logged in. The real check, with an MFA prompt and an identity different from the default admin, came a day later.

“You have no permissions”: two authorization layers, and a file that disagreed with the live index

Getting the login to work wasn’t the end. A browser capture of the failed click showed the 500 coming from the dashboard’s own /auth/saml/login route, before the browser ever reached Authentik. After the rebuild, the same capture showed the assertion accepted and a redirect into the dashboard. And the session was still useless: the Wazuh API token carried an empty role list, and the Security page said “You have no permissions.”

Turns out there are two separate layers. The indexer maps the SAML role to an index role, which gets you into the dashboard. The Wazuh API has its own role mappings, which decide whether you can see agents or settings. The second layer had also been lost in the October teardown.

I recreated it from the dashboard, logged in as the local admin in a different browser, mapping backend_roles FIND the role name to administrator, and then again for the read-only role. Along the way I typed the mapping’s own name into the user-field box. It saves without complaint and never matches anyone. Sneaky.

The read-only path had a quieter problem. The live security index still held the read-only role and its mapping, but the files on disk had lost them. Nothing was broken yet. The next securityadmin.sh push from those files would have deleted read-only access without an error. The only way to see that kind of drift is to check live state through the API, then make the files match.

I proved the path with a throwaway user in a browser with no session. It could see alerts and agents, the Security page turned it away, and the deploy-agent button was greyed out. Then I disabled the user.

The thing that would have caught all of this five weeks sooner is a test after every restart: push the config, log in as each role, read authinfo. That’s a runbook step now.

The commands: Wazuh API role mappings and the read-only role

A successful SAML login proves the indexer accepted the assertion. It does not prove Wazuh’s own API will give the session any rights. The dashboard has a second, separate role layer for the Wazuh API. In the failure described above it was empty: the API token carried "rbac_roles":[], the Security page said “You have no permissions”, and agent lists were flaky.

Fix it in the dashboard, logged in as the local admin account in a different browser from your SSO session (a second window of the same browser shares cookies). Go to Server management, Security, then the Roles mapping tab. Not the Roles tab, which creates new empty roles:

Mapping nameRoleRule
authentik-adminsadministratoruser field backend_roles, operation FIND, value wazuh-admins
authentik-readonlyreadonlyuser field backend_roles, operation FIND, value wazuh-readonly

The user field is literally the text backend_roles. If you type the mapping’s own name in there, it saves without complaint and never matches anyone. Log out and back in through SSO afterwards, because the API token is issued at login.

Read-only role on the indexer side. The live security index and the files on disk can disagree. After the October teardown the live cluster still had the read-only role and its mapping, but the files had lost them. The next securityadmin.sh push from those files would have deleted read-only access with no error. Check live state, then make the files match:

# on: wazuh host
curl -sk -u admin -w '\nHTTP %{http_code}\n' https://localhost:9200/_plugins/_security/api/roles/wazuh_readonly
curl -sk -u admin -w '\nHTTP %{http_code}\n' https://localhost:9200/_plugins/_security/api/rolesmapping/wazuh_readonly

Here are the blocks, appended to the two files with the same markers the automation uses. Back both files up first. No push is needed when live state is already right:

# roles.yml
# BEGIN ANSIBLE MANAGED BLOCK - wazuh_readonly role
wazuh_readonly:
  reserved: false
  hidden: false
  cluster_permissions:
    - "cluster_composite_ops_ro"
  index_permissions:
    - index_patterns:
        - "*"
      allowed_actions:
        - "read"
  tenant_permissions:
    - tenant_patterns:
        - "global_tenant"
      allowed_actions:
        - "kibana_all_read"
# END ANSIBLE MANAGED BLOCK - wazuh_readonly role
# roles_mapping.yml
# BEGIN ANSIBLE MANAGED BLOCK - wazuh_readonly mapping
wazuh_readonly:
  reserved: false
  hidden: false
  backend_roles:
  - "wazuh-readonly"
# END ANSIBLE MANAGED BLOCK - wazuh_readonly mapping

Prove the read-only path with a throwaway user, in a browser with no session at all. Log in, check that authinfo shows the read-only backend role, check that alerts and agents are visible, and check that Server management, Security says “You have no permissions” and the deploy-agent button is greyed out. Then disable the test user (don’t delete it).

Move old backups out of the security directory. Backup copies of config.yml hold retired keys, and the indexer scans that directory.

# on: wazuh host
sudo install -d -m 700 -o root -g root /root/wazuh-security-backups
sudo sh -c 'mv /etc/wazuh-indexer/opensearch-security/*.bak* /root/wazuh-security-backups/'
sudo sh -c 'chmod 600 /root/wazuh-security-backups/*'

The sh -c matters: a wildcard in a directory your user can’t read expands to nothing in your own shell.

Accounts: the default admin, a named admin, a break-glass account

I made a named admin with TOTP, and kept the recovery codes in a password manager that doesn’t depend on the IdP. Then I deleted the default admin account. I’d only meant to remove its Wazuh access. Oops.

Deleting a user in Authentik also deletes the user’s API tokens, so an automation token went with it. It was recoverable. The fix was to create a dedicated break-glass superuser and put alert rules on it, so any login or failed login on that account pages me at urgent priority.

Related finding: the Authentik brand has no recovery flow configured. If a user loses a password or an MFA device, they can’t self-recover, and an admin has to step in. That makes the recovery codes and the break-glass account the real recovery plan, so both are written down as exactly that.

The commands: accounts and identity checks

Named admin, break-glass, and what to do about the default admin. Make a named superuser with TOTP and keep its recovery codes in a password manager that doesn’t depend on the IdP. Make a separate break-glass superuser in the authentik Admins group only, with a long random password and no MFA (a break-glass account that needs a phone defeats its own purpose), and put alert rules 100725 and 100726 on it so any use pages you. Take the default admin out of the Wazuh admin group, not out of the system: open the group’s Users tab and click Remove. Deleting the user deletes its tokens too. Then test the break-glass login once, on purpose, from a browser that has never touched the IdP, and confirm both the login and the alarm.

Proving which account you actually logged in with. The dashboard’s authinfo hash and the IdP’s own record are your evidence, not what the browser seems to show. The Authentik authorize_application event names the user:

# on: authentik host
sudo grep '"action":"authorize_application"' /var/log/authentik-wazuh/events.json | tail -3 | grep -o '"created":"[^"]*"\|"username":"[^"]*"\|"name":"Wazuh[^"]*"'

Browsers remember the last Authentik user even in a private window (you’ll see “Not you?”). A second window of the same browser shares cookies, so use a different browser or a fresh profile, click the Wazuh tile from the right IdP session, and compare the name= hash in authinfo with the previous user’s.

Reputation policy can block you silently. During the October recovery, Authentik’s reputation policy had an entry for a username that never existed on the IdP (a mistyped basic-auth login against the dashboard), and it quietly stalled the identification stage: no login_failed event, the form just didn’t advance. If a login hangs with no failure event, look at the reputation entries.

# on: authentik host
sudo docker exec <server-container> ak shell -c "
from authentik.policies.reputation.models import Reputation
for r in Reputation.objects.all().order_by('score'):
    print(r.identifier, r.score)
"

The .env move, in short. The entrypoint used to fetch the secret key and database password from the vault by AppRole every time a container started, which meant the IdP couldn’t boot whenever the vault was sealed after a reboot. I replaced the fetch with a read from a root-only .env (mode 600) and removed the AppRole variables. Now the entrypoint just writes the two values to the container’s /run/secrets and starts the process, and it exits with an error if either is missing. It trades a boot-order dependency for a plaintext file on the IdP host. I made that trade on purpose and wrote it in the decision log. The file is part of the restore set and has to be backed up with the database.

#!/bin/sh
# entrypoint.sh (after the change)
set -e
/ak-root/.venv/bin/python3 - <<'PYEOF'
import os, sys
secret_key = os.environ.get("AUTHENTIK_SECRET_KEY_RAW")
pg_pass = os.environ.get("PG_PASS")
if not secret_key or not pg_pass:
    print("ENTRYPOINT ERROR: missing AUTHENTIK_SECRET_KEY_RAW or PG_PASS", file=sys.stderr)
    sys.exit(1)
os.makedirs("/run/secrets", exist_ok=True)
for name, val in (("secret_key", secret_key), ("pg_pass", pg_pass)):
    p = "/run/secrets/" + name
    with open(p, "w") as f:
        f.write(val)
    os.chmod(p, 0o644)
print("ENTRYPOINT: secrets written to /run/secrets", file=sys.stderr)
PYEOF
exec dumb-init -- ak "$@"

Agent enrollment, and a test that did harm

I closed unauthenticated agent enrollment with a registration password, then proved it with a negative test: try to enroll without the password.

Order matters here. An earlier negative test ran before I’d confirmed the hole was closed, and a rogue agent actually enrolled and overwrote a real agent’s key file. The real agent still showed as Active. “Active” tells you the agent is talking, not that its key file is the one you issued.

The rule I took away: confirm closure first, then run the negative test.

The commands: the agent registration password

Closing unauthenticated enrollment is two changes, and the order matters: write the password file first, then flip the setting. If the setting flips while the file’s missing, the manager makes up its own random password and logs it.

# on: ansible control node (tasks added to the manager playbook)
- name: Read agent registration password
  ansible.builtin.set_fact:
    wazuh_authd_pass: "{{ lookup('file', '~/.ansible-secrets/wazuh-authd-pass') | trim }}"
  no_log: true
  delegate_to: localhost
  become: false

- name: Deploy registration password on the manager
  ansible.builtin.copy:
    content: "{{ wazuh_authd_pass }}"
    dest: /var/ossec/etc/authd.pass
    owner: root
    group: wazuh
    mode: '0640'
  no_log: true
  notify: Restart wazuh-manager

- name: Require a password for agent enrolment
  ansible.builtin.lineinfile:
    path: /var/ossec/etc/ossec.conf
    regexp: '^\s*<use_password>'
    line: '    <use_password>yes</use_password>'
    owner: root
    group: wazuh
    mode: '0640'
  notify: Restart wazuh-manager

lineinfile instead of blockinfile because the auth block is a dozen lines of packaged defaults, and the playbook should only own the one line that matters. The agent playbook writes the same password file on each agent before the service first starts (enrollment happens on first start), and it disables the Wazuh package repo right after install so a routine update run can’t push an agent past the manager’s version.

Verify closure first, and only then run the negative test (an enrollment attempt without the password should print Invalid password). Remove any rogue agent the earlier, too-early test created, and check the real agent’s key file wasn’t overwritten.

Expected side effect: every manager restart briefly drops all agents. They reconnect on their own.

Seeing what the IdP does

Authentik records logins, failures and config changes, but Wazuh doesn’t read them out of the box. So a small collector polls Authentik’s Events API every 60 seconds and writes JSON lines, and the local agent ships them along.

A set of custom rules (100700 to 100726) turns those into alerts:

  • failed logins
  • five failures from one source, or against one name
  • deletes and changes on providers, flows, tokens, users and groups
  • a collector error or gap
  • any use of the break-glass account

The collector runs as its own service account with exactly one permission, view events, and a single API token with a one-year expiry. I checked its limits instead of assuming them: it reads events, and gets “permission denied” when it tries to list users.

The token went into a root-only file by typing it at a waiting prompt, so it never touched shell history or chat. The collector itself runs as an unprivileged system user under a sandboxed systemd unit that scores 3.6 on systemd-analyze security (an unhardened one scores 9.6). It writes one heartbeat per run, delivers at least once, and starts from “now” on its first run so old history doesn’t replay as fresh alerts. I tested it against a mock Events API before it went anywhere near the identity provider.

A few things worth knowing:

  • Some changes leave no event. The Authentik UI wouldn’t save the token’s expiry (it kept resetting to thirty minutes), so I set it from the management shell and read it back. That went straight to the database, and Authentik’s event log never saw it. Anyone with shell access to the IdP host can edit tokens, users and providers without leaving a trace the collector can see. That has to be caught from the host side, and I haven’t built that detection yet.
  • A pipeline that fails by going quiet needs its own alarm. “No events” and “dead collector” look identical. So a watchdog alerts if the output file hasn’t been written for five minutes. I proved it by stopping the collector’s timer for ten minutes and watching the alert fire three times.
  • Authentik logs one event per request. One failed login makes two events, two seconds apart, so a threshold of five failures in five minutes is counting requests, not intent.
  • Failed logins against names that don’t exist get logged too, with the attempted name in the event. So username guessing is visible.
  • Rule files load alphabetically, and a child rule’s parent has to load first. My first break-glass rules file sorted before the file holding its parent rule, so it was silently ignored. And wazuh-analysisd -t still printed CONFIG OK, because it prints that even when it also warns that a rule is being skipped. Read all the output, and name child files so they sort after their parents.

The commands: the Authentik event pipeline

This is the full set that was running on 2026-11-16. Paths are the ones used throughout this post.

A least-privilege reader

  1. Directory, Roles: create wazuh-event-reader with exactly one global permission, Can view Event (model: Event).
  2. Directory, Users: create a service account wazuh-event-collector with Create group off. Add it to the role from the role’s Users tab. The list hides service accounts by default, so turn off Hide service-accounts to see it.
  3. Directory, Tokens and App passwords: create an API Token for that user with a one-year expiry, and delete the auto-created app password so the account has exactly one credential. Set a calendar reminder before the expiry date. When it lapses the collector stops. The watchdog will catch that, but a reminder is cheaper.

The expiry field in this Authentik version didn’t save from the UI (it kept resetting to now plus 30 minutes). I set it from the management shell and read it back from the database:

# on: authentik host
cd /opt/authentik && sudo docker compose exec worker ak shell -c "from authentik.core.models import Token; from django.utils.timezone import now; from datetime import timedelta; n = Token.objects.filter(identifier='<token-identifier>').update(expires=now() + timedelta(days=365), expiring=True); t = Token.objects.get(identifier='<token-identifier>'); print('updated:', n, '| expires:', t.expires, '| expiring:', t.expiring, '| intent:', t.intent, '| user:', t.user.username)"

A change made this way goes straight to the database and never shows up in Authentik’s event log, so the collector can’t see it. Anyone with shell access to the IdP host can edit tokens, users and providers without a trace in Events. That has to be caught from the host side, for example by watching for docker exec on that host. It’s a detection I still need to build.

Put the token on the host without it touching history or chat

# on: authentik host
sudo install -d -m 700 -o root -g root /etc/authentik-wazuh
sudo sh -c 'umask 077; cat > /etc/authentik-wazuh/token'
# paste the token, press Enter, then Ctrl-D. The command looks hung while it waits.
sudo useradd --system --no-create-home --shell /usr/sbin/nologin ak-collector
sudo chgrp ak-collector /etc/authentik-wazuh && sudo chmod 750 /etc/authentik-wazuh
sudo chown ak-collector:ak-collector /etc/authentik-wazuh/token
sudo install -d -m 750 -o ak-collector -g ak-collector /var/lib/authentik-wazuh /var/log/authentik-wazuh

Test what the token can and can’t do, without printing it. It should read events and get refused on users:

# on: authentik host
sudo sh -c 'T=$(tr -d "\n" < /etc/authentik-wazuh/token); curl -s -o /dev/null -w "events API: %{http_code}\n" -H "Authorization: Bearer $T" "http://127.0.0.1:9000/api/v3/events/events/?page_size=1"'
sudo sh -c 'T=$(tr -d "\n" < /etc/authentik-wazuh/token); curl -s -H "Authorization: Bearer $T" "http://127.0.0.1:9000/api/v3/core/users/"'

You should see 200, then You do not have permission to perform this action.

The collector

Standard library only. Delivery is at-least-once: events are written and flushed before the cursor advances, so a crash can repeat events but never skip them. Every run writes a heartbeat line (ok, error, gap or initialized). On its first run it starts from now instead of replaying history as fresh alerts. Install it as /usr/local/bin/authentik-events-collector (mode 755), and compare a SHA-256 of the installed file against the one from your source, because a pasted copy can get silently garbled.

The full collector script is in Appendix A at the end of this post.

I tested it against a mock Events API before it went near the IdP host. The test covered: first run doesn’t replay history, new events come out oldest first, no duplicates on an idle run, a late event sharing a timestamp is collected once, 250 events across three pages arrive in order, a backlog over 2000 reports a gap, an HTTP 500 and a wrong token produce error heartbeats and a non-zero exit, the token never shows up in output or state, and an oversized event gets truncated under the line limit.

Service, timer, log rotation

Sandboxed so the collector can only write to its two directories and has no capabilities. systemd-analyze security scored the unit 3.6, against 9.6 for an unhardened one.

# /etc/systemd/system/authentik-events-collector.service
[Unit]
Description=Poll authentik Events API for Wazuh
After=network-online.target docker.service
Wants=network-online.target

[Service]
Type=oneshot
User=ak-collector
Group=ak-collector
ExecStart=/usr/local/bin/authentik-events-collector
TimeoutStartSec=120
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=yes
LockPersonality=yes
CapabilityBoundingSet=
SystemCallArchitectures=native
ReadOnlyPaths=/etc/authentik-wazuh
ReadWritePaths=/var/lib/authentik-wazuh /var/log/authentik-wazuh
# /etc/systemd/system/authentik-events-collector.timer
[Unit]
Description=Run authentik Events collector every 60s

[Timer]
OnBootSec=2min
OnUnitActiveSec=60s
AccuracySec=5s

[Install]
WantedBy=timers.target
# /etc/logrotate.d/authentik-wazuh
/var/log/authentik-wazuh/events.json {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 0640 ak-collector ak-collector
    su ak-collector ak-collector
}
# on: authentik host
sudo systemd-analyze verify /etc/systemd/system/authentik-events-collector.service /etc/systemd/system/authentik-events-collector.timer
sudo logrotate --debug /etc/logrotate.d/authentik-wazuh 2>&1 | tail -3
sudo systemctl daemon-reload
sudo systemctl enable --now authentik-events-collector.timer
systemctl list-timers authentik-events-collector.timer --no-pager
systemd-analyze security authentik-events-collector.service --no-pager | tail -1

NEXT - right after enabling is normal. The timer schedules each run 60 seconds after the previous one finishes.

Point the agent at the file

# on: authentik host
sudo cp -p /var/ossec/etc/ossec.conf /var/ossec/etc/ossec.conf.bak-$(date +%Y%m%d-%H%M)
sudo python3 - <<'EOF'
import sys
p = "/var/ossec/etc/ossec.conf"
src = open(p).read()
loc = "/var/log/authentik-wazuh/events.json"
if loc in src:
    sys.exit("ABORT: already configured")
block = f"""  <localfile>
    <log_format>json</log_format>
    <location>{loc}</location>
    <label key="@source">authentik-collector</label>
  </localfile>

"""
i = src.rfind("</ossec_config>")
if i == -1:
    sys.exit("ABORT: no closing </ossec_config>")
open(p, "w").write(src[:i] + block + src[i:])
print("added localfile block")
EOF
sudo sh -c 'diff /var/ossec/etc/ossec.conf.bak-* /var/ossec/etc/ossec.conf'
sudo systemctl restart wazuh-agent
sudo grep -E 'authentik-wazuh|ERROR' /var/ossec/logs/ossec.log | tail -5

Run the diff through sudo sh -c, because the glob doesn’t expand for a normal user in that directory.

The watchdog

Rules can’t fire on something that never arrives, so a dead collector needs an alarm that doesn’t depend on the collector.

# on: authentik host
sudo tee /usr/local/bin/authentik-collector-watchdog >/dev/null <<'EOF'
#!/bin/sh
f=/var/log/authentik-wazuh/events.json
if [ -n "$(find "$f" -mmin -5 2>/dev/null)" ]; then
  echo "authentik-collector-watchdog: ok"
else
  echo "authentik-collector-watchdog: STALE"
fi
EOF
sudo chown root:root /usr/local/bin/authentik-collector-watchdog
sudo chmod 755 /usr/local/bin/authentik-collector-watchdog
sudo /usr/local/bin/authentik-collector-watchdog

Agent side: an extra ossec_config block appended to ossec.conf (back it up first, then run wazuh-logcollector -t and restart the agent):

<ossec_config>
  <localfile>
    <log_format>command</log_format>
    <command>/usr/local/bin/authentik-collector-watchdog</command>
    <alias>authentik-collector-watchdog</alias>
    <frequency>120</frequency>
  </localfile>
</ossec_config>

Manager side:

# on: wazuh host
sudo tee /var/ossec/etc/rules/authentik_watchdog_rules.xml >/dev/null <<'EOF'
<group name="authentik,authentik_collector,">
  <rule id="100724" level="12">
    <if_sid>530</if_sid>
    <match>authentik-collector-watchdog: STALE</match>
    <description>authentik collector watchdog: no heartbeat written in over 5 minutes, event pipeline may be dead</description>
    <group>authentik_collector,</group>
  </rule>
</group>
EOF
sudo chown wazuh:wazuh /var/ossec/etc/rules/authentik_watchdog_rules.xml
sudo chmod 660 /var/ossec/etc/rules/authentik_watchdog_rules.xml
sudo /var/ossec/bin/wazuh-analysisd -t && echo "CONFIG OK"

Prove it by breaking it on purpose: stop the collector timer, wait about eight minutes, confirm rule 100724 fired, then start the timer again. The next heartbeat may say gap, which is correct, and the collector catches up from recent history.

# on: authentik host
sudo systemctl stop authentik-events-collector.timer     # ...wait ~8 minutes, check the alert, then:
sudo systemctl start authentik-events-collector.timer

The rules

These are the custom rule IDs, all in the 100700 block. The decoder is the built-in json decoder, and fields are matched as authentik.action, authentik.user.username, authentik.client_ip, authentik.context.model.model_name and collector.status.

IDLevelFires on
1007025a failed login, naming the user and source
(brute-force pair)10five failures in five minutes from one source or against one name
10071012a model deleted (provider, flow, token, user, group), with MITRE T1562
1007118a model created or updated
1007200a healthy collector heartbeat (base rule, no alert)
10072210a collector heartbeat reporting an error
(gap)10a collector heartbeat reporting a gap
10072412the watchdog reporting a stale file
10072512any successful login by the break-glass account
10072612any failed login against the break-glass account

Test each rule with wazuh-logtest using a sample line first, then with a real event. A sample line proves the rule parses. Only a real event proves the field names match what Authentik actually sends. A real create-then-delete of a throwaway group exercised 100711 and 100710.

Run wazuh-logtest on a failed-login sample before the rules exist and it falls through to the catch-all rule 1002 (“Unknown problem somewhere in the system”). After the rules load it should hit 100702. That before-and-after is the quickest proof the manager is reading your file.

Name child-rule files so they sort after their parents (a base file, a break-glass file whose name sorts after it, and a watchdog file), and read every line of wazuh-analysisd -t, not just the CONFIG OK.

Building the alert channel

The notification server is ntfy, on a different host from the thing most likely to be the subject of an alert. The image is pinned by digest, access is deny-all, it’s bound to one address, and it has memory limits and log rotation. Anonymous publish and subscribe both returned 403 before I’d created a single account.

There are three identities: an admin, a sender that can only write to one topic, and a phone account that can only read it. So a compromised manager can send noise but can’t read history, and a lost phone can’t forge alerts.

Two mistakes on the way:

  • The port mapping. The container’s internal port is 80, so my 8080:8080 mapping gave me a container that looked healthy in its own logs and answered nothing on the host.
  • The pasted token. The sender’s token printed once, in a terminal capture I pasted, so I rotated it right away and proved both directions: new token publishes, old token gets 401.

The delivery script is standard library only, reads the token from a file, and sends level 12 and above as urgent. I tested it by hand as the wazuh user before touching the manager’s config, since that’s the more restrictive case. The threshold is level 10.

The first real alert to make the whole trip was a throwaway group getting deleted. The second was an unplanned one: me deleting the default admin account by mistake.

The commands: the alert channel

ntfy compose file

Digest-pinned image, deny-all by default, bound to one address, memory-limited, capabilities dropped, log rotation on. Give the host a fixed address (a DHCP reservation) first. The compose file binds to an exact IP, and a changed lease would silently stop every alert.

# on: ansible control node, files/ntfy/compose.yml, deployed to /opt/ntfy/compose.yml on the notification host
services:
  ntfy:
    image: binwiederhier/ntfy@sha256:<digest>
    container_name: ntfy
    command: serve
    restart: unless-stopped
    environment:
      NTFY_BASE_URL: http://<ntfy-ip>:8080
      NTFY_BEHIND_PROXY: "false"
      NTFY_CACHE_FILE: /var/cache/ntfy/cache.db
      NTFY_CACHE_DURATION: "168h"
      NTFY_AUTH_FILE: /var/lib/ntfy/user.db
      NTFY_AUTH_DEFAULT_ACCESS: deny-all
    volumes:
      - ./cache:/var/cache/ntfy
      - ./lib:/var/lib/ntfy
    ports:
      - "<ntfy-ip>:8080:80"
    mem_limit: 256m
    security_opt:
      - no-new-privileges:true
    cap_drop: [ALL]
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"

The container listens on port 80 inside, so the mapping is 8080:80. My first draft mapped 8080:8080, and the container came up healthy in its own logs while nothing answered on the host port. The digest check and compose config -q both passed. Only a request to the published port showed the mistake.

# on: ansible control node
ansible <ntfy-host> -b -m file -a "path=/opt/ntfy state=directory owner=root group=root mode=0755"
ansible <ntfy-host> -b -m copy -a "src=files/ntfy/compose.yml dest=/opt/ntfy/compose.yml owner=root group=root mode=0644"
ansible <ntfy-host> -b -m shell -a "docker compose -f /opt/ntfy/compose.yml config -q && echo COMPOSE OK"
# on: notification host
cd /opt/ntfy && sudo docker compose up -d
curl -sS -i http://<ntfy-ip>:8080/v1/health

Negative test, then identities

# on: notification host
# anonymous access must fail (expect 403 and 403)
curl -sS -o /dev/null -w 'publish: %{http_code}\n' -d "anon test" http://<ntfy-ip>:8080/<topic>
curl -sS -o /dev/null -w 'subscribe: %{http_code}\n' "http://<ntfy-ip>:8080/<topic>/json?poll=1"

# admin account (prompts for a password; store it in your password manager first)
sudo docker exec -it ntfy ntfy user add --role=admin admin

# write-only sender account with a random password nobody will ever type
sudo docker exec -e NTFY_PASSWORD="$(openssl rand -base64 24)" ntfy ntfy user add wazuh
sudo docker exec ntfy ntfy access wazuh <topic> write-only

# read-only account for the phone
sudo docker exec -it ntfy ntfy user add phone
sudo docker exec ntfy ntfy access phone <topic> read-only
sudo docker exec ntfy ntfy access

# the sender's token (prints once; do not paste the output anywhere)
sudo docker exec ntfy ntfy token add wazuh

A compromised manager can send noise but can’t read your alert history, and a lost phone can read but can’t forge alerts.

The token printed once in clear text in a pasted terminal capture, so I rotated it right away: remove the old token, add a new one, and prove both directions with the sender (new token 200, old token 401). The rotation commands are in the token rotation section of Part 2.

# on: wazuh host
sudo -v
read -rsp "ntfy token: " T; echo
printf '%s' "$T" | sudo tee /var/ossec/etc/ntfy-token >/dev/null
unset T
sudo chown root:wazuh /var/ossec/etc/ntfy-token
sudo chmod 640 /var/ossec/etc/ntfy-token
sudo grep -c '^tk_' /var/ossec/etc/ntfy-token

The phone app: add the server URL and the read-only account, then subscribe to the topic. It only reaches the server on the home network until you add a private route (VPN) to that host.

The integration script

Standard library only, so there’s nothing to install. It reads the token from the root:wazuh file, sends level 12 and above as urgent and levels 10 and 11 as high priority, logs every delivery or error to integrations.log, and never raises. The title header is forced to ASCII, because HTTP headers choke on anything else.

The full integration script is in Appendix B at the end of this post.

# on: wazuh host
# wrapper (Wazuh runs integrations by name) and permissions
sudo tee /var/ossec/integrations/custom-ntfy >/dev/null <<'EOF'
#!/bin/sh
exec /var/ossec/framework/python/bin/python3 /var/ossec/integrations/custom-ntfy.py "$@"
EOF
sudo chown root:wazuh /var/ossec/integrations/custom-ntfy /var/ossec/integrations/custom-ntfy.py
sudo chmod 750 /var/ossec/integrations/custom-ntfy /var/ossec/integrations/custom-ntfy.py
sudo /var/ossec/framework/python/bin/python3 -c "import ast; ast.parse(open('/var/ossec/integrations/custom-ntfy.py').read()); print('SYNTAX OK')"
sudo sha256sum /var/ossec/integrations/custom-ntfy.py

Test it by hand before touching ossec.conf, as the wazuh user. That’s the more restrictive case, so it surfaces permission problems the real daemon would hit:

# on: wazuh host
cat > /tmp/test-alert.json <<'EOF'
{"timestamp":"2026-01-01T00:00:00.000+0000","rule":{"level":12,"description":"integration test alert","id":"999999","groups":["test"]},"agent":{"id":"000","name":"wazuh","ip":"127.0.0.1"},"full_log":"Manual test."}
EOF
sudo -u wazuh /var/ossec/integrations/custom-ntfy /tmp/test-alert.json none http://<ntfy-ip>:8080/<topic>; echo "exit: $?"
sudo tail -3 /var/ossec/logs/integrations.log
rm /tmp/test-alert.json

You want exit: 0 and a log line reading sent rule 999999 level 12 http 200.

Wire it into the manager

# on: wazuh host
sudo cp -p /var/ossec/etc/ossec.conf /var/ossec/etc/ossec.conf.bak-$(date +%F)-ntfy
sudo tee -a /var/ossec/etc/ossec.conf >/dev/null <<'EOF'

<ossec_config>
  <integration>
    <name>custom-ntfy</name>
    <hook_url>http://<ntfy-ip>:8080/<topic></hook_url>
    <level>10</level>
    <alert_format>json</alert_format>
  </integration>
</ossec_config>
EOF
sudo /var/ossec/bin/wazuh-analysisd -t && echo "CONFIG OK"
sudo systemctl restart wazuh-manager
sudo /var/ossec/bin/wazuh-control status | grep -i integrator

You want wazuh-integratord is running.... Before the block exists the integrator says “not running”, so seeing it running proves the wiring took. Then fire a real alert (create and delete a throwaway group in Authentik) and look for sent rule 100710 level 12 http 200.

I picked level 10 because, in this setup, it covers config deletions, the dead-collector alarm, collector errors and brute force, and leaves out routine single failed logins.

The alert channel needs its own review

On 2026-11-15, a vulnerability scan produced hundreds of built-in High and Critical alerts (rules 23505 and 23506, one per CVE per package) in one burst. ntfy answered with HTTP 429 for 111 deliveries.

The danger isn’t the missing vulnerability alerts. It’s that an urgent alert arriving in the middle of a burst gets dropped. And an attacker generating failed-login noise could do the same thing on purpose.

So I added a deny list to the delivery script. Skipped alerts stay in the dashboard and leave a line in the integration log:

SKIP_RULE_IDS = {"23505", "23506"}
...
if str(rule.get("id", "")) in SKIP_RULE_IDS:
    log(f"skipped rule {rule.get('id')} (deny list)")
    return 0

My custom detection rules never go on that list. To review what actually pages your phone, count by rule, and read the log for errors, not just successes:

sudo grep -o 'rule [0-9]*' /var/ossec/logs/integrations.log | sort | uniq -c | sort -rn | head

Part 2: Keeping it patched without locking yourself out

The rules I run by

  • Central components must match to the patch level. The indexer, manager and dashboard need the same version, and the manager has to be the same or newer than its agents. Mine was out of spec: a 4.14.7 manager with 4.14.9 agents.
  • Packages are held and the repo entry is commented out. Upgrades are on purpose. I enable the repo, unhold, upgrade, then hold and comment it out again.
  • The indexer can’t be downgraded. Lucene won’t allow it, so after the indexer upgrades, the only rollback is a VM snapshot. That makes the snapshot a requirement, not a nicety.
  • Read the release notes before the upgrade, not after. 4.14.10 had hardening fixes (a rootcheck command injection, an agent diff-folder path traversal, and some RBAC fixes) and no breaking changes between 4.14.7 and 4.14.10. That’s a five-minute read that tells you whether the next hour is routine.

The upgrade, condensed

  1. Pre-flight, read only: OS, installed versions, holds, free disk, services active.
  2. Read the release notes for every version between where you are and where you’re going.
  3. Enable the repo, unhold the packages, and confirm all three Wazuh packages show the same candidate version.
  4. Back up configs. Wazuh’s guide says to restore from .old copies, so make those, plus an archive of everything custom (rules, integration scripts, ossec.conf, dashboard and indexer config). That archive contains private keys, so keep it root-only and never paste its contents anywhere.
  5. Stop Filebeat and the dashboard, back up the security config, set shard allocation to primaries, flush, then stop the manager and the indexer.
  6. Take a cold VM snapshot with the services stopped. Don’t continue until you can see it in the list.
  7. Upgrade the indexer, start it, wait for green. Reapply the security config and set allocation back to all.
  8. Upgrade the manager, test the rules, start it.
  9. Update the Filebeat module and alerts template to the new version. The Filebeat package itself stays put.
  10. Upgrade the dashboard and prove the SAML config survived.
  11. Verify, then run a controlled test.
  12. Hold the packages and comment the repo out again.

The thing that makes this safe on a customized install is one flag on apt-get:

sudo DEBIAN_FRONTEND=noninteractive apt-get install -y \
  -o Dpkg::Options::="--force-confold" wazuh-indexer=4.14.10-1

--force-confold keeps every config file you’ve edited and never stops at an interactive prompt. If the new package ships a different default, it lands next to yours as *.dpkg-new, so you can see what changed without losing what you had. After the dashboard upgrade I compared the SAML-bearing dashboard config against its backup with cmp. Byte-identical, or stop.

How it ended up: all three central components on 4.14.10, 217 shards active and green with none unassigned, eight agents plus the manager active, alerts indexing again within minutes, and SAML login working through the new dashboard. Custom rule files, the integration script hash and wazuh-analysisd -t all came through unchanged. After the upgrade I ran a controlled failed login against the break-glass account and watched the alert go through the new manager to the notification host.

The manager was dark for about three hours, and most of that was the snapshot step. Agents buffer events while the manager is away, but a busy agent can overflow its buffer, so take the snapshot promptly.

The commands: the full patch upgrade, step by step

Everything in this section runs on the Wazuh host. This is the order I ran it on 2026-11-16 for 4.14.7 to 4.14.10.

Step 0: pre-flight, read only

# on: wazuh host
. /etc/os-release; echo "$PRETTY_NAME"; dpkg -l | grep -E 'wazuh|filebeat' | awk '{print $2, $3}'; apt-mark showhold; df -h / /var | cat; systemctl is-active wazuh-indexer wazuh-manager wazuh-dashboard filebeat

Step 1: read the release notes for every version between where you are and where you’re going. Check the 4.x warnings. They live at documentation.wazuh.com/current/release-notes.

Step 2: enable the repo, unhold, check candidates

# on: wazuh host
sudo sed -i 's/^#deb /deb /' /etc/apt/sources.list.d/wazuh.list && sudo apt-get update
sudo apt-mark unhold wazuh-indexer wazuh-manager wazuh-dashboard filebeat
for p in wazuh-indexer wazuh-manager wazuh-dashboard filebeat; do apt-cache policy $p | sed -n '2,3p'; done

All three Wazuh packages should show the same candidate version.

Step 3: back up configs

# on: wazuh host
sudo cp -a /etc/wazuh-dashboard/opensearch_dashboards.yml{,.old}
sudo cp -a /etc/wazuh-indexer/jvm.options{,.old}
sudo cp -a /etc/filebeat/filebeat.yml{,.old}
sudo tar czf /var/backups/wazuh-pre-<ver>-<date>.tar.gz --ignore-failed-read /etc/wazuh-indexer /etc/wazuh-dashboard /etc/filebeat /usr/share/wazuh-dashboard/data/wazuh/config /var/ossec/etc /var/ossec/integrations
sudo chmod 600 /var/backups/wazuh-pre-<ver>-<date>.tar.gz

That archive has private keys in it, so keep it root-only. Make sure it lists the dashboard config, the indexer security files, client.keys, ossec.conf, your custom rule files and your integration scripts. A normal user can’t list inside /etc/wazuh-indexer or /etc/wazuh-dashboard, so use sudo for any listing there. A wildcard expands to nothing without it and can break a && chain halfway through.

Step 4: stop and prepare the indexer

Use the admin client certificate for local indexer calls. A wrong typed password gives you HTTP 401 with an empty body, and curl -s hides it.

# on: wazuh host
ic() { sudo curl -sSk --cert /etc/wazuh-indexer/certs/admin.pem --key /etc/wazuh-indexer/certs/admin-key.pem -w '\nHTTP %{http_code}\n' "$@"; }
sudo systemctl stop filebeat wazuh-dashboard
sudo /usr/share/wazuh-indexer/bin/indexer-security-init.sh --options "-backup /etc/wazuh-indexer/opensearch-security -icl -nhnv" 2>&1 | tail -6
ic -X PUT "https://127.0.0.1:9200/_cluster/settings" -H 'Content-Type: application/json' -d '{"persistent":{"cluster.routing.allocation.enable":"primaries"}}'
ic -X POST "https://127.0.0.1:9200/_flush"
sudo systemctl stop wazuh-manager && sudo systemctl stop wazuh-indexer

Check that the four services are inactive and nothing is listening (not run as written):

# on: wazuh host
systemctl is-active wazuh-indexer wazuh-manager wazuh-dashboard filebeat
ss -ltn | grep -E ':(9200|1514|1515|55000)\b' || echo no-listeners

Step 5: snapshot the VM in the hypervisor with the services stopped, disk only, no RAM. Name it pre-<ver>-<date>. Don’t go on until you can see it in the list.

Step 6: upgrade the indexer, start it, wait for green

# on: wazuh host
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confold" wazuh-indexer=<ver>-1
sudo systemctl daemon-reload && sudo systemctl enable wazuh-indexer; sudo systemctl start wazuh-indexer
sudo find /etc/wazuh-indexer -name '*.dpkg-*'

--force-confold keeps your edited config files. If upstream ships a different default, it’s saved next to yours as *.dpkg-new, and the find lists them. Red status in the first few seconds is normal. Poll health until it’s green with nothing initializing and no unassigned primaries (not run as written):

# on: wazuh host
ic "https://127.0.0.1:9200/_cluster/health?pretty"

Step 7: reapply security config and restore allocation

# on: wazuh host
sudo /usr/share/wazuh-indexer/bin/indexer-security-init.sh 2>&1 | tail -6
ic -X PUT "https://127.0.0.1:9200/_cluster/settings" -H 'Content-Type: application/json' -d '{"persistent":{"cluster.routing.allocation.enable":"all"}}'

You should see “Done with success” and 10 updated config types.

Step 8: upgrade the manager, test the rules, start

# on: wazuh host
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confold" wazuh-manager=<ver>-1
sudo /var/ossec/bin/wazuh-analysisd -t        # read ALL output; INFO lines about rule tree memory are normal
sudo sha256sum /var/ossec/integrations/custom-ntfy.py; sudo ls /var/ossec/etc/rules | grep authentik
sudo systemctl daemon-reload && sudo systemctl enable wazuh-manager; sudo systemctl start wazuh-manager

On a single node, wazuh-clusterd, wazuh-maild, wazuh-agentlessd and wazuh-csyslogd say “not running” by design. wazuh-integratord is the one that has to be running.

Step 9: Filebeat module and template (the Filebeat package stays at its version, but the module and alerts template follow Wazuh’s)

# on: wazuh host
sudo cp -a /etc/filebeat/wazuh-template.json{,.old-<date>}
curl -fsS https://packages.wazuh.com/4.x/filebeat/wazuh-filebeat-0.5.tar.gz | sudo tar -xz -C /usr/share/filebeat/module
sudo curl -fsS -o /etc/filebeat/wazuh-template.json https://raw.githubusercontent.com/wazuh/wazuh/v<ver>/extensions/elasticsearch/7.x/wazuh-template.json && sudo chmod go+r /etc/filebeat/wazuh-template.json
sudo python3 -m json.tool /etc/filebeat/wazuh-template.json >/dev/null && echo valid
sudo systemctl daemon-reload && sudo systemctl enable filebeat; sudo systemctl start filebeat
sudo filebeat test output; sudo filebeat setup --pipelines; sudo filebeat setup --index-management -E output.logstash.enabled=false

Step 10: upgrade the dashboard, prove the SAML config is untouched, start

# on: wazuh host
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confold" wazuh-dashboard=<ver>-1
sudo cmp /etc/wazuh-dashboard/opensearch_dashboards.yml /etc/wazuh-dashboard/opensearch_dashboards.yml.old && echo identical
sudo systemctl daemon-reload && sudo systemctl enable wazuh-dashboard; sudo systemctl start wazuh-dashboard

Test the SAML login in a second browser profile before you close any working session.

Step 11: verify

# on: wazuh host  (not run as written; the checks themselves are the ones listed in the upgrade record)
dpkg -l wazuh-indexer wazuh-manager wazuh-dashboard filebeat | awk 'NR>5{print $2, $3}'
sudo /var/ossec/bin/agent_control -l
ic -X GET "https://127.0.0.1:9200/wazuh-alerts-*/_count" -H 'Content-Type: application/json' -d '{"query":{"range":{"timestamp":{"gte":"now-15m"}}}}'

Then one controlled test: a failed login against the break-glass account should produce rule 100726, show up in /var/ossec/logs/integrations.log and reach the notification host.

Step 12: lock the result

# on: wazuh host
sudo sed -i 's/^deb /#deb /' /etc/apt/sources.list.d/wazuh.list
sudo apt-mark hold wazuh-indexer wazuh-manager wazuh-dashboard filebeat

Rollback, kept separate on purpose. Don’t paste this under a live step.

  • Before the indexer upgrade: start the services again and set allocation back to all.
  • After: restore the VM snapshot. Config-only problems get fixed from the .old copies or the archive.
  • Delete the snapshot after a few days of clean running. Long-lived snapshots slow the VM down.

The commands: verification

# on: wazuh host
# rules load and parse (read ALL output for WARNINGs, not just CONFIG OK)
sudo /var/ossec/bin/wazuh-analysisd -t
# integration daemon running
sudo /var/ossec/bin/wazuh-control status | grep -i integrator
# last deliveries
sudo tail -5 /var/ossec/logs/integrations.log
# integration script is the deployed version (use sudo; a normal user cannot read the directory)
sudo sha256sum /var/ossec/integrations/custom-ntfy.py
# component versions and holds
dpkg -l wazuh-indexer wazuh-manager wazuh-dashboard filebeat | awk 'NR>5{print $2, $3}'; apt-mark showhold
# what pages the phone, by rule
sudo grep -o 'rule [0-9]*' /var/ossec/logs/integrations.log | sort | uniq -c | sort -rn | head
# on: authentik host
# collector alive
systemctl list-timers authentik-events-collector.timer --no-pager
sudo tail -2 /var/log/authentik-wazuh/events.json | cut -c1-200
# on: any host that can reach the notification server
# deny-all still holds (expect 403, 403)
curl -s -o /dev/null -w '%{http_code}\n' -d x http://<ntfy-host>:8080/<topic>
curl -s -o /dev/null -w '%{http_code}\n' 'http://<ntfy-host>:8080/<topic>/json?poll=1'

The commands: notification token rotation and script rollback

# on: notification host
sudo docker exec ntfy ntfy token remove wazuh <old-token>
sudo docker exec ntfy ntfy token add wazuh

On the Wazuh host, write the new token to /var/ossec/etc/ntfy-token with read -rsp so it never hits shell history or chat, set the owner to root:wazuh and the mode to 640. Then prove both directions: the new token returns 200 and the old one returns 401.

# on: wazuh host
# restore the previous integration script
sudo cp -a /var/backups/custom-ntfy.py.bak-<date> /var/ossec/integrations/custom-ntfy.py

Small things that cost real time

  • A wrong admin password gives HTTP 401 with an empty body, and curl -s shows you nothing. For local indexer calls I use curl -sS with the admin client certificate and no typed password. The ic helper in the upgrade commands above does that.

  • A “warning” grep also matches harmless INFO lines. The 4.14.10 rule-tree memory message tripped mine.

  • needrestart defers service restarts after apt runs (dbus, docker, logind and friends). Don’t restart them mid-upgrade. They belong with a planned reboot.

  • On a single node, clusterd, maild, agentlessd and csyslogd show “not running” by design. integratord is the one that has to be running.

  • A rollback block sitting right under the real step will get pasted by mistake. Mine did, once. Harmless that time only because the variable it needed was empty.

  • Half my lost time over two months was a correct command on the wrong host. One labeled terminal per host, read the prompt, then paste.

The identity provider is not a normal service

For an IdP, a database dump isn’t a backup. Authentik’s restore set is the PostgreSQL database, the media and data files, and the secret key, all together. Restore the database without the original secret key and every encrypted value in it is gone for good.

In my stack, the secret key now lives in a root-only environment file next to the compose file. So that file is on the restore list, and it’s in the archive I take before any change.

Before touching the Authentik containers for log rotation, I stopped and asked one question: does starting the IdP depend on anything that might be down? The containers’ entrypoint used to pull secrets from OpenBao, which meant a sealed OpenBao after a reboot could stop the IdP from starting. I read the current entrypoint instead of assuming. It reads from the local environment file now and doesn’t call OpenBao anymore, so a recreate only needs local files and cached images. That cleared the one hard rule, so I went ahead.

Container log rotation: a low-risk change, done carefully

Docker’s default json-file driver doesn’t rotate. A busy container will eventually fill a disk, and a full disk on an identity provider is an outage you caused with a log file. None of the three Authentik services had a logging: block.

The change is five lines per service:

logging:
  driver: json-file
  options:
    max-size: "10m"
    max-file: "3"

The order I did it in is more useful than the change itself:

  1. A fresh database dump (230 table-data entries when I listed it, so the dump is actually readable) and an archive of the whole stack directory, including the environment file. Both root-only.
  2. A VM snapshot, disk only.
  3. Back up the compose file, apply the edit with sed, then read the diff: three identical additions, nothing removed. Validate with docker compose config -q.
  4. Recreate with docker compose up -d --pull never. That flag matters: it guarantees nothing gets downloaded, so a mutable image tag can’t change under you mid-maintenance.
  5. Check, don’t assume: docker inspect on each container for the log config, container health, and the readiness endpoint. (This version returns 200 from the ready endpoint. I’d written the check expecting 204, so the loop ran to the end instead of stopping early. Be skeptical of your own expectations.) The stack was ready by the third check.
  6. The check that matters: log in to Wazuh through SAML from a second browser profile while the first admin session stays open.

The result: the SAML login worked from a second browser profile with the first admin session still open, and authinfo returned the wazuh-admins backend role. The log-rotation change didn’t disturb the identity path.

The commands: Authentik backup, then log rotation

Back up the full restore set. For Authentik that’s a database dump plus the whole stack directory: the compose file, the entrypoint, the environment file that holds the secret key, and the data, certificate and custom-template directories. Both files below are root-only. Never paste their contents.

# on: authentik host
sudo docker exec authentik-postgresql-1 sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' | sudo tee /var/backups/authentik-db-<date>.dump >/dev/null
sudo tar czf /var/backups/authentik-opt-<date>.tar.gz /opt/authentik 2>&1 | grep -v 'Removing leading'
sudo chmod 600 /var/backups/authentik-db-<date>.dump /var/backups/authentik-opt-<date>.tar.gz
sudo ls -l /var/backups/authentik-*<date>*; sudo sha256sum /var/backups/authentik-*<date>*
# the dump is readable if this prints a number above zero
sudo cat /var/backups/authentik-db-<date>.dump | sudo docker exec -i authentik-postgresql-1 pg_restore -l | grep -cE 'TABLE DATA'
# the archive holds the environment file, compose file and entrypoint
sudo tar tzf /var/backups/authentik-opt-<date>.tar.gz | grep -E '\.env$|compose\.yml$|entrypoint\.sh$'

The dump hash changes every run because pg_dump embeds timestamps. The archive hash stays the same if the stack files didn’t change.

Then take a hypervisor snapshot of the Authentik VM (disk only).

Add rotation to each service and validate.

# on: authentik host
sudo cp -p /opt/authentik/compose.yml /opt/authentik/compose.yml.bak-<date>
sudo sed -i '/^    restart: unless-stopped$/a\    logging:\n      driver: json-file\n      options:\n        max-size: "10m"\n        max-file: "3"' /opt/authentik/compose.yml
sudo diff /opt/authentik/compose.yml.bak-<date> /opt/authentik/compose.yml
grep -c '^    logging:$' /opt/authentik/compose.yml
cd /opt/authentik && sudo docker compose config -q && echo CONFIG_OK

The sed line assumes each service has exactly one restart: unless-stopped line at four-space indent. Read the diff: three identical additions, nothing removed, and a count equal to the number of services.

Recreate, wait for readiness, and check the log config. --pull never guarantees nothing gets downloaded.

# on: authentik host
cd /opt/authentik && sudo docker compose up -d --pull never
for i in $(seq 1 24); do c=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9000/-/health/ready/); echo "$i: $c"; case "$c" in 200|204) break;; esac; sleep 5; done
sudo docker ps --format '{{.Names}}\t{{.Status}}'
for n in authentik-postgresql-1 authentik-server-1 authentik-worker-1; do echo -n "$n: "; sudo docker inspect -f '{{.HostConfig.LogConfig.Type}} {{.HostConfig.LogConfig.Config}}' $n; done

On this Authentik version the ready endpoint returned 200, not 204, which is why the loop accepts either. You should see json-file map[max-file:3 max-size:10m] for each container.

# on: authentik host
# rollback for the compose edit, kept separate on purpose
sudo cp -p /opt/authentik/compose.yml.bak-<date> /opt/authentik/compose.yml

Finish with a SAML login to Wazuh from a second browser profile while your first admin session stays open.

After any restart: the runbook that would have caught the gap

After any restart of the Wazuh host:

  1. Confirm the three services are active.
  2. Push the security configuration so the live index matches disk (the securityadmin.sh command from the first commands section).
  3. Test SSO in a fresh private window for both the admin and the read-only path, and read authinfo for each.
  4. Confirm the local admin still works as the break-glass path.

This fails fast, which is the point. In this story, the integration sat half-torn-down for five weeks and the first click on the SSO button was the first test.

Why I built it this way

A few choices that look random and aren’t:

  • The Events API as the source. I was figuring out how to pull the data, and I wanted the API, not the UI, to be the thing I depended on. The cost: up to a minute of polling latency, a token that expires and needs a calendar reminder, and a collector that needs its own watchdog.
  • ntfy for alerts. It’s free and self-hosted, so no alert content leaves the network. The cost is that it’s now a single point of failure for alerting.
  • Secrets in a local file for the IdP’s start path. I had OpenBao hold the key at first. It was too much work every time a machine rebooted, because the secrets manager had to be unsealed before the identity provider could start. Now the IdP restarts on local files alone. The price is a key sitting on disk in a root-only file that has to be in every backup.
  • Manual, snapshot-first patching. Wazuh wants matching patch versions across its parts, and the indexer can’t be downgraded. The one rollback is a snapshot, so the snapshot comes first. Anything that holds a schema or an identity never gets auto-updated.
  • A decision log, not just a runbook. The runbook says what exists. A separate log says why, what it costs, and what would make me change it. The reason is always the first thing I forget.

What’s still open

Writing the open items down is part of the method, so here they are.

  • Authentik backups aren’t copied offsite yet. A backup living on the machine it protects is only a partial backup.
  • I haven’t run a restore drill on the identity provider. A backup that’s never been restored is an assumption. This is the most important item on the list.
  • ntfy is a single point of failure for alerting. If the notification host or the service goes down, alerts stop silently. It needs an external uptime check.
  • The phone only reaches ntfy on the home network. A VPN route fixes alerts away from home.
  • No playbook deploys the collector, rules and integration files yet. The files are in version control, but a rebuild is manual.
  • A planned reboot is pending on the Wazuh host for the service restarts that got deferred.
  • No alert yet for shell access to the Authentik host, and no file integrity monitoring on the security configs.

Compliance Summary

Control areaNIST 800-53SOC 2PCI-DSS v4.0CIS Controls
SAML SSO, role mapping, MFAAC-2, AC-3, IA-2CC6.1, CC6.2Req 7.2.1, 8.4.2CIS 6.5, 6.8
Break-glass account and recovery pathAC-2, IA-5CC6.1, CC6.2Req 8.2.2CIS 5.4
IdP event collection and detection rulesAU-2, AU-6, SI-4CC7.2Req 10.2.1, 10.4.1CIS 8.2, 8.11
Alert channel integrity, watchdog, least-privilege tokensAU-5, SI-4, AC-6CC7.2, CC7.3Req 10.7.2CIS 8.11, 13.1
Agent enrollment passwordIA-3, AC-3CC6.1, CC6.6Req 2.2.1CIS 4.1, 6.1
Secrets handling (root-only files, no pasting tokens)IA-5, SC-28, CM-6CC6.1Req 8.6.2CIS 3.11, 4.1
Manual, snapshot-first patchingSI-2, CM-3, CP-9CC7.1, CC8.1Req 6.3.3, 6.5.1CIS 7.3, 7.4
IdP backup and restore drill (still open)CP-4, CP-9A1.2, A1.3Req 12.10.1CIS 11.2, 11.5

What I’d tell someone starting out

The installer gets you a SIEM. It doesn’t get you a SIEM you can trust, reach, or recover.

Keep one login that doesn’t depend on your identity provider, and test that it still works. Prove SSO with a user you can tell apart from the one you were already logged in as. Give your alerting its own alarm, and read the delivery log for failures. Take the snapshot before the upgrade, not during the incident. And before you change anything that holds identity, ask what it needs in order to start, then go read the file that answers it.

Appendix A: the event collector script

Install it as /usr/local/bin/authentik-events-collector (mode 755) and compare a SHA-256 of the installed file against the one from your source, because a pasted copy can get silently garbled. Setup around it is in the event pipeline commands above.

#!/usr/bin/env python3
"""authentik-events-collector

Polls the authentik Events API and appends one JSON line per new event to a
file that the Wazuh agent tails. Stdlib only. Intended to run from a systemd
timer as an unprivileged user.

Delivery is at-least-once: events are written and flushed before the cursor
advances, so a crash can repeat events but never skip them.

Every run also writes one heartbeat line (collector.status = ok | error |
gap | initialized) so a dead collector is detectable in Wazuh.
"""
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone

API = os.environ.get("AK_URL", "http://127.0.0.1:9000").rstrip("/")
TOKEN_FILE = os.environ.get("AK_TOKEN_FILE", "/etc/authentik-wazuh/token")
STATE_FILE = os.environ.get("AK_STATE_FILE", "/var/lib/authentik-wazuh/state.json")
OUT_FILE = os.environ.get("AK_OUT_FILE", "/var/log/authentik-wazuh/events.json")
BACKFILL_HOURS = float(os.environ.get("AK_BACKFILL_HOURS", "0"))
PAGE_SIZE = 100
MAX_PAGES = 20          # 2000 events per run; beyond that we report a gap
MAX_LINE = 60000        # Wazuh drops events over 64 KiB
TIMEOUT = 15


def parse_ts(value: str) -> datetime:
    dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt


def read_token() -> str:
    with open(TOKEN_FILE, encoding="utf-8") as fh:
        token = fh.read().strip()
    if not token:
        raise RuntimeError(f"token file {TOKEN_FILE} is empty")
    return token


def api_get(path: str, params: dict, token: str) -> dict:
    url = f"{API}{path}?{urllib.parse.urlencode(params)}"
    req = urllib.request.Request(
        url,
        headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
    )
    try:
        with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
            return json.load(resp)
    except urllib.error.HTTPError as exc:
        # Never include request headers (the token) in the error.
        raise RuntimeError(f"HTTP {exc.code} from {path}") from None
    except urllib.error.URLError as exc:
        raise RuntimeError(f"cannot reach {API}: {exc.reason}") from None


def load_state():
    try:
        with open(STATE_FILE, encoding="utf-8") as fh:
            state = json.load(fh)
        return parse_ts(state["cursor"]), set(state.get("seen", []))
    except FileNotFoundError:
        return None, set()


def save_state(cursor: datetime, seen: set) -> None:
    tmp = STATE_FILE + ".tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump({"cursor": cursor.isoformat(), "seen": sorted(seen)}, fh)
        fh.flush()
        os.fsync(fh.fileno())
    os.replace(tmp, STATE_FILE)


def fetch_new(token: str, cursor: datetime, seen: set):
    """Walk events newest-first until we pass the cursor. Returns (events_oldest_first, gap)."""
    found = []
    for page in range(1, MAX_PAGES + 1):
        data = api_get(
            "/api/v3/events/events/",
            {"ordering": "-created", "page": page, "page_size": PAGE_SIZE},
            token,
        )
        results = data.get("results", [])
        for ev in results:
            created = parse_ts(ev["created"])
            if created < cursor or (created == cursor and ev["pk"] in seen):
                return list(reversed(found)), False
            found.append(ev)
        if not data.get("pagination", {}).get("next"):
            return list(reversed(found)), False
    return list(reversed(found)), True


def to_line(ev: dict) -> str:
    user = ev.get("user") or {}
    brand = ev.get("brand") or {}
    record = {
        "integration": "authentik",
        "authentik": {
            "pk": ev.get("pk"),
            "action": ev.get("action"),
            "app": ev.get("app"),
            "created": ev.get("created"),
            "client_ip": ev.get("client_ip"),
            "user": {
                "username": user.get("username"),
                "pk": user.get("pk"),
                "email": user.get("email"),
            },
            "brand": brand.get("name") if isinstance(brand, dict) else brand,
            "context": ev.get("context") or {},
        },
    }
    line = json.dumps(record, separators=(",", ":"), default=str)
    if len(line) > MAX_LINE:
        ctx = record["authentik"]["context"]
        record["authentik"]["context"] = {
            "truncated": True,
            "keys": sorted(ctx.keys()) if isinstance(ctx, dict) else [],
        }
        line = json.dumps(record, separators=(",", ":"), default=str)
    return line


def heartbeat(out, status: str, started: float, **extra) -> None:
    record = {
        "integration": "authentik",
        "collector": {
            "status": status,
            "duration_ms": int((time.monotonic() - started) * 1000),
            "ts": datetime.now(timezone.utc).isoformat(),
            **extra,
        },
    }
    out.write(json.dumps(record, separators=(",", ":")) + "\n")
    out.flush()


def main() -> int:
    started = time.monotonic()
    with open(OUT_FILE, "a", encoding="utf-8") as out:
        try:
            token = read_token()
            cursor, seen = load_state()

            if cursor is None:
                # First run: start from now (or a deliberate backfill window),
                # so old history is not replayed as fresh alerts.
                cursor = datetime.now(timezone.utc) - timedelta(hours=BACKFILL_HOURS)
                if BACKFILL_HOURS <= 0:
                    save_state(cursor, set())
                    heartbeat(out, "initialized", started, new_events=0)
                    return 0

            events, gap = fetch_new(token, cursor, seen)
            for ev in events:
                out.write(to_line(ev) + "\n")
            out.flush()
            os.fsync(out.fileno())

            if events:
                newest = parse_ts(events[-1]["created"])
                new_seen = {e["pk"] for e in events if parse_ts(e["created"]) == newest}
                if newest == cursor:
                    new_seen |= seen
                save_state(newest, new_seen)
            elif not os.path.exists(STATE_FILE):
                save_state(cursor, seen)

            if gap:
                heartbeat(out, "gap", started, new_events=len(events),
                          detail=f"more than {MAX_PAGES * PAGE_SIZE} events since last run; oldest may be missing")
            else:
                heartbeat(out, "ok", started, new_events=len(events))
            return 0
        except Exception as exc:  # noqa: BLE001 - report every failure as a heartbeat
            heartbeat(out, "error", started, error=str(exc)[:500])
            return 1


if __name__ == "__main__":
    sys.exit(main())

Appendix B: the ntfy integration script

Install it as /var/ossec/integrations/custom-ntfy.py with the wrapper and permissions from the alert channel commands above.

#!/usr/bin/env python3
"""Wazuh to ntfy integration. Stdlib only. Run by wazuh-integratord."""
import json
import sys
import time
import urllib.error
import urllib.request

TOKEN_FILE = "/var/ossec/etc/ntfy-token"
LOG_FILE = "/var/ossec/logs/integrations.log"
TIMEOUT = 10
MAX_LOG = 500
SKIP_RULE_IDS = {"23505", "23506"}   # built-in per-CVE vulnerability alerts; stay in the dashboard


def log(msg):
    stamp = time.strftime("%Y/%m/%d %H:%M:%S")
    try:
        with open(LOG_FILE, "a", encoding="utf-8") as fh:
            fh.write(f"{stamp} custom-ntfy: {msg}\n")
    except OSError:
        pass


def ascii_only(text):
    return text.encode("ascii", "replace").decode("ascii")


def main():
    if len(sys.argv) < 4:
        log("ERROR: usage: custom-ntfy <alert_file> <api_key> <hook_url>")
        return 2
    alert_file, hook_url = sys.argv[1], sys.argv[3]
    if not hook_url.startswith(("http://", "https://")):
        log("ERROR: hook_url must be http or https")
        return 2
    try:
        with open(alert_file, encoding="utf-8") as fh:
            alert = json.load(fh)
        with open(TOKEN_FILE, encoding="utf-8") as fh:
            token = fh.read().strip()
    except (OSError, ValueError) as exc:
        log(f"ERROR: cannot read inputs: {exc}")
        return 1

    rule = alert.get("rule", {})
    agent = alert.get("agent", {})
    if str(rule.get("id", "")) in SKIP_RULE_IDS:
        log(f"skipped rule {rule.get('id')} (deny list)")
        return 0
    level = int(rule.get("level", 0))
    desc = str(rule.get("description", "no description"))
    urgent = level >= 12
    lines = [
        f"Agent: {agent.get('name', '?')} ({agent.get('ip', '?')})",
        f"Rule: {rule.get('id', '?')} level {level}",
        f"Groups: {', '.join(rule.get('groups', []))}",
        f"Time: {alert.get('timestamp', '?')}",
        f"Log: {str(alert.get('full_log', ''))[:MAX_LOG]}",
    ]
    headers = {
        "Authorization": f"Bearer {token}",
        "Title": ascii_only(f"Wazuh L{level}: {desc}")[:120],
        "Priority": "5" if urgent else "4",
        "Tags": "rotating_light" if urgent else "warning",
    }
    req = urllib.request.Request(
        hook_url,
        data="\n".join(lines).encode("utf-8"),
        method="POST",
        headers=headers,
    )
    try:
        with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
            status = resp.status
    except (urllib.error.URLError, OSError) as exc:
        log(f"ERROR: delivery failed for rule {rule.get('id', '?')}: {exc}")
        return 1
    log(f"sent rule {rule.get('id', '?')} level {level} http {status}")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Sources & References

Documentation

SourceReference
Wazuh – Single sign-on with authentikdocumentation.wazuh.com/current/…/single-sign-on/authentik.html
Wazuh – Single sign-on, administrator and read-only rolesdocumentation.wazuh.com/current/…/single-sign-on/administrator
Wazuh – Release notesdocumentation.wazuh.com/current/release-notes
authentik – Integrate with Wazuhintegrations.goauthentik.io/monitoring/wazuh
authentik – Documentationdocs.goauthentik.io
OpenSearch – SAML authentication (security plugin)opensearch.org/docs/security/authentication-backends/saml
OpenSearch – SAML troubleshootingdocs.opensearch.org/3.1/troubleshoot/saml
ntfy – Documentationdocs.ntfy.sh

Compliance Frameworks

FrameworkCanonical Reference
NIST SP 800-53 Rev. 5 – Security and Privacy Controlscsrc.nist.gov/pubs/sp/800/53/r5/upd1/final
SOC 2 Trust Services Criteria – AICPAaicpa-cima.com/resources/download/trust-services-criteria
PCI DSS v4.0.1 – PCI Security Standards Councilpcisecuritystandards.org/standards/pci-dss
CIS Controls v8.1cisecurity.org/controls/v8-1

Software Versions

ComponentVersionNotes
Wazuh indexer, manager, dashboard4.14.10Upgraded from 4.14.7. No breaking changes between the two.
Wazuh agents4.14.xManager must be at or above the agent version
Filebeatpackage held at installed versionWazuh module and alerts template updated to match 4.14.10
AuthentikDocker Compose deploymentReady endpoint returned 200 on this version
ntfyimage pinned by digestDeny-all access, bound to one address
Collector and integration scriptsPython 3, standard library onlyFull source in Appendix A and Appendix B

Disclaimers

All work was performed against infrastructure owned and operated by the author in a private homelab environment. Unauthorized access to computer systems is illegal under the Computer Fraud and Abuse Act (18 U.S.C. § 1030) and equivalent laws in other jurisdictions. This content is provided for educational and defensive security research purposes only. Do not test against systems you do not own or have explicit written authorization to test.

This content represents personal educational work conducted in a home lab environment on personal equipment. It does not reflect the views, opinions, or positions of any employer or affiliated organization. All security methodologies are derived from publicly available frameworks, vendor documentation, and open-source tool documentation.

Published by Oob Skulden™ | Stay Paranoid.