1import logging
2import os
3
4import click
5
6_logger = logging.getLogger(__name__)
7
8
[docs]
9def find_rules_file(root: str) -> str:
10 """Find the Suricata rules file in the given directory."""
11 if not os.path.exists(root):
12 msg = f"Error: {root} does not exist."
13 _logger.critical(msg)
14 raise click.BadParameter(f"Error: {msg}")
15
16 is_root_dir = os.path.isdir(root)
17 if not root.endswith(".rules") and not is_root_dir:
18 msg = f"Error: {root} is not a rules file or directory."
19 _logger.critical(msg)
20 raise click.BadParameter(f"Error: {msg}")
21
22 if not is_root_dir:
23 rules_file = root
24 else:
25 full_path = os.path.abspath(root)
26 _logger.info("Searching for Suricata rules file in %s", full_path)
27
28 rules_files: list[str] = []
29 for path, _, files in os.walk(root):
30 for file in files:
31 if file.endswith(".rules"):
32 rules_files.append(os.path.join(path, file))
33
34 if len(rules_files) == 0:
35 msg = f"No Suricata rules file found in {root}"
36 _logger.critical(msg)
37 raise click.BadParameter(f"Error: {msg}")
38 if len(rules_files) > 1:
39 msg = f"Multiple Suricata rules files found in {root}\n" + "\n".join(
40 rules_files,
41 )
42 _logger.critical(msg)
43 raise click.BadParameter(f"Error: {msg}")
44
45 rules_file = rules_files[0]
46
47 _logger.info("Found Suricata rules file: %s", rules_file)
48
49 return rules_file