Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- `WalterEgo.Core`: alter ego model (`HoneyToken`) with a mandatory placement, a decoy class (generic or unique)
and severity defaults derived from the class.
- `WalterEgo.Core`: immutable token registry (`ITokenRegistry`) with allocation-free lookups by identifier and by
raw value.
- `WalterEgo.Core`: keyed digests of decoy values (`ISecretHasher`, `SecretDigest`): HMAC-SHA256 with a mandatory
key of at least 32 bytes and one derived subkey per trigger domain, so reading the configuration does not reveal
which values are decoys.
19 changes: 19 additions & 0 deletions src/WalterEgo.Core/Domain/DecoyClass.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
namespace WalterEgo;

/// <summary>
/// How much a trip of an alter ego can be trusted.
/// </summary>
public enum DecoyClass
{
/// <summary>
/// A well-known decoy that any scanner finds without a leak, such as <c>/.env</c> or <c>admin</c>.
/// Its trips signal reconnaissance and carry low confidence.
/// </summary>
Generic = 1,

/// <summary>
/// A decoy that can only be found through the place where it was planted.
/// Its trips signal that this place leaked and carry high confidence.
/// </summary>
Unique = 2,
}
153 changes: 153 additions & 0 deletions src/WalterEgo.Core/Domain/HoneyToken.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
using System.Collections.Frozen;

namespace WalterEgo;

/// <summary>
/// An alter ego: a fake asset that no legitimate user has a reason to touch. A trip of an alter ego tells where
/// it was planted (<see cref="Placement"/>) and how much the trip can be trusted (<see cref="Class"/>).
/// </summary>
/// <remarks>
/// An instance only carries metadata. The decoy values that trip the alter ego are never part of it, so it can be
/// copied into events, logs and alert channels safely. Instances are immutable and always valid.
/// </remarks>
public sealed record HoneyToken
{
/// <summary>
/// Creates an alter ego.
/// </summary>
/// <param name="id">The identifier of the alter ego.</param>
/// <param name="kind">The kind of asset the alter ego imitates.</param>
/// <param name="decoyClass">Whether the alter ego is a generic decoy or a unique one.</param>
/// <param name="placement">
/// Where the alter ego was planted, such as "LEGACY_KEY variable in the CI of the orders repository". Up to 512
/// characters, not blank, without control characters or line separators.
/// </param>
/// <param name="severity">The severity of a trip of the alter ego.</param>
/// <param name="name">
/// A readable name. Up to 128 characters, not blank, without control characters or line separators. When
/// <see langword="null"/>, the identifier is used.
/// </param>
/// <param name="description">
/// An optional description. Up to 1024 characters, without control characters or line separators.
/// </param>
/// <param name="tags">
/// Optional tags. Up to 16 entries; keys are lowercase slugs of up to 32 characters; values are not blank, have up
/// to 128 characters and no control characters or line separators. The entries are copied.
/// </param>
/// <exception cref="ArgumentException">Any argument breaks the rules above, <paramref name="id"/> is the default
/// value, or an enumeration argument is not a defined value.</exception>
public HoneyToken(
HoneyTokenId id,
HoneyTokenKind kind,
DecoyClass decoyClass,
string placement,
Severity severity,
string? name = null,
string? description = null,
IReadOnlyDictionary<string, string>? tags = null)
{
if (id.IsDefault)
{
throw new ArgumentException("The identifier is required.", nameof(id));
}

ThrowIfUndefined(HoneyTokenRules.IsDefined(kind), nameof(kind));
ThrowIfUndefined(HoneyTokenRules.IsDefined(decoyClass), nameof(decoyClass));
ThrowIfUndefined(HoneyTokenRules.IsDefined(severity), nameof(severity));
ThrowIfInvalid(HoneyTokenRules.CheckPlacement(placement), nameof(placement));
ThrowIfInvalid(HoneyTokenRules.CheckName(name), nameof(name));
ThrowIfInvalid(HoneyTokenRules.CheckDescription(description), nameof(description));

// The copy is validated, not the argument, so a dictionary that changes after the check cannot slip invalid
// tags in.
var frozenTags = tags?.ToFrozenDictionary(StringComparer.Ordinal);
ThrowIfInvalid(HoneyTokenRules.CheckTags(frozenTags), nameof(tags));

Id = id;
Kind = kind;
Class = decoyClass;
Placement = placement;
Severity = severity;
Name = name ?? id.Value;
Description = description;
Tags = frozenTags ?? FrozenDictionary<string, string>.Empty;
}

/// <summary>Gets the identifier of the alter ego.</summary>
public HoneyTokenId Id { get; }

/// <summary>Gets the kind of asset the alter ego imitates.</summary>
public HoneyTokenKind Kind { get; }

/// <summary>Gets whether the alter ego is a generic decoy or a unique one.</summary>
public DecoyClass Class { get; }

/// <summary>Gets the readable name, which is the identifier when no name was given.</summary>
public string Name { get; }

/// <summary>Gets where the alter ego was planted.</summary>
public string Placement { get; }

/// <summary>Gets the optional description.</summary>
public string? Description { get; }

/// <summary>Gets the severity of a trip of the alter ego.</summary>
public Severity Severity { get; }

/// <summary>Gets the tags, compared by ordinal keys. Empty when no tags were given.</summary>
public IReadOnlyDictionary<string, string> Tags { get; }

/// <summary>
/// Compares two alter egos by all their values, including the content of <see cref="Tags"/>.
/// </summary>
/// <param name="other">The alter ego to compare with.</param>
/// <returns><see langword="true"/> when both alter egos have the same values.</returns>
public bool Equals(HoneyToken? other) =>
other is not null
&& Id == other.Id
&& Kind == other.Kind
&& Class == other.Class
&& Severity == other.Severity
&& string.Equals(Name, other.Name, StringComparison.Ordinal)
&& string.Equals(Placement, other.Placement, StringComparison.Ordinal)
&& string.Equals(Description, other.Description, StringComparison.Ordinal)
&& TagsEqual(Tags, other.Tags);

/// <inheritdoc/>
public override int GetHashCode() =>
HashCode.Combine(Id, Kind, Class, Severity, Name, Placement, Description, Tags.Count);

private static bool TagsEqual(IReadOnlyDictionary<string, string> left, IReadOnlyDictionary<string, string> right)
{
if (left.Count != right.Count)
{
return false;
}

foreach (var (key, value) in left)
{
if (!right.TryGetValue(key, out var otherValue) || !string.Equals(value, otherValue, StringComparison.Ordinal))
{
return false;
}
}

return true;
}

private static void ThrowIfUndefined(bool isDefined, string parameterName)
{
if (!isDefined)
{
throw new ArgumentException("The value is not defined in its enumeration.", parameterName);
}
}

private static void ThrowIfInvalid(string? error, string parameterName)
{
if (error is not null)
{
throw new ArgumentException(error, parameterName);
}
}
}
63 changes: 63 additions & 0 deletions src/WalterEgo.Core/Domain/HoneyTokenId.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System.Diagnostics.CodeAnalysis;

