Back to Wazuh

Architecture

docs/ref/modules/server-api/architecture.md

4.14.49.7 KB
Original Source

Architecture

The Wazuh Server API is a layered system where an HTTP server delegates to a Python framework, which in turn communicates with internal daemons and databases through Unix sockets.


System Architecture Overview

mermaid
graph TD
    A["Client (curl / SDK / Dashboard)"] --> B["Wazuh Server API (REST, JWT, RBAC)"]
    B --> C["Wazuh Python Framework"]
    C --> D["Core Logic Layer"]
    
    D --> E["Unix sockets (daemons)"]
    D --> F["Wazuh Database (WDB)"]
    D --> G["Configuration files"]
    D --> H["Internal queues"]

    style A fill:#f9f,stroke:#333,stroke-width:2px,color:#fff
    style B fill:#bbf,stroke:#333,stroke-width:2px,color:#fff
    style C fill:#baf,stroke:#333,stroke-width:2px,color:#fff
    style D fill:#1ad,stroke:#333,stroke-width:2px,color:#fff
    style E fill:#666,stroke:#333,color:#fff
    style F fill:#666,stroke:#333,color:#fff
    style G fill:#666,stroke:#333,color:#fff
    style H fill:#666,stroke:#333,color:#fff

Directory Structure

API Interface Layer

wazuh/framework/wazuh/

This layer:

  • Exposes API-facing functions
  • Validates input
  • Enforces RBAC
  • Formats responses

It must not contain business logic.

