Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIM System tests: Test actions and implement first scenario #521

Merged
merged 103 commits into from
Feb 24, 2020
Merged
Show file tree
Hide file tree
Changes from 100 commits
Commits
Show all changes
103 commits
Select commit Hold shift + click to select a range
4335d36
Add required vars for verification scripts and update formatting
Feb 18, 2020
7dcb919
Update default FIM vars
Feb 18, 2020
37a2837
Update default avriables at /fim/vars.yml files
Feb 18, 2020
be6cd83
Create delete_files.yml tasks to execute delete_files.py
Feb 18, 2020
80b64c0
Change verify_alerts.yml vars for standarization purposes
Feb 18, 2020
5fb3eab
Create agents_local_output_path var and update agents_results_manager…
Feb 18, 2020
0718913
Add comment for clarification in /fim/vars/main.yml
Feb 18, 2020
2afff9d
Update delete_files's conditional
Feb 18, 2020
dea9419
Add prepare tasks
rshad Feb 18, 2020
b29f62f
Apply updates to default variables
Feb 18, 2020
7fa564d
Re-adapt scenarios folder structure
rshad Feb 18, 2020
799b8a3
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://git…
rshad Feb 18, 2020
5e2b93c
Fix conditional of agents in delete_files.yml
Feb 18, 2020
8c85e09
Create modify_files.py
Feb 18, 2020
3fe74e3
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://www…
Feb 18, 2020
e6c72e3
Fix modify_files.yml description task
Feb 18, 2020
2d70fc9
Add prepare tasks for Windows agents
rshad Feb 18, 2020
d4fccb7
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://git…
rshad Feb 18, 2020
08fcfd8
Fix a typo in a variable name
rshad Feb 19, 2020
287bc46
Remove "output_file" from files_configuration.json in default scenario
Feb 19, 2020
74dd8cc
Add Prepare tasks to launch_scenario.yml
rshad Feb 19, 2020
55637f3
Convert prepare.yml into tasks file
rshad Feb 19, 2020
732bcd7
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://git…
rshad Feb 19, 2020
a2f1cd0
Fix windows tasks in Prepare tasks
rshad Feb 19, 2020
37596ae
Create default ossec.conf files for first scenario
Feb 19, 2020
08a740a
Save modified files and log errors
Feb 19, 2020
828cc01
Fix PEP8
Feb 19, 2020
d3c96df
Fix PEP8
Feb 19, 2020
83222b4
Update logfile
Feb 19, 2020
a7800d8
Rename files
Feb 19, 2020
3d2b13f
Make every file unique
Feb 19, 2020
5ff2e9e
Add new cofig variables
rshad Feb 19, 2020
5365ace
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://git…
rshad Feb 19, 2020
67cd975
Update files configuration for linux and windows
Feb 19, 2020
50b72a5
Remove become and with_items from prepare.yml
Feb 19, 2020
751c2e8
ADD manager and linux agent ossec.conf and update parameters for veri…
DFolchA Feb 19, 2020
aa32cce
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://git…
DFolchA Feb 19, 2020
9ec3842
Fix variable in task name
Feb 19, 2020
f198ec8
Update prepare.yml and main.yml vars
Feb 19, 2020
b7c0095
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://www…
Feb 19, 2020
bb8aaaf
Initialize the launch_scenario.yml playbook with prepare and create t…
Feb 19, 2020
b669f93
Fix paths in prepare.yml
Feb 19, 2020
e779cfd
Add ossec folder as parameter
rshad Feb 19, 2020
2309707
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://git…
rshad Feb 19, 2020
cda1d02
Initial support for create files
Feb 19, 2020
80a4be7
Add tasks to stop/start wazuh services + copy ossec.conf
rshad Feb 19, 2020
723830e
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://git…
rshad Feb 19, 2020
380d48b
Add files_configuration config. files
rshad Feb 19, 2020
a7f6c05
Add task to create folder structure for agents outputs in elasticsear…
rshad Feb 19, 2020
7bc89af
Add a var. with the path to the agent otuputs folder in elasticsearch…
rshad Feb 19, 2020
f4b8aa9
Remove duplicate files config.
rshad Feb 19, 2020
6812347
Fix file config. path in prepare.yml
rshad Feb 19, 2020
f829550
Fix files config. remote path for create_files.yml
rshad Feb 19, 2020
83cee5f
Use win_shell to execute script
Feb 19, 2020
925b283
Re-order launch_scenario playbook and remove redundant conditions
rshad Feb 19, 2020
3b1139b
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://git…
rshad Feb 19, 2020
47b92d5
Use script module to run files generating on Windows
rshad Feb 19, 2020
39325d2
Fix memory error
Feb 19, 2020
11bc1af
Split Linux Windows modify tasks
Feb 19, 2020
4569425
Delete tasks. Win/Linux support
Feb 19, 2020
3f67edb
Use become
Feb 19, 2020
747e4f5
Adapted folders names to Syscheck events names
rshad Feb 19, 2020
2581d84
Added tasks to launch_scenario.yml:
DFolchA Feb 19, 2020
5b78c52
Delete redundant tasks in launch_scenario.yml
DFolchA Feb 19, 2020
677aff5
Add folders for agents output in each scenario folder
rshad Feb 19, 2020
70d42a5
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://git…
rshad Feb 19, 2020
a3880dd
Run elasticsearch related task as sudo
rshad Feb 19, 2020
25d62ee
Added tasks to transfer output files from agnets to managers
rshad Feb 19, 2020
d614aec
Parameterize event name in create_files.yml
rshad Feb 19, 2020
8a757dd
Add a tasks file with the tasks to transfet the output files from age…
rshad Feb 19, 2020
2786888
Change loop from lauch_environment to verify_alerts
DFolchA Feb 20, 2020
70903c4
Merge branch 'feature-480-ansible-tasks-actions-tests' of https://git…
DFolchA Feb 20, 2020
c2bbd9f
Remove become and acces to correct dict indices
DFolchA Feb 20, 2020
4d84bf7
Copy files to elastic node and add necessary becomes
DFolchA Feb 20, 2020
f208c3f
Duplicate a task for windows and linux
DFolchA Feb 20, 2020
22d01a4
Create and use handlers. Minor changes to python scripts.
DFolchA Feb 20, 2020
402d750
Use handlers in create, modify and delete tasks
DFolchA Feb 20, 2020
3798606
Change handlers location
DFolchA Feb 20, 2020
a0f66b6
Add copy tasks to modify and delete tasks.
DFolchA Feb 20, 2020
9c12a00
Exit with return code from main
Feb 20, 2020
a8ee6ca
Use logging module, log to stdout and file
Feb 20, 2020
7c393da
Update files configuration to remove 1GB file from default settings
Feb 20, 2020
b22d79a
Update default ossec.confs for Linux and Windows Agent
Feb 20, 2020
1693342
Specify alerts type
Feb 20, 2020
6eba5f8
Write only missing alerts
Feb 20, 2020
f76ad5d
Raise default timeout to 60s
Feb 20, 2020
7dc9897
Add force: yes to copy tasks
DFolchA Feb 21, 2020
18725d0
Move force inside copy clause.
DFolchA Feb 21, 2020
2ebbec2
Delete unnecessary becomes and change copy path, also removed Elasti…
DFolchA Feb 21, 2020
09809cb
Add flush_handlers after alert generation tasks
DFolchA Feb 21, 2020
905ad55
invalid windows characters on alerts handling
Zenidd Feb 21, 2020
5b0f5e5
Refactor file creation to use templates
Feb 21, 2020
ea5539e
Merge branch 'feature-480-ansible-tasks-actions-tests'
Feb 21, 2020
98b8540
Several fixes on create, modify, delete
Feb 21, 2020
1bde6df
Update syscheck frequency and recursion level of default paths
Feb 21, 2020
babab22
Remove notify and start windows agent
DFolchA Feb 21, 2020
5c95bff
Add retry to elasticsearch script and change windows path to lowercase.
DFolchA Feb 24, 2020
0857bfc
Fixy typo in synchronize task of "modify_files.yml"
Feb 24, 2020
f031385
Set agents_windows_output_path to lowercase
Feb 24, 2020
0e6e895
Merge branch 'fim-system-tests' into feature-480-ansible-tasks-action…
Feb 24, 2020
9208efa
Rename "files_configuration.json.jinja" to "files_configuration.json.j2"
Feb 24, 2020
90a98ab
Rename "launch_scenario.yml" to "launch_test_scenario.yml"
Feb 24, 2020
45e4a34
Delete trasnfer_output_files.yml
Feb 24, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions tests/system/fim/common_tasks/create_files.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
- block:
- name: Run script generate_files.py on agents | Linux
script: "generate_files.py -c {{ files_config_linux_destination_path }} -o {{ files_generated_output_path }}"
args:
executable: "python3"
chdir: "{{ agents_linux_output_path }}"

