-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
configuration.py
executable file
·1356 lines (1121 loc) · 42.9 KB
/
configuration.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2015, Wazuh Inc.
# Created by Wazuh, Inc. <info@wazuh.com>.
# This program is free software; you can redistribute it and/or modify it under the terms of GPLv2
import json
import logging
import os
import re
import subprocess
import sys
import tempfile
from configparser import RawConfigParser, NoOptionError
from io import StringIO
from os import remove, path as os_path
from types import MappingProxyType
from typing import Union, List
from defusedxml.ElementTree import tostring
from defusedxml.minidom import parseString
from wazuh.core import common
from wazuh.core import wazuh_socket
from wazuh.core.exception import WazuhInternalError, WazuhError
from wazuh.core.exception import WazuhResourceNotFound
from wazuh.core.utils import cut_array, load_wazuh_xml, safe_move
logger = logging.getLogger('wazuh')
# Aux functions
# Type of configuration sections:
# * Duplicate -> there can be multiple independent sections. Must be returned as multiple json entries.
# * Merge -> there can be multiple sections but all are dependent with each other. Must be returned as a single json
# entry.
# * Last -> there can be multiple sections in the configuration but only the last one will be returned.
# The rest are ignored.
CONF_SECTIONS = MappingProxyType({
'active-response': {'type': 'duplicate', 'list_options': []},
'command': {'type': 'duplicate', 'list_options': []},
'agentless': {'type': 'duplicate', 'list_options': []},
'localfile': {'type': 'duplicate', 'list_options': ["ignore"]},
'remote': {'type': 'duplicate', 'list_options': []},
'syslog_output': {'type': 'duplicate', 'list_options': []},
'integration': {'type': 'duplicate', 'list_options': []},
'alerts': {'type': 'merge', 'list_options': []},
'client': {'type': 'merge', 'list_options': []},
'database_output': {'type': 'merge', 'list_options': []},
'email_alerts': {
'type': 'merge',
'list_options': ['email_to']
},
'reports': {
'type': 'merge',
'list_options': ['email_to']
},
'global': {
'type': 'merge',
'list_options': ['white_list']
},
'open-scap': {
'type': 'merge',
'list_options': ['content']
},
'cis-cat': {
'type': 'merge',
'list_options': ['content']
},
'syscollector': {
'type': 'merge',
'list_options': []
},
'rootcheck': {
'type': 'merge',
'list_options': ['rootkit_files', 'rootkit_trojans', 'windows_audit', 'system_audit', 'windows_apps',
'windows_malware']
},
'ruleset': {
'type': 'merge',
'list_options': ['include', 'rule', 'rule_dir', 'decoder', 'decoder_dir', 'list', 'rule_exclude',
'decoder_exclude']
},
'syscheck': {
'type': 'merge',
'list_options': ['directories', 'ignore', 'nodiff']
},
'auth': {
'type': 'merge',
'list_options': []
},
'cluster': {
'type': 'last',
'list_options': ['nodes']
},
'osquery': {
'type': 'merge',
'list_options': ['pack']
},
'labels': {
'type': 'duplicate',
'list_options': ['label']
},
'sca': {
'type': 'merge',
'list_options': ['policies']
},
'vulnerability-detection': {
'type': 'last',
'list_options': []
},
'indexer': {
'type': 'last',
'list_options': ['hosts']
}
})
GETCONFIG_COMMAND = "getconfig"
UPDATE_CHECK_OSSEC_FIELD = 'update_check'
GLOBAL_KEY = 'global'
YES_VALUE = 'yes'
CTI_URL_FIELD = 'cti-url'
DEFAULT_CTI_URL = 'https://cti.wazuh.com'
def _insert(json_dst: dict, section_name: str, option: str, value: str):
"""Insert element (option:value) in a section (json_dst) called section_name.
Parameters
----------
json_dst : dict
Destination.
section_name : str
Name of the section.
option : str
Option to be updated or added.
value : str
Value of the option to be updated / added.
"""
if not value:
return
if option in json_dst:
if type(json_dst[option]) is list:
json_dst[option].append(value) # Append new values
else:
json_dst[option] = value # Update values
else:
if option in CONF_SECTIONS.get(section_name, {}).get('list_options', []):
json_dst[option] = [value] # Create as list
else:
json_dst[option] = value # Update values
def _insert_section(json_dst: dict, section_name: str, section_data: dict):
"""Insert a new section (section_data) called section_name in json_dst.
Parameters
----------
json_dst : dict
Destination.
section_name : str
Name of the section.
section_data : dict
Section be added.
"""
if CONF_SECTIONS.get(section_name, {}).get('type') == 'duplicate':
if section_name in json_dst:
json_dst[section_name].append(section_data) # Append new values
else:
json_dst[section_name] = [section_data] # Create as list
elif CONF_SECTIONS.get(section_name, {}).get('type') == 'merge':
if section_name in json_dst:
for option in section_data:
if option in json_dst[section_name] and option in CONF_SECTIONS[section_name].get('list_options', []):
json_dst[section_name][option].extend(section_data[option]) # Append new values
else:
json_dst[section_name][option] = section_data[option] # Update values
else:
json_dst[section_name] = section_data # Create
elif CONF_SECTIONS.get(section_name, {}).get('type') == 'last':
if section_name in json_dst:
# if the option already exists it is overwritten. But a warning is shown.
logger.warning(f'There are multiple {section_name} sections in configuration. Using only last section.')
json_dst[section_name] = section_data # Create
def _read_option(section_name: str, opt: str) -> tuple:
"""Read an option (inside a section) and returns the name and the value.
Parameters
----------
section_name : str
Name of the section to be read.
opt : str
Option to be read.
Returns
-------
tuple
Name and value of the option.
"""
opt_name = opt.tag.lower()
if section_name == 'open-scap':
if opt.attrib:
opt_value = {}
for a in opt.attrib:
opt_value[a] = opt.attrib[a]
# profiles
profiles_list = []
for profiles in opt.iter():
profiles_list.append(profiles.text)
if profiles_list:
opt_value['profiles'] = profiles_list
else:
opt_value = opt.text
elif section_name == 'syscheck' and opt_name == 'directories':
opt_value = []
json_attribs = {}
for a in opt.attrib:
json_attribs[a] = opt.attrib[a]
if opt.text:
for path in opt.text.split(','):
json_path = json_attribs.copy()
json_path['path'] = path.strip()
opt_value.append(json_path)
elif section_name == 'syscheck' and opt_name in ('synchronization', 'whodata'):
opt_value = {}
for child in opt:
child_section, child_config = _read_option(child.tag.lower(), child)
opt_value[child_section] = child_config.split(',') if child_config.find(',') > 0 else child_config
elif (section_name == 'cluster' and opt_name == 'nodes') or \
(section_name == 'sca' and opt_name == 'policies') or \
(section_name == 'indexer' and opt_name == 'hosts') :
opt_value = [child.text for child in opt]
elif section_name == 'labels' and opt_name == 'label':
opt_value = {'value': opt.text}
for a in opt.attrib:
opt_value[a] = opt.attrib[a]
elif section_name == 'localfile' and opt_name == 'query':
# Remove new lines, empty spaces and backslashes
regex = rf'<{opt_name}>(.*)</{opt_name}>'
opt_value = re.match(regex,
re.sub('(?:(\n) +)', '',
tostring(opt, encoding='unicode').replace('\\<', '<').replace('\\>', '>')
).strip()).group(1)
elif section_name == 'remote' and opt_name == 'protocol':
opt_value = [elem.strip() for elem in opt.text.split(',')]
else:
if opt.attrib or list(opt):
opt_value = {}
for a in opt.attrib:
opt_value[a] = opt.attrib[a]
if list(opt):
for child in opt:
child_section, child_config = _read_option(child.tag.lower(), child)
try:
opt_value[child_section].append(child_config)
except KeyError:
opt_value[child_section] = [child_config]
else:
opt_value['item'] = opt.text
else:
opt_value = opt.text
return opt_name, _replace_custom_values(opt_value)
def _replace_custom_values(opt_value: Union[list, dict, str]) -> Union[list, dict, str]:
"""Replace custom values introduced by 'load_wazuh_xml' with their real values.
Parameters
----------
opt_value : list or dict or str
Value to be replaced.
"""
if type(opt_value) is list:
for i in range(0, len(opt_value)):
opt_value[i] = _replace_custom_values(opt_value[i])
elif type(opt_value) is dict:
for key in opt_value.keys():
opt_value[key] = _replace_custom_values(opt_value[key])
elif type(opt_value) is str:
return opt_value.replace('_custom_amp_lt_', '<').replace('_custom_amp_gt_', '>')
return opt_value
def _conf2json(src_xml: str, dst_json: dict):
"""Parse src_xml to JSON. It is inserted in dst_json.
Parameters
----------
src_xml : str
Configuration to be parsed to JSON.
dst_json : dict
Destination.
"""
for section in list(src_xml):
section_name = section.attrib['name'] if section.tag.lower() == 'wodle' else section.tag.lower()
section_json = {}
for option in list(section):
option_name, option_value = _read_option(section_name, option)
if type(option_value) is list and not (section_name == 'remote' and option_name == 'protocol'):
for ov in option_value:
_insert(section_json, section_name, option_name, ov)
else:
_insert(section_json, section_name, option_name, option_value)
_insert_section(dst_json, section_name, section_json)
def _ossecconf2json(xml_conf: str) -> dict:
"""Return ossec.conf in JSON from XML.
Parameters
----------
xml_conf : str
Configuration to be parsed to JSON.
Returns
-------
dict
Final JSON with the ossec.conf content.
"""
final_json = {}
for root in list(xml_conf):
if root.tag.lower() == "ossec_config":
_conf2json(root, final_json)
return final_json
def _agentconf2json(xml_conf: str) -> dict:
"""Return agent.conf in JSON from XML.
Parameters
----------
xml_conf : str
Configuration to be parsed to JSON.
Returns
-------
dict
Final JSON with the agent.conf content.
"""
final_json = []
for root in xml_conf.iter():
if root.tag.lower() == "agent_config":
# Get attributes (os, name, profile)
filters = {}
for attr in root.attrib:
filters[attr] = root.attrib[attr]
# Check if we have read the same filters before (we will need to merge them)
previous_config = -1
for idx, item in enumerate(final_json):
if 'filters' in item and item['filters'] == filters:
previous_config = idx
break
if previous_config != -1:
_conf2json(root, final_json[previous_config]['config'])
else:
config = {}
_conf2json(root, config)
final_json.append({'filters': filters, 'config': config})
return final_json
def _rcl2json(filepath: str) -> dict:
"""
Returns the RCL file as dictionary.
Parameters
----------
filepath : str
Path to the RCL file.
Raises
------
WazuhError(1101)
Requested component does not exist.
Returns
-------
dict
RCL file (system_audit, windows_audit) as dictionary.
"""
data = {'vars': {}, 'controls': []}
# [Application name] [any or all] [reference]
# type: '<entry name>;'
regex_comment = re.compile(r"^\s*#")
regex_title = re.compile(r"^\s*\[(.*)\]\s*\[(.*)\]\s*\[(.*)\]\s*")
regex_name_groups = re.compile(r"({\w+:\s+\S+\s*\S*\})")
regex_check = re.compile(r"^\s*(\w:.+)")
regex_var = re.compile(r"^\s*\$(\w+)=(.+)")
try:
item = {}
with open(filepath) as f:
for line in f:
if re.search(regex_comment, line):
continue
match_title = re.search(regex_title, line)
if match_title:
# Previous
data['controls'].append(item)
# New
name = match_title.group(1)
condition = match_title.group(2)
reference = match_title.group(3)
item = {}
# Name
end_name = name.find('{')
item['name'] = name[:end_name].strip()
# Extract PCI and CIS from name
name_groups = list()
name_groups.extend(re.findall(regex_name_groups, name))
cis, pci = list(), list()
for group in name_groups:
# {CIS: 1.1.2 RHEL7}
g_value = group.split(':')[-1][:-1].strip()
if 'CIS' in group:
cis.append(g_value)
elif 'PCI' in group:
pci.append(g_value)
item['cis'] = cis
item['pci'] = pci
# Conditions
if condition:
item['condition'] = condition
if reference:
item['reference'] = reference
item['checks'] = []
continue
match_checks = re.search(regex_check, line)
if match_checks:
item['checks'].append(match_checks.group(1))
continue
match_var = re.search(regex_var, line)
if match_var:
data['vars'][match_var.group(1)] = match_var.group(2)
continue
# Last item
data['controls'].append(item)
except Exception as e:
raise WazuhError(1101, str(e))
return data
def _rootkit_files2json(filepath: str) -> dict:
"""Return the rootkit file as dictionary.
Parameters
----------
filepath : str
Path to the rootkit file.
Raises
------
WazuhError(1101)
Requested component does not exist.
Returns
-------
dict
Rootkit file as dictionary.
"""
data = []
# file_name ! Name ::Link to it
regex_comment = re.compile(r"^\s*#")
regex_check = re.compile(r"^(.+)!(.+)::(.+)")
try:
with open(filepath) as f:
for line in f:
if re.search(regex_comment, line):
continue
if match_check := re.search(regex_check, line):
new_check = {'filename': match_check.group(1).strip(), 'name': match_check.group(2).strip(),
'link': match_check.group(3).strip()}
data.append(new_check)
except Exception as e:
raise WazuhError(1101, str(e))
return data
def _rootkit_trojans2json(filepath: str) -> dict:
"""Return the rootkit trojans file as dictionary.
Parameters
----------
filepath : str
Path to the rootkit trojans file.
Raises
------
WazuhError(1101)
Requested component does not exist.
Returns
-------
dict
Rootkit trojans file as dictionary.
"""
data = []
# file_name !string_to_search!Description
regex_comment = re.compile(r"^\s*#")
regex_check = re.compile(r"^(.+)!(.+)!(.+)")
regex_binary_check = re.compile(r"^(.+)!(.+)!")
try:
with open(filepath) as f:
for line in f:
if re.search(regex_comment, line):
continue
match_check = re.search(regex_check, line)
match_binary_check = re.search(regex_binary_check, line)
if match_check:
new_check = {'filename': match_check.group(1).strip(), 'name': match_check.group(2).strip(),
'description': match_check.group(3).strip()}
data.append(new_check)
elif match_binary_check:
new_check = {'filename': match_binary_check.group(1).strip(),
'name': match_binary_check.group(2).strip()}
data.append(new_check)
except Exception as e:
raise WazuhError(1101, str(e))
return data
def _ar_conf2json(file_path: str) -> dict:
"""Return the lines of the ar.conf file.
Parameters
----------
file_path : str
Path to the ar.conf file.
Returns
-------
dict
ar.conf file as dictionary.
"""
with open(file_path) as f:
data = [line.strip('\n') for line in f.readlines()]
return data
def _merged_mg2json(file_path: str) -> List[dict]:
"""Parse the merged.mg file.
Parameters
----------
file_path : str
Path to the merged.mg file.
Returns
-------
dict
merged.mg file as a list of dictionaries.
"""
data = []
# ![file_size] [file_name]
regex_header = re.compile(r"^!(\d+)\s*(.*)")
try:
item = {}
file_content = []
with open(file_path) as f:
# Skip first line
next(f)
for line in f:
if match_header := re.search(regex_header, line):
if item:
# Append previous item
item['file_content'] = ''.join(file_content)
data.append(item)
file_size = match_header.group(1)
file_name = match_header.group(2)
file_content = []
item = {'file_name': file_name, 'file_size': int(file_size)}
continue
file_content.append(line)
# Append last item
data.append(item)
except Exception as e:
raise WazuhError(1101, str(e))
return data
# Main functions
def get_ossec_conf(section: str = None, field: str = None, conf_file: str = common.OSSEC_CONF,
from_import: bool = False, distinct: bool = False) -> dict:
"""Return ossec.conf (manager) as dictionary.
Parameters
----------
section : str
Filters by section (i.e. rules).
field : str
Filters by field in section (i.e. included).
conf_file : str
Path of the configuration file to read. Default: common.OSSEC_CONF
from_import : bool
This flag indicates whether this function has been called from a module load (True) or from a function (False).
distinct : bool
Look for distinct values.
Raises
------
WazuhError(1101)
Requested component does not exist.
WazuhError(1102)
Invalid section.
WazuhError(1103)
Invalid field in section.
WazuhError(1106)
Requested section not present in configuration.
Returns
-------
dict
ossec.conf (manager) as dictionary.
"""
try:
# Read XML
xml_data = load_wazuh_xml(conf_file)
# Parse XML to JSON
data = _ossecconf2json(xml_data)
except Exception as e:
if not from_import:
raise WazuhError(1101, extra_message=str(e))
else:
print(f"wazuh-apid: There is an error in the ossec.conf file: {str(e)}")
sys.exit(0)
if section:
try:
data = {section: data[section]}
except KeyError as e:
if section not in CONF_SECTIONS.keys():
raise WazuhError(1102, extra_message=e.args[0])
else:
raise WazuhError(1106, extra_message=e.args[0])
if section and field:
try:
if isinstance(data[section], list):
data = {section: [{field: item[field]} for item in data[section]]}
else:
field_data = data[section][field]
if distinct and section == 'ruleset':
if field in ('decoder_dir', 'rule_dir'):
# Remove duplicates
values = []
[values.append(x) for x in field_data if x not in values]
field_data = values
data = {section: {field: field_data}}
except KeyError:
raise WazuhError(1103)
return data
def get_agent_conf(group_id: str = None, offset: int = 0, limit: int = common.DATABASE_LIMIT,
filename: str = 'agent.conf', raw: bool = False) -> Union[dict, str]:
"""Return agent.conf as dictionary.
Parameters
----------
group_id : str
ID of the group with the agent.conf we want to get.
offset : int
First element to return in the collection.
limit : int
Maximum number of elements to return.
filename : str
Name of the file to get. Default: 'agent.conf'
raw : bool
Respond in raw format.
Raises
------
WazuhResourceNotFound(1710)
Group was not found.
WazuhError(1006)
agent.conf does not exist or there is a problem with the permissions.
WazuhError(1101)
Requested component does not exist.
Returns
-------
dict or str
agent.conf as dictionary.
"""
if not os_path.exists(os_path.join(common.SHARED_PATH, group_id)):
raise WazuhResourceNotFound(1710, group_id)
agent_conf = os_path.join(common.SHARED_PATH, group_id if group_id is not None else '', filename)
if not os_path.exists(agent_conf):
raise WazuhError(1006, agent_conf)
try:
# Read RAW file
if filename == 'agent.conf' and raw:
with open(agent_conf, 'r') as raw_data:
data = raw_data.read()
return data
# Parse XML to JSON
else:
# Read XML
xml_data = load_wazuh_xml(agent_conf)
data = _agentconf2json(xml_data)
except Exception as e:
raise WazuhError(1101, str(e))
return {'total_affected_items': len(data), 'affected_items': cut_array(data, offset=offset, limit=limit)}
def get_agent_conf_multigroup(multigroup_id: str = None, offset: int = 0, limit: int = common.DATABASE_LIMIT,
filename: str = None) -> dict:
"""Return agent.conf as dictionary.
Parameters
----------
multigroup_id : str
ID of the group with the agent.conf we want to get.
offset : int
First element to return in the collection.
limit : int
Maximum number of elements to return.
filename : str
Name of the file to get. Default: 'agent.conf'
Raises
------
WazuhResourceNotFound(1710)
Group was not found.
WazuhError(1006)
agent.conf does not exist or there is a problem with the permissions.
WazuhError(1101)
Requested component does not exist.
Returns
-------
dict
agent.conf as dictionary.
"""
# Check if a multigroup_id is provided and it exists
if multigroup_id and not os_path.exists(os_path.join(common.MULTI_GROUPS_PATH, multigroup_id)) or not multigroup_id:
raise WazuhResourceNotFound(1710, extra_message=multigroup_id if multigroup_id else "No multigroup provided")
agent_conf_name = filename if filename else 'agent.conf'
agent_conf = os_path.join(common.MULTI_GROUPS_PATH, multigroup_id, agent_conf_name)
if not os_path.exists(agent_conf):
raise WazuhError(1006, extra_message=os_path.join("WAZUH_PATH", "var", "multigroups", agent_conf))
try:
# Read XML
xml_data = load_wazuh_xml(agent_conf)
# Parse XML to JSON
data = _agentconf2json(xml_data)
except Exception:
raise WazuhError(1101)
return {'totalItems': len(data), 'items': cut_array(data, offset=offset, limit=limit)}
def get_file_conf(filename: str, group_id: str = None, type_conf: str = None, raw: bool = False) -> dict | str:
"""Return the configuration file content.
Parameters
----------
group_id : str
ID of the group with the file we want to get.
filename : str
Name of the file to get.
type_conf : str
Type of the configuration we want to get.
raw : bool
Respond in raw format.
Raises
------
WazuhResourceNotFound(1710)
Group was not found.
WazuhError(1006)
The file does not exist or there is a problem with the permissions.
WazuhError(1104)
Invalid file type.
Returns
-------
dict or str
File content as plain text or dictionary.
"""
if not os_path.exists(os_path.join(common.SHARED_PATH, group_id)):
raise WazuhResourceNotFound(1710, group_id)
file_path = os_path.join(common.SHARED_PATH, group_id if not filename == 'ar.conf' else '', filename)
if not os_path.exists(file_path):
raise WazuhError(1006, file_path)
if raw:
with open(file_path, 'r') as raw_data:
data = raw_data.read()
return data
types = {
'conf': get_agent_conf,
'rootkit_files': _rootkit_files2json,
'rootkit_trojans': _rootkit_trojans2json,
'rcl': _rcl2json
}
if type_conf:
if type_conf in types:
if type_conf == 'conf':
data = types[type_conf](group_id, limit=None, filename=filename, raw=raw)
else:
data = types[type_conf](file_path)
else:
raise WazuhError(1104, f'{type_conf}. Valid types: {types.keys()}')
else:
if filename == 'agent.conf':
data = get_agent_conf(group_id, limit=None, filename=filename, raw=raw)
elif filename == 'rootkit_files.txt':
data = _rootkit_files2json(file_path)
elif filename == 'rootkit_trojans.txt':
data = _rootkit_trojans2json(file_path)
elif filename == 'ar.conf':
data = _ar_conf2json(file_path)
elif filename == 'merged.mg':
data = _merged_mg2json(file_path)
else:
data = _rcl2json(file_path)
return data
def parse_internal_options(high_name: str, low_name: str) -> str:
"""Parse internal_options.conf file.
Parameters
----------
high_name : str
Name of the daemon with the option we want to parse.
low_name : str
Option we want to parse.
Raises
------
WazuhInternalError(1107)
Internal options file not found.
WazuhInternalError(1108)
Value not found in internal_options.conf.
Returns
-------
str
Value of the internal_options.conf option.
"""
def get_config(config_path: str) -> dict:
"""Read configuration given by its path.
Parameters
----------
config_path : str
Configuration path.
Returns
-------
dict
Configuration as a dictionary.
"""
with open(config_path) as f:
str_config = StringIO('[root]\n' + f.read())
config = RawConfigParser()
config.read_file(str_config)
return config
if not os_path.exists(common.INTERNAL_OPTIONS_CONF):
raise WazuhInternalError(1107)
# Check if the option exists at local internal options
if os_path.exists(common.LOCAL_INTERNAL_OPTIONS_CONF):
try:
return get_config(common.LOCAL_INTERNAL_OPTIONS_CONF).get('root', f'{high_name}.{low_name}')
except NoOptionError:
pass
try:
return get_config(common.INTERNAL_OPTIONS_CONF).get('root', f'{high_name}.{low_name}')
except NoOptionError as e:
raise WazuhInternalError(1108, e.args[0])
def get_internal_options_value(high_name: str, low_name: str, max_: int, min_: int) -> int:
"""Get value of a specific internal option from internal_options.conf.
Parameters
----------
high_name : str
Name of the daemon with the option we want to get.
low_name : str
Option we want to get.
max_ : int
Maximum value of the option.
min_ : int
Minimum value of the option.
Raises
------
WazuhError(1109)
Option must be a digit.
WazuhError(1110)
Option value is out of the limits.
Returns
-------
int
Value of the internal_options.conf option.
"""
option = parse_internal_options(high_name, low_name)
if not option.isdigit():
raise WazuhError(1109, f'Option: {high_name}.{low_name}. Value: {option}')
option = int(option)
if option < min_ or option > max_:
raise WazuhError(1110, f'Max value: {max_}. Min value: {min_}. Found: {option}.')
return option
def upload_group_configuration(group_id: str, file_content: str) -> str:
"""Update group configuration.
Parameters
----------
group_id : str
Group to update.