2024-01-25 20:40:15 +00:00
|
|
|
"""Rule definition."""
|
2019-04-04 14:06:18 +00:00
|
|
|
|
2021-05-04 19:55:44 +00:00
|
|
|
import copy
|
2021-01-30 15:52:48 +00:00
|
|
|
import importlib
|
|
|
|
import inspect
|
|
|
|
import os
|
|
|
|
import pathlib
|
|
|
|
import re
|
2023-02-10 07:51:17 +00:00
|
|
|
from abc import ABCMeta, abstractmethod
|
2021-01-30 15:52:48 +00:00
|
|
|
from collections import defaultdict
|
2023-04-20 06:23:12 +00:00
|
|
|
from urllib.parse import urlparse
|
2019-04-04 14:06:18 +00:00
|
|
|
|
2021-01-30 15:52:48 +00:00
|
|
|
import toolz
|
|
|
|
import yaml
|
|
|
|
from yamllint import linter
|
|
|
|
from yamllint.config import YamlLintConfig
|
2019-04-02 14:34:03 +00:00
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
from ansiblelater.exceptions import LaterAnsibleError, LaterError
|
|
|
|
from ansiblelater.utils import Singleton, sysexit_with_message
|
|
|
|
from ansiblelater.utils.yamlhelper import (
|
|
|
|
UnsafeTag,
|
|
|
|
VaultTag,
|
|
|
|
action_tasks,
|
|
|
|
normalize_task,
|
|
|
|
normalized_yaml,
|
|
|
|
parse_yaml_linenumbers,
|
|
|
|
)
|
2019-04-02 14:34:03 +00:00
|
|
|
|
|
|
|
|
2024-01-25 20:40:15 +00:00
|
|
|
class RuleMeta(type):
|
2023-02-10 07:51:17 +00:00
|
|
|
def __call__(cls, *args):
|
2021-01-30 15:52:48 +00:00
|
|
|
mcls = type.__call__(cls, *args)
|
2024-01-27 18:56:35 +00:00
|
|
|
mcls.rid = cls.rid
|
2023-02-10 07:51:17 +00:00
|
|
|
mcls.description = getattr(cls, "description", "__unknown__")
|
|
|
|
mcls.helptext = getattr(cls, "helptext", "")
|
|
|
|
mcls.types = getattr(cls, "types", [])
|
2021-01-30 15:52:48 +00:00
|
|
|
return mcls
|
|
|
|
|
|
|
|
|
2024-01-25 20:40:15 +00:00
|
|
|
class RuleExtendedMeta(RuleMeta, ABCMeta):
|
2021-01-30 15:52:48 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
2024-01-25 20:40:15 +00:00
|
|
|
class RuleBase(metaclass=RuleExtendedMeta):
|
2023-04-20 06:23:12 +00:00
|
|
|
SHELL_PIPE_CHARS = "&|<>;$\n*[]{}?"
|
|
|
|
|
2021-01-30 15:52:48 +00:00
|
|
|
@property
|
|
|
|
@abstractmethod
|
2024-01-27 18:56:35 +00:00
|
|
|
def rid(self):
|
2021-01-30 15:52:48 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def check(self, candidate, settings):
|
|
|
|
pass
|
2019-04-02 14:34:03 +00:00
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
def __repr__(self):
|
2024-01-25 20:40:15 +00:00
|
|
|
return f"Rule: {self.description} (types: {self.types})"
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2023-02-10 07:51:17 +00:00
|
|
|
def get_tasks(candidate, settings): # noqa
|
2021-01-30 15:52:48 +00:00
|
|
|
errors = []
|
|
|
|
yamllines = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
with open(candidate.path, encoding="utf-8") as f:
|
2021-01-30 15:52:48 +00:00
|
|
|
yamllines = parse_yaml_linenumbers(f, candidate.path)
|
|
|
|
except LaterError as ex:
|
|
|
|
e = ex.original
|
|
|
|
errors.append(
|
2024-01-25 20:40:15 +00:00
|
|
|
RuleBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
except LaterAnsibleError as e:
|
2024-01-25 20:40:15 +00:00
|
|
|
errors.append(RuleBase.Error(e.line, f"syntax error: {e.message}"))
|
2021-01-30 15:52:48 +00:00
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return yamllines, errors
|
|
|
|
|
|
|
|
@staticmethod
|
2023-02-10 07:51:17 +00:00
|
|
|
def get_action_tasks(candidate, settings): # noqa
|
2021-01-30 15:52:48 +00:00
|
|
|
tasks = []
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
with open(candidate.path, encoding="utf-8") as f:
|
2021-01-30 15:52:48 +00:00
|
|
|
yamllines = parse_yaml_linenumbers(f, candidate.path)
|
|
|
|
|
|
|
|
if yamllines:
|
|
|
|
tasks = action_tasks(yamllines, candidate)
|
|
|
|
except LaterError as ex:
|
|
|
|
e = ex.original
|
|
|
|
errors.append(
|
2024-01-25 20:40:15 +00:00
|
|
|
RuleBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
except LaterAnsibleError as e:
|
2024-01-25 20:40:15 +00:00
|
|
|
errors.append(RuleBase.Error(e.line, f"syntax error: {e.message}"))
|
2021-01-30 15:52:48 +00:00
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return tasks, errors
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_normalized_task(task, candidate, settings):
|
|
|
|
normalized = None
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
|
|
|
normalized = normalize_task(
|
2021-05-04 19:55:44 +00:00
|
|
|
copy.copy(task), candidate.path, settings["ansible"]["custom_modules"]
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
except LaterError as ex:
|
|
|
|
e = ex.original
|
|
|
|
errors.append(
|
2024-01-25 20:40:15 +00:00
|
|
|
RuleBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
except LaterAnsibleError as e:
|
2024-01-25 20:40:15 +00:00
|
|
|
errors.append(RuleBase.Error(e.line, f"syntax error: {e.message}"))
|
2021-01-30 15:52:48 +00:00
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return normalized, errors
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_normalized_tasks(candidate, settings, full=False):
|
|
|
|
normalized = []
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
with open(candidate.path, encoding="utf-8") as f:
|
2021-01-30 15:52:48 +00:00
|
|
|
yamllines = parse_yaml_linenumbers(f, candidate.path)
|
|
|
|
|
|
|
|
if yamllines:
|
|
|
|
tasks = action_tasks(yamllines, candidate)
|
|
|
|
for task in tasks:
|
|
|
|
# An empty `tags` block causes `None` to be returned if
|
|
|
|
# the `or []` is not present - `task.get("tags", [])`
|
|
|
|
# does not suffice.
|
|
|
|
|
|
|
|
# Deprecated.
|
|
|
|
if "skip_ansible_lint" in (task.get("tags") or []) and not full:
|
|
|
|
# No need to normalize_task if we are skipping it.
|
|
|
|
continue
|
|
|
|
|
|
|
|
if "skip_ansible_later" in (task.get("tags") or []) and not full:
|
|
|
|
# No need to normalize_task if we are skipping it.
|
|
|
|
continue
|
|
|
|
|
2024-01-31 21:49:19 +00:00
|
|
|
normalized_task = normalize_task(
|
|
|
|
task, candidate.path, settings["ansible"]["custom_modules"]
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
2024-01-31 21:49:19 +00:00
|
|
|
normalized_task["__raw_task__"] = task
|
|
|
|
|
|
|
|
normalized.append(normalized_task)
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
except LaterError as ex:
|
|
|
|
e = ex.original
|
|
|
|
errors.append(
|
2024-01-25 20:40:15 +00:00
|
|
|
RuleBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
except LaterAnsibleError as e:
|
2024-01-25 20:40:15 +00:00
|
|
|
errors.append(RuleBase.Error(e.line, f"syntax error: {e.message}"))
|
2021-01-30 15:52:48 +00:00
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return normalized, errors
|
|
|
|
|
|
|
|
@staticmethod
|
2023-02-10 07:51:17 +00:00
|
|
|
def get_normalized_yaml(candidate, settings, options=None): # noqa
|
2021-01-30 15:52:48 +00:00
|
|
|
errors = []
|
|
|
|
yamllines = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
if not options:
|
|
|
|
options = defaultdict(dict)
|
|
|
|
options.update(remove_empty=True)
|
|
|
|
options.update(remove_markers=True)
|
|
|
|
|
|
|
|
try:
|
|
|
|
yamllines = normalized_yaml(candidate.path, options)
|
|
|
|
except LaterError as ex:
|
|
|
|
e = ex.original
|
|
|
|
errors.append(
|
2024-01-25 20:40:15 +00:00
|
|
|
RuleBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
except LaterAnsibleError as e:
|
2024-01-25 20:40:15 +00:00
|
|
|
errors.append(RuleBase.Error(e.line, f"syntax error: {e.message}"))
|
2021-01-30 15:52:48 +00:00
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return yamllines, errors
|
|
|
|
|
|
|
|
@staticmethod
|
2023-02-10 07:51:17 +00:00
|
|
|
def get_raw_yaml(candidate, settings): # noqa
|
2021-01-30 15:52:48 +00:00
|
|
|
content = None
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
with open(candidate.path, encoding="utf-8") as f:
|
2021-01-30 15:52:48 +00:00
|
|
|
yaml.add_constructor(
|
|
|
|
UnsafeTag.yaml_tag, UnsafeTag.yaml_constructor, Loader=yaml.SafeLoader
|
|
|
|
)
|
2021-04-13 20:27:26 +00:00
|
|
|
yaml.add_constructor(
|
|
|
|
VaultTag.yaml_tag, VaultTag.yaml_constructor, Loader=yaml.SafeLoader
|
|
|
|
)
|
2021-01-30 15:52:48 +00:00
|
|
|
content = yaml.safe_load(f)
|
|
|
|
except yaml.YAMLError as e:
|
|
|
|
errors.append(
|
2024-01-25 20:40:15 +00:00
|
|
|
RuleBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
|
|
|
|
|
|
|
return content, errors
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def run_yamllint(candidate, options="extends: default"):
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
if not candidate.faulty:
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
with open(candidate.path, encoding="utf-8") as f:
|
2021-01-30 15:52:48 +00:00
|
|
|
for problem in linter.run(f, YamlLintConfig(options)):
|
2024-01-25 20:40:15 +00:00
|
|
|
errors.append(RuleBase.Error(problem.line, problem.desc))
|
2021-01-30 15:52:48 +00:00
|
|
|
except yaml.YAMLError as e:
|
|
|
|
errors.append(
|
2024-01-25 20:40:15 +00:00
|
|
|
RuleBase.Error(e.problem_mark.line + 1, f"syntax error: {e.problem}")
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
candidate.faulty = True
|
2023-01-16 20:56:06 +00:00
|
|
|
except (TypeError, ValueError) as e:
|
2024-01-25 20:40:15 +00:00
|
|
|
errors.append(RuleBase.Error(None, f"yamllint error: {e}"))
|
2023-01-16 20:56:06 +00:00
|
|
|
candidate.faulty = True
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
return errors
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_first_cmd_arg(task):
|
|
|
|
if "cmd" in task["action"]:
|
|
|
|
first_cmd_arg = task["action"]["cmd"].split()[0]
|
|
|
|
elif "argv" in task["action"]:
|
|
|
|
first_cmd_arg = task["action"]["argv"][0]
|
|
|
|
else:
|
|
|
|
first_cmd_arg = task["action"]["__ansible_arguments__"][0]
|
|
|
|
|
2023-03-27 11:18:25 +00:00
|
|
|
return first_cmd_arg
|
2021-01-30 15:52:48 +00:00
|
|
|
|
2023-04-20 06:23:12 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_safe_cmd(task):
|
|
|
|
if "cmd" in task["action"]:
|
|
|
|
cmd = task["action"].get("cmd", "")
|
|
|
|
else:
|
|
|
|
cmd = " ".join(task["action"].get("__ansible_arguments__", []))
|
|
|
|
|
|
|
|
cmd = re.sub(r"{{.+?}}", "JINJA_EXPRESSION", cmd)
|
|
|
|
cmd = re.sub(r"{%.+?%}", "JINJA_STATEMENT", cmd)
|
|
|
|
cmd = re.sub(r"{#.+?#}", "JINJA_COMMENT", cmd)
|
|
|
|
|
|
|
|
parts = cmd.split()
|
|
|
|
parts = [p if not urlparse(p.strip('"').strip("'")).scheme else "URL" for p in parts]
|
|
|
|
|
|
|
|
return " ".join(parts)
|
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
class Error:
|
2021-01-30 15:52:48 +00:00
|
|
|
"""Default error object created if a rule failed."""
|
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
def __init__(self, lineno, message, **kwargs):
|
2021-01-30 15:52:48 +00:00
|
|
|
"""
|
|
|
|
Initialize a new error object and returns None.
|
|
|
|
|
|
|
|
:param lineno: Line number where the error from de rule occures
|
|
|
|
:param message: Detailed error description provided by the rule
|
|
|
|
|
|
|
|
"""
|
|
|
|
self.lineno = lineno
|
|
|
|
self.message = message
|
|
|
|
self.kwargs = kwargs
|
2023-11-10 13:50:48 +00:00
|
|
|
for key, value in kwargs.items():
|
2021-01-30 15:52:48 +00:00
|
|
|
setattr(self, key, value)
|
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
def __repr__(self):
|
2021-01-30 15:52:48 +00:00
|
|
|
if self.lineno:
|
2023-01-09 10:59:25 +00:00
|
|
|
return f"{self.lineno}: {self.message}"
|
2023-02-10 07:51:17 +00:00
|
|
|
return f" {self.message}"
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
def to_dict(self):
|
2023-02-10 07:51:17 +00:00
|
|
|
result = {"lineno": self.lineno, "message": self.message}
|
2023-11-10 13:50:48 +00:00
|
|
|
for key, value in self.kwargs.items():
|
2021-01-30 15:52:48 +00:00
|
|
|
result[key] = value
|
|
|
|
return result
|
|
|
|
|
2023-02-10 07:51:17 +00:00
|
|
|
class Result:
|
2021-01-30 15:52:48 +00:00
|
|
|
"""Generic result object."""
|
|
|
|
|
|
|
|
def __init__(self, candidate, errors=None):
|
|
|
|
self.candidate = candidate
|
|
|
|
self.errors = errors or []
|
|
|
|
|
|
|
|
def message(self):
|
2023-01-09 10:59:25 +00:00
|
|
|
return "\n".join([f"{self.candidate}:{error}" for error in self.errors])
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
|
2024-01-25 20:40:15 +00:00
|
|
|
class RulesLoader:
|
2021-01-30 15:52:48 +00:00
|
|
|
def __init__(self, source):
|
|
|
|
self.rules = []
|
|
|
|
|
|
|
|
for s in source:
|
|
|
|
for p in pathlib.Path(s).glob("*.py"):
|
|
|
|
filename = os.path.splitext(os.path.basename(p))[0]
|
|
|
|
if not re.match(r"^[A-Za-z]+$", filename):
|
|
|
|
continue
|
|
|
|
|
|
|
|
spec = importlib.util.spec_from_file_location(filename, p)
|
|
|
|
module = importlib.util.module_from_spec(spec)
|
|
|
|
|
|
|
|
try:
|
|
|
|
spec.loader.exec_module(module)
|
|
|
|
except (ImportError, NameError) as e:
|
2023-06-15 07:30:03 +00:00
|
|
|
sysexit_with_message(f"Failed to load roles file {filename}: \n {e!s}")
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
try:
|
2023-02-10 07:51:17 +00:00
|
|
|
for _name, obj in inspect.getmembers(module):
|
2021-01-30 15:52:48 +00:00
|
|
|
if self._is_plugin(obj):
|
|
|
|
self.rules.append(obj())
|
|
|
|
except TypeError as e:
|
2023-05-28 21:13:08 +00:00
|
|
|
sysexit_with_message(f"Failed to load roles file: \n {e!s}")
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
self.validate()
|
|
|
|
|
|
|
|
def _is_plugin(self, obj):
|
2023-11-10 13:50:48 +00:00
|
|
|
return (
|
2024-01-25 20:40:15 +00:00
|
|
|
inspect.isclass(obj) and issubclass(obj, RuleBase) and obj is not RuleBase and not None
|
2023-11-10 13:50:48 +00:00
|
|
|
)
|
2021-01-30 15:52:48 +00:00
|
|
|
|
|
|
|
def validate(self):
|
2024-01-27 18:56:35 +00:00
|
|
|
normalize_rule = list(toolz.remove(lambda x: x.rid == "", self.rules))
|
|
|
|
unique_rule = len(list(toolz.unique(normalize_rule, key=lambda x: x.rid)))
|
|
|
|
all_rules = len(normalize_rule)
|
|
|
|
if all_rules != unique_rule:
|
2021-01-30 15:52:48 +00:00
|
|
|
sysexit_with_message(
|
2024-01-25 20:40:15 +00:00
|
|
|
"Found duplicate tags in rules definition. Please use unique tags only."
|
2021-01-30 15:52:48 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-01-25 20:40:15 +00:00
|
|
|
class SingleRules(RulesLoader, metaclass=Singleton):
|
2021-01-30 15:52:48 +00:00
|
|
|
"""Singleton config class."""
|
|
|
|
|
|
|
|
pass
|