- name: Copy list of created files from Agents to Ansible Controller host | Linux
fetch:
src: "{{ agents_linux_output_path }}/{{ files_generated_output_path }}"
dest: "agents_outputs/{{ event }}/{{ files_generated_output_path }}-{{ inventory_hostname }}"
flat: yes

become: yes
when:
- inventory_hostname in groups['linuxagents']


- block:
- name: Run script generate_files.py on agents | Windows
script: "generate_files.py -c {{ files_config_windows_destination_path }} -o {{ files_generated_output_path }}"
args:
executable: "python"
chdir: "{{ agents_windows_output_path }}"

- name: Copy list of created files from Windows Agents to Ansible Controller host | Windows
fetch:
src: "{{ agents_windows_output_path }}/{{ files_generated_output_path }}"
dest: "agents_outputs/{{ event }}/{{ files_generated_output_path }}-{{ inventory_hostname }}"
flat: yes

when:
- inventory_hostname in groups['windowsagents']

- name: Copy the output files from Ansible Controller to the Managers
become: true
synchronize:
src: "agents_outputs/added/"
dest: "{{ agents_results_manager_path }}/{{ event }}/"
when:
- inventory_hostname in groups['masters']
33 changes: 19 additions & 14 deletions tests/system/fim/common_tasks/delete_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@

