| 1 |
"""Secret masking registry. |
| 2 |
|
| 3 |
``SecretMasker`` is the public side: it registers secret values (length rules, trimming, de-duplication, |
| 4 |
new-secret tracking, locking) and redacts every occurrence of them from strings. Matching is delegated to |
| 5 |
a matcher object with a small interface (``add``, ``spans``) so the algorithm can be swapped, for example |
| 6 |
for a compiled extension, without touching the registry semantics: |
| 7 |
|
| 8 |
* every occurrence of every secret is found (overlapping included) and the union of the spans is |
| 9 |
redacted, with overlapping and adjacent spans merged into one placeholder, so no character that |
| 10 |
belongs to a secret occurrence is left visible and the number of secrets is not revealed |
| 11 |
* secrets of 4-6 characters are masked only at a word boundary (both neighbours non-alphanumeric or |
| 12 |
the string edge); a short secret that overlaps or is adjacent to another secret will be masked |
| 13 |
unconditionally. An occurrence lying entirely inside another is not counted as an overlap, but if |
| 14 |
the inner secret qualified by itself it will qualify the outer run to be safe |
| 15 |
|
| 16 |
``_Fixed4Matcher`` is a custom string matcher/registry implementation tuned for Ansible. |
| 17 |
|
| 18 |
* the matcher stores only the first ``_ANCHOR_LEN`` characters of each secret in a dictionary and uses |
| 19 |
a sliding window scan of the data it is attempting to mask; a hit is verified against the full secrets |
| 20 |
registered under that anchor with slice lookups. |
| 21 |
* before the full comparison, ``_PROBE_LEN`` characters from the middle of the candidate are checked |
| 22 |
against teh middles of the registered secrets of that length, so a near-miss costs the probe rather |
| 23 |
than the full length whatever the secret looks like (shared prefixes and suffixes such as PEM headers |
| 24 |
do not help an attacker trying to overload the matching with long secrets that are not present) |
| 25 |
""" |
| 26 |
|
| 27 |
from __future__ import annotations |
| 28 |
|
| 29 |
import json.encoder as _json_encoder |
| 30 |
import operator as _operator |
| 31 |
import typing as _t |
| 32 |
|
| 33 |
from ansible.module_utils._internal._concurrent._fork_safe_lock import ForkSafeLock |
| 34 |
|
| 35 |
# shared frozenset optimization for no secrets found |
| 36 |
_emptyfrozenset: frozenset[str] = frozenset() |
| 37 |
|
| 38 |
# Bucket layout: (length, probe_offset, probe_stop, probes, secrets) |
| 39 |
# All secrets of one length sharing one 4-char anchor prefix. Visited longest-first for |
| 40 |
# leftmost-longest matching. The probe is compared before the full secret so a near-miss |
| 41 |
# costs the probe slice rather than the full length. |
| 42 |
_Bucket = tuple[int, int, int, set[str], set[str]] |
| 43 |
|
| 44 |
|
| 45 |
# If any of these are changed we need to ensure that Ansible.Secrets.cs is updated to match. |
| 46 |
_MINIMUM_SECRET_LENGTH = 4 # below this, not registered at all |
| 47 |
_MAXIMUM_SHORT_SECRET_LENGTH = 6 # above this, mask unconditionally |
| 48 |
_MAXIMUM_SECRET_LENGTH = 65536 # trims to this length as a cap for registration and matching |
| 49 |
_STRIP_CHARS = " \t\r\n" # stripped from both ends before registration |
| 50 |
|
| 51 |
_ANCHOR_LEN = _MINIMUM_SECRET_LENGTH # Keeping these two the same means we only need 1 sliding window scan |
| 52 |
_PROBE_LEN = 8 # chars compared from the middle of a candidate before the full comparison |
| 53 |
|
| 54 |
|
| 55 |
def _sits_at_boundary(value: str, start: int, end: int) -> bool: |
| 56 |
"""Return True if the candidate at value[start:end] is at a word boundary.""" |
| 57 |
at_beginning = start == 0 |
| 58 |
at_end = end == len(value) |
| 59 |
boundary_left = at_beginning or not value[start - 1].isalnum() |
| 60 |
boundary_right = at_end or not value[end].isalnum() |
| 61 |
return boundary_left and boundary_right |
| 62 |
|
| 63 |
|
| 64 |
def _span_is_qualified(value: str, start: int, end: int) -> bool: |
| 65 |
"""Return True if the occurrence at value[start:end] qualified on its own.""" |
| 66 |
return end - start > _MAXIMUM_SHORT_SECRET_LENGTH or _sits_at_boundary(value, start, end) |
| 67 |
|
| 68 |
|
| 69 |
def _merge_spans(value: str, spans: list[tuple[int, int]]) -> list[tuple[int, int]]: |
| 70 |
"""Merge overlapping/touching spans into one placeholder each and drop the runs that do not qualify.""" |
| 71 |
if not spans: |
| 72 |
return spans |
| 73 |
|
| 74 |
result: list[tuple[int, int]] = [] |
| 75 |
|
| 76 |
# A run being tracked is a contiguous sequence of overlapping or touching spans. |
| 77 |
run_start, run_end = spans[0] |
| 78 |
keep = _span_is_qualified(value, run_start, run_end) |
| 79 |
|
| 80 |
for start, end in spans[1:]: |
| 81 |
if start > run_end: |
| 82 |
# The current run in progress is complete as the new span starts after it. Append the |
| 83 |
# completed run if it qualified and start tracking the new run with this span. |
| 84 |
if keep: |
| 85 |
result.append((run_start, run_end)) |
| 86 |
run_start, run_end = start, end |
| 87 |
keep = _span_is_qualified(value, start, end) |
| 88 |
elif end > run_end: |
| 89 |
# The current span starts inside, or is adjacent to the current run AND it extends |
| 90 |
# beyond the run. We treat secrets that overlap or touch as qualified, regardless of |
| 91 |
# length or word boundary, so we extend the current run and mark it to be kept. |
| 92 |
# ["pass","private"] in "passprivate": (0,4) then (4,11) -> one run (0,11) |
| 93 |
# ["abab"] in "ababab": (0,4) then (2,6) -> one run (0,6) |
| 94 |
run_end = end |
| 95 |
keep = True |
| 96 |
elif not keep: |
| 97 |
# The current run does not qualify by itself (too short and not at a word boundary). |
| 98 |
# The current span lies entirely inside the run and may qualify on its own. If the |
| 99 |
# inner span qualifies on its own, we redact the whole run to be safe. |
| 100 |
# ["abcd-x","abcd"] in " abcd-xy": |
| 101 |
# (1,7) fails on the "y" (short + word boundary) |
| 102 |
# (1,5) passes the word boundary ("-" is non-alphanumeric) |
| 103 |
# As the inner span qualifies on its own, the whole run IS masked. |
| 104 |
# ["abcdef","abcd"] in " abcdefg": |
| 105 |
# (1,7) fails on the "g" (short + word boundary) |
| 106 |
# (1,5) fails on the "e" as well |
| 107 |
# This run does not qualify and IS NOT masked |
| 108 |
keep = _span_is_qualified(value, start, end) |
| 109 |
|
| 110 |
if keep: |
| 111 |
result.append((run_start, run_end)) |
| 112 |
|
| 113 |
return result |
| 114 |
|
| 115 |
|
| 116 |
def _probe_span(length: int) -> tuple[int, int]: |
| 117 |
"""(offset, size) of the probe window inside a secret of ``length``: its middle, where structured |
| 118 |
secrets keep their entropy, clipped to the secret for secrets shorter than the probe.""" |
| 119 |
size = min(_PROBE_LEN, length) |
| 120 |
return max(0, length // 2 - size // 2), size |
| 121 |
|
| 122 |
|
| 123 |
class AnsibleSecretMaskError(Exception): |
| 124 |
"""Raised when secret masking fails. |
| 125 |
|
| 126 |
Deliberately carries no reference to the value being masked so that a masking |
| 127 |
failure can never leak the unmasked value through the exception itself. |
| 128 |
""" |
| 129 |
|
| 130 |
|
| 131 |
class _Fixed4Matcher: |
| 132 |
"""Matcher indexing every secret by its first ``_ANCHOR_LEN`` characters. |
| 133 |
|
| 134 |
Each anchor owns one bucket per distinct secret length, holding the probes and the |
| 135 |
secrets of that length as sets, so a candidate is resolved with two set lookups |
| 136 |
instead of a walk over every secret sharing the anchor. Buckets are visited longest |
| 137 |
first for leftmost-longest matching. |
| 138 |
""" |
| 139 |
|
| 140 |
def __init__(self) -> None: |
| 141 |
# anchor -> buckets, longest first |
| 142 |
self._scan: dict[str, list[_Bucket]] = {} |
| 143 |
# anchor -> length -> bucket |
| 144 |
self._buckets: dict[str, dict[int, _Bucket]] = {} |
| 145 |
|
| 146 |
def add(self, word: str) -> None: |
| 147 |
"""Add a word to the matcher.""" |
| 148 |
word_len = len(word) |
| 149 |
anchor = word[:_ANCHOR_LEN] |
| 150 |
|
| 151 |
by_length = self._buckets.setdefault(anchor, {}) |
| 152 |
anchor_buckets = self._scan.setdefault(anchor, []) |
| 153 |
|
| 154 |
bucket = by_length.get(word_len) |
| 155 |
if bucket is None: |
| 156 |
offset, size = _probe_span(word_len) |
| 157 |
bucket = (word_len, offset, offset + size, set(), set()) |
| 158 |
by_length[word_len] = bucket |
| 159 |
anchor_buckets.append(bucket) |
| 160 |
# Sorted for _merge_spans which expects spans ordered by length descending. |
| 161 |
anchor_buckets.sort(key=_operator.itemgetter(0), reverse=True) |
| 162 |
|
| 163 |
length, probe_offset, probe_stop, probes, secrets = bucket |
| 164 |
probes.add(word[probe_offset:probe_stop]) |
| 165 |
secrets.add(word) |
| 166 |
|
| 167 |
def spans(self, value: str) -> list[tuple[int, int]]: |
| 168 |
"""Find secret occurrences in ``value`` as (start, end) spans, including overlaps.""" |
| 169 |
value_len = len(value) |
| 170 |
spans: list[tuple[int, int]] = [] |
| 171 |
scan_get = self._scan.get |
| 172 |
|
| 173 |
for start in range(value_len - _ANCHOR_LEN + 1): |
| 174 |
buckets = scan_get(value[start : start + _ANCHOR_LEN]) |
| 175 |
if not buckets: |
| 176 |
continue |
| 177 |
|
| 178 |
for length, probe_offset, probe_stop, probes, secrets in buckets: |
| 179 |
end = start + length |
| 180 |
if end > value_len: |
| 181 |
continue |
| 182 |
if value[start + probe_offset : start + probe_stop] not in probes: |
| 183 |
continue |
| 184 |
if value[start:end] not in secrets: |
| 185 |
continue |
| 186 |
|
| 187 |
spans.append((start, end)) |
| 188 |
|
| 189 |
return spans |
| 190 |
|
| 191 |
|
| 192 |
class SecretMasker: |
| 193 |
# Instantiating this permanently registers os.register_at_fork handlers (via |
| 194 |
# ForkSafeLock) that cannot be unregistered, so this is intended to be used as a |
| 195 |
# long-lived singleton (see the shared _secret_masker instance below). |
| 196 |
def __init__(self) -> None: |
| 197 |
self._new_secret_trackers: set[NewSecretTracker] = set() |
| 198 |
self._lock = ForkSafeLock() |
| 199 |
self._matcher = _Fixed4Matcher() |
| 200 |
self._secrets: set[str] = set() # the registered secrets, as given (stripped and trimmed) |
| 201 |
self._forms: set[str] = set() # every string the matcher knows: secrets and their derived forms |
| 202 |
# JSON-encoded form -> the secret it is the encoding of, for forms that differ from the secret |
| 203 |
self._json_forms: dict[str, str] = {} |
| 204 |
|
| 205 |
def track_new_secrets(self) -> NewSecretTracker: |
| 206 |
with self._lock: |
| 207 |
self._new_secret_trackers.add(tracker := NewSecretTracker(self)) |
| 208 |
return tracker |
| 209 |
|
| 210 |
def register_secret_text(self, secret: str, /) -> str: |
| 211 |
"""Register a secret for masking, returning the value unchanged.""" |
| 212 |
self.register_secret_texts((secret,)) |
| 213 |
|
| 214 |
return secret |
| 215 |
|
| 216 |
def register_secret_texts(self, secrets: _t.Iterable[str], /) -> None: |
| 217 |
"""Register every secret in ``secrets`` for masking.""" |
| 218 |
with self._lock: |
| 219 |
new = set() |
| 220 |
for secret in secrets: |
| 221 |
# Surrounding whitespace is not part of the secret: values often |
| 222 |
# arrive with a trailing newline (vaulted files, stdin) but are used |
| 223 |
# stripped. The stripped value matches every occurrence the original |
| 224 |
# would have, plus the stripped uses. |
| 225 |
# FUTURE: Look into string normalisation \u00e9 vs \u0065\u0301, etc. to avoid |
| 226 |
# leaking secrets that are equivalent but not identical. Would require logic |
| 227 |
# on the masking side either to normalise and mutate the input or to register |
| 228 |
# multiple normalised forms of each secret. |
| 229 |
trimmed = secret.strip(_STRIP_CHARS)[:_MAXIMUM_SECRET_LENGTH] |
| 230 |
|
| 231 |
if len(trimmed) < _MINIMUM_SECRET_LENGTH: |
| 232 |
continue |
| 233 |
|
| 234 |
if self._add(trimmed): |
| 235 |
new.add(trimmed) |
| 236 |
|
| 237 |
for tracker in self._new_secret_trackers: |
| 238 |
tracker._new_secrets.update(new) |
| 239 |
|
| 240 |
def mask_string(self, value: str, /, *, mask_placeholder: str = "$REDACTED$") -> str: |
| 241 |
"""Masks any registered secret in the provided string with the provided placeholder. Returns the masked string.""" |
| 242 |
if not value: |
| 243 |
return value |
| 244 |
|
| 245 |
try: |
| 246 |
spans = [] |
| 247 |
with self._lock: |
| 248 |
if self._forms: |
| 249 |
spans = self._matcher.spans(value) |
| 250 |
|
| 251 |
spans = _merge_spans(value, spans) |
| 252 |
if not spans: |
| 253 |
return value |
| 254 |
|
| 255 |
parts = [] |
| 256 |
value_pos = 0 |
| 257 |
|
| 258 |
for start, end in spans: |
| 259 |
parts.append(value[value_pos:start]) |
| 260 |
parts.append(mask_placeholder) |
| 261 |
value_pos = end |
| 262 |
|
| 263 |
parts.append(value[value_pos:]) |
| 264 |
|
| 265 |
return "".join(parts) |
| 266 |
except Exception: |
| 267 |
# We deliberately do not include the value or original exception |
| 268 |
# to avoid leaking secrets through the exception. |
| 269 |
raise AnsibleSecretMaskError("secret masking failed") from None |
| 270 |
|
| 271 |
def secrets_in_json(self, value: str) -> frozenset[str]: |
| 272 |
"""Return the registered secrets present in a JSON document, as their literal values.""" |
| 273 |
if not value: |
| 274 |
return _emptyfrozenset |
| 275 |
|
| 276 |
spans = None |
| 277 |
with self._lock: |
| 278 |
if self._forms: |
| 279 |
spans = self._matcher.spans(value) |
| 280 |
|
| 281 |
if not spans: |
| 282 |
return _emptyfrozenset |
| 283 |
|
| 284 |
# Every matched form is either a registered secret or a JSON-encoded form derived from one. |
| 285 |
# If it's a derived form, return the secret it was derived from. The result is a set of the |
| 286 |
# literal secrets the JSON represents and not how they appear in the JSON. The receiver of |
| 287 |
# the secrets can register them which builds the derived forms again internally. |
| 288 |
json_forms = self._json_forms |
| 289 |
return frozenset(json_forms.get(form, form) for form in (value[start:end] for start, end in spans)) |
| 290 |
|
| 291 |
def _add(self, secret: str) -> bool: |
| 292 |
"""Register ``secret`` (already length-checked and trimmed) and every form it can appear in. |
| 293 |
|
| 294 |
Returns False if ``secret`` was already registered. A form shared with another secret (a |
| 295 |
secret that is itself the JSON-escaped form of another) is only handed to the matcher once. |
| 296 |
""" |
| 297 |
if secret in self._secrets: |
| 298 |
return False |
| 299 |
|
| 300 |
self._secrets.add(secret) |
| 301 |
|
| 302 |
# Majority of the output in Ansible is JSON and we use it when transferring module data to |
| 303 |
# the target. As JSON can escape characters we will also register the JSON encoded form of |
| 304 |
# the secret (without quotes). Both UTF-8 and non-ASCII escaped forms are registered as |
| 305 |
# the legacy module serialization profile does ensure_ascii=True while modern does not. If |
| 306 |
# the secret does not contain any special characters nothing extra is added to the registry. |
| 307 |
# FUTURE: measure the cost of deriving both forms on large registries. |
| 308 |
json_ascii_form = _json_encoder.encode_basestring_ascii(secret)[1:-1] |
| 309 |
secret_forms = {secret, json_ascii_form} |
| 310 |
if secret != json_ascii_form: |
| 311 |
# If the ASCII encoded form differs then we need to check the UTF-8 encoded form as well. |
| 312 |
secret_forms.add(_json_encoder.encode_basestring(secret)[1:-1]) |
| 313 |
|
| 314 |
for form in secret_forms: |
| 315 |
if form != secret: |
| 316 |
self._json_forms[form] = secret |
| 317 |
|
| 318 |
if form in self._forms: |
| 319 |
continue |
| 320 |
self._forms.add(form) |
| 321 |
self._matcher.add(form) |
| 322 |
|
| 323 |
return True |
| 324 |
|
| 325 |
|
| 326 |
class NewSecretTracker: |
| 327 |
"""Used to track newly registered secrets once the tracker was registered.""" |
| 328 |
|
| 329 |
def __init__(self, masker: SecretMasker): |
| 330 |
self._new_secrets: set[str] = set() |
| 331 |
self._masker = masker |
| 332 |
|
| 333 |
def unregister(self): |
| 334 |
with self._masker._lock: |
| 335 |
self._masker._new_secret_trackers.discard(self) |
| 336 |
|
| 337 |
def flush(self) -> frozenset[str]: |
| 338 |
with self._masker._lock: |
| 339 |
if not self._new_secrets: |
| 340 |
return _emptyfrozenset |
| 341 |
flushed = frozenset(self._new_secrets) |
| 342 |
self._new_secrets = set() |
| 343 |
return flushed |
| 344 |
|
| 345 |
|
| 346 |
_secret_masker = SecretMasker() # default shared instance |