namespace WalterEgo;

/// <summary>
/// Identifies an alter ego. The identifier is chosen by the user, must stay the same across restarts and is
/// included in every alert about the alter ego.
/// </summary>
/// <remarks>
/// A valid identifier has 1 to 64 characters, starts with a lowercase ASCII letter or digit and contains only
/// lowercase ASCII letters, digits, <c>-</c>, <c>.</c> and <c>_</c>. Identifiers compare ordinally.
/// The default value is not a valid identifier and is rejected wherever an identifier is required.
/// </remarks>
public readonly record struct HoneyTokenId
{
private readonly string? _value;

/// <summary>
/// Creates an identifier.
/// </summary>
/// <param name="value">The identifier text.</param>
/// <exception cref="ArgumentException"><paramref name="value"/> is not a valid identifier.</exception>
public HoneyTokenId(string value)
{
if (!HoneyTokenRules.IsSlug(value, HoneyTokenRules.MaxIdLength))
{
throw new ArgumentException(HoneyTokenRules.InvalidIdMessage, nameof(value));
}

_value = value;
}

/// <summary>
/// Gets the identifier text, or an empty string for the default value.
/// </summary>
public string Value => _value ?? string.Empty;

internal bool IsDefault => _value is null;

/// <summary>
/// Tries to create an identifier.
/// </summary>
/// <param name="value">The identifier text.</param>
/// <param name="id">The identifier, or the default value when <paramref name="value"/> is not valid.</param>
/// <returns><see langword="true"/> when <paramref name="value"/> is a valid identifier.</returns>
public static bool TryCreate([NotNullWhen(true)] string? value, out HoneyTokenId id)
{
if (!HoneyTokenRules.IsSlug(value, HoneyTokenRules.MaxIdLength))
{
id = default;
return false;
}

id = new HoneyTokenId(value);
return true;
}

/// <summary>
/// Returns the identifier text.
/// </summary>
/// <returns>The identifier text, or an empty string for the default value.</returns>
public override string ToString() => Value;
}
28 changes: 28 additions & 0 deletions src/WalterEgo.Core/Domain/HoneyTokenKind.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace WalterEgo;