def delete_files(input_file_path, n, output_file_path):
"""
Delete files, given a file with complete list of files where each line
Delete files, given a file with complete list of files where each line
represents a file path, we will randomly delete n files of them.

:param str input_file_path: path of the input file which contains the list of files.
:param int n: number of file to delete.
:return: Returns a file with the list of the deleted files.
"""
logger = logging.getLogger()
log_filename = 'delete_files.log'
logging.basicConfig(
filename=log_filename,
level=logging.DEBUG,
)
data = []
# Read data into the variable 'data'
try:
Expand All @@ -31,31 +35,31 @@ def delete_files(input_file_path, n, output_file_path):
data_ = f.readlines()
# remove whitespace characters like `\n` at the end of each line
data = [x.strip() for x in data_]
f.close() # close f
except Exception as e:
logger.error('Failed when reading the input file: ', exc_info=True)
f.close() # close f
except Exception:
logging.error('Failed when reading the input file: ', exc_info=True)


if n is not None: # Randomly select n paths from data
to_delete = random.sample(data,n)
else: # Delete all files
if n is not None: # Randomly select n paths from data
to_delete = random.sample(data, n)
else: # Delete all files
to_delete = data

# Delete the selected files
try:
for path in to_delete:
os.remove(path)
except Exception as e:
logger.error('Failed when deleting the selected files: ', exc_info=True)
except Exception:
logging.error('Failed when deleting the selected files: ', exc_info=True)