ModuleResponsibilityMain Endpoints
agent.pyAgent lifecycle and queries/agents
manager.pyManager status and configuration/manager
cluster.pyCluster operations/cluster
syscheck.pyFile Integrity Monitoring/syscheck
rootcheck.pyPolicy and rootcheck/rootcheck
security.pyAuthentication and users/security
rbac/Authorization logic/security/*
mitre.pyMITRE ATT&CK mappings/mitre
stats.pyManager statistics/manager/stats
task.pyAsync task handling/tasks

Core Logic Layer

wazuh/framework/wazuh/core/

This layer contains all real logic. It is API-agnostic and can be reused internally.

ComponentDescription
agent.py, manager.py, etc.Business logic implementation
common.pyGlobal constants, paths, context variables, and utility functions
results.pyStandardized result model (WazuhResult, AffectedItemsWazuhResult)
InputValidator.pyRegex-based input validation (names, lengths)
utils.pyGeneral utilities (caching, process management, helpers)
wazuh_socket.pyIPC with Wazuh daemons via Unix sockets
wazuh_queue.pyInternal async messaging
wdb.pyAsync interface to Wazuh DB (length-prefixed Unix socket protocol)
wdb_http.pyHTTP-based alternative WDB client (via aiohttp)
configuration.pyParse ossec.conf and related files
exception.pyCustom exception hierarchy and error code catalog
wlogging.pyCustom log rotation with gzip compression
pyDaemonModule.pyUNIX daemonization (double-fork pattern)
stats.pyStatistics processing logic
cluster/Cluster architecture (master, worker, DAPI, HAProxy helper)
indexer/Wazuh Indexer integration (credentials, disconnected agents)

API Server Layer

wazuh/api/api/

This layer implements the HTTP server that exposes the REST API.

ComponentDescription
controllers/Route handlers (one per resource: agent, cluster, security, etc.)
authentication.pyJWT token generation and validation using EC keys (PyJWT)
middlewares.pyRequest/response pipeline (security headers, rate limiting, access logging)
error_handler.pyCentralized error handling and brute-force protection
validator.pyComprehensive regex-based validation for all API input parameters
signals.pyAPI lifecycle events and background tasks (key generation, CTI updates)
constants.pyAPI filesystem paths (/api/configuration, /api/security, etc.)
encoder.pyCustom JSON serialization
uri_parser.pyURI parsing utilities
alogging.pyAsync-aware API logging
spec/spec.yamlOpenAPI 3.0 specification (defines all endpoints, schemas, parameters)
configuration/API configuration management
models/Data models for request/response objects

Controllers

Each controller wraps framework calls in the DAPI (Distributed API) layer to transparently route requests across cluster nodes.

ControllerResponsibility
agent_controller.pyAgent CRUD and lifecycle
cluster_controller.pyCluster node operations
security_controller.pyUsers, roles, policies, RBAC
active_response_controller.pyTrigger active response commands
syscheck_controller.pyFIM operations
rootcheck_controller.pyRootcheck/SCA results
mitre_controller.pyMITRE ATT&CK mappings
task_controller.pyAsync task queries
overview_controller.pyAgent overview/summary
default_controller.pyBasic API info (version, hostname, timestamp)

RBAC Sub-module

wazuh/framework/wazuh/rbac/

FileResponsibility
decorators.pyexpose_resources decorator that enforces action/resource permissions
orm.pyORM models for roles, policies, and user-role mappings
preprocessor.pyResource preprocessing before permission checks
default_resources.pyBuilt-in default RBAC resource definitions
auth_context.pyAuthentication context handling

Cluster Sub-module

wazuh/framework/wazuh/core/cluster/

FileResponsibility
dapi/Distributed API — routes requests to the correct cluster node
master.pyMaster node logic
worker.pyWorker node logic
client.pyWorker → master communication
server.pyCluster server
local_client.pyLocal cluster client
local_server.pyLocal cluster server
control.pyCluster control operations
cluster.pyCore cluster logic
common.pyCluster-specific shared utilities
config.pyCluster configuration schema
utils.pyCluster utilities (get_cluster_items, etc.)
hap_helper/HAProxy integration for load balancing

Indexer Sub-module

wazuh/framework/wazuh/core/indexer/

FileResponsibility
indexer.pyMain Wazuh Indexer client
credential_manager.pyIndexer credential management
disconnected_agents.pyHandling disconnected agents in the indexer
max_version_components.pyVersion component handling

Execution Flow

Example: GET /agents?status=active

  1. HTTP request reaches the Server API (Starlette/Connexion)
  2. Middlewares process the request (security headers, rate limiting, access logging)
  3. JWT token is validated via authentication.py
  4. Input parameters are validated via validator.py (regex-based)
  5. Request is routed to the controller (agent_controller.py)
  6. Controller wraps the call in the DAPI layer for cluster routing
  7. DAPI determines the target node (local_master, local_any, etc.)
  8. Framework function (wazuh/agent.py) is invoked
  9. RBAC permissions are checked via expose_resources decorator
  10. Core logic (core/agent.py) is executed
  11. Data is fetched from:
    • WDB (via Unix socket or HTTP)
    • Manager daemon (via Unix socket)
    • Filesystem
  12. Result is wrapped in AffectedItemsWazuhResult or WazuhResult
  13. Result is serialized to JSON and returned

Distributed API (DAPI)

In cluster deployments, not all requests can be handled by the node receiving them.

The DAPI layer (core/cluster/dapi/) transparently routes requests:

Routing ModeDescription
local_masterMust execute on the master node
local_anyCan execute on any node
distributed_masterMaster distributes to relevant worker nodes
mermaid
graph LR
    A["Client"] --> B["API Node"]
    B --> C{"DAPI"}
    C -->|local_master| D["Master Node"]
    C -->|local_any| E["Current Node"]
    C -->|distributed| F["Worker Node(s)"]

Result Model

All framework functions return standardized result objects defined in core/results.py:

ClassDescription
WazuhResultBase dict-like result wrapper
AffectedItemsWazuhResultTracks affected/failed items with error details

Results support:

  • Merge operations (| operator) for combining results across cluster nodes
  • Iteration, length, and containment checks
  • Pagination metadata

Socket Communication Protocol

The framework communicates with Wazuh daemons via Unix domain sockets using a length-prefixed protocol.

Protocol Details

  • Messages use a 4-byte little-endian header indicating the payload length
  • The same framing is used for both sending and receiving
  • WazuhAsyncSocket (in core/wdb.py) handles async socket connections

Key Socket Paths

SocketDaemonPurpose
wdbwazuh-dbDatabase queries
queue/sockets/queueanalysisdEvent ingestion
queue/sockets/authauthdAgent registration
queue/sockets/remoteremotedAgent communication
queue/sockets/requestvariousInternal requests

Logging Architecture

Custom Log Rotation (core/wlogging.py)

  • The CustomFileRotatingHandler class extends Python's logging to:
    • Rotate log files when they reach a size threshold
    • Compress rotated files with gzip
    • Set file permissions to 0o640
    • Store rotated logs in a dedicated directory

API Access Logging (api/alogging.py)

  • Every API request generates an access log entry
  • Passwords and sensitive data are sanitized from query strings and request bodies before logging