Skip to content

Commit bf20e1a

Browse files
[Bug] Rule Toml Write Formatting Wrongly Formats \\\\x (#4978)
* Fix rule and mitigate py toml * Bump patch version * Add reference to issue * Add unit test for path issues * Update comment * Certain strings were not properly escaped * Updated to use json instead of repr * replace _old_dump_str with json.dumps * Bump Version (cherry picked from commit dde448e)
1 parent eb554ab commit bf20e1a

File tree

3 files changed

+13
-4
lines changed

3 files changed

+13
-4
lines changed

detection_rules/etc/test_toml.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,14 @@
4848
]
4949
}
5050
},
51+
{
52+
"metadata": {
53+
"field": "value"
54+
},
55+
"rule": {
56+
"path": "?:\\\\Windows\\\\Sys?????\\\\x5lrs.dll"
57+
}
58+
},
5159
{
5260
"metadata": {
5361
"field": "value"

detection_rules/rule_formatter.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,6 @@ class RuleTomlEncoder(toml.TomlEncoder): # type: ignore[reportMissingTypeArgume
123123
def __init__(self, *args: Any, **kwargs: Any) -> None:
124124
"""Create the encoder but override some default functions."""
125125
super().__init__(*args, **kwargs) # type: ignore[reportUnknownMemberType]
126-
self._old_dump_str = toml.TomlEncoder().dump_funcs[str]
127126
self._old_dump_list = toml.TomlEncoder().dump_funcs[list]
128127
self.dump_funcs[str] = self.dump_str
129128
self.dump_funcs[str] = self.dump_str
@@ -148,10 +147,12 @@ def dump_str(self, v: str | NonformattedField) -> str:
148147
if multiline:
149148
if raw:
150149
return "".join([TRIPLE_DQ, *initial_newline, *lines, TRIPLE_DQ])
151-
return "\n".join([TRIPLE_SQ] + [self._old_dump_str(line)[1:-1] for line in lines] + [TRIPLE_SQ])
150+
return "\n".join([TRIPLE_SQ] + [json.dumps(line)[1:-1] for line in lines] + [TRIPLE_SQ])
152151
if raw:
153152
return f"'{lines[0]:s}'"
154-
return self._old_dump_str(v)
153+
# In the toml library there is a magic replace for \\\\x -> u00 that we wish to avoid until #4979 is resolved
154+
# Also addresses an issue where backslashes in certain strings are not properly escaped in self._old_dump_str(v)
155+
return json.dumps(v)
155156

156157
def _dump_flat_list(self, v: Iterable[Any]) -> str:
157158
"""A slightly tweaked version of original dump_list, removing trailing commas."""

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "detection_rules"
3-
version = "1.3.24"
3+
version = "1.3.25"
44
description = "Detection Rules is the home for rules used by Elastic Security. This repository is used for the development, maintenance, testing, validation, and release of rules for Elastic Security’s Detection Engine."
55
readme = "README.md"
66
requires-python = ">=3.12"

0 commit comments

Comments
 (0)