# Write the list of the deleted files into output_file_path
try:
with open(output_file_path, 'w') as f:
for item in to_delete:
f.write("%s\n" % item)
f.close()
except Exception as e:
logger.error('Failed when writing to the output file: ', exc_info=True)
except Exception:
logging.error('Failed when writing to the output file: ', exc_info=True)


def main():
parser = argparse.ArgumentParser()
Expand All @@ -72,5 +76,6 @@ def main():

delete_files(args.input_file, args.n_files, args.output_file)


if __name__ == '__main__':
main()
main()
43 changes: 43 additions & 0 deletions tests/system/fim/common_tasks/delete_files.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
- block:
- name: "Delete FIM test files at Wazuh Agents | Linux"
script: "delete_files.py -i {{ files_generated_output_path }} -o {{ files_deleted_output_path }}"
args:
executable: "python3"
chdir: "{{ agents_linux_output_path }}"

- name: Copy list of deleted files from Agents to Ansible Controller host | Linux
fetch:
src: "{{ agents_linux_output_path }}/{{ files_deleted_output_path }}"
dest: "agents_outputs/{{ event }}/{{ files_deleted_output_path }}-{{ inventory_hostname }}"
flat: yes

become: yes
when:
- inventory_hostname in groups['linuxagents']


- block:
- name: "Delete FIM test files at Wazuh Agents | Windows"
script: "delete_files.py -i {{ files_generated_output_path }} -o {{ files_deleted_output_path }}"
args:
executable: "python"
chdir: "{{ agents_windows_output_path }}"

- name: Copy list of deleted files from Windows Agents to Ansible Controller host
fetch:
src: "{{ agents_windows_output_path }}/{{ files_deleted_output_path }}"
dest: "agents_outputs/{{ event }}/{{ files_deleted_output_path }}-{{ inventory_hostname }}"
flat: yes

when:
- inventory_hostname in groups['windowsagents']


- name: Copy the output files from Ansible Controller to the Managers
become: true
synchronize:
src: "agents_outputs/added/"
dest: "{{ agents_results_manager_path }}/{{ event }}/"
when:
- inventory_hostname in groups['masters']
13 changes: 0 additions & 13 deletions tests/system/fim/common_tasks/files_configuration.json

This file was deleted.

