diff --git a/docs/deployment/air-gapped.md b/docs/deployment/air-gapped.md new file mode 100644 index 00000000..8fde0f8c --- /dev/null +++ b/docs/deployment/air-gapped.md @@ -0,0 +1,55 @@ +# Air-gapped and offline site bundles + +Sites with no network path to Azure or the Bower management API can export already-redacted +events and metadata-only site status into signed, hash-chained `.bowerbundle` archives for +sneakernet / media transfer. + +## Export on the offline collector + +```bash +bower export bundle \ + --database /var/lib/bower/queue.db \ + --out /media/transfer/site-a-001.bowerbundle \ + --signing-key /etc/bower/keys/export-private.pem \ + --collector-id site-a-collector \ + --environment site-a +``` + +Add `--encrypt-key-file /etc/bower/keys/aes256.key` (32 raw bytes, 64 hex characters, or +32-byte base64) to encrypt `events.ndjson` with AES-256-GCM bound to the signed manifest. +Each export advances a durable cursor in `queue_export_bundles` so consecutive exports +chain cleanly via `bundleSequence` and `previousBundleHash` without gaps or duplicates. + +## Verify before import + +```bash +bower verify bundle \ + --bundle /media/transfer/site-a-001.bowerbundle \ + --trusted-key /etc/bower/keys/export-public.pem \ + --expect-sequence 1 \ + --expect-previous-hash genesis +``` + +Verification fails closed (exit code 3) if the ECDSA P-256 signature is missing or +untrusted, the payload digest does not match the signed manifest, the event count differs, +or the chain sequence/hash is broken. + +## Import on the connected side + +```bash +bower import bundle \ + --bundle /media/transfer/site-a-001.bowerbundle \ + --trusted-key /etc/bower/keys/export-public.pem \ + --collector-url https://collector.connected.example:4319 \ + --management-url https://management.connected.example +``` + +- Already-redacted events (`events.ndjson`) are sent **only** to the receiving collector + (`/v1/events`), which deduplicates by fingerprint so re-importing a bundle is idempotent. +- Only the signed metadata-only `status-report.json` (zero event payloads, preserving + ISM-1985) is posted to `POST /api/fleet/offline-import`. Configure + `BOWER_OFFLINE_IMPORT_TRUSTED_KEYS` on the management API to trust the offline site's + public signing key. +- Imported offline collectors appear in the plain-English fleet view (`GET /api/fleet` and + the console) under **Offline site** (`offline-site`) instead of being flagged as stale or + offline. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 7490d237..7d360dd0 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -66,6 +66,13 @@ Commands: bower archive verify --archive DIR [--anchor SEQUENCE:HASH] bower archive replay --archive DIR --collector-url URL [--from ISO] [--to ISO] [--event-type TYPE]... [--collector-id ID] [--dry-run] + bower export bundle --database FILE --out FILE --signing-key PRIVATE.pem + [--collector-id ID] [--environment ENV] [--policy-hash HASH] + [--privacy-profile-hash HASH] [--encrypt-key-file FILE] [--max-events N] + bower verify bundle --bundle FILE --trusted-key PUBLIC.pem + [--expect-sequence N] [--expect-previous-hash HASH] [--decrypt-key-file FILE] + bower import bundle --bundle FILE --trusted-key PUBLIC.pem + [--collector-url URL] [--management-url URL] [--decrypt-key-file FILE] [--dry-run] bower sources check --expectations FILE [--database FILE] bower wec subscription generate --config FILE --subscription ID [--mode MinLatency|Normal|MinBandwidth|Custom] [--max-items N --max-latency-seconds N] [--heartbeat-seconds N] [--read-existing] [--subscription-id NAME] @@ -94,6 +101,9 @@ Commands: | `bower privacy` | [Custom redaction rules](../privacy/custom-redaction-rules.md) | | `bower policy` | [Suppression, population diff and archive](../operations/suppression-archive-and-source-silence.md) | | `bower archive` | [Suppression, population diff and archive](../operations/suppression-archive-and-source-silence.md) | +| `bower export` | [Air-gapped bundles](../deployment/air-gapped.md) | +| `bower verify` | [Air-gapped bundles](../deployment/air-gapped.md) | +| `bower import` | [Air-gapped bundles](../deployment/air-gapped.md) | | `bower sources` | [Source silence](../operations/suppression-archive-and-source-silence.md) | | `bower wec` | [Windows Event Forwarding](../deployment/windows-event-forwarding.md) | | `bower tap` | [Tap and top](../operations/tap-and-top.md) | diff --git a/src/Bower.Cli/Commands/BundleCommands.cs b/src/Bower.Cli/Commands/BundleCommands.cs new file mode 100644 index 00000000..bb7279c3 --- /dev/null +++ b/src/Bower.Cli/Commands/BundleCommands.cs @@ -0,0 +1,229 @@ +using System.Globalization; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Bower.Abstractions; +using Bower.Contracts; +using Bower.Evidence; +using Bower.Persistence; + +namespace Bower.Cli.Commands; + +internal static class BundleCommands +{ + /// + /// bower export bundle --database FILE --out FILE --signing-key PRIVATE.pem + /// [--collector-id ID] [--environment ENV] [--policy-hash HASH] [--privacy-profile-hash HASH] + /// [--encrypt-key-file FILE] [--max-events N] + /// + public static async Task ExportAsync(string[] args) + { + SqliteEventStore store = await QueueCommands.OpenStoreAsync(args); + string outPath = CliOptions.Required(args, "--out"); + string signingKeyPath = CliOptions.Required(args, "--signing-key"); + string signingKeyPem = await File.ReadAllTextAsync(signingKeyPath); + byte[]? encryptionKey = CliOptions.Get(args, "--encrypt-key-file") is { } encFile + ? AirGappedBundle.ReadEncryptionKeyFile(encFile) + : null; + int maxEvents = CliOptions.Int(args, "--max-events", 50_000); + if (maxEvents is < 1 or > 100_000) + { + throw new ArgumentException("--max-events must be between 1 and 100000."); + } + + ExportBundleCursor? last = await store.GetLastExportBundleAsync(); + long afterSequence = last?.ToLedgerSequence ?? 0; + long nextBundleSequence = (last?.BundleSequence ?? 0) + 1; + string previousBundleHash = last?.BundleHash ?? AirGappedBundleManifest.GenesisBundleHash; + + IReadOnlyList events = await store.ReadLedgerEventsAsync(afterSequence, maxEvents); + QueueSnapshot snapshot = await store.GetSnapshotAsync(); + LedgerHead head = await store.GetLedgerHeadAsync(); + long fromSequence = events.Count > 0 ? events[0].Sequence : afterSequence; + long toSequence = events.Count > 0 ? events[^1].Sequence : afterSequence; + string headHash = events.Count > 0 ? events[^1].ChainHash : head.Hash; + DateTimeOffset now = DateTimeOffset.UtcNow; + string bundleId = $"bundle-{Guid.CreateVersion7():N}"; + + AirGappedBundleManifest manifest = new( + AirGappedBundleManifest.CurrentKind, + bundleId, + CliOptions.Get(args, "--collector-id") ?? Environment.MachineName, + Environment.MachineName, + CliOptions.Get(args, "--environment") ?? "air-gapped", + BowerVersion.Current, + CliOptions.Get(args, "--policy-hash") ?? "local", + CliOptions.Get(args, "--privacy-profile-hash") ?? "default", + nextBundleSequence, + previousBundleHash, + fromSequence, + toSequence, + headHash, + events.Count, + snapshot.Queued + snapshot.Retrying + snapshot.Uploading, + snapshot.DeadLettered, + string.Empty, + encryptionKey is not null, + now.ToString("O", CultureInfo.InvariantCulture)); + + AirGappedExportResult result = AirGappedBundle.Create( + outPath, + manifest, + events.Select(item => item.Payload), + signingKeyPem, + encryptionKey); + + await store.RecordExportBundleAsync(new ExportBundleCursor( + result.BundleSequence, + result.BundleId, + result.FromLedgerSequence, + result.ToLedgerSequence, + result.BundleHash, + now)); + + Console.WriteLine(JsonSerializer.Serialize( + new BundleExportOutput( + result.BundleId, + result.BundleSequence, + result.BundleHash, + result.FromLedgerSequence, + result.ToLedgerSequence, + result.EventCount, + result.Encrypted), + CliJsonContext.Default.BundleExportOutput)); + return 0; + } + + /// + /// bower verify bundle --bundle FILE --trusted-key PUBLIC.pem + /// [--expect-sequence N] [--expect-previous-hash HASH] [--decrypt-key-file FILE] + /// + public static int Verify(string[] args) + { + string bundlePath = CliOptions.Required(args, "--bundle"); + IReadOnlyList trustedKeyPaths = CliOptions.All(args, "--trusted-key"); + if (trustedKeyPaths.Count == 0) + { + throw new ArgumentException("At least one --trusted-key PUBLIC.pem is required."); + } + + string[] keys = trustedKeyPaths.Select(File.ReadAllText).ToArray(); + long? expectedSeq = CliOptions.Has(args, "--expect-sequence") + ? CliOptions.Int(args, "--expect-sequence", 0) + : null; + string? expectedPrev = CliOptions.Get(args, "--expect-previous-hash"); + byte[]? decryptionKey = CliOptions.Get(args, "--decrypt-key-file") is { } decFile + ? AirGappedBundle.ReadEncryptionKeyFile(decFile) + : null; + + AirGappedBundleVerification verification = AirGappedBundle.Verify( + bundlePath, keys, expectedSeq, expectedPrev, decryptionKey); + Console.WriteLine(JsonSerializer.Serialize( + new BundleVerifyOutput( + verification.Valid, + verification.Error, + verification.Manifest?.BundleId, + verification.Manifest?.CollectorId, + verification.Manifest?.BundleSequence, + verification.BundleHash, + verification.Manifest?.EventCount, + verification.Manifest?.Encrypted), + CliJsonContext.Default.BundleVerifyOutput)); + return verification.Valid ? 0 : 3; + } + + /// + /// bower import bundle --bundle FILE --trusted-key PUBLIC.pem + /// [--collector-url URL] [--management-url URL] [--decrypt-key-file FILE] [--dry-run] + /// Verifies the bundle first. Submits already-redacted events only to --collector-url, and + /// submits only the signed metadata-only status report to --management-url. + /// + public static Task ImportAsync(string[] args) => ImportAsync(args, null, Console.Out, Console.Error); + + internal static async Task ImportAsync( + string[] args, + HttpMessageHandler? handler, + TextWriter output, + TextWriter error) + { + string bundlePath = CliOptions.Required(args, "--bundle"); + IReadOnlyList trustedKeyPaths = CliOptions.All(args, "--trusted-key"); + if (trustedKeyPaths.Count == 0) + { + throw new ArgumentException("At least one --trusted-key PUBLIC.pem is required."); + } + + string[] keys = trustedKeyPaths.Select(File.ReadAllText).ToArray(); + byte[]? decryptionKey = CliOptions.Get(args, "--decrypt-key-file") is { } decFile + ? AirGappedBundle.ReadEncryptionKeyFile(decFile) + : null; + bool dryRun = CliOptions.Has(args, "--dry-run"); + string? collectorUrl = CliOptions.Get(args, "--collector-url"); + string? managementUrl = CliOptions.Get(args, "--management-url"); + + AirGappedBundleVerification verification = AirGappedBundle.Verify(bundlePath, keys, decryptionKey: decryptionKey); + if (!verification.Valid || verification.Manifest is null || verification.OfflineReport is null) + { + output.WriteLine(JsonSerializer.Serialize( + new BundleVerifyOutput(false, verification.Error, null, null, null, null, null, null), + CliJsonContext.Default.BundleVerifyOutput)); + error.WriteLine($"Bundle failed verification: {verification.Error}"); + return 3; + } + + IReadOnlyList events = AirGappedBundle.ReadVerifiedEvents(bundlePath, keys, decryptionKey); + SortedDictionary collectorResponses = new(StringComparer.Ordinal); + string? managementStatus = null; + + if (!dryRun && !string.IsNullOrWhiteSpace(collectorUrl)) + { + using HttpClient client = new(handler ?? new HttpClientHandler(), disposeHandler: handler is null) + { + BaseAddress = new Uri(collectorUrl.EndsWith('/') ? collectorUrl : collectorUrl + "/"), + Timeout = TimeSpan.FromSeconds(30) + }; + if (Environment.GetEnvironmentVariable("BOWER_INGEST_TOKEN") is { Length: > 0 } token) + { + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + } + + foreach (string payload in events) + { + using StringContent content = new(payload, Encoding.UTF8, "application/json"); + using HttpResponseMessage response = await client.PostAsync("v1/events", content); + string code = ((int)response.StatusCode).ToString(CultureInfo.InvariantCulture); + collectorResponses[code] = collectorResponses.GetValueOrDefault(code) + 1; + } + } + + if (!dryRun && !string.IsNullOrWhiteSpace(managementUrl)) + { + using HttpClient mgmt = new(handler ?? new HttpClientHandler(), disposeHandler: handler is null) + { + BaseAddress = new Uri(managementUrl.EndsWith('/') ? managementUrl : managementUrl + "/"), + Timeout = TimeSpan.FromSeconds(30) + }; + if (Environment.GetEnvironmentVariable("BOWER_MANAGEMENT_TOKEN") is { Length: > 0 } mgmtToken) + { + mgmt.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", mgmtToken); + } + + string reportJson = JsonSerializer.Serialize( + verification.OfflineReport, AirGappedBundleJsonContext.Default.SignedOfflineSiteReport); + using StringContent content = new(reportJson, Encoding.UTF8, "application/json"); + using HttpResponseMessage response = await mgmt.PostAsync("api/fleet/offline-import", content); + managementStatus = ((int)response.StatusCode).ToString(CultureInfo.InvariantCulture); + } + + output.WriteLine(JsonSerializer.Serialize( + new BundleImportOutput( + verification.Manifest.BundleId, + verification.Manifest.BundleSequence, + events.Count, + dryRun, + collectorResponses, + managementStatus), + CliJsonContext.Default.BundleImportOutput)); + return 0; + } +} diff --git a/src/Bower.Cli/Commands/CliHelp.cs b/src/Bower.Cli/Commands/CliHelp.cs index ee76d495..5225beb9 100644 --- a/src/Bower.Cli/Commands/CliHelp.cs +++ b/src/Bower.Cli/Commands/CliHelp.cs @@ -54,6 +54,13 @@ bower archive create --archive DIR [--database FILE] [--collector-id ID] bower archive verify --archive DIR [--anchor SEQUENCE:HASH] bower archive replay --archive DIR --collector-url URL [--from ISO] [--to ISO] [--event-type TYPE]... [--collector-id ID] [--dry-run] + bower export bundle --database FILE --out FILE --signing-key PRIVATE.pem + [--collector-id ID] [--environment ENV] [--policy-hash HASH] + [--privacy-profile-hash HASH] [--encrypt-key-file FILE] [--max-events N] + bower verify bundle --bundle FILE --trusted-key PUBLIC.pem + [--expect-sequence N] [--expect-previous-hash HASH] [--decrypt-key-file FILE] + bower import bundle --bundle FILE --trusted-key PUBLIC.pem + [--collector-url URL] [--management-url URL] [--decrypt-key-file FILE] [--dry-run] bower sources check --expectations FILE [--database FILE] bower wec subscription generate --config FILE --subscription ID [--mode MinLatency|Normal|MinBandwidth|Custom] [--max-items N --max-latency-seconds N] [--heartbeat-seconds N] [--read-existing] [--subscription-id NAME] diff --git a/src/Bower.Cli/Commands/CliJson.cs b/src/Bower.Cli/Commands/CliJson.cs index e69dbc48..fc06909f 100644 --- a/src/Bower.Cli/Commands/CliJson.cs +++ b/src/Bower.Cli/Commands/CliJson.cs @@ -238,6 +238,33 @@ internal sealed record SourceCheckItem( [property: JsonPropertyName("silentSeconds")] long? SilentSeconds, [property: JsonPropertyName("allowedSilenceSeconds")] long AllowedSilenceSeconds); +internal sealed record BundleExportOutput( + [property: JsonPropertyName("bundleId")] string BundleId, + [property: JsonPropertyName("bundleSequence")] long BundleSequence, + [property: JsonPropertyName("bundleHash")] string BundleHash, + [property: JsonPropertyName("fromLedgerSequence")] long FromLedgerSequence, + [property: JsonPropertyName("toLedgerSequence")] long ToLedgerSequence, + [property: JsonPropertyName("eventCount")] long EventCount, + [property: JsonPropertyName("encrypted")] bool Encrypted); + +internal sealed record BundleVerifyOutput( + [property: JsonPropertyName("valid")] bool Valid, + [property: JsonPropertyName("error")] string? Error, + [property: JsonPropertyName("bundleId")] string? BundleId, + [property: JsonPropertyName("collectorId")] string? CollectorId, + [property: JsonPropertyName("bundleSequence")] long? BundleSequence, + [property: JsonPropertyName("bundleHash")] string? BundleHash, + [property: JsonPropertyName("eventCount")] long? EventCount, + [property: JsonPropertyName("encrypted")] bool? Encrypted); + +internal sealed record BundleImportOutput( + [property: JsonPropertyName("bundleId")] string BundleId, + [property: JsonPropertyName("bundleSequence")] long BundleSequence, + [property: JsonPropertyName("eventCount")] long EventCount, + [property: JsonPropertyName("dryRun")] bool DryRun, + [property: JsonPropertyName("collectorResponses")] IReadOnlyDictionary CollectorResponses, + [property: JsonPropertyName("managementStatus")] string? ManagementStatus); + /// /// Source-generated metadata for CLI output: System.Text.Json default options with /// indentation, as the former new JsonSerializerOptions { WriteIndented = true }. @@ -256,6 +283,9 @@ internal sealed record SourceCheckItem( [JsonSerializable(typeof(SourcesCheckOutput))] [JsonSerializable(typeof(ArchiveCreateOutput))] [JsonSerializable(typeof(ArchiveVerifyOutput))] +[JsonSerializable(typeof(BundleExportOutput))] +[JsonSerializable(typeof(BundleVerifyOutput))] +[JsonSerializable(typeof(BundleImportOutput))] [JsonSerializable(typeof(QueueSnapshot))] [JsonSerializable(typeof(IReadOnlyList))] [JsonSerializable(typeof(SignedEvidence))] diff --git a/src/Bower.Cli/Program.cs b/src/Bower.Cli/Program.cs index ece6381e..23e195b5 100644 --- a/src/Bower.Cli/Program.cs +++ b/src/Bower.Cli/Program.cs @@ -44,6 +44,9 @@ static async Task RunAsync(string[] args) ["archive", "create", .. string[] rest] => await ArchiveCommands.CreateAsync(rest), ["archive", "verify", .. string[] rest] => await ArchiveCommands.VerifyAsync(rest), ["archive", "replay", .. string[] rest] => await ArchiveCommands.ReplayAsync(rest), + ["export", "bundle", .. string[] rest] => await BundleCommands.ExportAsync(rest), + ["verify", "bundle", .. string[] rest] => BundleCommands.Verify(rest), + ["import", "bundle", .. string[] rest] => await BundleCommands.ImportAsync(rest), ["sources", "check", .. string[] rest] => await SourceCommands.CheckAsync(rest), ["wec", "subscription", "generate", .. string[] rest] => WecCommands.GenerateSubscription(rest), ["tap", .. string[] rest] => await TapAndTopCommands.TapAsync(rest), diff --git a/src/Bower.Evidence/AirGappedBundle.cs b/src/Bower.Evidence/AirGappedBundle.cs new file mode 100644 index 00000000..6e377d78 --- /dev/null +++ b/src/Bower.Evidence/AirGappedBundle.cs @@ -0,0 +1,495 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using Bower.Integrity; + +namespace Bower.Evidence; + +/// +/// Signed manifest of an air-gapped export bundle (.bowerbundle). Every bundle chains +/// to its predecessor via and , +/// and binds the already-redacted NDJSON payload via . +/// +public sealed record AirGappedBundleManifest( + string Kind, + string BundleId, + string CollectorId, + string MachineName, + string Environment, + string Version, + string PolicyHash, + string PrivacyProfileHash, + long BundleSequence, + string PreviousBundleHash, + long FromLedgerSequence, + long ToLedgerSequence, + string LedgerHeadHash, + long EventCount, + long QueueDepth, + long DeadLettered, + string EventsSha256, + bool Encrypted, + string CreatedAt) +{ + public const string CurrentKind = "bower.airgapped.bundle.v1"; + public const string GenesisBundleHash = "genesis"; +} + +/// +/// Metadata-only offline site status report extracted from an air-gapped bundle and posted +/// to POST /api/fleet/offline-import. Contains zero event payloads, preserving the +/// management-plane metadata-only invariant (ISM-1985). +/// +public sealed record OfflineSiteReportDocument( + string Kind, + string BundleId, + string CollectorId, + string MachineName, + string Environment, + string Version, + string PolicyHash, + string PrivacyProfileHash, + long BundleSequence, + string PreviousBundleHash, + string BundleHash, + long LedgerSequence, + string LedgerHeadHash, + long EventCount, + long QueueDepth, + long DeadLettered, + string ExportedAt) +{ + public const string CurrentKind = "bower.offline.report.v1"; +} + +/// Signed metadata-only offline site status report. +public sealed record SignedOfflineSiteReport( + OfflineSiteReportDocument Report, + DetachedSignature Signature); + +/// Result of creating an air-gapped export bundle. +public sealed record AirGappedExportResult( + string BundlePath, + string BundleId, + long BundleSequence, + string BundleHash, + long FromLedgerSequence, + long ToLedgerSequence, + long EventCount, + bool Encrypted); + +/// Result of verifying an air-gapped export bundle. +public sealed record AirGappedBundleVerification( + bool Valid, + string? Error, + AirGappedBundleManifest? Manifest, + string? BundleHash, + SignedOfflineSiteReport? OfflineReport); + +[JsonSourceGenerationOptions(JsonSerializerDefaults.Web, WriteIndented = true)] +[JsonSerializable(typeof(AirGappedBundleManifest))] +[JsonSerializable(typeof(DetachedSignature))] +[JsonSerializable(typeof(OfflineSiteReportDocument))] +[JsonSerializable(typeof(SignedOfflineSiteReport))] +public sealed partial class AirGappedBundleJsonContext : JsonSerializerContext; + +/// +/// Creates, verifies and reads signed, hash-chained air-gapped export bundles +/// (.bowerbundle) with optional AES-256-GCM payload encryption. +/// +public static class AirGappedBundle +{ + private const string ManifestEntry = "manifest.json"; + private const string ManifestSigEntry = "manifest.sig"; + private const string PlainEventsEntry = "events.ndjson"; + private const string EncryptedEventsEntry = "events.ndjson.enc"; + private const string StatusReportEntry = "status-report.json"; + private const int NonceBytes = 12; + private const int TagBytes = 16; + private const int AesKeyBytes = 32; + + public static AirGappedExportResult Create( + string outputPath, + AirGappedBundleManifest manifestTemplate, + IEnumerable redactedEventJsonLines, + string signingPrivateKeyPem, + byte[]? encryptionKey = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(outputPath); + ArgumentNullException.ThrowIfNull(manifestTemplate); + ArgumentNullException.ThrowIfNull(redactedEventJsonLines); + ArgumentException.ThrowIfNullOrWhiteSpace(signingPrivateKeyPem); + if (encryptionKey is not null && encryptionKey.Length != AesKeyBytes) + { + throw new ArgumentException($"Encryption key must be exactly {AesKeyBytes} bytes (AES-256-GCM).", nameof(encryptionKey)); + } + + StringBuilder ndjson = new(); + long count = 0; + foreach (string line in redactedEventJsonLines) + { + if (string.IsNullOrWhiteSpace(line)) + { + continue; + } + + // Normalize to single-line NDJSON so line counts stay exact. + ndjson.Append(line.Replace("\r", string.Empty, StringComparison.Ordinal).Replace("\n", string.Empty, StringComparison.Ordinal)); + ndjson.Append('\n'); + count++; + } + + byte[] plainBytes = Encoding.UTF8.GetBytes(ndjson.ToString()); + string eventsSha256 = "sha256:" + Convert.ToHexStringLower(SHA256.HashData(plainBytes)); + bool encrypted = encryptionKey is not null; + + AirGappedBundleManifest manifest = manifestTemplate with + { + Kind = AirGappedBundleManifest.CurrentKind, + EventCount = count, + EventsSha256 = eventsSha256, + Encrypted = encrypted + }; + + byte[] manifestCanonical = CanonicalJson.Bytes( + JsonSerializer.SerializeToNode(manifest, AirGappedBundleJsonContext.Default.AirGappedBundleManifest)!); + string bundleHash = "sha256:" + Convert.ToHexStringLower(SHA256.HashData(manifestCanonical)); + DetachedSignature manifestSignature = DetachedSigner.Sign(manifestCanonical, signingPrivateKeyPem); + + OfflineSiteReportDocument reportDoc = new( + OfflineSiteReportDocument.CurrentKind, + manifest.BundleId, + manifest.CollectorId, + manifest.MachineName, + manifest.Environment, + manifest.Version, + manifest.PolicyHash, + manifest.PrivacyProfileHash, + manifest.BundleSequence, + manifest.PreviousBundleHash, + bundleHash, + manifest.ToLedgerSequence, + manifest.LedgerHeadHash, + manifest.EventCount, + manifest.QueueDepth, + manifest.DeadLettered, + manifest.CreatedAt); + byte[] reportCanonical = CanonicalJson.Bytes( + JsonSerializer.SerializeToNode(reportDoc, AirGappedBundleJsonContext.Default.OfflineSiteReportDocument)!); + DetachedSignature reportSignature = DetachedSigner.Sign(reportCanonical, signingPrivateKeyPem); + SignedOfflineSiteReport signedReport = new(reportDoc, reportSignature); + + byte[] payloadBytes = encrypted + ? EncryptPayload(plainBytes, encryptionKey!, manifestCanonical) + : plainBytes; + + string fullOutput = Path.GetFullPath(outputPath); + string? directory = Path.GetDirectoryName(fullOutput); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + string tempPath = fullOutput + $".{Guid.NewGuid():N}.tmp"; + try + { + using (FileStream fs = new(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (ZipArchive zip = new(fs, ZipArchiveMode.Create, leaveOpen: false)) + { + WriteEntry(zip, ManifestEntry, JsonSerializer.SerializeToUtf8Bytes(manifest, AirGappedBundleJsonContext.Default.AirGappedBundleManifest)); + WriteEntry(zip, ManifestSigEntry, JsonSerializer.SerializeToUtf8Bytes(manifestSignature, AirGappedBundleJsonContext.Default.DetachedSignature)); + WriteEntry(zip, encrypted ? EncryptedEventsEntry : PlainEventsEntry, payloadBytes); + WriteEntry(zip, StatusReportEntry, JsonSerializer.SerializeToUtf8Bytes(signedReport, AirGappedBundleJsonContext.Default.SignedOfflineSiteReport)); + } + + File.Move(tempPath, fullOutput, overwrite: true); + } + finally + { + if (File.Exists(tempPath)) + { + File.Delete(tempPath); + } + } + + return new AirGappedExportResult( + fullOutput, + manifest.BundleId, + manifest.BundleSequence, + bundleHash, + manifest.FromLedgerSequence, + manifest.ToLedgerSequence, + manifest.EventCount, + encrypted); + } + + public static AirGappedBundleVerification Verify( + string bundlePath, + IEnumerable trustedPublicKeyPems, + long? expectedSequence = null, + string? expectedPreviousBundleHash = null, + byte[]? decryptionKey = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(bundlePath); + ArgumentNullException.ThrowIfNull(trustedPublicKeyPems); + string[] keys = trustedPublicKeyPems.ToArray(); + if (keys.Length == 0) + { + return Invalid("At least one trusted public key is required."); + } + + if (!File.Exists(bundlePath)) + { + return Invalid("Bundle file does not exist."); + } + + try + { + using ZipArchive zip = ZipFile.OpenRead(bundlePath); + byte[]? manifestBytes = ReadEntry(zip, ManifestEntry); + byte[]? sigBytes = ReadEntry(zip, ManifestSigEntry); + byte[]? reportBytes = ReadEntry(zip, StatusReportEntry); + if (manifestBytes is null || sigBytes is null || reportBytes is null) + { + return Invalid("Bundle is missing manifest.json, manifest.sig or status-report.json."); + } + + AirGappedBundleManifest? manifest = JsonSerializer.Deserialize( + manifestBytes, AirGappedBundleJsonContext.Default.AirGappedBundleManifest); + DetachedSignature? signature = JsonSerializer.Deserialize( + sigBytes, AirGappedBundleJsonContext.Default.DetachedSignature); + SignedOfflineSiteReport? signedReport = JsonSerializer.Deserialize( + reportBytes, AirGappedBundleJsonContext.Default.SignedOfflineSiteReport); + if (manifest is null || signature is null || signedReport is null) + { + return Invalid("Bundle metadata could not be parsed."); + } + + if (!string.Equals(manifest.Kind, AirGappedBundleManifest.CurrentKind, StringComparison.Ordinal)) + { + return Invalid("Unsupported bundle manifest kind."); + } + + byte[] manifestCanonical = CanonicalJson.Bytes( + JsonSerializer.SerializeToNode(manifest, AirGappedBundleJsonContext.Default.AirGappedBundleManifest)!); + if (!DetachedSigner.Verify(manifestCanonical, signature, keys)) + { + return Invalid("Bundle manifest signature verification failed."); + } + + string bundleHash = "sha256:" + Convert.ToHexStringLower(SHA256.HashData(manifestCanonical)); + if (!VerifyOfflineSiteReport(signedReport, keys) + || !string.Equals(signedReport.Report.BundleHash, bundleHash, StringComparison.Ordinal) + || !string.Equals(signedReport.Report.CollectorId, manifest.CollectorId, StringComparison.Ordinal) + || signedReport.Report.BundleSequence != manifest.BundleSequence) + { + return Invalid("Bundle offline status report signature or binding verification failed."); + } + + if (expectedSequence is { } seq && manifest.BundleSequence != seq) + { + return Invalid($"Expected bundle sequence {seq}, found {manifest.BundleSequence}."); + } + + if (expectedPreviousBundleHash is { } prev + && !string.Equals(manifest.PreviousBundleHash, prev, StringComparison.Ordinal)) + { + return Invalid("Bundle previousBundleHash does not match the expected chain hash."); + } + + byte[]? rawPayload = ReadEntry(zip, manifest.Encrypted ? EncryptedEventsEntry : PlainEventsEntry); + if (rawPayload is null) + { + return Invalid("Bundle event payload entry is missing."); + } + + byte[] plainBytes; + if (manifest.Encrypted) + { + if (decryptionKey is null || decryptionKey.Length != AesKeyBytes) + { + return Invalid("Bundle is encrypted; provide a 32-byte --decrypt-key-file."); + } + + plainBytes = DecryptPayload(rawPayload, decryptionKey, manifestCanonical); + } + else + { + plainBytes = rawPayload; + } + + string actualEventsHash = "sha256:" + Convert.ToHexStringLower(SHA256.HashData(plainBytes)); + if (!string.Equals(actualEventsHash, manifest.EventsSha256, StringComparison.Ordinal)) + { + return Invalid("Event payload digest does not match signed manifest."); + } + + long actualLines = CountNonEmptyLines(plainBytes); + if (actualLines != manifest.EventCount) + { + return Invalid($"Event count mismatch: manifest declares {manifest.EventCount}, payload has {actualLines}."); + } + + return new AirGappedBundleVerification(true, null, manifest, bundleHash, signedReport); + } + catch (Exception exception) when (exception is InvalidDataException or JsonException or CryptographicException or IOException) + { + return Invalid($"Bundle verification failed ({exception.GetType().Name})."); + } + } + + public static IReadOnlyList ReadVerifiedEvents( + string bundlePath, + IEnumerable trustedPublicKeyPems, + byte[]? decryptionKey = null) + { + AirGappedBundleVerification verification = Verify(bundlePath, trustedPublicKeyPems, decryptionKey: decryptionKey); + if (!verification.Valid || verification.Manifest is null) + { + throw new InvalidDataException(verification.Error ?? "Bundle verification failed."); + } + + using ZipArchive zip = ZipFile.OpenRead(bundlePath); + byte[] raw = ReadEntry(zip, verification.Manifest.Encrypted ? EncryptedEventsEntry : PlainEventsEntry) + ?? throw new InvalidDataException("Bundle event payload entry is missing."); + byte[] plain = verification.Manifest.Encrypted + ? DecryptPayload( + raw, + decryptionKey!, + CanonicalJson.Bytes(JsonSerializer.SerializeToNode(verification.Manifest, AirGappedBundleJsonContext.Default.AirGappedBundleManifest)!)) + : raw; + + List lines = []; + using MemoryStream stream = new(plain); + using StreamReader reader = new(stream, Encoding.UTF8); + while (reader.ReadLine() is { } line) + { + if (!string.IsNullOrWhiteSpace(line)) + { + lines.Add(line); + } + } + + return lines; + } + + public static bool VerifyOfflineSiteReport( + SignedOfflineSiteReport signedReport, + IEnumerable trustedPublicKeyPems) + { + ArgumentNullException.ThrowIfNull(signedReport); + ArgumentNullException.ThrowIfNull(trustedPublicKeyPems); + if (signedReport.Report is null + || signedReport.Signature is null + || !string.Equals(signedReport.Report.Kind, OfflineSiteReportDocument.CurrentKind, StringComparison.Ordinal)) + { + return false; + } + + byte[] canonical = CanonicalJson.Bytes( + JsonSerializer.SerializeToNode(signedReport.Report, AirGappedBundleJsonContext.Default.OfflineSiteReportDocument)!); + return DetachedSigner.Verify(canonical, signedReport.Signature, trustedPublicKeyPems); + } + + public static byte[] ReadEncryptionKeyFile(string path) + { + byte[] bytes = File.ReadAllBytes(path); + if (bytes.Length == AesKeyBytes) + { + return bytes; + } + + string text = Encoding.UTF8.GetString(bytes).Trim(); + if (text.Length == 64 && text.All(char.IsAsciiHexDigit)) + { + return Convert.FromHexString(text); + } + + try + { + byte[] decoded = Convert.FromBase64String(text); + if (decoded.Length == AesKeyBytes) + { + return decoded; + } + } + catch (FormatException) + { + } + + throw new ArgumentException("Encryption key file must contain 32 raw bytes, 64 hex chars, or 32-byte base64."); + } + + private static byte[] EncryptPayload(byte[] plaintext, byte[] key, byte[] associatedData) + { + byte[] nonce = RandomNumberGenerator.GetBytes(NonceBytes); + byte[] ciphertext = new byte[plaintext.Length]; + byte[] tag = new byte[TagBytes]; + using AesGcm aes = new(key, TagBytes); + aes.Encrypt(nonce, plaintext, ciphertext, tag, associatedData); + byte[] combined = new byte[NonceBytes + TagBytes + ciphertext.Length]; + Buffer.BlockCopy(nonce, 0, combined, 0, NonceBytes); + Buffer.BlockCopy(tag, 0, combined, NonceBytes, TagBytes); + Buffer.BlockCopy(ciphertext, 0, combined, NonceBytes + TagBytes, ciphertext.Length); + return combined; + } + + private static byte[] DecryptPayload(byte[] combined, byte[] key, byte[] associatedData) + { + if (combined.Length < NonceBytes + TagBytes) + { + throw new CryptographicException("Encrypted payload is truncated."); + } + + ReadOnlySpan span = combined; + ReadOnlySpan nonce = span[..NonceBytes]; + ReadOnlySpan tag = span[NonceBytes..(NonceBytes + TagBytes)]; + ReadOnlySpan ciphertext = span[(NonceBytes + TagBytes)..]; + byte[] plaintext = new byte[ciphertext.Length]; + using AesGcm aes = new(key, TagBytes); + aes.Decrypt(nonce, ciphertext, tag, plaintext, associatedData); + return plaintext; + } + + private static void WriteEntry(ZipArchive zip, string name, byte[] bytes) + { + ZipArchiveEntry entry = zip.CreateEntry(name, CompressionLevel.Optimal); + using Stream stream = entry.Open(); + stream.Write(bytes); + } + + private static byte[]? ReadEntry(ZipArchive zip, string name) + { + ZipArchiveEntry? entry = zip.GetEntry(name); + if (entry is null) + { + return null; + } + + using Stream stream = entry.Open(); + using MemoryStream memory = new(); + stream.CopyTo(memory); + return memory.ToArray(); + } + + private static long CountNonEmptyLines(byte[] utf8Bytes) + { + long count = 0; + using MemoryStream stream = new(utf8Bytes); + using StreamReader reader = new(stream, Encoding.UTF8); + while (reader.ReadLine() is { } line) + { + if (!string.IsNullOrWhiteSpace(line)) + { + count++; + } + } + + return count; + } + + private static AirGappedBundleVerification Invalid(string error) => + new(false, error, null, null, null); +} diff --git a/src/Bower.Management.Api/FleetStatus.cs b/src/Bower.Management.Api/FleetStatus.cs index 55d02fea..b5894375 100644 --- a/src/Bower.Management.Api/FleetStatus.cs +++ b/src/Bower.Management.Api/FleetStatus.cs @@ -40,10 +40,12 @@ private static readonly (string Id, string Label)[] Catalogue = public static FleetRecord Evaluate( IReadOnlyList collectors, IReadOnlySet signedOut, - DateTimeOffset now) + DateTimeOffset now, + IReadOnlySet? offlineSites = null) { ArgumentNullException.ThrowIfNull(collectors); ArgumentNullException.ThrowIfNull(signedOut); + IReadOnlySet offline = offlineSites ?? new HashSet(StringComparer.Ordinal); // The newest release; a preview build (dev, rc) never makes released collectors old. // A fleet with no release yet compares its pre-releases, so drift still shows. string[] fresh = [.. collectors @@ -55,7 +57,7 @@ public static FleetRecord Evaluate( ?? fresh.LastOrDefault(); FleetCollector[] fleet = collectors - .Select(item => Collector(item, newest, signedOut.Contains(item.Id), now)) + .Select(item => Collector(item, newest, signedOut.Contains(item.Id), offline.Contains(item.Id), now)) .OrderBy(item => Rank(item.Light)) .ThenBy(item => Array.FindIndex(Catalogue, entry => entry.Id == item.State)) .ThenBy(item => item.Site, StringComparer.Ordinal) @@ -80,12 +82,14 @@ public static FleetRecord Evaluate( return new FleetRecord(now, fleet, states, sites, newest); } - private static FleetCollector Collector(CollectorRecord item, string? newest, bool signedOut, DateTimeOffset now) + private static FleetCollector Collector(CollectorRecord item, string? newest, bool signedOut, bool offlineSite, DateTimeOffset now) { - string connectivity = CollectorConnectivity.Evaluate(item, now); - string? path = item.Outputs.Count == 0 - ? null - : item.Outputs.Any(output => Is(output.Type, FleetPaths.Relay)) ? FleetPaths.Relay : FleetPaths.Direct; + string connectivity = offlineSite ? "offline-site" : CollectorConnectivity.Evaluate(item, now); + string? path = offlineSite + ? "offline-bundle" + : item.Outputs.Count == 0 + ? null + : item.Outputs.Any(output => Is(output.Type, FleetPaths.Relay)) ? FleetPaths.Relay : FleetPaths.Direct; bool viaRelay = path == FleetPaths.Relay; List entries = []; @@ -94,6 +98,30 @@ private static FleetCollector Collector(CollectorRecord item, string? newest, bo entries.Add(new Entry( FleetStates.Removed, FleetLights.None, "Was removed from Bower and can no longer connect.", null)); } + else if (offlineSite) + { + if (Is(item.DeliveryStatus, "ledger-regression")) + { + entries.Add(new Entry( + FleetStates.NeedsCheck, HomeStates.Red, + "Reported an event history that changed unexpectedly in its last signed import.", + new("Treat this as a possible tampering sign: check the offline site and the Audit page.", Audit))); + } + else if (item.DeadLettered > 0) + { + entries.Add(new Entry( + FleetStates.OfflineSite, HomeStates.Amber, + "Offline site (last signed import reported events set aside for review).", + new("Review set-aside events on the offline collector before the next export.", null))); + } + else + { + entries.Add(new Entry( + FleetStates.OfflineSite, HomeStates.Green, + "Offline site reporting via signed, hash-chained export bundles.", + null)); + } + } else { entries.AddRange(HomeStatus.ConditionIds(item, now).Select(id => Map(id, viaRelay, signedOut))); diff --git a/src/Bower.Management.Api/ManagementApplication.cs b/src/Bower.Management.Api/ManagementApplication.cs index fc3d189f..9d46865c 100644 --- a/src/Bower.Management.Api/ManagementApplication.cs +++ b/src/Bower.Management.Api/ManagementApplication.cs @@ -139,6 +139,8 @@ public static WebApplication Build( // Optional: without a key approved source setups cannot be downloaded signed (503). builder.Services.AddSingleton(SourceSetupSigner.FromFile( builder.Configuration[SourceSetupSigner.KeyFileSetting])); + // Optional: without trusted keys offline site bundle imports are refused (503). + builder.Services.AddSingleton(OfflineSiteTrustKeys.FromConfiguration(builder.Configuration)); string[] allowedOrigins = builder.Configuration .GetSection("Bower:AllowedOrigins") @@ -342,6 +344,8 @@ await store.FleetAsync(clock.GetUtcNow(), cancellationToken)) : Results.NotFound()) .RequireAuthorization("View"); + OfflineSiteEndpoints.Map(api); + api.MapGet( "/collectors", async ( diff --git a/src/Bower.Management.Api/ManagementJson.cs b/src/Bower.Management.Api/ManagementJson.cs index 1cad5d02..369ac1e7 100644 --- a/src/Bower.Management.Api/ManagementJson.cs +++ b/src/Bower.Management.Api/ManagementJson.cs @@ -98,6 +98,8 @@ public sealed record PipelineValidationResponse( [JsonSerializable(typeof(SourceSetupRequestDetail))] [JsonSerializable(typeof(List))] [JsonSerializable(typeof(SignedSourceSetup))] +[JsonSerializable(typeof(Bower.Evidence.OfflineSiteReportDocument))] +[JsonSerializable(typeof(Bower.Evidence.SignedOfflineSiteReport))] [JsonSerializable(typeof(Dictionary))] [JsonSerializable(typeof(Microsoft.AspNetCore.Mvc.ProblemDetails))] [JsonSerializable(typeof(HttpValidationProblemDetails))] diff --git a/src/Bower.Management.Api/ManagementStore.Fleet.cs b/src/Bower.Management.Api/ManagementStore.Fleet.cs index e303e9b7..0920447c 100644 --- a/src/Bower.Management.Api/ManagementStore.Fleet.cs +++ b/src/Bower.Management.Api/ManagementStore.Fleet.cs @@ -9,7 +9,9 @@ public sealed partial class ManagementStore public async Task FleetAsync(DateTimeOffset now, CancellationToken cancellationToken) { IReadOnlyList collectors = await ListAsync(null, cancellationToken); - return FleetStatus.Evaluate(collectors, await SignedOutCollectorsAsync(now, cancellationToken), now); + IReadOnlySet signedOut = await SignedOutCollectorsAsync(now, cancellationToken); + IReadOnlySet offlineSites = await OfflineSiteCollectorsAsync(cancellationToken); + return FleetStatus.Evaluate(collectors, signedOut, now, offlineSites); } /// diff --git a/src/Bower.Management.Api/ManagementStore.OfflineSites.cs b/src/Bower.Management.Api/ManagementStore.OfflineSites.cs new file mode 100644 index 00000000..0e79e48d --- /dev/null +++ b/src/Bower.Management.Api/ManagementStore.OfflineSites.cs @@ -0,0 +1,164 @@ +using Bower.Evidence; +using Microsoft.Data.Sqlite; + +namespace Bower.Management.Api; + +/// Thrown when an offline site import bundle breaks sequence or hash-chain continuity. +public sealed class OfflineBundleChainException(string message) : InvalidOperationException(message); + +public sealed partial class ManagementStore +{ + private static async Task InitializeOfflineSitesAsync(SqliteConnection connection, CancellationToken cancellationToken) + { + await AddColumnIfMissingAsync(connection, "collectors", "is_offline_site", "INTEGER NOT NULL DEFAULT 0", cancellationToken); + await AddColumnIfMissingAsync(connection, "collectors", "last_bundle_sequence", "INTEGER NULL", cancellationToken); + await AddColumnIfMissingAsync(connection, "collectors", "last_bundle_hash", "TEXT NULL", cancellationToken); + } + + public async Task> OfflineSiteCollectorsAsync(CancellationToken cancellationToken) + { + HashSet ids = new(StringComparer.Ordinal); + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = "SELECT id FROM collectors WHERE is_offline_site = 1;"; + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + while (await reader.ReadAsync(cancellationToken)) + { + ids.Add(reader.GetString(0)); + } + + return ids; + } + + /// + /// Records a verified metadata-only offline site status report from an air-gapped export + /// bundle. Enforces monotonic bundle sequence and hash-chain continuity (rejecting replay + /// or skipped bundles), checks ledger witness regression, marks the collector as an offline + /// site, and writes an audit row. Never receives or stores event payloads. + /// + public async Task ImportOfflineSiteReportAsync( + OfflineSiteReportDocument report, + string actorObjectId, + string actorName, + DateTimeOffset now, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(report); + if (string.IsNullOrWhiteSpace(report.CollectorId) || report.BundleSequence < 1) + { + throw new ArgumentException("Offline report must include a collector id and positive bundle sequence."); + } + + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = + (SqliteTransaction)await connection.BeginTransactionAsync(cancellationToken); + + long? lastSequence = null; + string? lastHash = null; + await using (SqliteCommand check = connection.CreateCommand()) + { + check.Transaction = transaction; + check.CommandText = "SELECT last_bundle_sequence, last_bundle_hash FROM collectors WHERE id = $id;"; + check.Parameters.AddWithValue("$id", report.CollectorId); + await using SqliteDataReader reader = await check.ExecuteReaderAsync(cancellationToken); + if (await reader.ReadAsync(cancellationToken)) + { + if (!reader.IsDBNull(0)) lastSequence = reader.GetInt64(0); + if (!reader.IsDBNull(1)) lastHash = reader.GetString(1); + } + } + + if (lastSequence is { } existingSeq) + { + if (report.BundleSequence <= existingSeq) + { + throw new OfflineBundleChainException( + $"Bundle sequence {report.BundleSequence} is not newer than already-imported sequence {existingSeq}."); + } + + if (report.BundleSequence != existingSeq + 1) + { + throw new OfflineBundleChainException( + $"Bundle sequence gap: expected {existingSeq + 1}, received {report.BundleSequence}."); + } + + if (lastHash is not null && !string.Equals(report.PreviousBundleHash, lastHash, StringComparison.Ordinal)) + { + throw new OfflineBundleChainException( + "Bundle previousBundleHash does not match the last imported bundle hash."); + } + } + + LedgerReport ledger = new(report.LedgerSequence, report.LedgerHeadHash); + string deliveryStatus = "healthy"; + if (await LedgerRegressedAsync(connection, transaction, report.CollectorId, ledger, cancellationToken)) + { + deliveryStatus = "ledger-regression"; + await InsertAuditAsync( + connection, transaction, "collector.ledger-regression", report.CollectorId, + actorObjectId, actorName, now, cancellationToken); + } + + await CommandAsync( + connection, + transaction, + """ + INSERT INTO collectors ( + id, machine_name, environment, version, status, principal_object_id, + first_seen_at, last_seen_at, configuration_hash, policy_hash, + queue_depth, delivery_status, dead_lettered, reported_privacy_profile_hash, + ledger_sequence, ledger_hash, is_offline_site, last_bundle_sequence, last_bundle_hash) + VALUES ( + $id, $machine, $environment, $version, 'Active', $principal, + $now, $now, 'air-gapped', $policy, + $queue, $delivery, $dlq, $privacy, + $ledger_seq, $ledger_hash, 1, $bundle_seq, $bundle_hash) + ON CONFLICT(id) DO UPDATE SET + machine_name = excluded.machine_name, + environment = excluded.environment, + version = excluded.version, + status = 'Active', + last_seen_at = excluded.last_seen_at, + policy_hash = excluded.policy_hash, + queue_depth = excluded.queue_depth, + delivery_status = excluded.delivery_status, + dead_lettered = excluded.dead_lettered, + reported_privacy_profile_hash = excluded.reported_privacy_profile_hash, + ledger_sequence = CASE WHEN excluded.delivery_status = 'ledger-regression' THEN collectors.ledger_sequence ELSE excluded.ledger_sequence END, + ledger_hash = CASE WHEN excluded.delivery_status = 'ledger-regression' THEN collectors.ledger_hash ELSE excluded.ledger_hash END, + is_offline_site = 1, + last_bundle_sequence = excluded.last_bundle_sequence, + last_bundle_hash = excluded.last_bundle_hash; + """, + [ + ("$id", report.CollectorId), + ("$machine", report.MachineName), + ("$environment", report.Environment), + ("$version", report.Version), + ("$principal", $"offline:{report.CollectorId}"), + ("$now", Format(now)), + ("$policy", report.PolicyHash), + ("$queue", report.QueueDepth), + ("$delivery", deliveryStatus), + ("$dlq", report.DeadLettered), + ("$privacy", report.PrivacyProfileHash), + ("$ledger_seq", report.LedgerSequence), + ("$ledger_hash", report.LedgerHeadHash), + ("$bundle_seq", report.BundleSequence), + ("$bundle_hash", report.BundleHash) + ], + cancellationToken); + + await InsertAuditAsync( + connection, + transaction, + "fleet.offline-bundle-imported", + report.CollectorId, + actorObjectId, + actorName, + now, + cancellationToken); + await transaction.CommitAsync(cancellationToken); + return (await GetAsync(report.CollectorId, cancellationToken))!; + } +} diff --git a/src/Bower.Management.Api/ManagementStore.cs b/src/Bower.Management.Api/ManagementStore.cs index 2cc4cde8..c4f02106 100644 --- a/src/Bower.Management.Api/ManagementStore.cs +++ b/src/Bower.Management.Api/ManagementStore.cs @@ -142,6 +142,7 @@ await AddColumnIfMissingAsync( connection, "collectors", "redactions_observed_since", "TEXT NULL", cancellationToken); await InitializeHomeAsync(connection, cancellationToken); await InitializeSourceSetupAsync(connection, cancellationToken); + await InitializeOfflineSitesAsync(connection, cancellationToken); } public async Task RegisterAsync( diff --git a/src/Bower.Management.Api/OfflineSiteEndpoints.cs b/src/Bower.Management.Api/OfflineSiteEndpoints.cs new file mode 100644 index 00000000..ac218616 --- /dev/null +++ b/src/Bower.Management.Api/OfflineSiteEndpoints.cs @@ -0,0 +1,86 @@ +using System.Security.Claims; +using Bower.Evidence; + +namespace Bower.Management.Api; + +/// +/// Trusted ECDSA P-256 public keys permitted to sign air-gapped offline site reports +/// (BOWER_OFFLINE_IMPORT_TRUSTED_KEYS). Fail-closed: when unconfigured, offline +/// imports are refused with HTTP 503. +/// +public sealed class OfflineSiteTrustKeys(IReadOnlyList publicKeyPems) +{ + public const string SettingName = "BOWER_OFFLINE_IMPORT_TRUSTED_KEYS"; + + public IReadOnlyList PublicKeyPems { get; } = publicKeyPems; + + public bool IsConfigured => PublicKeyPems.Count > 0; + + public static OfflineSiteTrustKeys FromConfiguration(IConfiguration configuration) + { + string? raw = configuration[SettingName]; + if (string.IsNullOrWhiteSpace(raw)) + { + return new OfflineSiteTrustKeys([]); + } + + List pems = []; + foreach (string path in raw.Split([';', ','], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + pems.Add(File.ReadAllText(path)); + } + + return new OfflineSiteTrustKeys(pems); + } +} + +internal static class OfflineSiteEndpoints +{ + public static void Map(RouteGroupBuilder api) + { + api.MapPost( + "/fleet/offline-import", + async ( + SignedOfflineSiteReport signedReport, + ClaimsPrincipal user, + OfflineSiteTrustKeys trustKeys, + ManagementStore store, + TimeProvider clock, + CancellationToken cancellationToken) => + { + if (!trustKeys.IsConfigured) + { + return Results.Json( + new ErrorResponse("Offline bundle import is not enabled (configure BOWER_OFFLINE_IMPORT_TRUSTED_KEYS)."), + ManagementJsonContext.Default.ErrorResponse, + statusCode: StatusCodes.Status503ServiceUnavailable); + } + + if (!AirGappedBundle.VerifyOfflineSiteReport(signedReport, trustKeys.PublicKeyPems)) + { + return Results.BadRequest(new ErrorResponse("Offline site report signature is missing, invalid or untrusted.")); + } + + DateTimeOffset now = clock.GetUtcNow(); + string actorId = user.FindFirstValue("oid") ?? user.Identity?.Name ?? "unknown"; + string actorName = user.FindFirstValue("name") ?? user.Identity?.Name ?? actorId; + try + { + _ = await store.ImportOfflineSiteReportAsync(signedReport.Report, actorId, actorName, now, cancellationToken); + FleetRecord fleet = await store.FleetAsync(now, cancellationToken); + FleetCollector? collector = fleet.Collectors.FirstOrDefault( + item => string.Equals(item.Id, signedReport.Report.CollectorId, StringComparison.Ordinal)); + return collector is null ? Results.Ok(fleet) : Results.Ok(collector); + } + catch (OfflineBundleChainException exception) + { + return Results.Conflict(new ErrorResponse(exception.Message)); + } + catch (ArgumentException exception) + { + return Results.BadRequest(new ErrorResponse(exception.Message)); + } + }) + .RequireAuthorization("Operate"); + } +} diff --git a/src/Bower.Persistence/SqliteEventStore.AirGap.cs b/src/Bower.Persistence/SqliteEventStore.AirGap.cs new file mode 100644 index 00000000..49c9387c --- /dev/null +++ b/src/Bower.Persistence/SqliteEventStore.AirGap.cs @@ -0,0 +1,103 @@ +using System.Globalization; +using Microsoft.Data.Sqlite; + +namespace Bower.Persistence; + +/// Last air-gapped export bundle recorded in the collector's queue database. +public sealed record ExportBundleCursor( + long BundleSequence, + string BundleId, + long FromLedgerSequence, + long ToLedgerSequence, + string BundleHash, + DateTimeOffset ExportedAt); + +public sealed partial class SqliteEventStore +{ + private const string ExportBundleSchema = + """ + CREATE TABLE IF NOT EXISTS queue_export_bundles ( + bundle_sequence INTEGER PRIMARY KEY NOT NULL, + bundle_id TEXT NOT NULL UNIQUE, + from_ledger_sequence INTEGER NOT NULL, + to_ledger_sequence INTEGER NOT NULL, + bundle_hash TEXT NOT NULL, + exported_at TEXT NOT NULL + ); + """; + + public async Task GetLastExportBundleAsync(CancellationToken cancellationToken = default) + { + await using SqliteConnection connection = await OpenAsync(cancellationToken); + if (!await ExportBundleTableExistsAsync(connection, cancellationToken)) + { + return null; + } + + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = + """ + SELECT bundle_sequence, bundle_id, from_ledger_sequence, to_ledger_sequence, bundle_hash, exported_at + FROM queue_export_bundles + ORDER BY bundle_sequence DESC + LIMIT 1; + """; + await using SqliteDataReader reader = await command.ExecuteReaderAsync(cancellationToken); + if (!await reader.ReadAsync(cancellationToken)) + { + return null; + } + + return new ExportBundleCursor( + reader.GetInt64(0), + reader.GetString(1), + reader.GetInt64(2), + reader.GetInt64(3), + reader.GetString(4), + DateTimeOffset.Parse(reader.GetString(5), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind)); + } + + public async Task RecordExportBundleAsync( + ExportBundleCursor cursor, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(cursor); + await using SqliteConnection connection = await OpenAsync(cancellationToken); + await using SqliteTransaction transaction = await BeginWriteAsync(connection, true, cancellationToken); + await using (SqliteCommand ddl = connection.CreateCommand()) + { + ddl.Transaction = transaction; + ddl.CommandText = ExportBundleSchema; + await ddl.ExecuteNonQueryAsync(cancellationToken); + } + + await using (SqliteCommand insert = connection.CreateCommand()) + { + insert.Transaction = transaction; + insert.CommandText = + """ + INSERT INTO queue_export_bundles ( + bundle_sequence, bundle_id, from_ledger_sequence, to_ledger_sequence, bundle_hash, exported_at) + VALUES ($seq, $id, $from_seq, $to_seq, $hash, $at); + """; + insert.Parameters.AddWithValue("$seq", cursor.BundleSequence); + insert.Parameters.AddWithValue("$id", cursor.BundleId); + insert.Parameters.AddWithValue("$from_seq", cursor.FromLedgerSequence); + insert.Parameters.AddWithValue("$to_seq", cursor.ToLedgerSequence); + insert.Parameters.AddWithValue("$hash", cursor.BundleHash); + insert.Parameters.AddWithValue("$at", cursor.ExportedAt.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture)); + await insert.ExecuteNonQueryAsync(cancellationToken); + } + + await transaction.CommitAsync(cancellationToken); + } + + private static async Task ExportBundleTableExistsAsync( + SqliteConnection connection, + CancellationToken cancellationToken) + { + await using SqliteCommand cmd = connection.CreateCommand(); + cmd.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'queue_export_bundles';"; + return Convert.ToInt64(await cmd.ExecuteScalarAsync(cancellationToken), CultureInfo.InvariantCulture) > 0; + } +} diff --git a/tests/Bower.UnitTests/AirGappedBundleTests.cs b/tests/Bower.UnitTests/AirGappedBundleTests.cs new file mode 100644 index 00000000..a668fce1 --- /dev/null +++ b/tests/Bower.UnitTests/AirGappedBundleTests.cs @@ -0,0 +1,254 @@ +using System.IO.Compression; +using System.Net; +using System.Net.Http.Json; +using System.Security.Cryptography; +using System.Text; +using Bower.Abstractions; +using Bower.Evidence; +using Bower.Integrity; +using Bower.Management.Api; +using Bower.Persistence; +using Microsoft.AspNetCore.Builder; + +namespace Bower.UnitTests; + +/// +/// Air-gapped signed export/import bundles (#111) and Offline site fleet view (#113): +/// ECDSA P-256 signing, bundle hash chaining, AES-256-GCM encryption, tamper detection, +/// Management API RBAC + chain continuity + OfflineSite fleet state. +/// +[Collection(SerialHostTests.Name)] +public sealed class AirGappedBundleTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 22, 9, 0, 0, TimeSpan.Zero); + + [Fact] + public async Task BundleCreateVerifyAndChain_DetectsTamperingUntrustedKeysAndSequenceGaps() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using SqliteTemporaryDirectory directory = new(); + (string privatePem, string publicPem, _) = DetachedSigner.GenerateKeyPair(); + (_, string untrustedPublicPem, _) = DetachedSigner.GenerateKeyPair(); + + SqliteEventStore store = new(Path.Combine(directory.Path, "queue.db"), 1024 * 1024); + await store.InitializeAsync(cancellation); + await store.EnqueueAsync(new QueuedEvent("air-1", "fp-air-1", "{\"eventId\":\"air-1\",\"eventType\":\"authentication_failure\"}", Now), cancellation); + await store.EnqueueAsync(new QueuedEvent("air-2", "fp-air-2", "{\"eventId\":\"air-2\",\"eventType\":\"authentication_failure\"}", Now.AddSeconds(1)), cancellation); + + IReadOnlyList batch1 = await store.ReadLedgerEventsAsync(0, 100, cancellation); + string bundle1Path = Path.Combine(directory.Path, "site-a-001.bowerbundle"); + AirGappedExportResult export1 = AirGappedBundle.Create( + bundle1Path, + BuildManifest("bundle-1", "site-a-01", 1, AirGappedBundleManifest.GenesisBundleHash, batch1), + batch1.Select(item => item.Payload), + privatePem); + await store.RecordExportBundleAsync(new ExportBundleCursor( + export1.BundleSequence, export1.BundleId, export1.FromLedgerSequence, export1.ToLedgerSequence, export1.BundleHash, Now), cancellation); + + // Verify bundle 1 succeeds with trusted key and fails with untrusted key. + AirGappedBundleVerification ok1 = AirGappedBundle.Verify( + bundle1Path, [publicPem], expectedSequence: 1, expectedPreviousBundleHash: AirGappedBundleManifest.GenesisBundleHash); + Assert.True(ok1.Valid, ok1.Error); + Assert.Equal(2, ok1.Manifest!.EventCount); + Assert.Equal(2, AirGappedBundle.ReadVerifiedEvents(bundle1Path, [publicPem]).Count); + + Assert.False(AirGappedBundle.Verify(bundle1Path, [untrustedPublicPem]).Valid); + + // Enqueue a third event and export chained bundle 2 from cursor. + await store.EnqueueAsync(new QueuedEvent("air-3", "fp-air-3", "{\"eventId\":\"air-3\",\"eventType\":\"role_membership_changed\"}", Now.AddSeconds(2)), cancellation); + ExportBundleCursor? cursor = await store.GetLastExportBundleAsync(cancellation); + Assert.NotNull(cursor); + IReadOnlyList batch2 = await store.ReadLedgerEventsAsync(cursor!.ToLedgerSequence, 100, cancellation); + Assert.Single(batch2); + + string bundle2Path = Path.Combine(directory.Path, "site-a-002.bowerbundle"); + AirGappedExportResult export2 = AirGappedBundle.Create( + bundle2Path, + BuildManifest("bundle-2", "site-a-01", cursor.BundleSequence + 1, cursor.BundleHash, batch2), + batch2.Select(item => item.Payload), + privatePem); + Assert.Equal(2, export2.BundleSequence); + + // Chain verification passes with bundle1 hash and fails on wrong previous hash. + Assert.True(AirGappedBundle.Verify(bundle2Path, [publicPem], expectedSequence: 2, expectedPreviousBundleHash: export1.BundleHash).Valid); + Assert.False(AirGappedBundle.Verify(bundle2Path, [publicPem], expectedSequence: 2, expectedPreviousBundleHash: "sha256:wrong").Valid); + Assert.False(AirGappedBundle.Verify(bundle2Path, [publicPem], expectedSequence: 3, expectedPreviousBundleHash: export1.BundleHash).Valid); + + // Tamper with events.ndjson inside bundle 2 -> verification must fail closed. + string tamperedPath = Path.Combine(directory.Path, "tampered.bowerbundle"); + File.Copy(bundle2Path, tamperedPath); + using (ZipArchive zip = ZipFile.Open(tamperedPath, ZipArchiveMode.Update)) + { + zip.GetEntry("events.ndjson")!.Delete(); + ZipArchiveEntry forged = zip.CreateEntry("events.ndjson"); + using StreamWriter writer = new(forged.Open(), Encoding.UTF8); + writer.Write("{\"eventId\":\"forged\"}\n"); + } + + AirGappedBundleVerification tampered = AirGappedBundle.Verify(tamperedPath, [publicPem]); + Assert.False(tampered.Valid); + } + + [Fact] + public void BundleEncryption_Aes256Gcm_HidesPlaintextAndRejectsWrongKey() + { + using TemporaryDirectory directory = new(); + (string privatePem, string publicPem, _) = DetachedSigner.GenerateKeyPair(); + byte[] key = RandomNumberGenerator.GetBytes(32); + byte[] wrongKey = RandomNumberGenerator.GetBytes(32); + string bundlePath = Path.Combine(directory.Path, "encrypted.bowerbundle"); + + AirGappedBundleManifest manifest = new( + AirGappedBundleManifest.CurrentKind, + "bundle-enc-1", + "site-b-01", + "site-b-host", + "site-b", + "1.0.1", + "sha256:pol", + "default", + 1, + AirGappedBundleManifest.GenesisBundleHash, + 1, + 1, + "sha256:head", + 1, + 0, + 0, + string.Empty, + true, + Now.ToString("O")); + + AirGappedExportResult created = AirGappedBundle.Create( + bundlePath, + manifest, + ["{\"eventId\":\"enc-evt-1\",\"marker\":\"secret-free-redacted-line\"}"], + privatePem, + key); + Assert.True(created.Encrypted); + + // Plaintext marker must not appear raw in the archive bytes. + string rawZipAscii = Encoding.Latin1.GetString(File.ReadAllBytes(bundlePath)); + Assert.DoesNotContain("secret-free-redacted-line", rawZipAscii, StringComparison.Ordinal); + + Assert.False(AirGappedBundle.Verify(bundlePath, [publicPem]).Valid); + Assert.False(AirGappedBundle.Verify(bundlePath, [publicPem], decryptionKey: wrongKey).Valid); + Assert.True(AirGappedBundle.Verify(bundlePath, [publicPem], decryptionKey: key).Valid); + string line = Assert.Single(AirGappedBundle.ReadVerifiedEvents(bundlePath, [publicPem], key)); + Assert.Contains("enc-evt-1", line, StringComparison.Ordinal); + } + + [Fact] + public async Task ManagementApiOfflineImport_EnforcesRbacSignaturesChainContinuityAndShowsOfflineSiteInFleet() + { + CancellationToken cancellation = TestContext.Current.CancellationToken; + using TemporaryDirectory directory = new(); + (string privatePem, string publicPem, _) = DetachedSigner.GenerateKeyPair(); + (string untrustedPriv, _, _) = DetachedSigner.GenerateKeyPair(); + string pubPath = Path.Combine(directory.Path, "offline.pub.pem"); + await File.WriteAllTextAsync(pubPath, publicPem, cancellation); + + await using WebApplication app = await ManagementApiTests.StartAsync( + directory, + cancellation, + $"--{OfflineSiteTrustKeys.SettingName}={pubPath}"); + + HttpClient viewer = ManagementApiTests.Client(app, BowerRoles.Viewer, "viewer-oid"); + HttpClient oper = ManagementApiTests.Client(app, BowerRoles.Operator, "operator-oid"); + + string bundle1Path = Path.Combine(directory.Path, "b1.bowerbundle"); + AirGappedExportResult exp1 = AirGappedBundle.Create( + bundle1Path, + new AirGappedBundleManifest( + AirGappedBundleManifest.CurrentKind, "b1", "airgap-site-01", "airgap-host", "scif-south", + "1.0.1", "sha256:pol1", "default", 1, AirGappedBundleManifest.GenesisBundleHash, + 1, 10, "sha256:head10", 1, 0, 0, string.Empty, false, Now.ToString("O")), + ["{\"eventId\":\"e1\"}"], + privatePem); + SignedOfflineSiteReport report1 = AirGappedBundle.Verify(bundle1Path, [publicPem]).OfflineReport!; + + // Viewer is forbidden from importing. + using HttpResponseMessage forbidden = await viewer.PostAsJsonAsync("/api/fleet/offline-import", report1, cancellation); + Assert.Equal(HttpStatusCode.Forbidden, forbidden.StatusCode); + + // Untrusted signer is rejected with 400. + string badBundlePath = Path.Combine(directory.Path, "bad.bowerbundle"); + AirGappedBundle.Create( + badBundlePath, + new AirGappedBundleManifest( + AirGappedBundleManifest.CurrentKind, "b-bad", "airgap-site-01", "airgap-host", "scif-south", + "1.0.1", "sha256:pol1", "default", 1, AirGappedBundleManifest.GenesisBundleHash, + 1, 10, "sha256:head10", 1, 0, 0, string.Empty, false, Now.ToString("O")), + ["{\"eventId\":\"e1\"}"], + untrustedPriv); + (_, string untrustedPub, _) = DetachedSigner.GenerateKeyPair(); + using (ZipArchive zip = ZipFile.OpenRead(badBundlePath)) + { + using StreamReader sr = new(zip.GetEntry("status-report.json")!.Open()); + SignedOfflineSiteReport untrustedReport = System.Text.Json.JsonSerializer.Deserialize( + await sr.ReadToEndAsync(cancellation), AirGappedBundleJsonContext.Default.SignedOfflineSiteReport)!; + using HttpResponseMessage badResp = await oper.PostAsJsonAsync("/api/fleet/offline-import", untrustedReport, cancellation); + Assert.Equal(HttpStatusCode.BadRequest, badResp.StatusCode); + } + + // Valid import succeeds and shows as Offline site in /api/fleet (#113). + using HttpResponseMessage ok1 = await oper.PostAsJsonAsync("/api/fleet/offline-import", report1, cancellation); + Assert.Equal(HttpStatusCode.OK, ok1.StatusCode); + FleetCollector imported = (await ok1.Content.ReadFromJsonAsync(ManagementApiTests.ApiJson, cancellation))!; + Assert.Equal(FleetStates.OfflineSite, imported.State); + Assert.Equal("Offline site", imported.Label); + Assert.Equal("offline-bundle", imported.Path); + + FleetRecord fleet = (await viewer.GetFromJsonAsync("/api/fleet", ManagementApiTests.ApiJson, cancellation))!; + Assert.Contains(fleet.Collectors, c => c.Id == "airgap-site-01" && c.State == FleetStates.OfflineSite); + + // Replaying bundle 1 fails with 409 Conflict (replay protection). + using HttpResponseMessage replay = await oper.PostAsJsonAsync("/api/fleet/offline-import", report1, cancellation); + Assert.Equal(HttpStatusCode.Conflict, replay.StatusCode); + + // Skipping sequence 2 -> importing sequence 3 fails with 409 Conflict (gap detection). + string bundle3Path = Path.Combine(directory.Path, "b3.bowerbundle"); + AirGappedBundle.Create( + bundle3Path, + new AirGappedBundleManifest( + AirGappedBundleManifest.CurrentKind, "b3", "airgap-site-01", "airgap-host", "scif-south", + "1.0.1", "sha256:pol1", "default", 3, exp1.BundleHash, + 11, 20, "sha256:head20", 1, 0, 0, string.Empty, false, Now.AddHours(1).ToString("O")), + ["{\"eventId\":\"e2\"}"], + privatePem); + SignedOfflineSiteReport report3 = AirGappedBundle.Verify(bundle3Path, [publicPem]).OfflineReport!; + using HttpResponseMessage gap = await oper.PostAsJsonAsync("/api/fleet/offline-import", report3, cancellation); + Assert.Equal(HttpStatusCode.Conflict, gap.StatusCode); + + // Audit log recorded the import. + List audits = (await viewer.GetFromJsonAsync>("/api/audit", ManagementApiTests.ApiJson, cancellation))!; + Assert.Contains(audits, a => a.Action == "fleet.offline-bundle-imported" && a.TargetId == "airgap-site-01"); + } + + private static AirGappedBundleManifest BuildManifest( + string bundleId, + string collectorId, + long sequence, + string previousHash, + IReadOnlyList events) => + new( + AirGappedBundleManifest.CurrentKind, + bundleId, + collectorId, + "airgap-host", + "site-a", + "1.0.1", + "sha256:pol", + "default", + sequence, + previousHash, + events[0].Sequence, + events[^1].Sequence, + events[^1].ChainHash, + events.Count, + events.Count, + 0, + string.Empty, + false, + Now.ToString("O")); +} diff --git a/tools/docs/generate_cli_reference.py b/tools/docs/generate_cli_reference.py index 85ed5537..f18b4e24 100644 --- a/tools/docs/generate_cli_reference.py +++ b/tools/docs/generate_cli_reference.py @@ -36,6 +36,9 @@ "top": ("Tap and top", "../operations/tap-and-top.md"), "version": ("Release versioning", "../operations/release-versioning.md"), "wec": ("Windows Event Forwarding", "../deployment/windows-event-forwarding.md"), + "export": ("Air-gapped bundles", "../deployment/air-gapped.md"), + "verify": ("Air-gapped bundles", "../deployment/air-gapped.md"), + "import": ("Air-gapped bundles", "../deployment/air-gapped.md"), } diff --git a/website/sidebars.ts b/website/sidebars.ts index ff34b011..ceb207da 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -146,6 +146,11 @@ const sidebars: SidebarsConfig = { "id": "deployment/relay", "label": "Relay networks" }, + { + "type": "doc", + "id": "deployment/air-gapped", + "label": "Air-gapped bundles" + }, { "type": "doc", "id": "deployment/s3-output",