#!/usr/bin/env bash
#
# Firewall starting point for an all-in-one Wazuh 5.0 host on Ubuntu.
# Ports are taken from the Wazuh 5.0 architecture reference:
# https://documentation.wazuh.com/5.0-beta/getting-started/architecture.html
#
# EDIT THE THREE RANGES BELOW BEFORE RUNNING. Nothing here should be
# exposed to 0.0.0.0/0. Run as root.

set -euo pipefail

# Where analysts browse from.
ADMIN_CIDR="203.0.113.0/24"

# Where agents live.
AGENT_CIDR="198.51.100.0/24"

# Where automation calls the manager API from.
AUTOMATION_CIDR="203.0.113.10/32"

# Set to "yes" only if you are keeping Wazuh 4.x agents on the legacy channel.
# Verified on 5.0.0-beta5: the shipped wazuh-manager.conf already contains an
# enabled <remote><legacy> block, so the manager IS listening on 1514 and 1515
# whether you want it to or not. Leaving this at "no" firewalls them off; to
# stop the listeners entirely, remove the <legacy> block and restart.
KEEP_LEGACY_AGENTS="no"

ufw --force reset
ufw default deny incoming
ufw default allow outgoing

# Keep your own SSH access before anything else.
ufw allow from "${ADMIN_CIDR}" to any port 22 proto tcp comment 'ssh admin'

# Dashboard.
ufw allow from "${ADMIN_CIDR}" to any port 443 proto tcp comment 'wazuh dashboard'

# Wazuh 5.x agents: enrolment, events, state sync, control, downloads.
ufw allow from "${AGENT_CIDR}" to any port 1517 proto tcp comment 'wazuh agents https'

# Manager API.
ufw allow from "${AUTOMATION_CIDR}" to any port 55000 proto tcp comment 'wazuh manager api'

# Legacy 4.x agent channel and enrolment service. The manager listens on both
# by default; these rules decide who can reach them.
if [ "${KEEP_LEGACY_AGENTS}" = "yes" ]; then
  ufw allow from "${AGENT_CIDR}" to any port 1514 proto tcp comment 'wazuh 4.x agents'
  ufw allow from "${AGENT_CIDR}" to any port 1515 proto tcp comment 'wazuh 4.x enrolment'
fi

# Deliberately NOT opened:
#   9200/TCP      indexer API        - loopback and cluster peers only
#   9300-9400/TCP indexer cluster    - only needed between indexer nodes
#   1516/TCP      manager cluster    - only needed between manager nodes

ufw --force enable
ufw status verbose
