feat(ldap): pin the LDAP server certificate by SHA-256 thumbprint (#180)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m26s
ci / java (push) Successful in 2m15s
ci / portable (push) Failing after 4m19s

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
This commit is contained in:
Joseph Doherty
2026-11-10 11:52:14 -05:00
parent 9c6ac0cdbc
commit 2b13564e04
12 changed files with 536 additions and 2 deletions
+1
View File
@@ -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 2>/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 <value>` (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" <value>` (the server carries `<UserSecretsId>mxaccessgw-server</UserSecretsId>`; 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. |
+9
View File
@@ -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*).
@@ -12,4 +12,5 @@ public sealed record EffectiveLdapConfiguration(
string UserNameAttribute,
string DisplayNameAttribute,
string GroupAttribute,
IReadOnlyList<string> FallbackServers);
IReadOnlyList<string> FallbackServers,
IReadOnlyList<string>? ServerCertificateThumbprintSha256 = null);
@@ -31,7 +31,8 @@ public sealed class GatewayConfigurationProvider(IOptions<GatewayOptions> 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,
@@ -26,6 +26,14 @@ public static class GatewayConfigurationServiceCollectionExtensions
services.AddValidatedOptions<GatewayOptions, GatewayOptionsValidator>(
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<GatewayOptions>(options =>
options.Ldap.ServerCertificateThumbprintSha256 = LdapServerCertificatePin.ReadConfiguredPins(
configuration.GetSection($"{GatewayOptions.SectionName}:Ldap")));
services.AddSingleton<IGatewayConfigurationProvider, GatewayConfigurationProvider>();
return services;
@@ -216,6 +216,37 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
builder.Add(
"MxGateway:Ldap:Transport must not be None (plaintext) in the Production environment; use Ldaps or StartTls.");
}
ValidateLdapCertificatePins(options, builder);
}
// mxaccessgw#180: a pin must be a SHA-256 thumbprint, and only means something over TLS.
private static void ValidateLdapCertificatePins(LdapOptions options, ValidationBuilder builder)
{
IReadOnlyList<string> 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)
@@ -83,4 +83,18 @@ public sealed class LdapOptions
/// </para>
/// </summary>
public IReadOnlyList<string> FallbackServers { get; init; } = [];
/// <summary>
/// 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
/// <see cref="ZB.MOM.WW.Auth.Abstractions.Ldap.LdapOptions"/> has no such field — the pins are
/// turned into its code-only <c>ServerCertificateValidationCallback</c> by
/// <see cref="LdapServerCertificatePin"/>.
/// <para>
/// Settable because it is filled by a post-configure step from
/// <see cref="LdapServerCertificatePin.ReadConfiguredPins"/> rather than by the binder: the
/// binder drops the comma-separated scalar form of the key silently.
/// </para>
/// </summary>
public IReadOnlyList<string> ServerCertificateThumbprintSha256 { get; set; } = [];
}
@@ -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;
/// <summary>
/// LDAP server-certificate pinning for <c>MxGateway:Ldap:ServerCertificateThumbprintSha256</c>
/// (mxaccessgw#180). Lets the dashboard bind over <c>Ldaps</c>/<c>StartTls</c> 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
/// <see cref="RemoteCertificateValidationCallback"/> handed to the shared provider through
/// <see cref="SharedLdapOptions.ServerCertificateValidationCallback"/>.
/// <para>
/// With no pin configured nothing changes — the shared options keep a <see langword="null"/>
/// callback and the LDAP client validates against the OS trust store as before. With a pin, the
/// server certificate is accepted <em>if and only if</em> 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).
/// </para>
/// </summary>
public static class LdapServerCertificatePin
{
/// <summary>The key, under <c>MxGateway:Ldap</c>, that carries the pins.</summary>
public const string ConfigurationKey = "ServerCertificateThumbprintSha256";
/// <summary>Length of a normalized pin: a SHA-256 digest is 32 bytes = 64 hex characters.</summary>
public const int NormalizedLength = 64;
private static readonly char[] EntrySeparators = [',', ';'];
/// <summary>
/// Reads the raw pin entries from the <c>MxGateway:Ldap</c> section. Accepts both a scalar
/// (<c>"AA:BB…,CC:DD…"</c>, comma- or semicolon-separated so a rotation can carry old + new) and
/// an array (<c>ServerCertificateThumbprintSha256:0</c>, <c>:1</c>, …; each element may itself be
/// separated). Read straight from configuration because the options binder silently binds a
/// scalar onto a list property as empty.
/// </summary>
/// <param name="ldapSection">The <c>MxGateway:Ldap</c> configuration section.</param>
/// <returns>The trimmed, non-empty entries, un-normalized (validation reports them verbatim).</returns>
public static IReadOnlyList<string> ReadConfiguredPins(IConfiguration ldapSection)
{
ArgumentNullException.ThrowIfNull(ldapSection);
IConfigurationSection pinSection = ldapSection.GetSection(ConfigurationKey);
var raw = new List<string>();
if (pinSection.Value is { } scalar)
{
raw.Add(scalar);
}
raw.AddRange(pinSection.GetChildren().Select(child => child.Value).OfType<string>());
return raw
.SelectMany(value => value.Split(EntrySeparators))
.Select(entry => entry.Trim())
.Where(entry => entry.Length > 0)
.ToArray();
}
/// <summary>
/// Normalizes one pin: strips colons, dashes and whitespace and upper-cases it, then requires
/// exactly <see cref="NormalizedLength"/> hex characters. So <c>openssl x509 -fingerprint -sha256</c>
/// output (<c>AB:CD:…</c>), a bare lower-case hex string and a space-separated form all match.
/// </summary>
/// <param name="pin">A raw configured entry.</param>
/// <param name="normalized">The upper-case 64-hex form when the entry is well formed.</param>
/// <returns><see langword="true"/> when the entry is a well-formed SHA-256 thumbprint.</returns>
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;
}
/// <summary>Computes the upper-case hex SHA-256 thumbprint of a certificate's DER encoding.</summary>
/// <param name="certificate">The certificate.</param>
/// <returns>The 64-character upper-case thumbprint.</returns>
public static string ComputeThumbprint(X509Certificate certificate)
{
ArgumentNullException.ThrowIfNull(certificate);
return Convert.ToHexString(SHA256.HashData(certificate.GetRawCertData()));
}
/// <summary>
/// Builds the pinning validation callback, or returns <see langword="null"/> when no pin is
/// configured (leaving the shared provider on default OS validation).
/// </summary>
/// <param name="pins">The raw configured entries.</param>
/// <returns>The callback, or <see langword="null"/> for an empty pin list.</returns>
/// <exception cref="InvalidOperationException">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".</exception>
public static RemoteCertificateValidationCallback? CreateValidationCallback(IReadOnlyList<string> pins)
{
ArgumentNullException.ThrowIfNull(pins);
if (pins.Count == 0)
{
return null;
}
var accepted = new HashSet<string>(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));
}
/// <summary>
/// Returns the shared provider's options with the pinning callback applied, or the options
/// unchanged when no pin is configured.
/// </summary>
/// <param name="options">The shared options as bound from <c>MxGateway:Ldap</c>.</param>
/// <param name="ldapSection">The <c>MxGateway:Ldap</c> configuration section.</param>
/// <returns>The effective shared options.</returns>
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 };
}
}
@@ -42,6 +42,19 @@ else
</td>
</tr>
<tr><th scope="row">LDAP transport</th><td>@Snapshot.Configuration.Ldap.Transport</td></tr>
<tr>
<th scope="row">LDAP certificate pins (SHA-256)</th>
<td>
@if (Snapshot.Configuration.Ldap.ServerCertificateThumbprintSha256 is not { Count: > 0 } pins)
{
<span class="text-muted">none (OS trust store)</span>
}
else
{
<code>@string.Join(", ", pins)</code>
}
</td>
</tr>
<tr><th scope="row">LDAP search base</th><td><code>@Snapshot.Configuration.Ldap.SearchBase</code></td></tr>
<tr><th scope="row">LDAP service account</th><td><code>@Snapshot.Configuration.Ldap.ServiceAccountDn</code></td></tr>
<tr><th scope="row">LDAP service password</th><td>@Snapshot.Configuration.Ldap.ServiceAccountPassword</td></tr>
@@ -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<ILdapAuthService>(sp =>
new LdapAuthService(
LdapServerCertificatePin.Apply(
sp.GetRequiredService<IOptions<SharedLdapOptions>>().Value,
configuration.GetSection("MxGateway:Ldap")),
sp.GetService<ILogger<LdapAuthService>>())));
services.AddSingleton<IDashboardSnapshotService, DashboardSnapshotService>();
services.AddSingleton<IDashboardSnapshotFeed, DashboardSnapshotFeed>();
services.AddSingleton<IDashboardLiveDataService, DashboardLiveDataService>();
@@ -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"));
}
}
@@ -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;
/// <summary>LDAP server-certificate pinning (mxaccessgw#180).</summary>
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<InvalidOperationException>(() => 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<string, string?> 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<string, string?> 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<GatewayOptions> configure in provider.GetServices<IConfigureOptions<GatewayOptions>>())
{
configure.Configure(options);
}
foreach (IPostConfigureOptions<GatewayOptions> postConfigure in provider.GetServices<IPostConfigureOptions<GatewayOptions>>())
{
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<string, string?> extra)
{
Dictionary<string, string?> 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<ILdapAuthService>();
LdapAuthService concrete = Assert.IsType<LdapAuthService>(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<SharedLdapOptions>(field.GetValue(concrete));
}
}