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
This commit is contained in:
@@ -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,
|
||||
|
||||
+8
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user