From e2f1039b2df17d3fdf3d1087cb5e8364fd86c23e Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 21 Oct 2026 00:45:16 +0200 Subject: [PATCH] fix(web-app-wazuh): give platform administrators indexer and Wazuh API access With single sign-on disabled, the platform administrator had no indexer account, so the dashboard login answered "Invalid username or password". internal_users.yml now carries that account with backend role "admin" while sso is off. The bcrypt salt is fixed per role, so a repeat deploy renders the same hash. The dashboard queries the Wazuh API with run_as. The default security rules only match the users "elastic" and "admin", so every other signed-in user got "You have no permissions" on the Wazuh pages. A new task runs api_administrators.py inside wazuh.manager with the manager's own API account. It creates the rule "infinito_administrators", corrects it when its content drifts, and links it to the "administrator" role. The rule matches the same three backend roles that roles_mapping.yml maps to all_access, so it grants nothing to a principal that did not already hold indexer all_access. The task prints CHANGED or OK and is idempotent. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../files/python/api_administrators.py | 58 ++++++++++++ roles/web-app-wazuh/tasks/00_core.yml | 3 + .../tasks/02_api_administrators.yml | 17 ++++ .../templates/internal_users.yml.j2 | 9 ++ roles/web-app-wazuh/vars/main.yml | 9 ++ .../python/roles/web-app-wazuh/__init__.py | 0 .../roles/web-app-wazuh/files/__init__.py | 0 .../web-app-wazuh/files/python/__init__.py | 3 + .../files/python/test_api_administrators.py | 88 +++++++++++++++++++ 9 files changed, 187 insertions(+) create mode 100644 roles/web-app-wazuh/files/python/api_administrators.py create mode 100644 roles/web-app-wazuh/tasks/02_api_administrators.yml create mode 100644 tests/unit/python/roles/web-app-wazuh/__init__.py create mode 100644 tests/unit/python/roles/web-app-wazuh/files/__init__.py create mode 100644 tests/unit/python/roles/web-app-wazuh/files/python/__init__.py create mode 100644 tests/unit/python/roles/web-app-wazuh/files/python/test_api_administrators.py diff --git a/roles/web-app-wazuh/files/python/api_administrators.py b/roles/web-app-wazuh/files/python/api_administrators.py new file mode 100644 index 0000000000..50ffee48b9 --- /dev/null +++ b/roles/web-app-wazuh/files/python/api_administrators.py @@ -0,0 +1,58 @@ +"""Grant the Wazuh API administrator role to the platform's administrator backend roles. + +Environment: + API_USERNAME: Wazuh API account name, set in the wazuh.manager container. + API_PASSWORD: Wazuh API account password, set in the wazuh.manager container. + WAZUH_RBAC_RULE_NAME: Name of the security rule this script owns. + WAZUH_RBAC_BACKEND_ROLES: JSON list of backend roles that receive the administrator role. + +Prints CHANGED when the rule or its link to the administrator role was written, OK otherwise. +""" + +import base64 +import json +import os +import ssl +import urllib.request + +API = "https://localhost:55000" +ADMINISTRATOR = "administrator" + + +def call(method, path, token=None, body=None, auth=None): + data = json.dumps(body).encode() if body is not None else None + request = urllib.request.Request(f"{API}{path}", method=method, data=data) + request.add_header("Content-Type", "application/json") + if auth is not None: + request.add_header("Authorization", "Basic " + base64.b64encode(auth.encode()).decode()) + else: + request.add_header("Authorization", f"Bearer {token}") + with urllib.request.urlopen(request, context=ssl._create_unverified_context()) as response: + return json.loads(response.read())["data"] + + +def items(path, token): + return call("GET", f"{path}?limit=500", token)["affected_items"] + + +def main(): + name = os.environ["WAZUH_RBAC_RULE_NAME"] + rule = {"OR": [{"FIND": {"backend_roles": role}} for role in json.loads(os.environ["WAZUH_RBAC_BACKEND_ROLES"])]} + token = call("POST", "/security/user/authenticate", auth=f"{os.environ['API_USERNAME']}:{os.environ['API_PASSWORD']}")["token"] + changed = False + current = next((item for item in items("/security/rules", token) if item["name"] == name), None) + if current is None: + current = call("POST", "/security/rules", token, {"name": name, "rule": rule})["affected_items"][0] + changed = True + elif current["rule"] != rule: + call("PUT", f"/security/rules/{current['id']}", token, {"rule": rule}) + changed = True + role = next(item for item in items("/security/roles", token) if item["name"] == ADMINISTRATOR) + if current["id"] not in role["rules"]: + call("POST", f"/security/roles/{role['id']}/rules?rule_ids={current['id']}", token) + changed = True + print("CHANGED" if changed else "OK") + + +if __name__ == "__main__": + main() diff --git a/roles/web-app-wazuh/tasks/00_core.yml b/roles/web-app-wazuh/tasks/00_core.yml index d3c4716301..1e6dcf5c69 100644 --- a/roles/web-app-wazuh/tasks/00_core.yml +++ b/roles/web-app-wazuh/tasks/00_core.yml @@ -127,3 +127,6 @@ retries: 30 delay: 5 no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🔐 Map the platform administrators onto the Wazuh API administrator role" + include_tasks: 02_api_administrators.yml diff --git a/roles/web-app-wazuh/tasks/02_api_administrators.yml b/roles/web-app-wazuh/tasks/02_api_administrators.yml new file mode 100644 index 0000000000..5c2afdcf6e --- /dev/null +++ b/roles/web-app-wazuh/tasks/02_api_administrators.yml @@ -0,0 +1,17 @@ +- name: "🔐 Grant the Wazuh API administrator role to the platform administrators" + ansible.builtin.shell: + cmd: >- + container exec -i + -e WAZUH_RBAC_RULE_NAME + -e WAZUH_RBAC_BACKEND_ROLES + {{ WAZUH_MANAGER_CONTAINER_ADDRESS }} + /var/ossec/framework/python/bin/python3 - + stdin: "{{ lookup('file', 'python/api_administrators.py') }}" + environment: + WAZUH_RBAC_RULE_NAME: "{{ WAZUH_API_ADMIN_RULE }}" + WAZUH_RBAC_BACKEND_ROLES: "{{ WAZUH_API_ADMIN_BACKEND_ROLES | to_json }}" + register: wazuh_api_administrators + changed_when: wazuh_api_administrators.stdout == 'CHANGED' + retries: 30 + delay: 10 + until: wazuh_api_administrators.rc == 0 diff --git a/roles/web-app-wazuh/templates/internal_users.yml.j2 b/roles/web-app-wazuh/templates/internal_users.yml.j2 index f0779f5367..de3c7d0c24 100644 --- a/roles/web-app-wazuh/templates/internal_users.yml.j2 +++ b/roles/web-app-wazuh/templates/internal_users.yml.j2 @@ -14,3 +14,12 @@ _meta: hash: "{{ WAZUH_DASHBOARD_SERVICE_HASH }}" reserved: true description: "Service account wazuh.dashboard uses for its own backend calls to wazuh.indexer." +{% if not WAZUH_OIDC_ENABLED %} + +"{{ WAZUH_PLATFORM_ADMIN_USERNAME }}": + hash: "{{ WAZUH_PLATFORM_ADMIN_HASH }}" + reserved: false + backend_roles: + - "admin" + description: "Platform administrator, signs in with HTTP basic auth while single sign-on is off." +{% endif %} diff --git a/roles/web-app-wazuh/vars/main.yml b/roles/web-app-wazuh/vars/main.yml index efe4bcdc79..9b61269624 100644 --- a/roles/web-app-wazuh/vars/main.yml +++ b/roles/web-app-wazuh/vars/main.yml @@ -2,6 +2,7 @@ application_id: "web-app-wazuh" WAZUH_MANAGER_CONTAINER: "{{ lookup('config', application_id, 'services.manager.name') }}" +WAZUH_MANAGER_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'manager') }}" WAZUH_INDEXER_CONTAINER: "{{ lookup('config', application_id, 'services.indexer.name') }}" WAZUH_INDEXER_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'indexer') }}" @@ -57,6 +58,9 @@ WAZUH_INDEXER_ADMIN_USERNAME: "{{ lookup('users', 'admin').username }}" WAZUH_INDEXER_ADMIN_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.indexer_admin_password') }}" WAZUH_INDEXER_ADMIN_HASH: "{{ WAZUH_INDEXER_ADMIN_PASSWORD | bcrypt_hash(application_id ~ ':indexer-admin') }}" +WAZUH_PLATFORM_ADMIN_USERNAME: "{{ lookup('users', IAM_PLATFORM_ADMIN_USER_KEY).username }}" +WAZUH_PLATFORM_ADMIN_HASH: "{{ lookup('users', IAM_PLATFORM_ADMIN_USER_KEY).password | bcrypt_hash(application_id ~ ':platform-admin') }}" + WAZUH_DASHBOARD_SERVICE_USERNAME: "{{ lookup('users', 'web-app-wazuh-dashboard').username }}" WAZUH_DASHBOARD_SERVICE_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.dashboard_service_password') }}" WAZUH_DASHBOARD_SERVICE_HASH: "{{ WAZUH_DASHBOARD_SERVICE_PASSWORD | bcrypt_hash(application_id ~ ':dashboard-service') }}" @@ -71,5 +75,10 @@ WAZUH_RBAC_ANALYST_GROUP: "/{{ lookup('rbac_group_path', application_id=applicat WAZUH_RBAC_READONLY_GROUP: "/{{ lookup('rbac_group_path', application_id=application_id, role='readonly-auditor') }}" WAZUH_RBAC_ADMIN_LDAP_CN: "{{ application_id }}-administrator" +WAZUH_API_ADMIN_RULE: "infinito_administrators" +WAZUH_API_ADMIN_BACKEND_ROLES: + - "admin" + - "{{ WAZUH_RBAC_ADMIN_GROUP }}" + - "{{ WAZUH_RBAC_ADMIN_LDAP_CN }}" WAZUH_RBAC_ANALYST_LDAP_CN: "{{ application_id }}-security-analyst" WAZUH_RBAC_READONLY_LDAP_CN: "{{ application_id }}-readonly-auditor" diff --git a/tests/unit/python/roles/web-app-wazuh/__init__.py b/tests/unit/python/roles/web-app-wazuh/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-wazuh/files/__init__.py b/tests/unit/python/roles/web-app-wazuh/files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-wazuh/files/python/__init__.py b/tests/unit/python/roles/web-app-wazuh/files/python/__init__.py new file mode 100644 index 0000000000..86efabd459 --- /dev/null +++ b/tests/unit/python/roles/web-app-wazuh/files/python/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] diff --git a/tests/unit/python/roles/web-app-wazuh/files/python/test_api_administrators.py b/tests/unit/python/roles/web-app-wazuh/files/python/test_api_administrators.py new file mode 100644 index 0000000000..10d72faaad --- /dev/null +++ b/tests/unit/python/roles/web-app-wazuh/files/python/test_api_administrators.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import base64 +import io +import json +import runpy +import unittest +from contextlib import redirect_stdout +from unittest.mock import patch + +from . import PROJECT_ROOT + +SCRIPT_PATH = PROJECT_ROOT / "roles/web-app-wazuh/files/python/api_administrators.py" +ROLES = ["admin", "/roles/web-app-wazuh/administrator", "web-app-wazuh-administrator"] +RULE = {"OR": [{"FIND": {"backend_roles": role}} for role in ROLES]} +ENV = { + "API_USERNAME": "wazuh-wui", + "API_PASSWORD": "s3cret", + "WAZUH_RBAC_RULE_NAME": "infinito_administrators", + "WAZUH_RBAC_BACKEND_ROLES": json.dumps(ROLES), +} + + +class FakeApi: + def __init__(self, rules: list[dict], admin_rules: list[int]): + self.rules = rules + self.roles = [{"id": 1, "name": "administrator", "rules": admin_rules}, {"id": 2, "name": "readonly", "rules": []}] + self.writes: list[tuple[str, str, object]] = [] + self.basic = None + + def __call__(self, request, context=None): + method, path = request.get_method(), request.full_url.removeprefix("https://localhost:55000") + body = json.loads(request.data) if request.data else None + if path == "/security/user/authenticate": + self.basic = request.get_header("Authorization") + data = {"token": "jwt"} + elif method == "GET" and path.startswith("/security/rules"): + data = {"affected_items": self.rules} + elif method == "GET" and path.startswith("/security/roles"): + data = {"affected_items": self.roles} + elif method == "POST" and path == "/security/rules": + created = {"id": 100, "name": body["name"], "rule": body["rule"]} + self.rules.append(created) + self.writes.append((method, path, body)) + data = {"affected_items": [created]} + else: + self.writes.append((method, path, body)) + data = {"affected_items": []} + return io.BytesIO(json.dumps({"data": data}).encode()) + + +def _run(api: FakeApi) -> str: + out = io.StringIO() + with patch("urllib.request.urlopen", api), patch.dict("os.environ", ENV), redirect_stdout(out): + runpy.run_path(str(SCRIPT_PATH), run_name="__main__") + return out.getvalue().strip() + + +class TestApiAdministrators(unittest.TestCase): + def test_fresh_manager_gets_the_rule_and_its_administrator_link(self): + api = FakeApi(rules=[{"id": 2, "name": "wui_opensearch_admin", "rule": {"FIND": {"user_name": "admin"}}}], admin_rules=[2]) + self.assertEqual(_run(api), "CHANGED") + self.assertEqual(api.writes[0], ("POST", "/security/rules", {"name": "infinito_administrators", "rule": RULE})) + self.assertEqual(api.writes[1][:2], ("POST", "/security/roles/1/rules?rule_ids=100")) + + def test_converged_manager_reports_ok_without_writing(self): + api = FakeApi(rules=[{"id": 100, "name": "infinito_administrators", "rule": RULE}], admin_rules=[2, 100]) + self.assertEqual(_run(api), "OK") + self.assertEqual(api.writes, []) + + def test_a_drifted_rule_is_rewritten_in_place(self): + api = FakeApi(rules=[{"id": 100, "name": "infinito_administrators", "rule": {"FIND": {"backend_roles": "old"}}}], admin_rules=[100]) + self.assertEqual(_run(api), "CHANGED") + self.assertEqual(api.writes, [("PUT", "/security/rules/100", {"rule": RULE})]) + + def test_an_unlinked_rule_is_linked_to_the_administrator_role(self): + api = FakeApi(rules=[{"id": 100, "name": "infinito_administrators", "rule": RULE}], admin_rules=[2]) + self.assertEqual(_run(api), "CHANGED") + self.assertEqual(api.writes[0][:2], ("POST", "/security/roles/1/rules?rule_ids=100")) + + def test_the_api_account_authenticates_with_basic_auth_from_the_environment(self): + api = FakeApi(rules=[{"id": 100, "name": "infinito_administrators", "rule": RULE}], admin_rules=[100]) + _run(api) + self.assertEqual(api.basic, "Basic " + base64.b64encode(b"wazuh-wui:s3cret").decode()) + + +if __name__ == "__main__": + unittest.main()