12 changes: 12 additions & 0 deletions tests/system/fim/common_tasks/files_configuration.json.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"root_folder": "{{ agents_fim_testing_path }}",
"recursion_level": 3,
"folder_length": 5,
"file_length": 5,
"file_size_specifications":[
{ "size": 10240, "amount": 4000},
{ "size": 524288, "amount": 500},
{ "size": 1048576, "amount": 500},
{ "size": 10485760, "amount": 10}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import json
import random
import string
import secrets
import argparse


Expand Down Expand Up @@ -118,7 +119,13 @@ def create_files(files_path):
"""
for key, value in files_path.items():
with open(key, "wb") as f:
f.write(b'0'*value)
if value > 1048576:
nval = value // 1048576
for val in range(nval):
f.write(b'0' * 1048576)
else:
f.write(b'0' * value)
f.write(secrets.token_bytes(32))


def create_file_summary(files_path, logfile):
Expand All @@ -132,7 +139,7 @@ def create_file_summary(files_path, logfile):
os.remove(logfile)
with open(logfile, 'w') as f:
for path in files_path:
f.write(path+'\n')
f.write(path + '\n')


def main():
Expand All @@ -146,10 +153,10 @@ def main():
output_file = args.output_list
config = parse_files_configuration(config_file)
folders = generate_folders_paths(
config["root_folder"],
config["recursion_level"],
config["folder_length"]
)
config["root_folder"],
config["recursion_level"],
config["folder_length"]
)
create_folders(folders)
n_files = sum(x['amount'] for x in config['file_size_specifications'])
files = generate_files_paths(folders, n_files, config["file_length"])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import sys
import random
import platform
import argparse
import logging
if platform.system() == 'Linux':
import pwd
import grp
Expand Down Expand Up @@ -51,7 +53,7 @@ def modify_file(filepath, owner, group, mode):
'uid': uid,
'gid': gid,
'mode': oct(mode).split('o')[1].zfill(3) # convert to octal string
}
}


def modify_file_content(filepath):
Expand All @@ -60,22 +62,63 @@ def modify_file_content(filepath):

:param str filepath: The path of the file to modify
"""
content = 'qazxswedcvbnmklpoiuytggdfert'*random.randint(1, 10)
content = 'qazxswedcvbnmklpoiuytggdfert' * random.randint(1, 10)
content += str(random.random())
if not os.path.exists(filepath):
raise FileNotFoundError
with open(filepath, 'ab') as f:
f.write(bytes(content, 'utf8'))


def log_modified_files(files_path, logfile):
"""
Creates a file that summarizes all the modified files

:param dict files_path: Contains the list of modified files
:param str logfile: File to write the list of paths
"""
if os.path.exists(logfile):
os.remove(logfile)
with open(logfile, 'w') as f:
for path in files_path:
f.write(path + '\n')


def main():
import argparse
log_filename = 'modify_files.log'
logging.basicConfig(
filename=log_filename,
level=logging.DEBUG,
)
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input-list", type=str, required=True, dest='input_file',
parser.add_argument("-i", "--input-list", type=str,
required=True, dest='input_file',
help="File containing the list of files to modify")
parser.add_argument("-o", "--output-list", type=str,
required=True, dest='output_file',
help="File containing the list of modified files")
args = parser.parse_args()

input_file = args.input_file
output_file = args.output_file

changed_files = []

with open(input_file) as flist:
for path in flist:
modify_file_content(path[:-1])
try:
modify_file_content(path[:-1])
changed_files.append(path[:-1])
except PermissionError:
logging.error("Not enough permissions to modify: {}".format(path[:-1]))
continue
except FileNotFoundError:
logging.error("File not found: {}".format(path[:-1]))
continue
except Exception:
logging.error("Unexpected error: ", exc_info=True)
continue
log_modified_files(changed_files, output_file)


if __name__ == "__main__":
Expand Down
42 changes: 42 additions & 0 deletions tests/system/fim/common_tasks/modify_files.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
- block:
- name: "Modify FIM test files at Wazuh Managers | Linux"
script: "modify_files.py -i {{ files_generated_output_path }} -o {{ files_modified_output_path }}"
args:
executable: "python3"
chdir: "{{ agents_linux_output_path }}"

- name: Copy list of modified files from Agents to Ansible Controller host | Linux
fetch:
src: "{{ agents_linux_output_path }}/{{ files_modified_output_path }}"
dest: "agents_outputs/{{ event }}/{{ files_modified_output_path }}-{{ inventory_hostname }}"
flat: yes

become: yes
when:
- inventory_hostname in groups['linuxagents']


- block:
- name: "Modify FIM test files at Wazuh Managers | Windows"
script: "modify_files.py -i {{ files_generated_output_path }} -o {{ files_modified_output_path }}"
args:
executable: "python"
chdir: "{{ agents_windows_output_path }}"

- name: Copy list of modified files from Agents to Ansible Controller host | Windows
fetch:
src: "{{ agents_windows_output_path }}/{{ files_generated_output_path }}"
dest: "agents_outputs/{{ event }}/{{ files_modified_output_path }}-{{ inventory_hostname }}"
flat: yes

when:
- inventory_hostname in groups['windowsagents']

- name: Copy the output files from Ansible Controller to the Managers
become: true
synchronize:
src: "agents_outputs/modified/"
dest: "{{ agents_results_manager_path }}/{{ event }}/"
when:
- inventory_hostname in groups['masters']
Loading