Repository navigation
feat(airgap): add signed hash-chained export/import bundles and Offline site fleet view (#111, #113) #308
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(airgap): add signed hash-chained export/import bundles and Offline site fleet view (#111, #113) #308
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| { | ||
| /// <summary> | ||
| /// 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] | ||
| /// </summary> | ||
| public static async Task<int> 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<LedgerEvent> events = await store.ReadLedgerEventsAsync(afterSequence, maxEvents); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Stop the export when the ledger skips a sequence after the saved cursor.
The export must detect any missing sequence between the saved cursor and the ledger head. On a gap, it must fail before it writes the bundle or records the cursor. The error must name the missing sequence range. Decide separately whether purge should wait for the export cursor.
|
||
| 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; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep the ledger sequence and head hash from the same observation. If the event read returns no rows after sequence 10, and event 11 commits before the head read, export signs sequence 10 with event 11’s hash. Use a consistent ledger read or fetch the hash for the exact sequence the bundle reports. Keep the nonempty case tied to the last exported event.
|
||
| 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( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Recover a published bundle before allocating its sequence again. If export stops after
|
||
| 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; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// bower verify bundle --bundle FILE --trusted-key PUBLIC.pem | ||
| /// [--expect-sequence N] [--expect-previous-hash HASH] [--decrypt-key-file FILE] | ||
| /// </summary> | ||
| public static int Verify(string[] args) | ||
| { | ||
| string bundlePath = CliOptions.Required(args, "--bundle"); | ||
| IReadOnlyList<string> 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; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// 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. | ||
| /// </summary> | ||
| public static Task<int> ImportAsync(string[] args) => ImportAsync(args, null, Console.Out, Console.Error); | ||
|
|
||
| internal static async Task<int> ImportAsync( | ||
| string[] args, | ||
| HttpMessageHandler? handler, | ||
| TextWriter output, | ||
| TextWriter error) | ||
| { | ||
| string bundlePath = CliOptions.Required(args, "--bundle"); | ||
| IReadOnlyList<string> 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<string> events = AirGappedBundle.ReadVerifiedEvents(bundlePath, keys, decryptionKey); | ||
| SortedDictionary<string, long> 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); | ||
|
Comment on lines
+190
to
+193
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reject out-of-order bundles before sending their events. If management has accepted sequence 1 and the operator imports sequence 3 with both URLs, this loop posts the events before management returns the chain conflict. Signature verification does not establish that a bundle is next. Check the chain at the point that authorizes delivery, including collector-only imports, without marking the bundle complete before delivery succeeds.
|
||
| 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; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Return a nonzero exit code if a requested destination rejects the import. The command returns
|
||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Document how the import command authenticates to the management API.
The example runs
bower import bundlewith--management-urlonly. The command sends no credential unlessBOWER_MANAGEMENT_TOKENis set. The management endpointapi/fleet/offline-importrequires theOperatepolicy, so the unauthenticated POST is rejected and the fleet state is not updated. The command still exits with status 0 and reports the rejection only asmanagementStatusin its output.Add the prerequisite to the procedure. State that
BOWER_MANAGEMENT_TOKENmust hold a credential that grantsOperateon the management API. Show how the operator sets it before the import. Also state that a non-2xxmanagementStatusmeans the fleet state was not updated.Source: Learnings