diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 090a42b..208197c 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -4,6 +4,7 @@ using Heimdall.Agent; using Heimdall.Agent.Logging; using Heimdall.Agent.Services; using Heimdall.Application.Discovery; +using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; @@ -50,10 +51,27 @@ builder.Services.AddHttpClient("IpResolver", client => client.Timeout = TimeSpan.FromSeconds(5); }); +// Data Protection — encrypts the agent API key at rest (issue #21). The key +// ring is persisted next to the state file so the agent can decrypt its +// identity after a restart. Directory locked to owner-only (0700). For +// production hardening against full-volume compromise, bind the key ring to a +// TPM/HSM-backed store or mount it outside the backed-up volume. +var stateDir = builder.Configuration["Agent:StateDirectory"] + ?? (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory()); +var keysDir = Path.Combine(stateDir, "dp-keys"); +Directory.CreateDirectory(keysDir); +if (OperatingSystem.IsLinux()) + File.SetUnixFileMode(keysDir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); +builder.Services.AddDataProtection() + .SetApplicationName("Heimdall.Agent") + .PersistKeysToFileSystem(new DirectoryInfo(keysDir)); + // Agent services builder.Services.AddSingleton(sp => { - var state = new AgentState(); + var state = new AgentState( + sp.GetRequiredService().CreateProtector(AgentState.KeyProtectionPurpose), + sp.GetRequiredService>()); var options = sp.GetRequiredService>().Value; var stateDir = options.StateDirectory diff --git a/src/Heimdall.Agent/Services/AgentState.cs b/src/Heimdall.Agent/Services/AgentState.cs index 7c91109..fc1ef2c 100644 --- a/src/Heimdall.Agent/Services/AgentState.cs +++ b/src/Heimdall.Agent/Services/AgentState.cs @@ -1,5 +1,8 @@ using System.Runtime.InteropServices; +using System.Security.Cryptography; using System.Text.Json; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.Logging; namespace Heimdall.Agent.Services; @@ -9,8 +12,31 @@ namespace Heimdall.Agent.Services; /// Uses an immutable snapshot pattern with for /// thread-safe concurrent reads/writes from multiple services. /// +/// +/// +/// Security: the API key is encrypted at rest with ASP.NET Core Data Protection +/// () before being written to agent-state.json +/// (0600). The key ring lives in {StateDirectory}/dp-keys (0700). +/// +/// +/// Threat model: encryption stops the key from leaking through a casual read of +/// the state file (backup of a single file, accidental copy, file viewer). A +/// compromise of the whole volume that also exposes the key ring defeats it — +/// for that threat model, bind the key ring to a hardware keystore (TPM/HSM) or +/// mount it outside the backed-up volume (see issue #21, prod hardening). +/// +/// public sealed class AgentState { + /// Data Protection purpose used to encrypt/decrypt the API key. + public const string KeyProtectionPurpose = "Heimdall.Agent.ApiKey"; + + private const string StateFileName = "agent-state.json"; + + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + private readonly IDataProtector? _protector; + private readonly ILogger? _logger; private string _stateDir = "/var/lib/heimdall"; private AgentSnapshot _snapshot = AgentSnapshot.Default; @@ -24,6 +50,31 @@ public sealed class AgentState public static readonly AgentSnapshot Default = new(Guid.Empty, null, null, null, null); } + /// + /// Wire format of the state file. holds the Data + /// Protection ciphertext (base64) when is + /// true. Files written before the encryption change (legacy) carry the + /// plaintext key with the flag absent/false and are migrated on load. + /// + private sealed record PersistedState( + Guid AgentId, + string? ApiKey, + bool ApiKeyProtected, + string? ApiKeyPrefix, + string? PublicIp, + int? HeartbeatIntervalSeconds); + + /// + /// Creates a state store. The protector is required to persist the API key + /// securely; throws if a key must be written without + /// one (fail-fast, no silent plaintext fallback). + /// + public AgentState(IDataProtector? protector = null, ILogger? logger = null) + { + _protector = protector; + _logger = logger; + } + /// /// Sets the directory for the state file. Called during DI setup. /// @@ -32,7 +83,7 @@ public sealed class AgentState _stateDir = directory; } - private string StatePath => Path.Combine(_stateDir, "agent-state.json"); + private string StatePath => Path.Combine(_stateDir, StateFileName); public Guid AgentId { @@ -69,7 +120,9 @@ public sealed class AgentState } /// - /// Loads a previously saved identity, or returns null if none exists. + /// Loads a previously saved identity, or returns null if none exists or the + /// state cannot be read. Legacy plaintext files are detected, kept in + /// memory and immediately rewritten encrypted (migration). /// public async Task LoadAsync(CancellationToken ct = default) { @@ -79,8 +132,40 @@ public sealed class AgentState try { var json = await File.ReadAllTextAsync(StatePath, ct); - var state = JsonSerializer.Deserialize(json); - return state is not null && state.AgentId != Guid.Empty ? state : null; + var persisted = JsonSerializer.Deserialize(json, JsonOptions); + if (persisted is null || persisted.AgentId == Guid.Empty) + return null; + + var loaded = new AgentState(_protector, _logger); + loaded.ConfigureStateDirectory(_stateDir); + loaded.AgentId = persisted.AgentId; + loaded.ApiKeyPrefix = persisted.ApiKeyPrefix; + loaded.PublicIp = persisted.PublicIp; + loaded.HeartbeatIntervalSeconds = persisted.HeartbeatIntervalSeconds; + + if (persisted.ApiKeyProtected) + { + loaded.ApiKey = persisted.ApiKey is null || _protector is null + ? null + : _protector.Unprotect(persisted.ApiKey); + } + else + { + // Legacy plaintext state — keep the key, rewrite the file encrypted. + loaded.ApiKey = persisted.ApiKey; + _logger?.LogInformation( + "Migrating legacy agent state to encrypted API key storage ({StatePath})", StatePath); + await loaded.SaveAsync(ct); + } + + return loaded; + } + catch (CryptographicException ex) + { + _logger?.LogWarning(ex, + "Failed to decrypt the agent API key from {StatePath}; the agent will re-register with Central", + StatePath); + return null; } catch (Exception ex) when (ex is IOException or JsonException) { @@ -90,18 +175,30 @@ public sealed class AgentState /// /// Persists the current identity to disk with restrictive permissions (0600). - /// The API key is stored as plaintext — in a production deployment, consider - /// encrypting the file or using a hardware-bound keystore (e.g., TPM/TPM2). + /// The API key is encrypted with Data Protection before being written; the + /// plaintext key never touches the file. /// public async Task SaveAsync(CancellationToken ct = default) { + if (ApiKey is not null && _protector is null) + throw new InvalidOperationException( + "AgentState requires an IDataProtector to persist the API key securely."); + Directory.CreateDirectory(_stateDir); // Set restrictive directory permissions (owner only) if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) File.SetUnixFileMode(_stateDir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); - var json = JsonSerializer.Serialize(this); + var persisted = new PersistedState( + AgentId, + ApiKey is null ? null : _protector!.Protect(ApiKey), + ApiKey is not null, + ApiKeyPrefix, + PublicIp, + HeartbeatIntervalSeconds); + + var json = JsonSerializer.Serialize(persisted, JsonOptions); await File.WriteAllTextAsync(StatePath, json, ct); // Restrict file to owner read/write only (0600) diff --git a/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs b/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs index 4dd5152..5a65c64 100644 --- a/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs @@ -1,6 +1,7 @@ using System.Net; using System.Text.Json; using Heimdall.Agent.Services; +using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using NSubstitute; @@ -9,6 +10,10 @@ namespace Heimdall.Agent.Tests; public class AgentRegistrationServiceTests : IDisposable { + /// Shared provider so the file written by the fixture can be read + /// back by the singleton state (same Data Protection key). + private static readonly EphemeralDataProtectionProvider Provider = new(); + private readonly AgentOptions _options = new() { CentralUrl = "http://heimdall.test", @@ -20,7 +25,7 @@ public class AgentRegistrationServiceTests : IDisposable }; private readonly TempDir _tmp = new(); - private readonly AgentState _state = new(); + private readonly AgentState _state = new(Provider.CreateProtector(AgentState.KeyProtectionPurpose)); private readonly SystemMetricsProvider _metrics = new(); public AgentRegistrationServiceTests() @@ -94,7 +99,7 @@ public class AgentRegistrationServiceTests : IDisposable public async Task ExistingIdentity_SkipsRegistration() { // Pre-populate the state file so LoadAsync() finds an identity - var saved = new AgentState(); + var saved = new AgentState(Provider.CreateProtector(AgentState.KeyProtectionPurpose)); saved.ConfigureStateDirectory(_tmp.Path); saved.AgentId = Guid.NewGuid(); saved.ApiKey = "existing-key"; @@ -202,7 +207,7 @@ public class AgentRegistrationServiceTests : IDisposable public async Task ExistingIdentity_Heartbeat_UsesXApiKeyHeader() { // Pre-populate the state file so LoadAsync() finds an identity - var saved = new AgentState(); + var saved = new AgentState(Provider.CreateProtector(AgentState.KeyProtectionPurpose)); saved.ConfigureStateDirectory(_tmp.Path); saved.AgentId = Guid.NewGuid(); saved.ApiKey = "existing-key"; diff --git a/tests/Heimdall.Agent.Tests/AgentStateTests.cs b/tests/Heimdall.Agent.Tests/AgentStateTests.cs index f870b93..80ba6b8 100644 --- a/tests/Heimdall.Agent.Tests/AgentStateTests.cs +++ b/tests/Heimdall.Agent.Tests/AgentStateTests.cs @@ -1,16 +1,29 @@ using Heimdall.Agent.Services; +using Microsoft.AspNetCore.DataProtection; namespace Heimdall.Agent.Tests; public class AgentStateTests { + /// Shared provider so save+load within a test use the same key. + private static readonly EphemeralDataProtectionProvider Provider = new(); + + private static IDataProtector CreateProtector() => + Provider.CreateProtector(AgentState.KeyProtectionPurpose); + + private static AgentState CreateState(string dir) + { + var state = new AgentState(CreateProtector()); + state.ConfigureStateDirectory(dir); + return state; + } + [Fact] public async Task SaveAndLoad_PersistsIdentity() { using var tmp = new TempDir(); - var state = new AgentState(); - state.ConfigureStateDirectory(tmp.Path); + var state = CreateState(tmp.Path); state.AgentId = Guid.NewGuid(); state.ApiKey = "test-api-key-abc123"; state.ApiKeyPrefix = "abc"; @@ -18,8 +31,7 @@ public class AgentStateTests await state.SaveAsync(); - var loaded = new AgentState(); - loaded.ConfigureStateDirectory(tmp.Path); + var loaded = CreateState(tmp.Path); var result = await loaded.LoadAsync(); result.ShouldNotBeNull(); @@ -29,14 +41,93 @@ public class AgentStateTests result.PublicIp.ShouldBe("192.168.1.1"); } + [Fact] + public async Task Save_DoesNotPersistApiKeyInPlaintext() + { + using var tmp = new TempDir(); + + var state = CreateState(tmp.Path); + state.AgentId = Guid.NewGuid(); + state.ApiKey = "super-secret-key-42"; + state.ApiKeyPrefix = "ssk"; + + await state.SaveAsync(); + + var path = Path.Combine(tmp.Path, "agent-state.json"); + File.Exists(path).ShouldBeTrue(); + var json = await File.ReadAllTextAsync(path); + json.ShouldNotContain("super-secret-key-42"); + json.ShouldContain("\"apiKeyProtected\":true"); + } + + [Fact] + public async Task Load_MigratesLegacyPlaintextFile() + { + using var tmp = new TempDir(); + var agentId = Guid.NewGuid(); + var legacyJson = + $$"""{"AgentId":"{{agentId}}","ApiKey":"legacy-plain-key","ApiKeyPrefix":"abc","PublicIp":"10.0.0.1","HeartbeatIntervalSeconds":null}"""; + await File.WriteAllTextAsync(Path.Combine(tmp.Path, "agent-state.json"), legacyJson); + + var result = await CreateState(tmp.Path).LoadAsync(); + + result.ShouldNotBeNull(); + result!.AgentId.ShouldBe(agentId); + result.ApiKey.ShouldBe("legacy-plain-key"); + + // Migration: the file is rewritten encrypted, the key is no longer in clear. + var json = await File.ReadAllTextAsync(Path.Combine(tmp.Path, "agent-state.json")); + json.ShouldNotContain("legacy-plain-key"); + json.ShouldContain("\"apiKeyProtected\":true"); + + // A second load decrypts the migrated file. + var again = await CreateState(tmp.Path).LoadAsync(); + again.ShouldNotBeNull(); + again!.ApiKey.ShouldBe("legacy-plain-key"); + } + + [Fact] + public async Task Load_WhenCipherCannotBeDecrypted_ReturnsNull() + { + using var tmp = new TempDir(); + + var state = CreateState(tmp.Path); + state.AgentId = Guid.NewGuid(); + state.ApiKey = "key-encrypted-with-provider-a"; + await state.SaveAsync(); + + // A different Data Protection provider holds a different key and cannot + // decrypt the ciphertext → treated like a corrupt state file. + var foreign = new AgentState( + new EphemeralDataProtectionProvider().CreateProtector(AgentState.KeyProtectionPurpose)); + foreign.ConfigureStateDirectory(tmp.Path); + var result = await foreign.LoadAsync(); + + result.ShouldBeNull(); + } + + [Fact] + public async Task Save_WithoutProtector_Throws() + { + using var tmp = new TempDir(); + + var state = new AgentState(); // no protector + state.ConfigureStateDirectory(tmp.Path); + state.AgentId = Guid.NewGuid(); + state.ApiKey = "should-not-be-saved"; + + await Should.ThrowAsync(state.SaveAsync()); + + // Nothing was persisted. + File.Exists(Path.Combine(tmp.Path, "agent-state.json")).ShouldBeFalse(); + } + [Fact] public async Task Load_WhenNoFile_ReturnsNull() { using var tmp = new TempDir(); - var state = new AgentState(); - state.ConfigureStateDirectory(tmp.Path); - var result = await state.LoadAsync(); + var result = await CreateState(tmp.Path).LoadAsync(); result.ShouldBeNull(); } @@ -48,9 +139,7 @@ public class AgentStateTests Directory.CreateDirectory(tmp.Path); await File.WriteAllTextAsync(Path.Combine(tmp.Path, "agent-state.json"), "not-json"); - var state = new AgentState(); - state.ConfigureStateDirectory(tmp.Path); - var result = await state.LoadAsync(); + var result = await CreateState(tmp.Path).LoadAsync(); result.ShouldBeNull(); } @@ -60,8 +149,7 @@ public class AgentStateTests { using var tmp = new TempDir(); - var state = new AgentState(); - state.ConfigureStateDirectory(tmp.Path); + var state = CreateState(tmp.Path); state.AgentId = Guid.NewGuid(); await state.SaveAsync(); @@ -75,15 +163,12 @@ public class AgentStateTests { using var tmp = new TempDir(); - var state = new AgentState(); - state.ConfigureStateDirectory(tmp.Path); + var state = CreateState(tmp.Path); state.AgentId = Guid.Empty; state.ApiKey = "some-key"; await state.SaveAsync(); - var loaded = new AgentState(); - loaded.ConfigureStateDirectory(tmp.Path); - var result = await loaded.LoadAsync(); + var result = await CreateState(tmp.Path).LoadAsync(); result.ShouldBeNull(); } diff --git a/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj b/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj index 47474bb..9943eb8 100644 --- a/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj +++ b/tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj @@ -9,6 +9,7 @@ +