/// <summary>
/// The kind of asset an alter ego imitates.
/// </summary>
public enum HoneyTokenKind
{
/// <summary>An HTTP route that no legitimate client calls.</summary>
Endpoint = 1,

/// <summary>A username or e-mail address that belongs to nobody.</summary>
User = 2,

/// <summary>An API key in the application's own format that never authorizes anything.</summary>
ApiKey = 3,

/// <summary>A fictitious database row.</summary>
Row = 4,

/// <summary>A configuration entry that carries a beacon or another decoy value.</summary>
Config = 5,

/// <summary>A session token, such as a JWT or a cookie, that never validates.</summary>
SessionToken = 6,

/// <summary>A file that carries decoy credentials or a beacon.</summary>
File = 7,
}
108 changes: 108 additions & 0 deletions src/WalterEgo.Core/Domain/HoneyTokenRules.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;

namespace WalterEgo;

internal static class HoneyTokenRules
{
internal const int MaxIdLength = 64;
internal const int MaxNameLength = 128;
internal const int MaxPlacementLength = 512;
internal const int MaxDescriptionLength = 1024;
internal const int MaxTagCount = 16;
internal const int MaxTagKeyLength = 32;
internal const int MaxTagValueLength = 128;

internal const string InvalidIdMessage =
"The identifier must have 1 to 64 characters, start with a lowercase ASCII letter or digit and contain only lowercase ASCII letters, digits, '-', '.' and '_'.";

internal static bool IsSlug([NotNullWhen(true)] string? value, int maxLength)
{
if (string.IsNullOrEmpty(value) || value.Length > maxLength || !IsLowercaseAlphanumeric(value[0]))
{
return false;
}

foreach (var c in value.AsSpan(1))
{
if (!IsLowercaseAlphanumeric(c) && c is not ('-' or '.' or '_'))
{
return false;
}
}

return true;
}

internal static bool IsDefined(HoneyTokenKind kind) => kind is >= HoneyTokenKind.Endpoint and <= HoneyTokenKind.File;

internal static bool IsDefined(DecoyClass decoyClass) => decoyClass is DecoyClass.Generic or DecoyClass.Unique;

internal static bool IsDefined(Severity severity) => severity is >= Severity.Low and <= Severity.Critical;

internal static bool IsDefined(TriggerDomain domain) => domain is >= TriggerDomain.ApiKey and <= TriggerDomain.RequestPath;

internal static string? CheckPlacement(string? placement) =>
CheckText(placement, "The placement", MaxPlacementLength, allowBlank: false);

internal static string? CheckName(string? name) =>
name is null ? null : CheckText(name, "The name", MaxNameLength, allowBlank: false);

internal static string? CheckDescription(string? description) =>
description is null ? null : CheckText(description, "The description", MaxDescriptionLength, allowBlank: true);

internal static string? CheckTags(IReadOnlyDictionary<string, string>? tags)
{
if (tags is null)
{
return null;
}

if (tags.Count > MaxTagCount)
{
return "An alter ego can have at most 16 tags.";
}

foreach (var (key, value) in tags)
{
if (!IsSlug(key, MaxTagKeyLength))
{
return "Tag keys must have 1 to 32 characters, start with a lowercase ASCII letter or digit and contain only lowercase ASCII letters, digits, '-', '.' and '_'.";
}

if (CheckText(value, "Each tag value", MaxTagValueLength, allowBlank: false) is { } error)
{
return error;
}
}

return null;
}

private static string? CheckText(string? text, string subject, int maxLength, bool allowBlank)
{
if (text is null || (!allowBlank && string.IsNullOrWhiteSpace(text)))
{
return $"{subject} must not be empty or white space.";
}

if (text.Length > maxLength)
{
return $"{subject} must have at most {maxLength} characters.";
}

// Line and paragraph separators are rejected with the control characters because they also break
// log lines and message layouts in alert channels.
foreach (var c in text)
{
if (char.GetUnicodeCategory(c) is UnicodeCategory.Control or UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator)
{
return $"{subject} must not contain control characters or line separators.";
}
}

return null;
}

private static bool IsLowercaseAlphanumeric(char c) => char.IsAsciiLetterLower(c) || char.IsAsciiDigit(c);
}
Loading
Loading