| 1 |
using System; |
| 2 |
using System.Collections.Generic; |
| 3 |
using System.Globalization; |
| 4 |
using System.Runtime.InteropServices; |
| 5 |
using System.Security; |
| 6 |
using System.Text; |
| 7 |
|
| 8 |
namespace Ansible.Secrets |
| 9 |
{ |
| 10 |
// See lib/ansible/module_utils/_internal/_secrets.py for the Python impl and details behind algorithm choices. |
| 11 |
public class SecretMasker |
| 12 |
{ |
| 13 |
// Not marked readonly so integration tests can reset the singleton to a |
| 14 |
// pristine instance via reflection between test cases (setting a static |
| 15 |
// readonly field via reflection is not supported on CoreCLR). |
| 16 |
private static SecretMasker _instance = new SecretMasker(); |
| 17 |
|
| 18 |
// If any of these are changed we need to ensure that _secrets.py is updated to match. |
| 19 |
private const int MinimumSecretLength = 4; // below this, not registered at all |
| 20 |
private const int MaximumShortSecretLength = 6; // above this, mask unconditionally |
| 21 |
private const int MaximumSecretLength = 65536; // trims to this length as a cap for registration and matching |
| 22 |
private static readonly char[] StripChars = new char[] { ' ', '\t', '\r', '\n' }; // stripped from both ends before registration |
| 23 |
private const int AnchorLength = MinimumSecretLength; |
| 24 |
private const int ProbeLength = 8; // chars compared from the middle of a candidate before the full comparison |
| 25 |
|
| 26 |
private readonly Dictionary<string, List<Bucket>> _scan; // anchor -> buckets, longest first |
| 27 |
private readonly HashSet<string> _registered; |
| 28 |
private HashSet<string> _newSecrets; |
| 29 |
|
| 30 |
private sealed class Bucket |
| 31 |
{ |
| 32 |
public readonly int Length; // in UTF-16 chars, like the spans |
| 33 |
public readonly int ProbeOffset; |
| 34 |
public readonly int ProbeSize; |
| 35 |
public readonly HashSet<string> Probes = new HashSet<string>(StringComparer.Ordinal); |
| 36 |
public readonly HashSet<string> Values = new HashSet<string>(StringComparer.Ordinal); |
| 37 |
|
| 38 |
public Bucket(int length) |
| 39 |
{ |
| 40 |
Length = length; |
| 41 |
ProbeSize = Math.Min(ProbeLength, length); |
| 42 |
ProbeOffset = Math.Max(0, length / 2 - ProbeSize / 2); |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
/// <summary> |
| 47 |
/// Internal API: Used to register initial secrets known to Ansible. |
| 48 |
/// </summary> |
| 49 |
/// <param name="secrets">The initial secrets to register with the masker</param> |
| 50 |
public static void _RegisterAnsibleSecrets(IEnumerable<SecureString> secrets) |
| 51 |
{ |
| 52 |
SecretMasker masker = _instance; |
| 53 |
|
| 54 |
foreach (SecureString secret in secrets) |
| 55 |
{ |
| 56 |
masker.RegisterSecretImpl(secret); |
| 57 |
} |
| 58 |
|
| 59 |
masker.DrainNewSecretsImpl(); |
| 60 |
} |
| 61 |
|
| 62 |
/// <summary> |
| 63 |
/// Drains any new secrets that have been registered since the last call to this method. |
| 64 |
/// Used to determine what secrets need to be sent to the Ansible controller for masking. |
| 65 |
/// </summary> |
| 66 |
/// <returns>The unique secrets that have been registered.</returns> |
| 67 |
public static HashSet<string> DrainNewSecrets() |
| 68 |
{ |
| 69 |
return _instance.DrainNewSecretsImpl(); |
| 70 |
} |
| 71 |
|
| 72 |
/// <summary> |
| 73 |
/// Registers a new secret with the masker. |
| 74 |
/// </summary> |
| 75 |
/// <param name="secret">The secret to register</param> |
| 76 |
public static void RegisterSecret(SecureString secret) |
| 77 |
{ |
| 78 |
_instance.RegisterSecretImpl(secret); |
| 79 |
} |
| 80 |
|
| 81 |
/// <summary> |
| 82 |
/// Registers a new secret with the masker. |
| 83 |
/// Use the SecureString overload if possible to avoid AMSI logging in PowerShell. |
| 84 |
/// </summary> |
| 85 |
/// <param name="secret">The secret to register</param> |
| 86 |
public static void RegisterSecret(string secret) |
| 87 |
{ |
| 88 |
_instance.RegisterSecretImpl(secret); |
| 89 |
} |
| 90 |
|
| 91 |
/// <summary> |
| 92 |
/// Masks any registered secrets found in the input string with the default placeholder "$REDACTED$". |
| 93 |
/// </summary> |
| 94 |
/// <param name="value">The input string to mask</param> |
| 95 |
/// <returns>The masked string</returns> |
| 96 |
public static string MaskString(string value) |
| 97 |
{ |
| 98 |
return MaskString(value, "$REDACTED$"); |
| 99 |
} |
| 100 |
|
| 101 |
/// <summary> |
| 102 |
/// Masks any registered secrets found in the input string with the specified placeholder. |
| 103 |
/// </summary> |
| 104 |
/// <param name="value">The input string to mask</param> |
| 105 |
/// <param name="maskPlaceholder">The placeholder to use for masking secrets</param> |
| 106 |
/// <returns>The masked string</returns> |
| 107 |
public static string MaskString(string value, string maskPlaceholder) |
| 108 |
{ |
| 109 |
return _instance.MaskStringImpl(value, maskPlaceholder); |
| 110 |
} |
| 111 |
|
| 112 |
private SecretMasker() |
| 113 |
{ |
| 114 |
_scan = new Dictionary<string, List<Bucket>>(StringComparer.Ordinal); |
| 115 |
_registered = new HashSet<string>(StringComparer.Ordinal); |
| 116 |
_newSecrets = new HashSet<string>(StringComparer.Ordinal); |
| 117 |
} |
| 118 |
|
| 119 |
private HashSet<string> DrainNewSecretsImpl() |
| 120 |
{ |
| 121 |
HashSet<string> result = _newSecrets; |
| 122 |
_newSecrets = new HashSet<string>(StringComparer.Ordinal); |
| 123 |
return result; |
| 124 |
} |
| 125 |
|
| 126 |
private void RegisterSecretImpl(SecureString secret) |
| 127 |
{ |
| 128 |
if (secret.Length == 0) |
| 129 |
{ |
| 130 |
return; |
| 131 |
} |
| 132 |
|
| 133 |
IntPtr stringPtr = IntPtr.Zero; |
| 134 |
try |
| 135 |
{ |
| 136 |
stringPtr = Marshal.SecureStringToBSTR(secret); |
| 137 |
string secretString = Marshal.PtrToStringBSTR(stringPtr); |
| 138 |
RegisterSecretImpl(secretString); |
| 139 |
} |
| 140 |
finally |
| 141 |
{ |
| 142 |
if (stringPtr != IntPtr.Zero) |
| 143 |
{ |
| 144 |
Marshal.ZeroFreeBSTR(stringPtr); |
| 145 |
} |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
private void RegisterSecretImpl(string secret) |
| 150 |
{ |
| 151 |
if (secret == null) |
| 152 |
{ |
| 153 |
return; |
| 154 |
} |
| 155 |
|
| 156 |
// Copies behaviour of Python to strip whitespace and trim to the |
| 157 |
// maximum length before registering. |
| 158 |
secret = TrimToCodePoints(secret.Trim(StripChars), MaximumSecretLength); |
| 159 |
if (CodePointCount(secret, 0, secret.Length) < MinimumSecretLength) |
| 160 |
{ |
| 161 |
return; |
| 162 |
} |
| 163 |
|
| 164 |
if (!_registered.Add(secret)) |
| 165 |
{ |
| 166 |
return; |
| 167 |
} |
| 168 |
|
| 169 |
_newSecrets.Add(secret); |
| 170 |
|
| 171 |
// Register the literal value and the forms it takes once JSON encoded. The ASCII |
| 172 |
// form escapes non-ASCII characters as well (legacy module serialization profile), |
| 173 |
// the other form only escapes what JSON requires (modern profile). When the ASCII |
| 174 |
// form is the same as the literal value neither form can differ from it. |
| 175 |
AddValue(secret); |
| 176 |
|
| 177 |
string jsonAsciiForm = JsonEncode(secret, true); |
| 178 |
if (jsonAsciiForm != secret) |
| 179 |
{ |
| 180 |
AddValue(jsonAsciiForm); |
| 181 |
AddValue(JsonEncode(secret, false)); |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
private void AddValue(string value) |
| 186 |
{ |
| 187 |
string anchor = value.Substring(0, AnchorLength); |
| 188 |
|
| 189 |
List<Bucket> buckets; |
| 190 |
if (!_scan.TryGetValue(anchor, out buckets)) |
| 191 |
{ |
| 192 |
buckets = new List<Bucket>(); |
| 193 |
_scan[anchor] = buckets; |
| 194 |
} |
| 195 |
|
| 196 |
Bucket bucket = buckets.Find(b => b.Length == value.Length); |
| 197 |
if (bucket == null) |
| 198 |
{ |
| 199 |
bucket = new Bucket(value.Length); |
| 200 |
buckets.Add(bucket); |
| 201 |
|
| 202 |
// Buckets are kept longest first so FindSpans reports the spans at one position |
| 203 |
// longest first, the order MergeSpans relies on. |
| 204 |
buckets.Sort((a, b) => b.Length.CompareTo(a.Length)); |
| 205 |
} |
| 206 |
|
| 207 |
bucket.Probes.Add(value.Substring(bucket.ProbeOffset, bucket.ProbeSize)); |
| 208 |
bucket.Values.Add(value); |
| 209 |
} |
| 210 |
|
| 211 |
private static int CodePointCount(string value, int start, int end) |
| 212 |
{ |
| 213 |
int count = end - start; |
| 214 |
for (int i = start; i < end - 1; i++) |
| 215 |
{ |
| 216 |
if (char.IsSurrogatePair(value[i], value[i + 1])) |
| 217 |
{ |
| 218 |
count--; |
| 219 |
i++; |
| 220 |
} |
| 221 |
} |
| 222 |
|
| 223 |
return count; |
| 224 |
} |
| 225 |
|
| 226 |
private static string TrimToCodePoints(string value, int maxCodePoints) |
| 227 |
{ |
| 228 |
if (value.Length <= maxCodePoints) |
| 229 |
{ |
| 230 |
return value; |
| 231 |
} |
| 232 |
|
| 233 |
int index = 0; |
| 234 |
for (int count = 0; count < maxCodePoints && index < value.Length; count++) |
| 235 |
{ |
| 236 |
index += char.IsSurrogatePair(value, index) ? 2 : 1; |
| 237 |
} |
| 238 |
|
| 239 |
return index < value.Length ? value.Substring(0, index) : value; |
| 240 |
} |
| 241 |
|
| 242 |
/// <summary> |
| 243 |
/// Encodes a string as the Python json module would, without the surrounding quotes. With |
| 244 |
/// <paramref name="asciiOnly"/> every character outside the printable ASCII range is escaped as |
| 245 |
/// \uXXXX (ensure_ascii=True), otherwise only the characters JSON requires to be escaped are. |
| 246 |
/// </summary> |
| 247 |
private static string JsonEncode(string value, bool asciiOnly) |
| 248 |
{ |
| 249 |
StringBuilder sb = null; |
| 250 |
|
| 251 |
for (int i = 0; i < value.Length; i++) |
| 252 |
{ |
| 253 |
char c = value[i]; |
| 254 |
string escaped = null; |
| 255 |
|
| 256 |
switch (c) |
| 257 |
{ |
| 258 |
case '"': |
| 259 |
escaped = "\\\""; |
| 260 |
break; |
| 261 |
case '\\': |
| 262 |
escaped = "\\\\"; |
| 263 |
break; |
| 264 |
case '\n': |
| 265 |
escaped = "\\n"; |
| 266 |
break; |
| 267 |
case '\r': |
| 268 |
escaped = "\\r"; |
| 269 |
break; |
| 270 |
case '\t': |
| 271 |
escaped = "\\t"; |
| 272 |
break; |
| 273 |
case '\b': |
| 274 |
escaped = "\\b"; |
| 275 |
break; |
| 276 |
case '\f': |
| 277 |
escaped = "\\f"; |
| 278 |
break; |
| 279 |
default: |
| 280 |
if (c < ' ' || (asciiOnly && c > '~')) |
| 281 |
{ |
| 282 |
// Python escapes each UTF-16 code unit, so a surrogate pair becomes two escapes. |
| 283 |
escaped = "\\u" + ((int)c).ToString("x4"); |
| 284 |
} |
| 285 |
break; |
| 286 |
} |
| 287 |
|
| 288 |
if (escaped == null) |
| 289 |
{ |
| 290 |
if (sb != null) |
| 291 |
{ |
| 292 |
sb.Append(c); |
| 293 |
} |
| 294 |
continue; |
| 295 |
} |
| 296 |
|
| 297 |
if (sb == null) |
| 298 |
{ |
| 299 |
sb = new StringBuilder(value.Length + 16); |
| 300 |
sb.Append(value, 0, i); |
| 301 |
} |
| 302 |
sb.Append(escaped); |
| 303 |
} |
| 304 |
|
| 305 |
return sb == null ? value : sb.ToString(); |
| 306 |
} |
| 307 |
|
| 308 |
private string MaskStringImpl(string value, string maskPlaceholder) |
| 309 |
{ |
| 310 |
if (string.IsNullOrEmpty(value) || _scan.Count == 0) |
| 311 |
{ |
| 312 |
return value; |
| 313 |
} |
| 314 |
|
| 315 |
List<int[]> spans = MergeSpans(value, FindSpans(value)); |
| 316 |
if (spans.Count == 0) |
| 317 |
{ |
| 318 |
return value; |
| 319 |
} |
| 320 |
|
| 321 |
StringBuilder sb = new StringBuilder(value.Length); |
| 322 |
int valuePos = 0; |
| 323 |
foreach (int[] span in spans) |
| 324 |
{ |
| 325 |
sb.Append(value, valuePos, span[0] - valuePos); |
| 326 |
sb.Append(maskPlaceholder); |
| 327 |
valuePos = span[1]; |
| 328 |
} |
| 329 |
sb.Append(value, valuePos, value.Length - valuePos); |
| 330 |
|
| 331 |
return sb.ToString(); |
| 332 |
} |
| 333 |
|
| 334 |
/// <summary> |
| 335 |
/// Every occurrence of every registered value in <paramref name="value"/> as [start, end) spans. |
| 336 |
/// </summary> |
| 337 |
private List<int[]> FindSpans(string value) |
| 338 |
{ |
| 339 |
List<int[]> spans = new List<int[]>(); |
| 340 |
int valueLength = value.Length; |
| 341 |
|
| 342 |
// A value shorter than the anchor never enters the loop and yields no spans. |
| 343 |
for (int start = 0; start <= valueLength - AnchorLength; start++) |
| 344 |
{ |
| 345 |
List<Bucket> buckets; |
| 346 |
if (!_scan.TryGetValue(value.Substring(start, AnchorLength), out buckets)) |
| 347 |
{ |
| 348 |
continue; |
| 349 |
} |
| 350 |
|
| 351 |
foreach (Bucket bucket in buckets) |
| 352 |
{ |
| 353 |
int end = start + bucket.Length; |
| 354 |
if (end > valueLength) |
| 355 |
{ |
| 356 |
continue; |
| 357 |
} |
| 358 |
|
| 359 |
if (!bucket.Probes.Contains(value.Substring(start + bucket.ProbeOffset, bucket.ProbeSize))) |
| 360 |
{ |
| 361 |
continue; |
| 362 |
} |
| 363 |
|
| 364 |
if (!bucket.Values.Contains(value.Substring(start, bucket.Length))) |
| 365 |
{ |
| 366 |
continue; |
| 367 |
} |
| 368 |
|
| 369 |
spans.Add(new int[] { start, end }); |
| 370 |
} |
| 371 |
} |
| 372 |
|
| 373 |
return spans; |
| 374 |
} |
| 375 |
|
| 376 |
/// <summary> |
| 377 |
/// Merges overlapping/touching spans into one placeholder each and drops the runs that do not |
| 378 |
/// qualify. Mirrors _merge_spans in _secrets.py, see there for the rules and examples. |
| 379 |
/// </summary> |
| 380 |
private static List<int[]> MergeSpans(string value, List<int[]> spans) |
| 381 |
{ |
| 382 |
if (spans.Count == 0) |
| 383 |
{ |
| 384 |
return spans; |
| 385 |
} |
| 386 |
|
| 387 |
List<int[]> result = new List<int[]>(); |
| 388 |
|
| 389 |
int runStart = spans[0][0]; |
| 390 |
int runEnd = spans[0][1]; |
| 391 |
bool keep = SpanIsQualified(value, runStart, runEnd); |
| 392 |
|
| 393 |
for (int i = 1; i < spans.Count; i++) |
| 394 |
{ |
| 395 |
int start = spans[i][0]; |
| 396 |
int end = spans[i][1]; |
| 397 |
|
| 398 |
if (start > runEnd) |
| 399 |
{ |
| 400 |
// Current run is complete, start new run with the current span. |
| 401 |
if (keep) |
| 402 |
{ |
| 403 |
result.Add(new int[] { runStart, runEnd }); |
| 404 |
} |
| 405 |
|
| 406 |
runStart = start; |
| 407 |
runEnd = end; |
| 408 |
keep = SpanIsQualified(value, start, end); |
| 409 |
} |
| 410 |
else if (end > runEnd) |
| 411 |
{ |
| 412 |
// Span is inside or touching the current run and extends it. |
| 413 |
runEnd = end; |
| 414 |
keep = true; |
| 415 |
} |
| 416 |
else if (!keep) |
| 417 |
{ |
| 418 |
// Span lies inside the current run that is not qualified by its own merit. |
| 419 |
keep = SpanIsQualified(value, start, end); |
| 420 |
} |
| 421 |
} |
| 422 |
|
| 423 |
if (keep) |
| 424 |
{ |
| 425 |
result.Add(new int[] { runStart, runEnd }); |
| 426 |
} |
| 427 |
|
| 428 |
return result; |
| 429 |
} |
| 430 |
|
| 431 |
private static bool SpanIsQualified(string value, int start, int end) |
| 432 |
{ |
| 433 |
// Every code point is at most two chars, so a span longer than twice the limit in chars is |
| 434 |
// long whatever it contains and the code points only need counting below that. |
| 435 |
int length = end - start; |
| 436 |
if (length > MaximumShortSecretLength * 2 || CodePointCount(value, start, end) > MaximumShortSecretLength) |
| 437 |
{ |
| 438 |
return true; |
| 439 |
} |
| 440 |
|
| 441 |
bool boundaryLeft = start == 0 || !IsAlphaNumeric(value, start - 1); |
| 442 |
bool boundaryRight = end == value.Length || !IsAlphaNumeric(value, end); |
| 443 |
return boundaryLeft && boundaryRight; |
| 444 |
} |
| 445 |
|
| 446 |
/// <summary> |
| 447 |
/// Matches Python's str.isalnum for the character at <paramref name="index"/>: any letter or number |
| 448 |
/// category, with a surrogate pair classified as the code point it encodes. |
| 449 |
/// </summary> |
| 450 |
private static bool IsAlphaNumeric(string value, int index) |
| 451 |
{ |
| 452 |
if (index > 0 && char.IsLowSurrogate(value[index]) && char.IsHighSurrogate(value[index - 1])) |
| 453 |
{ |
| 454 |
index--; |
| 455 |
} |
| 456 |
|
| 457 |
switch (CharUnicodeInfo.GetUnicodeCategory(value, index)) |
| 458 |
{ |
| 459 |
case UnicodeCategory.UppercaseLetter: |
| 460 |
case UnicodeCategory.LowercaseLetter: |
| 461 |
case UnicodeCategory.TitlecaseLetter: |
| 462 |
case UnicodeCategory.ModifierLetter: |
| 463 |
case UnicodeCategory.OtherLetter: |
| 464 |
case UnicodeCategory.DecimalDigitNumber: |
| 465 |
case UnicodeCategory.LetterNumber: |
| 466 |
case UnicodeCategory.OtherNumber: |
| 467 |
return true; |
| 468 |
default: |
| 469 |
return false; |
| 470 |
} |
| 471 |
} |
| 472 |
} |
| 473 |
} |