From 2b13564e04074a3a29275ee73ec66e076a9011b3 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 10 Nov 2026 11:52:14 -0500 Subject: [PATCH] feat(ldap): pin the LDAP server certificate by SHA-256 thumbprint (#180) New optional MxGateway:Ldap:ServerCertificateThumbprintSha256 (hex SHA-256 of the DER cert; case/colon/dash/space-insensitive; comma/semicolon-separated string or array, so a rotation can carry old + new). When set, the dashboard's shared LDAP provider gets a RemoteCertificateValidationCallback via LdapOptions.ServerCertificateValidationCallback (Auth 0.4.1) that accepts the server certificate iff its thumbprint matches a pin, ignoring chain/name errors only then. Unset keeps default OS trust-store validation untouched. The callback is an init-only, code-only property, so the ILdapAuthService registration from AddZbLdapAuth is replaced with one built from the bound options plus the callback. Pins are read straight from configuration because the binder silently binds the scalar form onto a list as empty. GatewayOptionsValidator rejects a pin that is not 64 hex chars after normalization and any pin with Transport=None; the Production hard stops are unchanged. Pins are shown on the Settings page. Docs: GatewayConfiguration.md, glauth.md. Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV --- docs/GatewayConfiguration.md | 1 + glauth.md | 9 + .../EffectiveLdapConfiguration.cs | 3 +- .../GatewayConfigurationProvider.cs | 3 +- ...onfigurationServiceCollectionExtensions.cs | 8 + .../Configuration/GatewayOptionsValidator.cs | 31 +++ .../Configuration/LdapOptions.cs | 14 + .../Configuration/LdapServerCertificatePin.cs | 147 +++++++++++ .../Components/Pages/SettingsPage.razor | 13 + .../DashboardServiceCollectionExtensions.cs | 17 ++ .../GatewayOptionsValidatorTests.cs | 52 ++++ .../LdapServerCertificatePinTests.cs | 240 ++++++++++++++++++ 12 files changed, 536 insertions(+), 2 deletions(-) create mode 100644 src/ZB.MOM.WW.MxGateway.Server/Configuration/LdapServerCertificatePin.cs create mode 100644 src/ZB.MOM.WW.MxGateway.Tests/Configuration/LdapServerCertificatePinTests.cs diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index e27da7f3..f0e1d90a 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -307,6 +307,7 @@ dev/test GLAuth posture (`glauth.md`), not a production posture. | `MxGateway:Ldap:Port` | `3893` | LDAP server port. Must be between `1` and `65535`. | | `MxGateway:Ldap:Transport` | `None` | Connection transport: `None` (plaintext), `StartTls` (upgrade), or `Ldaps` (implicit TLS). The dev default is `None` because the shared GLAuth instance has LDAPS disabled and binds send cleartext. **Production hard-stop (SEC-06):** when the host runs in the `Production` environment, `Transport` must not be `None` — startup validation fails otherwise. Deployed hosts must set `Ldaps` or `StartTls`. | | `MxGateway:Ldap:AllowInsecure` | `true` | Permits a plaintext bind. Must be `true` when `Transport` is `None`; set `false` (with `Ldaps`/`StartTls`) in production. | +| `MxGateway:Ldap:ServerCertificateThumbprintSha256` | *(empty)* | Pins the LDAP server certificate by its SHA-256 thumbprint (mxaccessgw#180), so `Ldaps`/`StartTls` works against a directory with a self-signed certificate (e.g. GLAuth) without installing that certificate in the OS trust store. Empty (the default) keeps default OS trust-store validation, unchanged. When set, the server certificate is accepted **if and only if** its thumbprint matches one of the pins: chain and name errors are ignored for a matching certificate, and a non-matching certificate is rejected even if it chains to a trusted root. Format: the hex SHA-256 of the DER certificate, case-, colon-, dash- and space-insensitive — paste the output of `openssl x509 -in cert.pem -noout -fingerprint -sha256` (drop the `sha256 Fingerprint=` prefix) or, for a live server, `openssl s_client -connect host:636 /dev/null \| openssl x509 -noout -fingerprint -sha256`. To carry old + new across a certificate rotation, give several pins as a comma/semicolon-separated string (`"AB:CD:…,12:34:…"`, env var `MxGateway__Ldap__ServerCertificateThumbprintSha256`) or as a JSON array (`MxGateway__Ldap__ServerCertificateThumbprintSha256__0`, `__1`, …). Startup validation rejects an entry that is not 64 hex characters after normalization, and rejects any pin combined with `Transport=None` (plaintext has no certificate to pin). Applies to every endpoint, including `FallbackServers`. Shown on the dashboard Settings page. | | `MxGateway:Ldap:SearchBase` | `dc=zb,dc=local` | Search base DN. | | `MxGateway:Ldap:ServiceAccountDn` | `cn=serviceaccount,dc=zb,dc=local` | Bind DN for the search account. | | `MxGateway:Ldap:ServiceAccountPassword` | `${secret:ldap/mxgateway/bind}` | Search-account password. **Never a committed plaintext value (SEC-36):** the shared GLAuth bind credential is supplied out-of-band through one of three channels, all binding to this key. **(1) Encrypted secrets store (shipped default):** `appsettings.json` ships the reference `${secret:ldap/mxgateway/bind}`, which the pre-host `${secret:}` expander resolves at startup from the encrypted secrets store (the code-side design default is blank, so a missing/unresolved value fails closed rather than falling back to a leaked credential). Seed it once with `secret set ldap/mxgateway/bind ` (the store's master key must be present via `ZB_SECRETS_MASTER_KEY`); startup aborts with `SecretNotFoundException` if the secret is absent. **(2) Deployed hosts — env var:** override directly with `MxGateway__Ldap__ServiceAccountPassword` (double-underscore form) in the NSSM service environment — a plain literal there is used as-is and the store lookup is skipped. **(3) Dev boxes — user-secrets:** `dotnet user-secrets set "MxGateway:Ldap:ServiceAccountPassword" ` (the server carries `mxaccessgw-server`; user-secrets load automatically in the Development environment and live under the user profile, outside the tree). The value comes from the GLAuth source of truth `scadaproj/infra/glauth/`, never from a repo file. **Rotation:** because the credential was historically committed, it was rotated in `scadaproj/infra/glauth/` (and the shared GLAuth on `10.100.0.35` redeployed) on 2026-08-07 (SEC-36) — see `docs/runbooks/SEC-36-ldap-credential-rotation.md` for the cutover procedure used, and for future rotations. A blank/unresolved value fails startup validation with a message naming the two supported channels. | diff --git a/glauth.md b/glauth.md index c0fd3508..94ef4e20 100644 --- a/glauth.md +++ b/glauth.md @@ -373,3 +373,12 @@ add a `tokenGroups` query as an enhancement. - LDAPS isn't enabled in dev; binding sends passwords cleartext on the wire. The shared GLAuth listens only on the LAN (`10.100.0.35`); never expose port 3893 externally without enabling TLS first. +- **Enabling LDAPS against GLAuth (self-signed cert).** GLAuth's `[ldaps]` + listener normally uses a self-signed certificate. Rather than installing it in + the gateway host's trust store, pin it: set `MxGateway:Ldap:Transport=Ldaps`, + the LDAPS `Port`, `AllowInsecure=false`, and + `MxGateway:Ldap:ServerCertificateThumbprintSha256` to the certificate's SHA-256 + thumbprint (`openssl x509 -in cert.pem -noout -fingerprint -sha256`). Several + pins (comma-separated or an array) carry a rotation. A pin with + `Transport=None` fails startup validation. See `docs/GatewayConfiguration.md` + (*LDAP Options*). diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/EffectiveLdapConfiguration.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/EffectiveLdapConfiguration.cs index 168a2976..90ce8785 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/EffectiveLdapConfiguration.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/EffectiveLdapConfiguration.cs @@ -12,4 +12,5 @@ public sealed record EffectiveLdapConfiguration( string UserNameAttribute, string DisplayNameAttribute, string GroupAttribute, - IReadOnlyList FallbackServers); + IReadOnlyList FallbackServers, + IReadOnlyList? ServerCertificateThumbprintSha256 = null); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigurationProvider.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigurationProvider.cs index 212c67d4..ed632201 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigurationProvider.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigurationProvider.cs @@ -31,7 +31,8 @@ public sealed class GatewayConfigurationProvider(IOptions option UserNameAttribute: value.Ldap.UserNameAttribute, DisplayNameAttribute: value.Ldap.DisplayNameAttribute, GroupAttribute: value.Ldap.GroupAttribute, - FallbackServers: value.Ldap.FallbackServers), + FallbackServers: value.Ldap.FallbackServers, + ServerCertificateThumbprintSha256: value.Ldap.ServerCertificateThumbprintSha256), Worker: new EffectiveWorkerConfiguration( ExecutablePath: value.Worker.ExecutablePath, WorkingDirectory: value.Worker.WorkingDirectory, diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigurationServiceCollectionExtensions.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigurationServiceCollectionExtensions.cs index d2762ae1..cef0560f 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigurationServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigurationServiceCollectionExtensions.cs @@ -26,6 +26,14 @@ public static class GatewayConfigurationServiceCollectionExtensions services.AddValidatedOptions( configuration, GatewayOptions.SectionName); + // The LDAP certificate pins accept both a comma-separated scalar and an array; the binder + // only understands the array form (a scalar binds to an empty list without complaint), so + // the shadow options take them from the one reader the runtime callback also uses. Runs + // before validation, so GatewayOptionsValidator sees exactly what will be enforced. + services.PostConfigure(options => + options.Ldap.ServerCertificateThumbprintSha256 = LdapServerCertificatePin.ReadConfiguredPins( + configuration.GetSection($"{GatewayOptions.SectionName}:Ldap"))); + services.AddSingleton(); return services; diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs index f8160c34..2acd8fcc 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs @@ -216,6 +216,37 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase pins = options.ServerCertificateThumbprintSha256; + if (pins.Count == 0) + { + return; + } + + foreach (string pin in pins) + { + if (!LdapServerCertificatePin.TryNormalize(pin, out _)) + { + builder.Add( + $"MxGateway:Ldap:{LdapServerCertificatePin.ConfigurationKey} entry '{pin}' is not a SHA-256 " + + $"thumbprint: expected {LdapServerCertificatePin.NormalizedLength} hex characters after " + + "removing ':', '-' and whitespace (e.g. the output of " + + "'openssl x509 -in cert.pem -noout -fingerprint -sha256')."); + } + } + + if (options.Transport == LdapTransport.None) + { + builder.Add( + $"MxGateway:Ldap:{LdapServerCertificatePin.ConfigurationKey} is set but Transport is None " + + "(plaintext): there is no server certificate to pin. Use Ldaps or StartTls, or remove the pin."); + } } private static void ValidateWorker(WorkerOptions options, ValidationBuilder builder) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/LdapOptions.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/LdapOptions.cs index b8f5330a..f844a4d1 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/LdapOptions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/LdapOptions.cs @@ -83,4 +83,18 @@ public sealed class LdapOptions /// /// public IReadOnlyList FallbackServers { get; init; } = []; + + /// + /// Gets the SHA-256 thumbprints the LDAP server certificate is pinned to (mxaccessgw#180). + /// Empty (the default) keeps default OS trust-store validation. Gateway-only: the shared + /// has no such field — the pins are + /// turned into its code-only ServerCertificateValidationCallback by + /// . + /// + /// Settable because it is filled by a post-configure step from + /// rather than by the binder: the + /// binder drops the comma-separated scalar form of the key silently. + /// + /// + public IReadOnlyList ServerCertificateThumbprintSha256 { get; set; } = []; } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/LdapServerCertificatePin.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/LdapServerCertificatePin.cs new file mode 100644 index 00000000..d5c893f6 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/LdapServerCertificatePin.cs @@ -0,0 +1,147 @@ +using System.Net.Security; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Microsoft.Extensions.Configuration; +using SharedLdapOptions = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapOptions; + +namespace ZB.MOM.WW.MxGateway.Server.Configuration; + +/// +/// LDAP server-certificate pinning for MxGateway:Ldap:ServerCertificateThumbprintSha256 +/// (mxaccessgw#180). Lets the dashboard bind over Ldaps/StartTls to a directory whose +/// certificate is self-signed (the shared GLAuth) without installing that certificate in the OS +/// trust store: the configured SHA-256 thumbprints are turned into a +/// handed to the shared provider through +/// . +/// +/// With no pin configured nothing changes — the shared options keep a +/// callback and the LDAP client validates against the OS trust store as before. With a pin, the +/// server certificate is accepted if and only if its thumbprint matches one of the pins: +/// chain and name errors are ignored for a matching certificate, and a non-matching certificate is +/// rejected even if it would otherwise chain to a trusted root (strict pinning). +/// +/// +public static class LdapServerCertificatePin +{ + /// The key, under MxGateway:Ldap, that carries the pins. + public const string ConfigurationKey = "ServerCertificateThumbprintSha256"; + + /// Length of a normalized pin: a SHA-256 digest is 32 bytes = 64 hex characters. + public const int NormalizedLength = 64; + + private static readonly char[] EntrySeparators = [',', ';']; + + /// + /// Reads the raw pin entries from the MxGateway:Ldap section. Accepts both a scalar + /// ("AA:BB…,CC:DD…", comma- or semicolon-separated so a rotation can carry old + new) and + /// an array (ServerCertificateThumbprintSha256:0, :1, …; each element may itself be + /// separated). Read straight from configuration because the options binder silently binds a + /// scalar onto a list property as empty. + /// + /// The MxGateway:Ldap configuration section. + /// The trimmed, non-empty entries, un-normalized (validation reports them verbatim). + public static IReadOnlyList ReadConfiguredPins(IConfiguration ldapSection) + { + ArgumentNullException.ThrowIfNull(ldapSection); + + IConfigurationSection pinSection = ldapSection.GetSection(ConfigurationKey); + var raw = new List(); + if (pinSection.Value is { } scalar) + { + raw.Add(scalar); + } + + raw.AddRange(pinSection.GetChildren().Select(child => child.Value).OfType()); + + return raw + .SelectMany(value => value.Split(EntrySeparators)) + .Select(entry => entry.Trim()) + .Where(entry => entry.Length > 0) + .ToArray(); + } + + /// + /// Normalizes one pin: strips colons, dashes and whitespace and upper-cases it, then requires + /// exactly hex characters. So openssl x509 -fingerprint -sha256 + /// output (AB:CD:…), a bare lower-case hex string and a space-separated form all match. + /// + /// A raw configured entry. + /// The upper-case 64-hex form when the entry is well formed. + /// when the entry is a well-formed SHA-256 thumbprint. + public static bool TryNormalize(string? pin, out string normalized) + { + normalized = string.Empty; + if (string.IsNullOrWhiteSpace(pin)) + { + return false; + } + + string stripped = new(pin.Where(c => c != ':' && c != '-' && !char.IsWhiteSpace(c)).ToArray()); + if (stripped.Length != NormalizedLength || !stripped.All(char.IsAsciiHexDigit)) + { + return false; + } + + normalized = stripped.ToUpperInvariant(); + return true; + } + + /// Computes the upper-case hex SHA-256 thumbprint of a certificate's DER encoding. + /// The certificate. + /// The 64-character upper-case thumbprint. + public static string ComputeThumbprint(X509Certificate certificate) + { + ArgumentNullException.ThrowIfNull(certificate); + return Convert.ToHexString(SHA256.HashData(certificate.GetRawCertData())); + } + + /// + /// Builds the pinning validation callback, or returns when no pin is + /// configured (leaving the shared provider on default OS validation). + /// + /// The raw configured entries. + /// The callback, or for an empty pin list. + /// An entry is not a SHA-256 thumbprint. The startup + /// validator rejects this first; the throw is defence in depth so a malformed pin can never + /// silently degrade into "no pin". + public static RemoteCertificateValidationCallback? CreateValidationCallback(IReadOnlyList pins) + { + ArgumentNullException.ThrowIfNull(pins); + if (pins.Count == 0) + { + return null; + } + + var accepted = new HashSet(StringComparer.Ordinal); + foreach (string pin in pins) + { + if (!TryNormalize(pin, out string normalized)) + { + throw new InvalidOperationException( + $"MxGateway:Ldap:{ConfigurationKey} entry '{pin}' is not a SHA-256 thumbprint " + + $"({NormalizedLength} hex characters after removing ':', '-' and whitespace)."); + } + + accepted.Add(normalized); + } + + // Chain/name errors (sslPolicyErrors) are deliberately ignored: the pin replaces chain + // trust. A null certificate (server presented none) never matches. + return (_, certificate, _, _) => + certificate is not null && accepted.Contains(ComputeThumbprint(certificate)); + } + + /// + /// Returns the shared provider's options with the pinning callback applied, or the options + /// unchanged when no pin is configured. + /// + /// The shared options as bound from MxGateway:Ldap. + /// The MxGateway:Ldap configuration section. + /// The effective shared options. + public static SharedLdapOptions Apply(SharedLdapOptions options, IConfiguration ldapSection) + { + ArgumentNullException.ThrowIfNull(options); + RemoteCertificateValidationCallback? callback = CreateValidationCallback(ReadConfiguredPins(ldapSection)); + return callback is null ? options : options with { ServerCertificateValidationCallback = callback }; + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/SettingsPage.razor b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/SettingsPage.razor index 33bc0343..d814162c 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/SettingsPage.razor +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/SettingsPage.razor @@ -42,6 +42,19 @@ else LDAP transport@Snapshot.Configuration.Ldap.Transport + + LDAP certificate pins (SHA-256) + + @if (Snapshot.Configuration.Ldap.ServerCertificateThumbprintSha256 is not { Count: > 0 } pins) + { + none (OS trust store) + } + else + { + @string.Join(", ", pins) + } + + LDAP search base@Snapshot.Configuration.Ldap.SearchBase LDAP service account@Snapshot.Configuration.Ldap.ServiceAccountDn LDAP service password@Snapshot.Configuration.Ldap.ServiceAccountPassword diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs index 3390a83b..7a9e3ec1 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs @@ -3,10 +3,14 @@ using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components.Server.Circuits; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using ZB.MOM.WW.Auth.Abstractions.Ldap; using ZB.MOM.WW.Auth.Abstractions.Roles; using ZB.MOM.WW.Auth.AspNetCore; +using ZB.MOM.WW.Auth.Ldap; +using SharedLdapOptions = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapOptions; using ZB.MOM.WW.MxGateway.Server.Configuration; using ZB.MOM.WW.MxGateway.Server.Security.Audit; @@ -48,6 +52,19 @@ public static class DashboardServiceCollectionExtensions // ValidateOnStart() so an insecure-transport misconfiguration fails fast at boot. services.AddZbLdapAuth(configuration, "MxGateway:Ldap"); + // mxaccessgw#180: MxGateway:Ldap:ServerCertificateThumbprintSha256 pins the directory's + // certificate. The shared LdapOptions only exposes that as the code-only (init) property + // ServerCertificateValidationCallback, so it cannot be set by a post-configure step on the + // bound options; instead the provider registration is replaced with one built from the + // bound options plus the callback. No pin => the options pass through unchanged (null + // callback, default OS validation) — same construction AddZbLdapAuth itself performs. + services.Replace(ServiceDescriptor.Singleton(sp => + new LdapAuthService( + LdapServerCertificatePin.Apply( + sp.GetRequiredService>().Value, + configuration.GetSection("MxGateway:Ldap")), + sp.GetService>()))); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs index a8d46ac0..cfeebb46 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs @@ -1453,4 +1453,56 @@ public sealed class GatewayOptionsValidatorTests Assert.True(result.Succeeded); } + + // mxaccessgw#180 — LDAP server-certificate pinning. + private const string ValidPin = "AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89"; + + private static LdapOptions PinnedLdapOptions(LdapTransport transport, params string[] pins) => new() + { + Enabled = true, + Transport = transport, + AllowInsecure = transport == LdapTransport.None, + ServiceAccountPassword = TestBindPassword, + ServerCertificateThumbprintSha256 = pins, + }; + + [Theory] + [InlineData(LdapTransport.Ldaps)] + [InlineData(LdapTransport.StartTls)] + public void Validate_Succeeds_WhenLdapPinWellFormedOverTls_InProduction(LdapTransport transport) + { + GatewayOptions options = CloneWithLdap(ValidOptions(), PinnedLdapOptions(transport, ValidPin, ValidPin.Replace(":", "").ToLowerInvariant())); + ValidateOptionsResult result = new GatewayOptionsValidator(isProduction: true).Validate(null, options); + Assert.True(result.Succeeded, string.Join(Environment.NewLine, result.Failures ?? [])); + } + + [Theory] + [InlineData("AB:CD")] + [InlineData("zz:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89")] + [InlineData("AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:00")] + public void Validate_Fails_WhenLdapPinMalformed(string pin) + { + GatewayOptions options = CloneWithLdap(ValidOptions(), PinnedLdapOptions(LdapTransport.Ldaps, ValidPin, pin)); + ValidateOptionsResult result = new GatewayOptionsValidator(isProduction: false).Validate(null, options); + Assert.True(result.Failed); + Assert.Contains(result.Failures!, f => f.Contains("ServerCertificateThumbprintSha256") && f.Contains(pin)); + } + + [Fact] + public void Validate_Fails_WhenLdapPinCombinedWithPlaintextTransport() + { + GatewayOptions options = CloneWithLdap(ValidOptions(), PinnedLdapOptions(LdapTransport.None, ValidPin)); + ValidateOptionsResult result = new GatewayOptionsValidator(isProduction: false).Validate(null, options); + Assert.True(result.Failed); + Assert.Contains(result.Failures!, f => f.Contains("ServerCertificateThumbprintSha256") && f.Contains("Transport is None")); + } + + [Fact] + public void Validate_KeepsProductionPlaintextHardStop_WhenLdapPinned() + { + GatewayOptions options = CloneWithLdap(ValidOptions(), PinnedLdapOptions(LdapTransport.None, ValidPin)); + ValidateOptionsResult result = new GatewayOptionsValidator(isProduction: true).Validate(null, options); + Assert.True(result.Failed); + Assert.Contains(result.Failures!, f => f.Contains("MxGateway:Ldap:Transport") && f.Contains("Production")); + } } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Configuration/LdapServerCertificatePinTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/LdapServerCertificatePinTests.cs new file mode 100644 index 00000000..8b15f032 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/LdapServerCertificatePinTests.cs @@ -0,0 +1,240 @@ +using System.Net.Security; +using System.Reflection; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.Auth.Abstractions.Ldap; +using ZB.MOM.WW.Auth.Ldap; +using ZB.MOM.WW.MxGateway.Server.Configuration; +using ZB.MOM.WW.MxGateway.Server.Dashboard; +using SharedLdapOptions = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapOptions; + +namespace ZB.MOM.WW.MxGateway.Tests.Configuration; + +/// LDAP server-certificate pinning (mxaccessgw#180). +public sealed class LdapServerCertificatePinTests +{ + private const SslPolicyErrors SelfSignedErrors = + SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNameMismatch; + + private static X509Certificate2 CreateSelfSigned(string subject) + { + using ECDsa key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + CertificateRequest request = new($"CN={subject}", key, HashAlgorithmName.SHA256); + return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(30)); + } + + // The shape `openssl x509 -noout -fingerprint -sha256` prints: upper-case, colon-separated. + private static string OpensslFingerprint(X509Certificate2 certificate) + => string.Join(':', Convert.ToHexString(SHA256.HashData(certificate.RawData)).Chunk(2).Select(c => new string(c))); + + private static bool Invoke(RemoteCertificateValidationCallback callback, X509Certificate? certificate, SslPolicyErrors errors) + => callback(new object(), certificate, null, errors); + + [Theory] + [InlineData("AB:CD")] + [InlineData("")] + [InlineData(" ")] + [InlineData(null)] + public void TryNormalize_RejectsWrongLength(string? pin) + => Assert.False(LdapServerCertificatePin.TryNormalize(pin, out _)); + + [Fact] + public void TryNormalize_RejectsNonHex() + => Assert.False(LdapServerCertificatePin.TryNormalize(new string('G', 64), out _)); + + [Fact] + public void TryNormalize_IsCaseColonSpaceAndDashInsensitive() + { + using X509Certificate2 certificate = CreateSelfSigned("pin-normalize"); + string expected = Convert.ToHexString(SHA256.HashData(certificate.RawData)); + string colon = OpensslFingerprint(certificate); + + string[] variants = + [ + colon, + colon.ToLowerInvariant(), + colon.Replace(':', ' '), + colon.Replace(':', '-'), + expected.ToLowerInvariant(), + " " + expected + " ", + ]; + + foreach (string variant in variants) + { + Assert.True(LdapServerCertificatePin.TryNormalize(variant, out string normalized), variant); + Assert.Equal(expected, normalized); + } + } + + [Fact] + public void CreateValidationCallback_ReturnsNull_WhenNoPin() + => Assert.Null(LdapServerCertificatePin.CreateValidationCallback([])); + + [Fact] + public void CreateValidationCallback_Throws_OnMalformedPin() + => Assert.Throws(() => LdapServerCertificatePin.CreateValidationCallback(["not-a-pin"])); + + [Fact] + public void Callback_AcceptsPinnedSelfSignedCertificate_DespiteChainAndNameErrors() + { + using X509Certificate2 certificate = CreateSelfSigned("glauth"); + RemoteCertificateValidationCallback callback = + LdapServerCertificatePin.CreateValidationCallback([OpensslFingerprint(certificate).ToLowerInvariant()])!; + + Assert.True(Invoke(callback, certificate, SelfSignedErrors)); + } + + [Fact] + public void Callback_RejectsUnpinnedCertificate_EvenWhenItWouldOtherwiseValidate() + { + using X509Certificate2 pinned = CreateSelfSigned("glauth"); + using X509Certificate2 other = CreateSelfSigned("impostor"); + RemoteCertificateValidationCallback callback = + LdapServerCertificatePin.CreateValidationCallback([OpensslFingerprint(pinned)])!; + + Assert.False(Invoke(callback, other, SelfSignedErrors)); + Assert.False(Invoke(callback, other, SslPolicyErrors.None)); + Assert.False(Invoke(callback, null, SslPolicyErrors.RemoteCertificateNotAvailable)); + } + + [Fact] + public void Callback_AcceptsEitherPin_DuringRotation() + { + using X509Certificate2 oldCert = CreateSelfSigned("glauth-old"); + using X509Certificate2 newCert = CreateSelfSigned("glauth-new"); + using X509Certificate2 other = CreateSelfSigned("impostor"); + IConfiguration ldap = Section(new() + { + ["MxGateway:Ldap:ServerCertificateThumbprintSha256"] = + $"{OpensslFingerprint(oldCert)}, {OpensslFingerprint(newCert)}", + }); + + RemoteCertificateValidationCallback callback = + LdapServerCertificatePin.CreateValidationCallback(LdapServerCertificatePin.ReadConfiguredPins(ldap))!; + + Assert.True(Invoke(callback, oldCert, SelfSignedErrors)); + Assert.True(Invoke(callback, newCert, SelfSignedErrors)); + Assert.False(Invoke(callback, other, SelfSignedErrors)); + } + + [Fact] + public void ReadConfiguredPins_AcceptsScalarAndArrayForms() + { + IConfiguration scalar = Section(new() + { + ["MxGateway:Ldap:ServerCertificateThumbprintSha256"] = " aa , bb;cc ", + }); + IConfiguration array = Section(new() + { + ["MxGateway:Ldap:ServerCertificateThumbprintSha256:0"] = "aa", + ["MxGateway:Ldap:ServerCertificateThumbprintSha256:1"] = "bb,cc", + }); + + Assert.Equal(["aa", "bb", "cc"], LdapServerCertificatePin.ReadConfiguredPins(scalar)); + Assert.Equal(["aa", "bb", "cc"], LdapServerCertificatePin.ReadConfiguredPins(array)); + Assert.Empty(LdapServerCertificatePin.ReadConfiguredPins(Section(new()))); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void GatewayOptions_CarryPins_FromScalarOrArrayForm(bool arrayForm) + { + Dictionary values = arrayForm + ? new() { ["MxGateway:Ldap:ServerCertificateThumbprintSha256:0"] = "aa", ["MxGateway:Ldap:ServerCertificateThumbprintSha256:1"] = "bb" } + : new() { ["MxGateway:Ldap:ServerCertificateThumbprintSha256"] = "aa,bb" }; + IConfigurationRoot configuration = new ConfigurationBuilder().AddInMemoryCollection(values).Build(); + ServiceCollection services = new(); + services.AddGatewayConfiguration(configuration); + using ServiceProvider provider = services.BuildServiceProvider(); + + // Read the unvalidated value: 'aa' is malformed on purpose, this test is about binding. + GatewayOptions options = BindWithoutValidation(provider); + + Assert.Equal(["aa", "bb"], options.Ldap.ServerCertificateThumbprintSha256); + } + + [Fact] + public void Dashboard_HandsPinCallbackToSharedLdapOptions_WhenConfigured() + { + using X509Certificate2 pinned = CreateSelfSigned("glauth"); + using X509Certificate2 other = CreateSelfSigned("impostor"); + + SharedLdapOptions effective = ResolveEffectiveSharedOptions(new() + { + ["MxGateway:Ldap:ServerCertificateThumbprintSha256"] = OpensslFingerprint(pinned), + }); + + Assert.NotNull(effective.ServerCertificateValidationCallback); + Assert.True(Invoke(effective.ServerCertificateValidationCallback!, pinned, SelfSignedErrors)); + Assert.False(Invoke(effective.ServerCertificateValidationCallback!, other, SelfSignedErrors)); + + // The rest of the bound section still reaches the provider. + Assert.Equal("glauth.test", effective.Server); + Assert.Equal(LdapTransport.Ldaps, effective.Transport); + } + + [Fact] + public void Dashboard_LeavesSharedLdapCallbackNull_WhenNoPin() + { + SharedLdapOptions effective = ResolveEffectiveSharedOptions(new()); + + Assert.Null(effective.ServerCertificateValidationCallback); + Assert.Equal("glauth.test", effective.Server); + } + + private static IConfiguration Section(Dictionary values) + => new ConfigurationBuilder().AddInMemoryCollection(values).Build().GetSection("MxGateway:Ldap"); + + private static GatewayOptions BindWithoutValidation(IServiceProvider provider) + { + // Run the configure/post-configure pipeline without the validators. + GatewayOptions options = new(); + foreach (IConfigureOptions configure in provider.GetServices>()) + { + configure.Configure(options); + } + + foreach (IPostConfigureOptions postConfigure in provider.GetServices>()) + { + postConfigure.PostConfigure(Options.DefaultName, options); + } + + return options; + } + + // Builds the dashboard's real registrations and reads the options the resolved provider was + // constructed with — the end-to-end proof that the pin reaches the shared library. + private static SharedLdapOptions ResolveEffectiveSharedOptions(Dictionary extra) + { + Dictionary values = new() + { + ["MxGateway:Ldap:Server"] = "glauth.test", + ["MxGateway:Ldap:Port"] = "636", + ["MxGateway:Ldap:Transport"] = "Ldaps", + ["MxGateway:Ldap:AllowInsecure"] = "false", + ["MxGateway:Ldap:SearchBase"] = "dc=zb,dc=local", + ["MxGateway:Ldap:ServiceAccountDn"] = "cn=serviceaccount,dc=zb,dc=local", + ["MxGateway:Ldap:ServiceAccountPassword"] = "test-bind-password", + }; + foreach ((string key, string? value) in extra) + { + values[key] = value; + } + + IConfigurationRoot configuration = new ConfigurationBuilder().AddInMemoryCollection(values).Build(); + ServiceCollection services = new(); + services.AddLogging(); + services.AddGatewayDashboard(configuration); + using ServiceProvider provider = services.BuildServiceProvider(); + + ILdapAuthService service = provider.GetRequiredService(); + LdapAuthService concrete = Assert.IsType(service); + FieldInfo field = typeof(LdapAuthService).GetField("_options", BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("LdapAuthService._options not found — shared lib internals changed."); + return Assert.IsType(field.GetValue(concrete)); + } +}