Brak opisu

wazuh.py 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. from typing import Any
  2. import httpx
  3. class WazuhAdapter:
  4. def __init__(
  5. self,
  6. base_url: str,
  7. username: str,
  8. password: str,
  9. indexer_url: str | None = None,
  10. indexer_username: str | None = None,
  11. indexer_password: str | None = None,
  12. ) -> None:
  13. self.base_url = base_url.rstrip("/")
  14. self.username = username
  15. self.password = password
  16. self.indexer_url = (indexer_url or "").rstrip("/")
  17. self.indexer_username = indexer_username
  18. self.indexer_password = indexer_password
  19. async def _authenticate(self, client: httpx.AsyncClient) -> str:
  20. auth_url = f"{self.base_url}/security/user/authenticate?raw=true"
  21. response = await client.post(auth_url, auth=(self.username, self.password))
  22. response.raise_for_status()
  23. token = response.text.strip()
  24. if not token:
  25. raise RuntimeError("Wazuh authentication returned an empty token.")
  26. return token
  27. async def _get_with_bearer(
  28. self,
  29. client: httpx.AsyncClient,
  30. token: str,
  31. path: str,
  32. params: dict[str, Any] | None = None,
  33. ) -> dict[str, Any]:
  34. url = f"{self.base_url}{path}"
  35. response = await client.get(
  36. url,
  37. headers={"Authorization": f"Bearer {token}"},
  38. params=params,
  39. )
  40. response.raise_for_status()
  41. return response.json() if response.content else {"status_code": response.status_code}
  42. async def auth_test(self) -> dict[str, Any]:
  43. async with httpx.AsyncClient(verify=False, timeout=15.0) as client:
  44. token = await self._authenticate(client)
  45. return {"authenticated": True, "token_prefix": token[:12]}
  46. async def get_version(self) -> dict[str, Any]:
  47. async with httpx.AsyncClient(verify=False, timeout=15.0) as client:
  48. token = await self._authenticate(client)
  49. # API root should return API metadata when authenticated.
  50. try:
  51. return await self._get_with_bearer(client, token, "/")
  52. except httpx.HTTPStatusError:
  53. # Fallback endpoint for environments restricting root access.
  54. return await self._get_with_bearer(client, token, "/manager/info")
  55. async def get_manager_info(self) -> dict[str, Any]:
  56. async with httpx.AsyncClient(verify=False, timeout=15.0) as client:
  57. token = await self._authenticate(client)
  58. return await self._get_with_bearer(client, token, "/manager/info")
  59. async def list_agents(
  60. self, limit: int = 50, offset: int = 0, select: str | None = None
  61. ) -> dict[str, Any]:
  62. params: dict[str, Any] = {"limit": limit, "offset": offset}
  63. if select:
  64. params["select"] = select
  65. async with httpx.AsyncClient(verify=False, timeout=20.0) as client:
  66. token = await self._authenticate(client)
  67. return await self._get_with_bearer(client, token, "/agents", params=params)
  68. async def list_manager_logs(
  69. self,
  70. limit: int = 50,
  71. offset: int = 0,
  72. q: str | None = None,
  73. sort: str | None = None,
  74. ) -> dict[str, Any]:
  75. params: dict[str, Any] = {"limit": limit, "offset": offset}
  76. if q:
  77. params["q"] = q
  78. if sort:
  79. params["sort"] = sort
  80. async with httpx.AsyncClient(verify=False, timeout=20.0) as client:
  81. token = await self._authenticate(client)
  82. return await self._get_with_bearer(client, token, "/manager/logs", params=params)
  83. async def search_alerts(
  84. self,
  85. query: str,
  86. limit: int = 50,
  87. minutes: int = 120,
  88. ) -> dict[str, Any]:
  89. if not self.indexer_url:
  90. raise RuntimeError("Wazuh indexer URL is not configured.")
  91. body: dict[str, Any] = {
  92. "size": limit,
  93. "sort": [{"@timestamp": {"order": "desc"}}],
  94. "query": {
  95. "bool": {
  96. "must": [{"query_string": {"query": query}}],
  97. "filter": [
  98. {
  99. "range": {
  100. "@timestamp": {
  101. "gte": f"now-{minutes}m",
  102. "lte": "now",
  103. }
  104. }
  105. }
  106. ],
  107. }
  108. },
  109. }
  110. async with httpx.AsyncClient(
  111. verify=False,
  112. timeout=20.0,
  113. auth=(self.indexer_username, self.indexer_password),
  114. ) as client:
  115. response = await client.post(f"{self.indexer_url}/wazuh-alerts-*/_search", json=body)
  116. response.raise_for_status()
  117. return response.json()