Files
SGU-CredentialProvider/src/SGU.CredentialProvider/SguCredentialTile.cs
T

186 lines
6.2 KiB
C#

using System.Runtime.InteropServices;
using System.Security;
using Lithnet.CredentialProvider;
using SGU.AuthBroker.Core.Identity;
namespace SGU.CredentialProvider;
// LogonUI can only preserve the alpha channel of the provider logo when the
// credential exposes ICredentialProviderCredential3. CredentialTile2 returns
// an HBITMAP, which composites transparent pixels against #464646 and produces
// a visible grey square around the circular SGU mark.
internal sealed class SguCredentialTile : CredentialTile3
{
private TextboxControl userNameControl = null!;
private SecurePasswordTextboxControl passwordControl = null!;
public SguCredentialTile(CredentialProviderBase credentialProvider)
: base(credentialProvider)
{
GenericTileDisplayMode = GenericTileDisplayMode.DisplayAsDedicatedTile;
}
public SguCredentialTile(CredentialProviderBase credentialProvider, CredentialProviderUser user)
: base(credentialProvider, user)
{
}
public override void Initialize()
{
userNameControl = Controls.GetControl<TextboxControl>(ControlKeys.UserName);
passwordControl = Controls.GetControl<SecurePasswordTextboxControl>(ControlKeys.Password);
userNameControl.Text = User?.QualifiedUserName ?? string.Empty;
}
protected override CredentialResponseBase GetCredentials()
{
ProviderSettings settings = TryLoadDomainOnlySettings();
if (!TryGetWindowsLogonName(
userNameControl.Text,
settings.DomainNetbios,
out string domain,
out string userName))
{
return Failure("Escribe un usuario válido.");
}
SecureString securePassword = passwordControl.Password;
if (securePassword.Length == 0)
{
return Failure("La contraseña es requerida.");
}
// Ordinary Active Directory accounts go straight to Windows. Only an
// institutional key needs SGU validation and the account UPSERT.
if (!UserIdentityClassifier.TryParse(userNameControl.Text, out UserIdentity? identity) || identity is null)
{
return DomainCredential(domain, userName, securePassword);
}
string plainTextPassword = CopyToManagedString(securePassword);
try
{
BrokerDecision decision;
try
{
settings = ProviderSettings.Load();
using BrokerClient broker = new(settings);
decision = broker
.AuthenticateAsync(identity.UserName, plainTextPassword, CancellationToken.None)
.GetAwaiter()
.GetResult();
}
catch
{
decision = BrokerDecision.Unavailable("LOCAL_CONFIGURATION_OR_TLS_ERROR");
}
if (decision.Kind == BrokerDecisionKind.Authorized)
{
return DomainCredential(decision.Domain!, decision.UserName!, securePassword);
}
// An SGU rejection does not create an account. Pass the unchanged
// credential to Windows so an existing AD account with the same
// name can still authenticate. A non-existent account is rejected
// by the domain controller.
return DomainCredential(
domain,
userName,
securePassword,
decision.Kind == BrokerDecisionKind.Unavailable
? "El servicio SGU no está disponible; Windows validará la contraseña guardada en el dominio."
: null);
}
finally
{
// The immutable managed string cannot be zeroed; release our reference immediately.
// The unmanaged copy used to create it is zeroed by CopyToManagedString.
plainTextPassword = string.Empty;
}
}
private static ProviderSettings TryLoadDomainOnlySettings()
{
try
{
return ProviderSettings.Load();
}
catch
{
// LCI is the configured lab domain. This fallback still delegates the actual
// password decision to Windows LSA/cached domain credentials.
return new ProviderSettings { DomainNetbios = "LCI" };
}
}
private static bool TryGetWindowsLogonName(
string? enteredName,
string defaultDomain,
out string domain,
out string userName)
{
domain = string.Empty;
userName = enteredName?.Trim() ?? string.Empty;
if (userName.Length is 0 or > 256 || userName.Any(char.IsControl))
{
return false;
}
int slash = userName.LastIndexOf('\\');
if (slash >= 0)
{
domain = userName[..slash];
userName = userName[(slash + 1)..];
if (domain.Length is 0 or > 256 || domain.Contains('\\') || userName.Length == 0)
{
return false;
}
}
else if (!userName.Contains('@'))
{
domain = defaultDomain;
}
return userName.Length > 0 && domain.Length <= 256 && !domain.Any(char.IsControl);
}
private static CredentialResponseSecure DomainCredential(
string domain,
string userName,
SecureString password,
string? statusText = null) => new()
{
IsSuccess = true,
StatusIcon = statusText is null ? StatusIcon.None : StatusIcon.Warning,
StatusText = statusText,
Domain = domain,
Username = userName,
Password = password
};
private static CredentialResponseSecure Failure(string message) => new()
{
IsSuccess = false,
StatusIcon = StatusIcon.Error,
StatusText = message
};
private static string CopyToManagedString(SecureString value)
{
IntPtr pointer = IntPtr.Zero;
try
{
pointer = Marshal.SecureStringToGlobalAllocUnicode(value);
return Marshal.PtrToStringUni(pointer, value.Length) ?? string.Empty;
}
finally
{
if (pointer != IntPtr.Zero)
{
Marshal.ZeroFreeGlobalAllocUnicode(pointer);
}
}
}
}