main
py 294 lines 9.11 KB
Raw
1 from pathlib import Path
2 from typing import List
3
4 from loguru import logger
5
6 from app.connectors.wazuh_manager.utils.universal import (
7 send_delete_request as send_wazuh_delete_request,
8 )
9 from app.connectors.wazuh_manager.utils.universal import (
10 send_get_request as send_wazuh_get_request,
11 )
12 from app.connectors.wazuh_manager.utils.universal import (
13 send_post_request as send_wazuh_post_request,
14 )
15 from app.connectors.wazuh_manager.utils.universal import (
16 send_put_request as send_wazuh_put_request,
17 )
18 from app.customer_provisioning.schema.provision import ProvisionNewCustomer
19 from app.customer_provisioning.schema.wazuh_manager import WazuhAgentsTemplatePaths
20
21
22 ######### ! WAZUH MANAGER PROVISIONING ! ############
23 # Function to generate group codes
24 def generate_group_code(group, customer_code):
25 """
26 Generates a group code by combining the group name and customer code.
27
28 Args:
29 group (str): The name of the group.
30 customer_code (str): The customer code.
31
32 Returns:
33 str: The generated group code.
34 """
35 return f"{group}_{customer_code}"
36
37
38 # Separate function for sending POST requests to Wazuh
39 async def create_wazuh_group(group_code):
40 """
41 Create a Wazuh group with the given group code.
42
43 Args:
44 group_code (str): The code for the group.
45
46 Returns:
47 dict: The response from the Wazuh API.
48
49 """
50 endpoint = "/groups"
51 data = {"group_id": group_code}
52 return await send_wazuh_post_request(endpoint=endpoint, data=data)
53
54
55 # Main function to create Wazuh groups
56 async def create_wazuh_groups(request: ProvisionNewCustomer):
57 """
58 Create Wazuh groups for a customer.
59
60 Args:
61 request (ProvisionNewCustomer): The request object containing customer information.
62
63 Returns:
64 None
65 """
66 logger.info(
67 f"Creating Wazuh groups for customer {request.customer_name} with code {request.customer_code}",
68 )
69
70 wazuh_groups = [
71 "Linux",
72 "Windows",
73 "Mac",
74 ] # This list can be moved to a config file or a global variable
75
76 for group in wazuh_groups:
77 group_code = generate_group_code(group, request.customer_code)
78 logger.info(f"Creating group with code {group_code}")
79 try:
80 response = await create_wazuh_group(group_code)
81 logger.info(f"Response for {group_code}: {response}")
82 except Exception as e:
83 logger.error(f"Error creating group {group_code}: {e}")
84
85
86 # Function to get the template file path
87 def get_template_path(template_info: WazuhAgentsTemplatePaths) -> Path:
88 """
89 Get the path to the template file based on the provided template_info.
90
91 Args:
92 template_info (WazuhAgentsTemplatePaths): The template information.
93
94 Returns:
95 Path: The path to the template file.
96 """
97 folder_name, file_name = template_info.value
98 current_file = Path(__file__) # Path to the current file
99 base_dir = current_file.parent.parent # Move up two levels to the base directory
100 return base_dir / folder_name / file_name
101
102
103 # Function to update Wazuh group configuration
104 async def configure_wazuh_group(group_code, template_path, request: ProvisionNewCustomer):
105 """
106 Configures a Wazuh group with the provided group code and template file.
107
108 Args:
109 group_code (str): The code of the Wazuh group to configure.
110 template_path (str): The path to the template file.
111
112 Returns:
113 dict: The response from the API request to update the group configuration.
114 """
115 logger.info(f"Configuring Wazuh group {group_code}")
116
117 # Read the contents of the template file
118 with open(template_path, "r") as template_file:
119 config_template = template_file.read()
120
121 # Replace placeholder with the customer code
122 group_config = config_template.replace("REPLACE", group_code.split("_")[-1])
123 # Replace placeholder with the cluster name, use default if None
124 cluster_name = request.wazuh_cluster_name if request.wazuh_cluster_name else "YOUR_PATH"
125 group_config = group_config.replace("CLUSTER_NAME", cluster_name)
126
127 # Make the API request to update the group configuration
128 return await send_wazuh_put_request(
129 endpoint=f"/groups/{group_code}/configuration",
130 data=group_config,
131 xml_data=True,
132 )
133
134
135 # Function to apply configurations for all groups
136 async def apply_group_configurations(request: ProvisionNewCustomer):
137 """
138 Apply configurations for Wazuh groups for a new customer.
139
140 Args:
141 request (ProvisionNewCustomer): The request object containing customer information.
142
143 Returns:
144 None
145
146 Raises:
147 Exception: If there is an error configuring a group.
148
149 """
150 logger.info(
151 f"Applying configurations for Wazuh groups for customer {request.customer_name} with code {request.customer_code}",
152 )
153
154 group_templates = {
155 "Linux": WazuhAgentsTemplatePaths.LINUX_AGENT,
156 "Windows": WazuhAgentsTemplatePaths.WINDOWS_AGENT,
157 "Mac": WazuhAgentsTemplatePaths.MAC_AGENT,
158 }
159
160 for group, template in group_templates.items():
161 group_code = f"{group}_{request.customer_code}"
162 template_path = get_template_path(template)
163 try:
164 await configure_wazuh_group(group_code, template_path, request)
165 except Exception as e:
166 logger.error(f"Error configuring group {group_code}: {e}")
167
168
169 ######### ! WAZUH MANAGER DECOMISSIONING ! ############
170
171
172 async def get_agent_ids(group_code: str) -> List[str]:
173 """
174 Retrieves the agent IDs for a given group code.
175
176 Args:
177 group_code (str): The group code for which to retrieve the agent IDs.
178
179 Returns:
180 List[str]: A list of agent IDs.
181
182 """
183 try:
184 response = await send_wazuh_get_request(
185 endpoint="/agents",
186 params={"group": group_code},
187 )
188 logger.info(f"Response for {group_code}: {response}")
189
190 # Extracting agents from the nested response
191 agents_data = response.get("data", {}).get("data", {}).get("affected_items", [])
192
193 agent_ids = [agent.get("id") for agent in agents_data]
194 return agent_ids
195 except Exception as e:
196 logger.error(f"Error getting agents for group {group_code}: {e}")
197 return []
198
199
200 async def gather_wazuh_agents(customer_meta_wazuh_group: str):
201 """
202 Gather the Wazuh agents for a given customer meta Wazuh group.
203
204 Args:
205 customer_meta_wazuh_group (str): The customer meta Wazuh group.
206
207 Returns:
208 list: A list of agent IDs for the Wazuh agents.
209 """
210 # Append the Group Templates from the WazuhAgentsTemplatePaths Enum
211 wazuh_groups = ["Linux", "Windows", "Mac"]
212
213 # Initialize an empty list to store the agents
214 agents = []
215
216 # Loop through the groups and get the agent IDs for each group and append them to the list
217 for group in wazuh_groups:
218 group_code = generate_group_code(group, customer_meta_wazuh_group)
219 logger.info(f"Getting agents for group {group_code}")
220 agent_ids = await get_agent_ids(group_code)
221 agents.extend(agent_ids)
222
223 return agents
224
225
226 async def delete_wazuh_agents(agent_ids: List[str]):
227 """
228 Delete Wazuh agents.
229
230 Args:
231 agent_ids (List[str]): List of agent IDs to be deleted.
232
233 Returns:
234 List[str]: List of agent IDs that were successfully deleted.
235 """
236 # Initialize an empty list to store the agents
237 agents = []
238
239 # Loop through the groups and get the agent IDs for each group and append them to the list
240 for agent_id in agent_ids:
241 logger.info(f"Deleting agent {agent_id}")
242 try:
243 response = await send_wazuh_delete_request(
244 endpoint="/agents",
245 params={
246 "older_than": "0s",
247 "agents_list": agent_id,
248 "status": "all",
249 },
250 )
251 logger.info(f"Response for {agent_id}: {response}")
252 except Exception as e:
253 logger.error(f"Error deleting agent {agent_id}: {e}")
254 continue
255
256 agents.append(agent_id)
257
258 return agents
259
260
261 async def delete_wazuh_groups(customer_meta_wazuh_group: str):
262 """
263 Deletes Wazuh groups for a given customer.
264
265 Args:
266 customer_meta_wazuh_group (str): The customer's Wazuh group.
267
268 Returns:
269 list: A list of group codes that were successfully deleted.
270 """
271 wazuh_groups = ["Linux", "Windows", "Mac"]
272
273 # Initialize an empty list to store the groups deleted
274 groups_deleted = []
275
276 # Loop through the groups and get the agent IDs for each group and append them to the list
277 for group in wazuh_groups:
278 group_code = generate_group_code(group, customer_meta_wazuh_group)
279 logger.info(f"Deleting group {group_code}")
280 try:
281 response = await send_wazuh_delete_request(
282 endpoint="/groups",
283 params={
284 "groups_list": group_code,
285 },
286 )
287 logger.info(f"Response for {group_code}: {response}")
288 except Exception as e:
289 logger.error(f"Error deleting group {group_code}: {e}")
290 continue
291
292 groups_deleted.append(group_code)
293
294 return groups_deleted