diff --git a/plugins/filter/bcrypt_hash.py b/plugins/filter/bcrypt_hash.py index 21aefdd4bd..2f9d5e91e1 100644 --- a/plugins/filter/bcrypt_hash.py +++ b/plugins/filter/bcrypt_hash.py @@ -12,8 +12,32 @@ # such self-test and hashes correctly in the same environment. from __future__ import annotations +import base64 +import hashlib + import bcrypt +_STD_TO_BCRYPT_B64 = bytes.maketrans( + b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", + b"./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", +) + + +def _seeded_salt(seed: str, secret: bytes) -> bytes: + """A fixed bcrypt salt derived from the seed and the secret. + + Args: + seed: caller-chosen, non-empty string that separates otherwise equal secrets. + secret: the UTF-8 encoded secret being hashed. + + Returns: + ``$2b$12$`` plus 22 bcrypt-base64 characters encoding the first 16 + bytes of sha256(seed + secret). + """ + digest = hashlib.sha256(seed.encode("utf-8") + secret).digest()[:16] + encoded = base64.b64encode(digest)[:22].translate(_STD_TO_BCRYPT_B64) + return b"$2b$12$" + encoded + class FilterModule: def filters(self): @@ -22,8 +46,25 @@ class FilterModule: } @staticmethod - def bcrypt_hash(value): + def bcrypt_hash(value, salt_seed=None): if not isinstance(value, str) or not value: raise ValueError("bcrypt_hash: value must be a non-empty string") - return bcrypt.hashpw(value.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + secret = value.encode("utf-8") + if len(secret) > 72: + raise ValueError( + f"bcrypt_hash: secret is {len(secret)} bytes in UTF-8; bcrypt " + "accepts at most 72 bytes. Shorten the secret instead of " + "letting bcrypt truncate or reject it." + ) + + if salt_seed is None: + salt = bcrypt.gensalt() + elif isinstance(salt_seed, str) and salt_seed: + salt = _seeded_salt(salt_seed, secret) + else: + raise ValueError( + "bcrypt_hash: salt_seed must be a non-empty string when given" + ) + + return bcrypt.hashpw(secret, salt).decode("utf-8") diff --git a/roles/test-e2e-playwright/files/personas/utils/keycloak.js b/roles/test-e2e-playwright/files/personas/utils/keycloak.js index 2ed116db8f..cb4a2c75fb 100644 --- a/roles/test-e2e-playwright/files/personas/utils/keycloak.js +++ b/roles/test-e2e-playwright/files/personas/utils/keycloak.js @@ -359,28 +359,32 @@ async function keycloakRemoveUserFromGroupViaRest( opts = {}, ) { const accessToken = await keycloakAdminToken(request, keycloakBaseUrl, adminUsername, adminPassword, opts); - const auth = { Authorization: `Bearer ${accessToken}` }; + const headers = { Authorization: `Bearer ${accessToken}` }; - const usersResp = await request.get( - `${keycloakBaseUrl}/admin/realms/${encodeURIComponent(realmName)}/users?username=${encodeURIComponent(username)}&exact=true`, - { headers: auth }, + const userResp = await request.get( + `${keycloakBaseUrl}/admin/realms/${realmName}/users?username=${encodeURIComponent(username)}&exact=true`, + { headers }, ); - const users = await usersResp.json(); - const userId = users?.[0]?.id; - if (!userId) return; + if (!userResp.ok()) { + throw new Error(`Keycloak user lookup failed: ${userResp.status()} ${await userResp.text()}`); + } + const users = await userResp.json(); + const user = users.find((u) => u.username === username); + if (!user) { + throw new Error(`Keycloak user "${username}" not found`); + } - const groupResp = await request.get( - `${keycloakBaseUrl}/admin/realms/${encodeURIComponent(realmName)}/group-by-path/${groupPath.replace(/^\//, "")}`, - { headers: auth }, - ); - if (!groupResp.ok()) return; - const group = await groupResp.json(); - if (!group?.id) return; + const groupId = await keycloakResolveGroupId(request, keycloakBaseUrl, realmName, accessToken, groupPath); - await request.delete( - `${keycloakBaseUrl}/admin/realms/${encodeURIComponent(realmName)}/users/${userId}/groups/${group.id}`, - { headers: auth }, + const leaveResp = await request.delete( + `${keycloakBaseUrl}/admin/realms/${realmName}/users/${user.id}/groups/${groupId}`, + { headers }, ); + if (!leaveResp.ok()) { + throw new Error( + `Keycloak leave-group failed (user=${username}, group=${groupPath}): ${leaveResp.status()} ${await leaveResp.text()}`, + ); + } } module.exports = { diff --git a/roles/web-app-wazuh/files/playwright/_shared.js b/roles/web-app-wazuh/files/playwright/_shared.js index e76fd4642c..13ff04eb16 100644 --- a/roles/web-app-wazuh/files/playwright/_shared.js +++ b/roles/web-app-wazuh/files/playwright/_shared.js @@ -77,6 +77,7 @@ async function withBiberInGroup(browser, groupPath, fn) { const adminOpts = { adminRealm: env.keycloakAdminRealm, adminClientId: env.keycloakAdminCliClientId }; const adminCtx = await browser.newContext({ ignoreHTTPSErrors: true }); let biberAdded = false; + let bodyFailed = false; try { biberAdded = await keycloakAdmin.keycloakAdminAddUserToGroup( adminCtx.request, @@ -89,22 +90,31 @@ async function withBiberInGroup(browser, groupPath, fn) { adminOpts, ); return await fn(); + } catch (err) { + bodyFailed = true; + throw err; } finally { - if (biberAdded) { - await keycloakAdmin - .keycloakRemoveUserFromGroupViaRest( - adminCtx.request, - env.keycloakBaseUrl, - env.realmName, - env.superAdminUsername, - env.superAdminPassword, - groupPath, - env.biberUsername, - adminOpts, - ) - .catch((err) => console.warn(`Cleanup removal of biber from ${groupPath} failed: ${err}`)); + try { + if (biberAdded) { + await keycloakAdmin + .keycloakRemoveUserFromGroupViaRest( + adminCtx.request, + env.keycloakBaseUrl, + env.realmName, + env.superAdminUsername, + env.superAdminPassword, + groupPath, + env.biberUsername, + adminOpts, + ) + .catch((err) => { + if (!bodyFailed) throw err; + console.warn(`Cleanup removal of biber from ${groupPath} failed: ${err}`); + }); + } + } finally { + await adminCtx.close().catch(() => {}); } - await adminCtx.close().catch(() => {}); } } diff --git a/roles/web-app-wazuh/files/playwright/test-csp.js b/roles/web-app-wazuh/files/playwright/test-csp.js index 7de0422615..f32b4a7eee 100644 --- a/roles/web-app-wazuh/files/playwright/test-csp.js +++ b/roles/web-app-wazuh/files/playwright/test-csp.js @@ -34,7 +34,7 @@ async function typeIntoDevToolsConsole(page) { .first() .click({ timeout: resolveTimeout(5_000) }) .catch(() => {}); - await editor.click({ timeout: resolveTimeout(10_000) }); + await editor.focus({ timeout: resolveTimeout(10_000) }); await page.keyboard.type("GET _cluster/health", { delay: 50 }); await page.waitForTimeout(resolveTimeout(3_000)); } @@ -70,9 +70,7 @@ test("wazuh dashboard: script-src-elem unsafe-inline and worker-src blob: are de ).toContain("'unsafe-inline'"); expect(directives["worker-src"] || [], "Expected worker-src to grant blob:").toContain("blob:"); - await typeIntoDevToolsConsole(page).catch((err) => - console.warn(`wazuh dev tools console was not typed into: ${err}`), - ); + await typeIntoDevToolsConsole(page); await expectNoCspViolations(page, diagnostics, "wazuh dashboard (home + dev tools console)"); }); diff --git a/roles/web-app-wazuh/files/playwright/test-rbac-roles.js b/roles/web-app-wazuh/files/playwright/test-rbac-roles.js index 39e4138567..96477e3650 100644 --- a/roles/web-app-wazuh/files/playwright/test-rbac-roles.js +++ b/roles/web-app-wazuh/files/playwright/test-rbac-roles.js @@ -1,5 +1,5 @@ const { test, expect } = require("@playwright/test"); -const { installCspViolationObserver } = require("./personas"); +const { installCspViolationObserver, gotoOnion } = require("./personas"); const { skipUnlessServiceEnabled } = require("./service-gating"); const { resolveTimeout } = require("./timeouts"); const shared = require("./_shared"); @@ -10,12 +10,12 @@ const RBAC_TIERS = [ { role: "readonly-auditor", expectSecurityUi: false }, ]; -function becomesVisible(locator, timeout) { - return locator - .first() - .waitFor({ state: "visible", timeout: resolveTimeout(timeout) }) - .then(() => true) - .catch(() => false); +async function seenBy(page) { + const body = await page + .locator("body") + .innerText({ timeout: resolveTimeout(5_000) }) + .catch((err) => ``); + return `page: ${page.url()}, body: ${body.slice(0, 1500)}`; } exports.register = function () { @@ -36,30 +36,44 @@ exports.register = function () { shared.env.biberPassword, ); - await page - .goto(`${shared.env.appBaseUrl}/app/security-dashboards-plugin#/roles`, { - waitUntil: "domcontentloaded", - }) - .catch(() => {}); - const securityUiVisible = await becomesVisible( - page.getByText(/internal users|role mappings|create role/i), - 30_000, - ); + const nav = await gotoOnion(page, `${shared.env.appBaseUrl}/app/security-dashboards-plugin#/roles`, { + waitUntil: "domcontentloaded", + }); + expect( + nav ? nav.status() : 0, + `${tier.role} navigation to the Security management UI failed (${await seenBy(page)})`, + ).toBeLessThan(400); + const roleTable = page.locator("[data-test-subj='role-list']"); if (tier.expectSecurityUi) { - expect( - securityUiVisible, - `${tier.role} MUST reach the Security management UI (page: ${page.url()})`, - ).toBe(true); + await roleTable + .first() + .waitFor({ state: "visible", timeout: resolveTimeout(30_000) }) + .catch(async (err) => { + throw new Error( + `${tier.role} MUST reach the Security management UI (${await seenBy(page)}): ${err.message}`, + ); + }); } else { - const deniedMarker = await becomesVisible( - page.getByText(/no permissions|not authorized|forbidden|missing.*permission/i), - 10_000, - ); + await page.waitForTimeout(resolveTimeout(10_000)); + const seen = await seenBy(page); + // Exception: the explicit denial text is not verified yet; these two checks stand in for it until CI shows what a denied user sees. expect( - securityUiVisible === false || deniedMarker === true, - `${tier.role} MUST NOT reach the Security management UI (saw content=${securityUiVisible}, denied-marker=${deniedMarker}, page: ${page.url()})`, + page.url().startsWith(shared.env.appBaseUrl), + `${tier.role} MUST be denied inside the Wazuh app, not redirected away (${seen})`, ).toBe(true); + expect( + (await page.locator("body").innerText({ timeout: resolveTimeout(5_000) })).trim(), + `${tier.role} MUST see a denial or empty-permission page, not a blank page (${seen})`, + ).not.toBe(""); + await expect( + roleTable, + `${tier.role} MUST NOT reach the Security management UI (role table rendered, ${seen})`, + ).toHaveCount(0); + await expect( + page.locator("[data-test-subj='create-role']"), + `${tier.role} MUST NOT reach the Security management UI (create-role button rendered, ${seen})`, + ).toHaveCount(0); } } finally { await biberCtx.close().catch(() => {}); diff --git a/roles/web-app-wazuh/files/roles.yml b/roles/web-app-wazuh/files/roles.yml index 9b1373f214..6dee71147d 100644 --- a/roles/web-app-wazuh/files/roles.yml +++ b/roles/web-app-wazuh/files/roles.yml @@ -31,7 +31,7 @@ readonly_auditor: - "cluster_composite_ops_ro" index_permissions: - index_patterns: - - "*" + - "wazuh-*" allowed_actions: - "read" tenant_permissions: diff --git a/roles/web-app-wazuh/files/shell/certs-entrypoint.sh b/roles/web-app-wazuh/files/shell/certs-entrypoint.sh index 3b9fddb7c2..0a2ff422df 100755 --- a/roles/web-app-wazuh/files/shell/certs-entrypoint.sh +++ b/roles/web-app-wazuh/files/shell/certs-entrypoint.sh @@ -1,62 +1,39 @@ -#!/bin/bash -# Wazuh Docker Copyright (C) 2017, Wazuh Inc. (License GPLv2) +#!/usr/bin/env bash +set -euo pipefail + unset CURL_CA_BUNDLE SSL_CERT_FILE REQUESTS_CA_BUNDLE NODE_EXTRA_CA_CERTS -CERT_TOOL=wazuh-certs-tool.sh -# shellcheck disable=SC2034 # unmodified vendor logic -PASSWORD_TOOL=wazuh-passwords-tool.sh -PACKAGES_URL=https://packages.wazuh.com/$CERT_TOOL_VERSION/ -PACKAGES_DEV_URL=https://packages-dev.wazuh.com/$CERT_TOOL_VERSION/ +: "${CERT_TOOL_VERSION:?CERT_TOOL_VERSION must name the wazuh-certs-tool release}" +: "${WAZUH_MANAGER_NODE:?WAZUH_MANAGER_NODE must name the manager node in /config/certs.yml}" -OUTPUT_FILE="/$CERT_TOOL" +config_src="/config/certs.yml" +out_dir="/certificates" +tool_url="https://packages.wazuh.com/${CERT_TOOL_VERSION}/wazuh-certs-tool.sh" -download_package() { - local url=$1 - echo "Checking $url$CERT_TOOL ..." - if curl -fsL --connect-timeout 10 --max-time 60 --retry-all-errors --retry-delay 2 "$url$CERT_TOOL" -o "$OUTPUT_FILE"; then - echo "Downloaded $CERT_TOOL from $url" - return 0 - else - return 1 - fi -} +work_dir="$(mktemp -d)" +trap 'rm -rf "${work_dir}"' EXIT -if download_package "$PACKAGES_URL"; then - : -elif download_package "$PACKAGES_DEV_URL"; then - echo "WARNING: $CERT_TOOL was not found on the stable bucket ($PACKAGES_URL)." >&2 - echo "WARNING: falling back to the dev bucket ($PACKAGES_DEV_URL), which is unversioned/unstable upstream." >&2 -else - echo "The tool to create the certificates does not exist in any bucket" - echo "ERROR: certificates were not created" - exit 1 +if ! curl --connect-timeout 10 --max-time 120 --fail --silent --show-error --location \ + --retry 5 --retry-delay 5 --retry-all-errors \ + --output "${work_dir}/wazuh-certs-tool.sh" "${tool_url}"; then + echo "ERROR: downloading ${tool_url} failed; no certificates were generated" >&2 + exit 1 fi -cp /config/certs.yml /config.yml -chmod 700 "$OUTPUT_FILE" +cp "${config_src}" "${work_dir}/config.yml" +bash "${work_dir}/wazuh-certs-tool.sh" --all -# shellcheck disable=SC1090 # unmodified vendor logic; CERT_TOOL is a fixed, known filename -source /$CERT_TOOL -A -nodes_server=$( cert_parseYaml /config.yml | grep -E "nodes[_]+server[_]+[0-9]+=" | sed -e 's/nodes__server__[0-9]=//' | sed 's/"//g' ) -# shellcheck disable=SC2206 # unmodified vendor logic; node names are always simple hostnames, never contain spaces/globs -node_names=($nodes_server) +cp "${work_dir}"/wazuh-certificates/* "${out_dir}/" +cp "${out_dir}/root-ca.pem" "${out_dir}/root-ca-manager.pem" +cp "${out_dir}/root-ca.key" "${out_dir}/root-ca-manager.key" -echo "Moving created certificates to the destination directory" -cp /wazuh-certificates/* /certificates/ -echo "Changing certificate permissions" -chmod -R 500 /certificates -chmod -R 400 /certificates/* -echo "Setting UID indexer and dashboard" -chown 1000:1000 /certificates/* -echo "Setting UID for wazuh manager and worker" -cp /certificates/root-ca.pem /certificates/root-ca-manager.pem -cp /certificates/root-ca.key /certificates/root-ca-manager.key -chown 999:999 /certificates/root-ca-manager.pem -chown 999:999 /certificates/root-ca-manager.key +chmod 0400 "${out_dir}"/* +chown 1000:1000 "${out_dir}"/* +chown 999:999 \ + "${out_dir}/root-ca-manager.pem" \ + "${out_dir}/root-ca-manager.key" \ + "${out_dir}/${WAZUH_MANAGER_NODE}.pem" \ + "${out_dir}/${WAZUH_MANAGER_NODE}-key.pem" +chmod 0500 "${out_dir}" -# shellcheck disable=SC2068 # unmodified vendor logic; node names are always simple hostnames, never contain spaces/globs -for i in ${node_names[@]}; -do - chown 999:999 "/certificates/${i}.pem" - chown 999:999 "/certificates/${i}-key.pem" -done +echo "Wazuh certificates written to ${out_dir}" diff --git a/roles/web-app-wazuh/files/shell/indexer-entrypoint.sh b/roles/web-app-wazuh/files/shell/indexer-entrypoint.sh index 09d47f1bdc..35b2aec57d 100755 --- a/roles/web-app-wazuh/files/shell/indexer-entrypoint.sh +++ b/roles/web-app-wazuh/files/shell/indexer-entrypoint.sh @@ -1,106 +1,11 @@ #!/usr/bin/env bash -# Wazuh Docker Copyright (C) 2017, Wazuh Inc. (License GPLv2) -# nocheck: comments-valid from `set -e` onward this is an unmodified copy of the vendor's own /entrypoint.sh; its inline comments are upstream documentation. if [ -n "${CA_TRUST_CERT:-}" ] && [ -r "${CA_TRUST_CERT}" ]; then CACERTS="/usr/share/wazuh-indexer/jdk/lib/security/cacerts" - ALIAS="${CA_TRUST_NAME:-infinito-dev-ca}" + ALIAS="${CA_TRUST_NAME:?CA_TRUST_NAME must accompany CA_TRUST_CERT}" KEYTOOL="/usr/share/wazuh-indexer/jdk/bin/keytool" if ! "$KEYTOOL" -list -keystore "$CACERTS" -storepass changeit -alias "$ALIAS" >/dev/null 2>&1; then "$KEYTOOL" -importcert -noprompt -alias "$ALIAS" -file "$CA_TRUST_CERT" -keystore "$CACERTS" -storepass changeit fi fi -set -e - -umask 0002 - -export USER=wazuh-indexer -export INSTALLATION_DIR=/usr/share/wazuh-indexer -export OPENSEARCH_PATH_CONF=${INSTALLATION_DIR}/config -export JAVA_HOME=${INSTALLATION_DIR}/jdk -# shellcheck disable=SC2155 # unmodified vendor logic -export DISCOVERY=$(grep -oP "(?<=discovery.type: ).*" ${OPENSEARCH_PATH_CONF}/opensearch.yml) -# shellcheck disable=SC2155 # unmodified vendor logic -export CACERT=$(grep -oP "(?<=plugins.security.ssl.transport.pemtrustedcas_filepath: ).*" ${OPENSEARCH_PATH_CONF}/opensearch.yml) -export CERT="${OPENSEARCH_PATH_CONF}/certs/admin.pem" -export KEY="${OPENSEARCH_PATH_CONF}/certs/admin-key.pem" - -run_as_other_user_if_needed() { - if [[ "$(id -u)" == "0" ]]; then - # If running as root, drop to specified UID and run command - exec chroot --userspec=1000:0 / "${@}" - else - # Either we are running in Openshift with random uid and are a member of the root group - # or with a custom --user - exec "${@}" - fi -} - -# Allow user specify custom CMD, maybe bin/opensearch itself -# for example to directly specify `-E` style parameters for opensearch on k8s -# or simply to run /bin/bash to check the image -if [[ "$1" != "opensearchwrapper" ]]; then - if [[ "$(id -u)" == "0" && $(basename "$1") == "opensearch" ]]; then - # Rewrite CMD args to replace $1 with `opensearch` explicitly, - # Without this, user could specify `opensearch -E x.y=z` but - # `bin/opensearch -E x.y=z` would not work. - set -- "opensearch" "${@:2}" - # Use chroot to switch to UID 1000 / GID 0 - exec chroot --userspec=1000:0 / "$@" - else - # User probably wants to run something else, like /bin/bash, with another uid forced (Openshift?) - exec "$@" - fi -fi - -# Allow environment variables to be set by creating a file with the -# contents, and setting an environment variable with the suffix _FILE to -# point to it. This can be used to provide secrets to a container, without -# the values being specified explicitly when running the container. -# -# This is also sourced in opensearch-env, and is only needed here -# as well because we use INDEXER_PASSWORD below. Sourcing this script -# is idempotent. -# shellcheck disable=SC1091 # unmodified vendor logic; file only exists inside the real image -source /usr/share/wazuh-indexer/bin/opensearch-env-from-file - -if [[ -f bin/opensearch-users ]]; then - # Check for the INDEXER_PASSWORD environment variable to set the - # bootstrap password for Security. - # - # This is only required for the first node in a cluster with Security - # enabled, but we have no way of knowing which node we are yet. We'll just - # honor the variable if it's present. - if [[ -n "$INDEXER_PASSWORD" ]]; then - [[ -f /usr/share/wazuh-indexer/opensearch.keystore ]] || (run_as_other_user_if_needed opensearch-keystore create) - if ! (run_as_other_user_if_needed opensearch-keystore has-passwd --silent) ; then - # keystore is unencrypted - if ! (run_as_other_user_if_needed opensearch-keystore list | grep -q '^bootstrap.password$'); then - (run_as_other_user_if_needed echo "$INDEXER_PASSWORD" | opensearch-keystore add -x 'bootstrap.password') - fi - else - # keystore requires password - if ! (run_as_other_user_if_needed echo "$KEYSTORE_PASSWORD" \ - | opensearch-keystore list | grep -q '^bootstrap.password$') ; then - COMMANDS="$(printf "%s\n%s" "$KEYSTORE_PASSWORD" "$INDEXER_PASSWORD")" - (run_as_other_user_if_needed echo "$COMMANDS" | opensearch-keystore add -x 'bootstrap.password') - fi - fi - fi -fi - -if [[ "$(id -u)" == "0" ]]; then - # If requested and running as root, mutate the ownership of bind-mounts - if [[ -n "$TAKE_FILE_OWNERSHIP" ]]; then - chown -R 1000:0 /usr/share/wazuh-indexer/{data,logs} - fi -fi - - -#if [[ "$DISCOVERY" == "single-node" ]] && [[ ! -f "/var/lib/wazuh-indexer/.flag" ]]; then - # run securityadmin.sh for single node with CACERT, CERT and KEY parameter -# nohup /securityadmin.sh & -# touch "/var/lib/wazuh-indexer/.flag" -#fi - -run_as_other_user_if_needed /usr/share/wazuh-indexer/bin/opensearch <<<"$KEYSTORE_PASSWORD" +exec /entrypoint.sh "$@" diff --git a/roles/web-app-wazuh/meta/services.yml b/roles/web-app-wazuh/meta/services.yml index f1e7648938..99d5bb9312 100644 --- a/roles/web-app-wazuh/meta/services.yml +++ b/roles/web-app-wazuh/meta/services.yml @@ -76,6 +76,7 @@ manager: mem_reservation: 512m mem_limit: 2g pids_limit: 1024 + nofile: 655360 backup: no_stop_required: false ports: @@ -105,6 +106,7 @@ indexer: mem_reservation: 1g mem_limit: 2g pids_limit: 2048 + nofile: 65536 backup: no_stop_required: false ports: @@ -129,7 +131,7 @@ console: http: 8096 # nocheck: playwright-service-flag -# nocheck: variants-coverage sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in +# nocheck: variants-coverage โ€” sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in tor: bond: 0.5 enabled: "{{ 'svc-net-tor' in group_names }}" diff --git a/roles/web-app-wazuh/meta/users.yml b/roles/web-app-wazuh/meta/users.yml new file mode 100644 index 0000000000..648caa7e55 --- /dev/null +++ b/roles/web-app-wazuh/meta/users.yml @@ -0,0 +1,10 @@ +--- +admin: {} +web-app-wazuh-dashboard: + username: kibanaserver + accounts: [] + description: Service account wazuh.dashboard uses for its backend calls to wazuh.indexer +web-app-wazuh-api: + username: wazuh-wui + accounts: [] + description: Wazuh API account the dashboard connects with; created by wazuh.manager diff --git a/roles/web-app-wazuh/meta/volumes.yml b/roles/web-app-wazuh/meta/volumes.yml index fa6fd6e055..28b2dc2151 100644 --- a/roles/web-app-wazuh/meta/volumes.yml +++ b/roles/web-app-wazuh/meta/volumes.yml @@ -26,6 +26,7 @@ manager_queue: manager_var_multigroups: type: volume name: wazuh_manager_var_multigroups + backup: false mounts: - service: manager target: /var/ossec/var/multigroups @@ -97,7 +98,7 @@ certs_generator_entrypoint: mode: "0555" mounts: - service: certs_generator - target: &entrypoint_target /entrypoint.sh + target: &entrypoint_target /infinito-entrypoint.sh indexer_entrypoint: type: config source: "{{ [ lookup('container', 'web-app-wazuh', 'directories.instance'), 'indexer-entrypoint.sh' ] | path_join }}" diff --git a/roles/web-app-wazuh/tasks/00_core.yml b/roles/web-app-wazuh/tasks/00_core.yml index 7d06d596de..41b0a709b9 100644 --- a/roles/web-app-wazuh/tasks/00_core.yml +++ b/roles/web-app-wazuh/tasks/00_core.yml @@ -35,6 +35,19 @@ - wazuh.yml notify: compose-up +- name: "๐Ÿ“„ Render per-service env files for the Wazuh manager and dashboard" + stack_host_template: + src: "{{ item.src }}" + dest: "{{ item.dest }}" + mode: "0640" + force: true + loop: + - { src: manager.env.j2, dest: "{{ WAZUH_MANAGER_ENV_FILE }}" } + - { src: dashboard.env.j2, dest: "{{ WAZUH_DASHBOARD_ENV_FILE }}" } + loop_control: + label: "{{ item.src }}" + notify: compose-up + - name: "๐Ÿ“‹ Copy static Wazuh indexer roles.yml" ansible.builtin.copy: # nocheck: stack-host-consumer (already gated by `when: IS_STACK_HOST | bool` below) src: roles.yml @@ -54,8 +67,11 @@ when: IS_STACK_HOST | bool notify: compose-up -- name: "๐Ÿ”„ Flush compose-up before front-proxy can shadow application_id" - ansible.builtin.meta: flush_handlers +- name: "๐Ÿ” Pre-generate the Wazuh certs before the swarm stack deploys" + include_tasks: certs/swarm.yml + when: + - IS_STACK_HOST | bool + - DEPLOYMENT_MODE == 'swarm' - name: "๐Ÿ”ง Set vm.max_map_count for the Wazuh indexer (OpenSearch requirement)" ansible.posix.sysctl: @@ -66,6 +82,9 @@ sysctl_file: "{{ WAZUH_SYSCTL_CONF }}" when: not (DOCKER_IN_CONTAINER | bool) +- name: "๐Ÿ”„ Flush compose-up before front-proxy can shadow application_id" + ansible.builtin.meta: flush_handlers + - name: "๐Ÿ“‚ Include front proxy for {{ application_id }}" include_role: name: sys-stk-front-proxy @@ -92,7 +111,7 @@ uri_retry: url: "{{ WAZUH_INDEXER_INTERNAL_API_URL }}/_cluster/health" method: GET - user: admin + user: "{{ WAZUH_INDEXER_ADMIN_USERNAME }}" password: "{{ WAZUH_INDEXER_ADMIN_PASSWORD }}" force_basic_auth: true validate_certs: false diff --git a/roles/web-app-wazuh/tasks/01_securityadmin.yml b/roles/web-app-wazuh/tasks/01_securityadmin.yml index ebfba70319..29346b503e 100644 --- a/roles/web-app-wazuh/tasks/01_securityadmin.yml +++ b/roles/web-app-wazuh/tasks/01_securityadmin.yml @@ -13,9 +13,7 @@ chdir: "{{ WAZUH_INSTANCE_DIR }}" register: wazuh_securityadmin changed_when: "'Done with success' in wazuh_securityadmin.stdout" - failed_when: - - wazuh_securityadmin.rc != 0 - - "'Done with success' not in wazuh_securityadmin.stdout" + failed_when: wazuh_securityadmin.rc != 0 or 'Done with success' not in wazuh_securityadmin.stdout retries: 10 delay: 10 until: wazuh_securityadmin.rc == 0 diff --git a/roles/web-app-wazuh/tasks/certs/swarm.yml b/roles/web-app-wazuh/tasks/certs/swarm.yml new file mode 100644 index 0000000000..2c5ff6e10a --- /dev/null +++ b/roles/web-app-wazuh/tasks/certs/swarm.yml @@ -0,0 +1,114 @@ +--- +- name: "๐Ÿ” Read the Wazuh certs completion marker" + ansible.builtin.slurp: + src: "{{ WAZUH_CERTS_MARKER_HOST }}" + register: wazuh_certs_marker + failed_when: false + +- name: "๐Ÿ” Checksum the rendered Wazuh certs.yml" + ansible.builtin.stat: + path: "{{ WAZUH_CERTS_CONFIG_HOST }}" + checksum_algorithm: sha256 + register: wazuh_certs_config + +- name: "๐Ÿ” Stat every Wazuh cert file the stack bind-mounts" + ansible.builtin.stat: + path: "{{ item }}" + loop: "{{ WAZUH_CERTS_REQUIRED_FILES }}" + register: wazuh_certs_files + +- name: "๐Ÿ” List the services of a running Wazuh stack" + ansible.builtin.command: + argv: + - container + - service + - ls + - --quiet + - --filter + - "label=com.docker.stack.namespace={{ application_id | get_entity_name }}" + register: wazuh_certs_stack + changed_when: false + +- name: "๐Ÿงฎ Decide whether the Wazuh certs are current" + vars: + expected: "{{ wazuh_certs_config.stat.checksum }} {{ WAZUH_CERTS_TOOL_VERSION }}" + recorded: "{{ wazuh_certs_marker.content | default('') | b64decode | trim }}" + present: >- + {{ wazuh_certs_files.results | selectattr('stat.size', 'defined') | selectattr('stat.size', 'gt', 0) | list | length }} + ansible.builtin.set_fact: + wazuh_certs_expected: "{{ expected }}" + wazuh_certs_recorded: "{{ recorded }}" + wazuh_certs_present: "{{ present | int }}" + wazuh_certs_current: "{{ present | int == WAZUH_CERTS_REQUIRED_FILES | length and recorded == expected }}" + +- name: "โ›” Refuse to rotate the Wazuh CA under a running stack" + ansible.builtin.fail: + msg: >- + Wazuh TLS certs on {{ inventory_hostname }} are not current, and the stack + '{{ application_id | get_entity_name }}' is running, so they were NOT regenerated: that would + swap the CA under the live services. + Marker {{ WAZUH_CERTS_MARKER_HOST }} reads '{{ wazuh_certs_recorded or 'missing' }}', + expected '{{ wazuh_certs_expected }}' (sha256 of certs.yml, then tool version); + {{ wazuh_certs_present }}/{{ WAZUH_CERTS_REQUIRED_FILES | length }} cert files in + {{ WAZUH_CERTS_DIR_HOST }} exist and are non-empty. + To regenerate: run 'docker stack rm {{ application_id | get_entity_name }}', then redeploy. + To keep certs you know are good (a host deployed before this marker existed): write + '{{ wazuh_certs_expected }}' to {{ WAZUH_CERTS_MARKER_HOST }}, then redeploy. + when: + - not (wazuh_certs_current | bool) + - wazuh_certs_stack.stdout | trim | length > 0 + +- name: "โฌ‡๏ธ Pull the Wazuh certs generator image on the stack host" + ansible.builtin.command: + argv: + - container + - pull + - "{{ WAZUH_CERTS_GENERATOR_IMAGE }}" + register: wazuh_certs_pull + retries: 10 + delay: 6 + until: wazuh_certs_pull.rc == 0 + changed_when: false + when: not (wazuh_certs_current | bool) + +- name: "๐Ÿ” Run the Wazuh certs generator once on the stack host" + ansible.builtin.shell: | + set -euo pipefail + container ps -aq --filter {{ ('name=^' ~ WAZUH_CERTS_GENERATOR_CONTAINER ~ '$') | quote }} | xargs -r container rm -f + timeout -k 30 {{ lookup('timeout', 600) | int }} container run --rm \ + --name {{ WAZUH_CERTS_GENERATOR_CONTAINER | quote }} \ + --entrypoint {{ WAZUH_CERTS_ENTRYPOINT_TARGET | quote }} \ + --env CERT_TOOL_VERSION={{ WAZUH_CERTS_TOOL_VERSION | quote }} \ + --env WAZUH_MANAGER_NODE={{ WAZUH_MANAGER_CONTAINER | quote }} \ + {% for mount in WAZUH_CERTS_GENERATOR_MOUNTS %}--mount {{ mount | quote }} {% endfor %}\ + {{ WAZUH_CERTS_GENERATOR_IMAGE | quote }} + args: + executable: /bin/bash + register: wazuh_certs_generate + retries: 3 + delay: 10 + until: wazuh_certs_generate.rc == 0 + when: not (wazuh_certs_current | bool) + +- name: "โœ… Verify the generated Wazuh certs and record the marker" + when: wazuh_certs_generate is not skipped + block: + - name: "๐Ÿ” Stat the Wazuh cert files the generator wrote" + ansible.builtin.stat: + path: "{{ item }}" + loop: "{{ WAZUH_CERTS_REQUIRED_FILES }}" + register: wazuh_certs_written + + - name: "โœ… Assert every Wazuh cert file exists and is non-empty" + ansible.builtin.assert: + that: + - >- + wazuh_certs_written.results | selectattr('stat.size', 'defined') | selectattr('stat.size', 'gt', 0) + | list | length == WAZUH_CERTS_REQUIRED_FILES | length + fail_msg: "The Wazuh certs generator exited 0 but left a required cert file missing or empty." + + - name: "๐Ÿ“ Record the Wazuh certs completion marker" + ansible.builtin.copy: + content: "{{ wazuh_certs_expected }}\n" + dest: "{{ WAZUH_CERTS_MARKER_HOST }}" + mode: "0644" diff --git a/roles/web-app-wazuh/templates/compose.yml.j2 b/roles/web-app-wazuh/templates/compose.yml.j2 index e538ffb84c..9651216426 100644 --- a/roles/web-app-wazuh/templates/compose.yml.j2 +++ b/roles/web-app-wazuh/templates/compose.yml.j2 @@ -1,82 +1,65 @@ {% include 'roles/sys-svc-compose/templates/base.yml.j2' %} +{# Exception: swarm ignores depends_on, so in swarm tasks/certs/swarm.yml generates the certs before the stack deploys. #} +{% set certs_generator_dependency = {'certs_generator': {'condition': 'service_completed_successfully'}} if DEPLOYMENT_MODE == 'compose' else {} %} + {% if DEPLOYMENT_MODE == 'compose' %} {% set service_name = 'certs_generator' %} {% set docker_restart_policy = 'no' %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {{ lookup('container_image', application_id, 'certs_generator') }} {{ lookup('compose_only', 'container_name', WAZUH_CERTS_GENERATOR_CONTAINER) }} + entrypoint: ["{{ WAZUH_CERTS_ENTRYPOINT_TARGET }}"] environment: - - CERT_TOOL_VERSION=4.14 + - CERT_TOOL_VERSION={{ WAZUH_CERTS_TOOL_VERSION }} + - WAZUH_MANAGER_NODE={{ WAZUH_MANAGER_CONTAINER }} {{ lookup('container_volumes', service_name) | indent(4) }} + {% endif %} {% set service_name = 'manager' %} {% set docker_restart_policy = DOCKER_RESTART_POLICY %} + {% set docker_compose_env = WAZUH_MANAGER_ENV_FILE %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {{ lookup('container_image', application_id, 'manager') }} {{ lookup('compose_only', 'container_name', WAZUH_MANAGER_CONTAINER) }} hostname: "{{ WAZUH_MANAGER_CONTAINER }}" ulimits: - memlock: - soft: -1 - hard: -1 nofile: - soft: 655360 - hard: 655360 - environment: - - "INDEXER_URL=https://{{ WAZUH_INDEXER_CONTAINER }}:{{ WAZUH_INDEXER_INTERNAL_PORT }}" - - "INDEXER_USERNAME=admin" - - "INDEXER_PASSWORD={{ WAZUH_INDEXER_ADMIN_PASSWORD }}" - - "FILEBEAT_SSL_VERIFICATION_MODE=full" - - "SSL_CERTIFICATE_AUTHORITIES={{ lookup('volume', application_id, 'root_ca_manager_pem').target }}" - - "SSL_CERTIFICATE={{ lookup('volume', application_id, 'manager_filebeat_pem').target }}" - - "SSL_KEY={{ lookup('volume', application_id, 'manager_filebeat_key_pem').target }}" - - "API_USERNAME=wazuh-wui" - - "API_PASSWORD={{ WAZUH_WUI_PASSWORD }}" + soft: {{ lookup('config', application_id, 'services.manager.nofile') }} + hard: {{ lookup('config', application_id, 'services.manager.nofile') }} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} - {{ lookup('container_depends_on', application_id, extra={ - 'certs_generator': {'condition': 'service_completed_successfully'}, -}) | indent(4) }} + {{ lookup('container_depends_on', application_id, extra=certs_generator_dependency) | indent(4) }} {% set service_name = 'indexer' %} + {% set docker_compose_env = '' %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {{ lookup('container_image', application_id, 'indexer') }} {{ lookup('compose_only', 'container_name', WAZUH_INDEXER_CONTAINER) }} hostname: "{{ WAZUH_INDEXER_CONTAINER }}" + entrypoint: ["{{ WAZUH_INDEXER_ENTRYPOINT_TARGET }}"] + command: ["opensearchwrapper"] {{ lookup('container_ports', ['indexer', 'http', DOCKER_BIND_HOST]) | indent(4) }} environment: - "OPENSEARCH_JAVA_OPTS=-Xms{{ WAZUH_INDEXER_HEAP }} -Xmx{{ WAZUH_INDEXER_HEAP }}" ulimits: - memlock: - soft: -1 - hard: -1 nofile: - soft: 65536 - hard: 65536 + soft: {{ lookup('config', application_id, 'services.indexer.nofile') }} + hard: {{ lookup('config', application_id, 'services.indexer.nofile') }} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} - {{ lookup('container_depends_on', application_id, extra={ - 'certs_generator': {'condition': 'service_completed_successfully'}, -}) | indent(4) }} + {{ lookup('container_depends_on', application_id, extra=certs_generator_dependency) | indent(4) }} {{ lookup('container_healthcheck', service_name) | indent(4) }} {% set service_name = 'dashboard' %} + {% set docker_compose_env = WAZUH_DASHBOARD_ENV_FILE %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {{ lookup('container_image', application_id, 'console') }} {{ lookup('compose_only', 'container_name', WAZUH_DASHBOARD_CONTAINER) }} hostname: "{{ WAZUH_DASHBOARD_CONTAINER }}" {{ lookup('container_ports', ['console', 'http', DOCKER_BIND_HOST]) | indent(4) }} - environment: - - "INDEXER_USERNAME=admin" - - "INDEXER_PASSWORD={{ WAZUH_INDEXER_ADMIN_PASSWORD }}" - - "WAZUH_API_URL=https://{{ WAZUH_MANAGER_CONTAINER }}" - - "DASHBOARD_USERNAME=kibanaserver" - - "DASHBOARD_PASSWORD={{ WAZUH_DASHBOARD_SERVICE_PASSWORD }}" - - "API_USERNAME=wazuh-wui" - - "API_PASSWORD={{ WAZUH_WUI_PASSWORD }}" {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} {{ lookup('container_depends_on', application_id, extra={ diff --git a/roles/web-app-wazuh/templates/config.yml.j2 b/roles/web-app-wazuh/templates/config.yml.j2 index fa13ee829d..add5441494 100644 --- a/roles/web-app-wazuh/templates/config.yml.j2 +++ b/roles/web-app-wazuh/templates/config.yml.j2 @@ -47,7 +47,7 @@ config: - "{{ LDAP.SERVER.URI | regex_replace('^ldaps?://', '') }}" enable_ssl: "{{ LDAP.SERVER.SECURITY == 'ldaps' }}" enable_start_tls: "{{ LDAP.SERVER.SECURITY == 'starttls' }}" - verify_hostnames: false + verify_hostnames: true bind_dn: "{{ LDAP.DN.ADMINISTRATOR.DATA }}" password: "{{ LDAP.BIND_CREDENTIAL }}" userbase: "{{ LDAP.DN.OU.USERS }}" @@ -60,6 +60,6 @@ config: rolename: "cn" resolve_nested_roles: true skip_users: - - admin - - kibanaserver + - "{{ WAZUH_INDEXER_ADMIN_USERNAME }}" + - "{{ WAZUH_DASHBOARD_SERVICE_USERNAME }}" {% endif %} diff --git a/roles/web-app-wazuh/templates/dashboard.env.j2 b/roles/web-app-wazuh/templates/dashboard.env.j2 new file mode 100644 index 0000000000..8fdd534da3 --- /dev/null +++ b/roles/web-app-wazuh/templates/dashboard.env.j2 @@ -0,0 +1,7 @@ +API_PASSWORD={{ WAZUH_WUI_PASSWORD | dotenv_quote }} +API_USERNAME={{ WAZUH_WUI_USERNAME }} +DASHBOARD_PASSWORD={{ WAZUH_DASHBOARD_SERVICE_PASSWORD | dotenv_quote }} +DASHBOARD_USERNAME={{ WAZUH_DASHBOARD_SERVICE_USERNAME }} +INDEXER_PASSWORD={{ WAZUH_INDEXER_ADMIN_PASSWORD | dotenv_quote }} +INDEXER_USERNAME={{ WAZUH_INDEXER_ADMIN_USERNAME }} +WAZUH_API_URL=https://{{ WAZUH_MANAGER_CONTAINER }} diff --git a/roles/web-app-wazuh/templates/internal_users.yml.j2 b/roles/web-app-wazuh/templates/internal_users.yml.j2 index f3b71e5ef0..f0779f5367 100644 --- a/roles/web-app-wazuh/templates/internal_users.yml.j2 +++ b/roles/web-app-wazuh/templates/internal_users.yml.j2 @@ -3,14 +3,14 @@ _meta: type: "internalusers" config_version: 2 -admin: +"{{ WAZUH_INDEXER_ADMIN_USERNAME }}": hash: "{{ WAZUH_INDEXER_ADMIN_HASH }}" reserved: true backend_roles: - "admin" description: "Bootstrap/service account used by securityadmin.sh, health checks, and manager/dashboard INDEXER_PASSWORD." -kibanaserver: +"{{ WAZUH_DASHBOARD_SERVICE_USERNAME }}": hash: "{{ WAZUH_DASHBOARD_SERVICE_HASH }}" reserved: true description: "Service account wazuh.dashboard uses for its own backend calls to wazuh.indexer." diff --git a/roles/web-app-wazuh/templates/manager.env.j2 b/roles/web-app-wazuh/templates/manager.env.j2 new file mode 100644 index 0000000000..1caf080fac --- /dev/null +++ b/roles/web-app-wazuh/templates/manager.env.j2 @@ -0,0 +1,9 @@ +API_PASSWORD={{ WAZUH_WUI_PASSWORD | dotenv_quote }} +API_USERNAME={{ WAZUH_WUI_USERNAME }} +FILEBEAT_SSL_VERIFICATION_MODE=full +INDEXER_PASSWORD={{ WAZUH_INDEXER_ADMIN_PASSWORD | dotenv_quote }} +INDEXER_URL={{ WAZUH_INDEXER_URL }} +INDEXER_USERNAME={{ WAZUH_INDEXER_ADMIN_USERNAME }} +SSL_CERTIFICATE={{ lookup('volume', application_id, 'manager_filebeat_pem').target }} +SSL_CERTIFICATE_AUTHORITIES={{ lookup('volume', application_id, 'root_ca_manager_pem').target }} +SSL_KEY={{ lookup('volume', application_id, 'manager_filebeat_key_pem').target }} diff --git a/roles/web-app-wazuh/templates/opensearch_dashboards.yml.j2 b/roles/web-app-wazuh/templates/opensearch_dashboards.yml.j2 index 8e6b26c26e..f27fcc2fe0 100644 --- a/roles/web-app-wazuh/templates/opensearch_dashboards.yml.j2 +++ b/roles/web-app-wazuh/templates/opensearch_dashboards.yml.j2 @@ -1,7 +1,7 @@ server.host: 0.0.0.0 server.port: {{ WAZUH_DASHBOARD_INTERNAL_PORT }} server.ssl.enabled: false -opensearch.hosts: https://{{ WAZUH_INDEXER_CONTAINER }}:{{ WAZUH_INDEXER_INTERNAL_PORT }} +opensearch.hosts: {{ WAZUH_INDEXER_URL }} opensearch.ssl.verificationMode: certificate opensearch.ssl.certificateAuthorities: ["/usr/share/wazuh-dashboard/certs/root-ca.pem"] opensearch.requestHeadersWhitelist: ["securitytenant", "Authorization"] diff --git a/roles/web-app-wazuh/templates/playwright.env.j2 b/roles/web-app-wazuh/templates/playwright.env.j2 index ce247e4b9b..4e31495c87 100644 --- a/roles/web-app-wazuh/templates/playwright.env.j2 +++ b/roles/web-app-wazuh/templates/playwright.env.j2 @@ -31,6 +31,6 @@ RBAC_GROUP_PATH_PREFIX={{ ('/' ~ (RBAC.GROUP.NAME | trim('/')) ~ '/' ~ applicati SSO_SERVICE_ENABLED={{ WAZUH_OIDC_ENABLED | string | lower }} -SUPER_ADMIN_PASSWORD={{ lookup('config', 'web-app-keycloak', 'secrets.credentials.administrator_password') | dotenv_quote }} +SUPER_ADMIN_PASSWORD={{ (lookup('config', 'web-app-keycloak', 'secrets.credentials.administrator_password') | dotenv_quote) if (WAZUH_OIDC_ENABLED | bool) else '""' }} -SUPER_ADMIN_USERNAME={{ lookup('config', 'web-app-keycloak', 'services.keycloak.accounts.system.username') | dotenv_quote }} +SUPER_ADMIN_USERNAME={{ (lookup('config', 'web-app-keycloak', 'services.keycloak.accounts.system.username') | dotenv_quote) if (WAZUH_OIDC_ENABLED | bool) else '""' }} diff --git a/roles/web-app-wazuh/templates/roles_mapping.yml.j2 b/roles/web-app-wazuh/templates/roles_mapping.yml.j2 index 7c688ddb9b..984b5dcadd 100644 --- a/roles/web-app-wazuh/templates/roles_mapping.yml.j2 +++ b/roles/web-app-wazuh/templates/roles_mapping.yml.j2 @@ -31,4 +31,4 @@ kibana_read_only: kibana_server: reserved: false users: - - "kibanaserver" + - "{{ WAZUH_DASHBOARD_SERVICE_USERNAME }}" diff --git a/roles/web-app-wazuh/templates/wazuh.yml.j2 b/roles/web-app-wazuh/templates/wazuh.yml.j2 index 60ebf31f82..d2d9885325 100644 --- a/roles/web-app-wazuh/templates/wazuh.yml.j2 +++ b/roles/web-app-wazuh/templates/wazuh.yml.j2 @@ -2,6 +2,6 @@ hosts: - default: url: "https://{{ WAZUH_MANAGER_CONTAINER }}" port: {{ lookup('config', application_id, 'services.manager.ports.internal.api') }} - username: wazuh-wui + username: "{{ WAZUH_WUI_USERNAME }}" password: "{{ WAZUH_WUI_PASSWORD }}" run_as: true diff --git a/roles/web-app-wazuh/templates/wazuh_manager.conf.j2 b/roles/web-app-wazuh/templates/wazuh_manager.conf.j2 index 7cf05f3036..f450d5d9a1 100644 --- a/roles/web-app-wazuh/templates/wazuh_manager.conf.j2 +++ b/roles/web-app-wazuh/templates/wazuh_manager.conf.j2 @@ -88,7 +88,7 @@ yes - https://{{ WAZUH_INDEXER_CONTAINER }}:{{ WAZUH_INDEXER_INTERNAL_PORT }} + {{ WAZUH_INDEXER_URL }} diff --git a/roles/web-app-wazuh/vars/main.yml b/roles/web-app-wazuh/vars/main.yml index 1f12e07474..0aacb0c432 100644 --- a/roles/web-app-wazuh/vars/main.yml +++ b/roles/web-app-wazuh/vars/main.yml @@ -7,6 +7,7 @@ WAZUH_INDEXER_CONTAINER: "{{ lookup('config', application_id, 'services.indexer. WAZUH_INDEXER_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'indexer') }}" WAZUH_INDEXER_HTTP_PORT: "{{ lookup('config', application_id, 'services.indexer.ports.local.http') }}" WAZUH_INDEXER_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.indexer.ports.internal.http') }}" +WAZUH_INDEXER_URL: "https://{{ WAZUH_INDEXER_CONTAINER }}:{{ WAZUH_INDEXER_INTERNAL_PORT }}" WAZUH_INDEXER_HEAP: "{{ lookup('service_memory_mb', application_id, 'indexer', 0.5) }}m" WAZUH_DASHBOARD_CONTAINER: "{{ lookup('config', application_id, 'services.console.name') }}" @@ -14,10 +15,31 @@ WAZUH_DASHBOARD_HTTP_PORT: "{{ lookup('config', application_id, 'services.consol WAZUH_DASHBOARD_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.console.ports.internal.http') }}" WAZUH_CERTS_GENERATOR_CONTAINER: "{{ lookup('config', application_id, 'services.certs_generator.name') }}" +WAZUH_CERTS_GENERATOR_IMAGE: "{{ lookup('image', application_id, 'certs_generator', tag_only=True) }}" +WAZUH_CERTS_GENERATOR_MOUNTS: + - "type=bind,source={{ WAZUH_CERTS_CONFIG_HOST }},target={{ lookup('volume', application_id, 'certs_generator_config').target }},readonly" + - "type=bind,source={{ WAZUH_CERTS_ENTRYPOINT_HOST }},target={{ WAZUH_CERTS_ENTRYPOINT_TARGET }},readonly" + - "type=bind,source={{ WAZUH_CERTS_DIR_HOST }},target={{ lookup('volume', application_id, 'wazuh_certs_dir').target }}" +WAZUH_CERTS_TOOL_VERSION: "{{ lookup('config', application_id, 'services.manager.version') | regex_replace('^(\\d+\\.\\d+).*$', '\\1') }}" WAZUH_INSTANCE_DIR: "{{ lookup('container', application_id, 'directories.instance') }}" +WAZUH_MANAGER_ENV_FILE: "{{ [lookup('container', application_id, 'directories.env'), 'manager.env'] | path_join }}" +WAZUH_DASHBOARD_ENV_FILE: "{{ [lookup('container', application_id, 'directories.env'), 'dashboard.env'] | path_join }}" WAZUH_CERTS_DIR_HOST: "{{ [ WAZUH_INSTANCE_DIR, 'certs' ] | path_join }}" WAZUH_CERTS_CONFIG_HOST: "{{ [ WAZUH_INSTANCE_DIR, 'certs.yml' ] | path_join }}" +WAZUH_CERTS_ENTRYPOINT_HOST: "{{ [ WAZUH_INSTANCE_DIR, 'certs-entrypoint.sh' ] | path_join }}" +WAZUH_CERTS_ENTRYPOINT_TARGET: "{{ lookup('volume', application_id, 'certs_generator_entrypoint').target }}" +WAZUH_INDEXER_ENTRYPOINT_TARGET: "{{ lookup('volume', application_id, 'indexer_entrypoint').target }}" +WAZUH_CERTS_MARKER_HOST: "{{ [ WAZUH_INSTANCE_DIR, 'certs.complete' ] | path_join }}" +WAZUH_CERTS_REQUIRED_FILES: + - "{{ [ WAZUH_CERTS_DIR_HOST, 'root-ca.pem' ] | path_join }}" + - "{{ [ WAZUH_CERTS_DIR_HOST, 'root-ca-manager.pem' ] | path_join }}" + - "{{ [ WAZUH_CERTS_DIR_HOST, 'admin.pem' ] | path_join }}" + - "{{ [ WAZUH_CERTS_DIR_HOST, 'admin-key.pem' ] | path_join }}" + - "{{ [ WAZUH_CERTS_DIR_HOST, WAZUH_MANAGER_CONTAINER ~ '.pem' ] | path_join }}" + - "{{ [ WAZUH_CERTS_DIR_HOST, WAZUH_MANAGER_CONTAINER ~ '-key.pem' ] | path_join }}" + - "{{ [ WAZUH_CERTS_DIR_HOST, WAZUH_INDEXER_CONTAINER ~ '.pem' ] | path_join }}" + - "{{ [ WAZUH_CERTS_DIR_HOST, WAZUH_INDEXER_CONTAINER ~ '-key.pem' ] | path_join }}" WAZUH_INDEXER_CERTS_DIR_CONTAINER: "/usr/share/wazuh-indexer/config/certs" # nocheck: container-var-name-lookup in-container path, not a container name WAZUH_INDEXER_SECURITY_DIR_CONTAINER: "/usr/share/wazuh-indexer/config/opensearch-security" # nocheck: container-var-name-lookup in-container path, not a container name @@ -29,12 +51,15 @@ WAZUH_INDEXER_INTERNAL_API_URL: "https://{{ DOCKER_REACH_HOST }}:{{ WAZUH_INDEXE WAZUH_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') | bool }}" WAZUH_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enabled') | bool }}" +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 }}" +WAZUH_INDEXER_ADMIN_HASH: "{{ WAZUH_INDEXER_ADMIN_PASSWORD | bcrypt_hash(application_id ~ ':indexer-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 }}" +WAZUH_DASHBOARD_SERVICE_HASH: "{{ WAZUH_DASHBOARD_SERVICE_PASSWORD | bcrypt_hash(application_id ~ ':dashboard-service') }}" +WAZUH_WUI_USERNAME: "{{ lookup('users', 'web-app-wazuh-api').username }}" WAZUH_WUI_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.wazuh_wui_password') }}" WAZUH_CLUSTER_KEY: "{{ lookup('config', application_id, 'secrets.credentials.manager_cluster_key') }}" @@ -46,6 +71,3 @@ WAZUH_RBAC_READONLY_GROUP: "/{{ lookup('rbac_group_path', application_id=applica WAZUH_RBAC_ADMIN_LDAP_CN: "{{ application_id }}-administrator" WAZUH_RBAC_ANALYST_LDAP_CN: "{{ application_id }}-security-analyst" WAZUH_RBAC_READONLY_LDAP_CN: "{{ application_id }}-readonly-auditor" - -test_e2e_playwright_wait_retries: 120 -test_e2e_playwright_wait_delay: 5 diff --git a/tests/unit/python/plugins/filter/test_bcrypt_hash.py b/tests/unit/python/plugins/filter/test_bcrypt_hash.py index 8732d95e14..de6de1ae67 100644 --- a/tests/unit/python/plugins/filter/test_bcrypt_hash.py +++ b/tests/unit/python/plugins/filter/test_bcrypt_hash.py @@ -35,6 +35,56 @@ class TestBcryptHash(unittest.TestCase): bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8")) ) + def test_72_byte_password_hashes_successfully(self): + password = "A" * 72 + hashed = self.f(password) + self.assertTrue( + bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8")) + ) + + def test_73_byte_password_raises(self): + with self.assertRaisesRegex(ValueError, "73 bytes.*at most 72 bytes"): + self.f("A" * 73) + + def test_multibyte_password_over_72_bytes_raises(self): + password = "รค" * 37 + self.assertEqual(len(password), 37) + with self.assertRaisesRegex(ValueError, "74 bytes"): + self.f(password) + + def test_same_secret_and_seed_give_the_same_hash(self): + self.assertEqual( + self.f("same-password", "app:indexer-admin"), + self.f("same-password", "app:indexer-admin"), + ) + + def test_different_seed_gives_a_different_hash(self): + self.assertNotEqual( + self.f("same-password", "app:indexer-admin"), + self.f("same-password", "app:dashboard-service"), + ) + + def test_different_secret_gives_a_different_hash(self): + self.assertNotEqual( + self.f("password-one", "app:indexer-admin"), + self.f("password-two", "app:indexer-admin"), + ) + + def test_seeded_hash_verifies_against_the_original_password(self): + password = "correct horse battery staple" + hashed = self.f(password, "app:indexer-admin") + self.assertTrue( + bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8")) + ) + self.assertTrue(hashed.startswith("$2b$12$")) + + def test_no_seed_stays_randomized(self): + self.assertNotEqual(self.f("same-password"), self.f("same-password")) + + def test_empty_seed_raises(self): + with self.assertRaises(ValueError): + self.f("some-password", "") + def test_none_raises(self): with self.assertRaises(ValueError): self.f(None)