Compare commits

..
4 Commits
16 changed files with 385 additions and 77 deletions

No files matched your search

+17 -10
View File
@@ -13,20 +13,27 @@ Ready-to-run bootstrap packages are published on the
## Authentication contract ## Authentication contract
1. The Windows tile collects a `DO`, `AL`, or `AD` institutional key and a password. 1. Windows selects **Acceso Institucional** by default. The built-in
2. It sends that exact password over mutually authenticated TLS to the broker. Microsoft password provider stays available for recovery.
3. The broker validates the same key/password pair against the lightweight SGU 2. Ordinary domain usernames go straight to Windows for Active Directory
NTLM root. Only an authoritative `401`/`403` rejects the credential. authentication. A `DO`, `AL`, or `AD` key is checked against SGU first.
4. After successful authentication, the broker makes a separately bounded, 3. The tile sends recognized institutional keys and their exact passwords over
best-effort request for the minimum available SGU profile fields. mutually authenticated TLS. After SGU accepts the credential, the broker
5. On success, the broker creates or moves the AD user, updates the available performs an idempotent Active Directory UPSERT: it creates or repairs the
name/mail/title/department/address metadata when available, and sets the AD password account, role OU and group, supported profile fields, and AD password.
to the exact submitted password. 4. If SGU rejects the key or is unavailable, the unchanged credentials go to
6. The Credential Provider serializes the original `SecureString` to Windows. Windows. Existing AD accounts can authenticate there; unknown or misspelled
accounts are rejected by Windows and are never created.
No derived password is created. Passwords are not written to a database, file, No derived password is created. Passwords are not written to a database, file,
event log, application log, command line, or response. event log, application log, command line, or response.
This makes Active Directory the only Windows sign-in account while preserving
automatic synchronization: if a person changes their institutional password,
the next successful Acceso Institucional sign-in updates the domain password
before Windows continues. A matching prefix alone never creates an account;
the institutional authority must first accept the submitted password.
For administrative accounts, profile enrichment first verifies the employee For administrative accounts, profile enrichment first verifies the employee
number against the incident overview, then reads the structured given names and number against the incident overview, then reads the structured given names and
surnames from `datos/personales.aspx` and the postal address from surnames from `datos/personales.aspx` and the postal address from
+19 -9
View File
@@ -52,15 +52,24 @@ Broker timeout, TLS failure, 429, or 5xx
-> only the last AD password succeeds -> only the last AD password succeeds
``` ```
An explicit `400` or `401` from the broker is different: the provider displays An explicit `400` or `401` from SGU does not create or update an account. The
an error and does not serialize the rejected credential. tile submits the unchanged credentials to Windows, which accepts them only if
they match an existing Active Directory account.
## Account synchronization ## Account synchronization
The broker normalizes the username to uppercase and accepts exactly two letters The visible Windows experience is one **Acceso Institucional** sign-in tile,
plus six digits. It searches `BaseDn` by `sAMAccountName`, creates the user when selected by default, with `Usuario` and `Contraseña`. Ordinary usernames go
absent, moves it to the mapped OU when required, sets `userPrincipalName`, and straight to Windows for domain authentication. A `DO`, `AL`, or `AD` key is
passes the submitted password directly to ADSI `SetPassword`. checked by the broker against SGU. After SGU accepts the submitted password,
the broker searches `BaseDn` by `sAMAccountName`, creates the user when absent,
moves it to the mapped OU when required, sets `userPrincipalName`, and passes
that same password directly to ADSI `SetPassword`. This is an idempotent UPSERT
performed on every successful sign-in, so the next sign-in after an institutional
password change updates AD before Windows validates the interactive logon. If
SGU rejects the credential or is unavailable, the unchanged credentials go to
Windows; only an existing AD account can then authenticate. A matching username
pattern alone never provisions an account.
Before an account becomes usable, the broker applies explicit deny ACEs for the Before an account becomes usable, the broker applies explicit deny ACEs for the
Active Directory `Change Password` extended right to SELF and Everyone. Users Active Directory `Change Password` extended right to SELF and Everyone. Users
@@ -125,9 +134,10 @@ Windows client maps the group into its local **Remote Desktop Users** group.
Every synchronized user also receives `La Salle` in the AD Every synchronized user also receives `La Salle` in the AD
`company` attribute unless deployment configuration supplies another default. `company` attribute unless deployment configuration supplies another default.
The generic SGU credential is rendered as a dedicated branded tile instead of The generic Acceso Institucional credential is rendered as a dedicated
being grouped below the anonymous **Other user** tile. Machine policy assigns branded tile instead of being grouped below the anonymous **Other user** tile.
the SGU CLSID as the default provider, hides the last signed-in identity, and Machine policy assigns
the provider CLSID as the default provider, hides the last signed-in identity, and
disables local-user enumeration while retaining the built-in Microsoft password disables local-user enumeration while retaining the built-in Microsoft password
provider and its **Other user** recovery path. The computer GPO also applies provider and its **Other user** recovery path. The computer GPO also applies
Windows' native default account picture to named Windows accounts; client Windows' native default account picture to named Windows accounts; client
+6 -3
View File
@@ -232,12 +232,15 @@ administradores.
El proveedor usa un mosaico genérico dedicado, no una credencial asociada al SID El proveedor usa un mosaico genérico dedicado, no una credencial asociada al SID
anónimo de **Other user**. Windows muestra la imagen institucional y la etiqueta anónimo de **Other user**. Windows muestra la imagen institucional y la etiqueta
`La Salle · Acceso SGU`; el encabezado `Acceso institucional SGU` `Acceso Institucional`; el encabezado `Iniciar sesión` se publica como
se publica como `CPFT_LARGE_TEXT` solamente en el mosaico seleccionado. LogonUI `CPFT_LARGE_TEXT` solamente en el mosaico seleccionado. El instalador selecciona
ese proveedor por defecto. Los usuarios de dominio se validan contra Active
Directory; las claves institucionales aceptadas por SGU hacen el UPSERT en AD
desde ese mismo mosaico. LogonUI
elige la familia, el peso y el tamaño final y no expone opciones de tipografía a elige la familia, el peso y el tamaño final y no expone opciones de tipografía a
un Credential Provider. un Credential Provider.
La configuración soportada garantiza que SGU queda seleccionado por defecto y La configuración soportada garantiza que Acceso Institucional queda seleccionado por defecto y
que no se conserva el último usuario. El orden vertical exacto de mosaicos lo que no se conserva el último usuario. El orden vertical exacto de mosaicos lo
decide LogonUI y no tiene una directiva pública. Por seguridad no se filtra ni decide LogonUI y no tiene una directiva pública. Por seguridad no se filtra ni
se elimina **Other user**: Microsoft recomienda conservar al menos un proveedor se elimina **Other user**: Microsoft recomienda conservar al menos un proveedor
+1 -1
View File
@@ -136,7 +136,7 @@ On Windows 10:
``` ```
Use Lithnet's `Invoke-CredUI` test utility when available, or sign out/restart Use Lithnet's `Invoke-CredUI` test utility when available, or sign out/restart
the VM and select **Acceso institucional SGU**. Keep the built-in Windows the VM and select **Acceso Institucional**. Keep the built-in Windows
password provider available through **Other user**. password provider available through **Other user**.
On the domain controller, apply the SGU user and computer policies once: On the domain controller, apply the SGU user and computer policies once:
+15
View File
@@ -0,0 +1,15 @@
# SGU Credential Provider 0.6.13
La pantalla de inicio de sesión ahora presenta una sola credencial visible:
**La Salle**, con los campos `Usuario` y `Contraseña`. Ya no muestra el texto
“Acceso Institucional SGU”.
La autenticación institucional permanece dentro del broker, sin una segunda
captura. Después de cada autenticación válida, el broker ejecuta su UPSERT de
Active Directory: crea o repara la cuenta, la OU, el grupo, los datos de perfil
disponibles y la contraseña de AD. Así, la siguiente sesión después de cambiar
una contraseña institucional sincroniza esa contraseña con el dominio.
El patrón `DO`, `AL` o `AD` con seis dígitos continúa siendo sólo un formato de
usuario. No autoriza ni crea cuentas por sí mismo: la autoridad institucional
debe validar la contraseña antes de que el UPSERT haga cambios en AD.
+18
View File
@@ -0,0 +1,18 @@
# SGU Credential Provider 0.6.14
El mosaico predeterminado se llama **Acceso Institucional**. En él se pueden
usar tanto cuentas existentes de Active Directory como claves institucionales
DO, AL y AD:
- Los usuarios de dominio que no son claves institucionales se envían
directamente a Windows para validación por Active Directory.
- Las claves institucionales se validan primero contra SGU. Si SGU las acepta,
el broker enriquece o actualiza la cuenta y sincroniza la contraseña con AD.
- Si SGU rechaza la clave o no está disponible, Windows valida la credencial
existente contra AD o las credenciales de dominio guardadas en caché. Una
cuenta inexistente no se crea sin una validación SGU correcta.
- El instalador y la GPO seleccionan **Acceso Institucional** como predeterminado
y conservan el proveedor de contraseña de Microsoft para recuperación.
El mosaico recopila el usuario y la contraseña una sola vez. La contraseña no
se deriva ni se guarda en un archivo, base de datos o registro.
+8 -6
View File
@@ -87,13 +87,15 @@ Use an enterprise CA with revocation checking in production.
## Recovery and availability ## Recovery and availability
The provider distinguishes an authoritative rejection from unavailable The provider distinguishes an SGU rejection from unavailable infrastructure:
infrastructure:
- `400`/`401`: fail closed and show an error. - `400`/`401`: do not create or update the account; submit the unchanged
- timeout, TLS/connectivity error, `429`, or `5xx`: submit the unchanged credential credential to Windows so an existing AD account can authenticate.
to Windows. Windows must still validate it against AD or the cached domain - timeout, TLS/connectivity error, `429`, or `5xx`: submit the unchanged
verifier, so this does not grant access without the last synchronized password. credential to Windows. Windows must still validate it against AD or its cached
domain verifier, so this does not grant access without a domain credential.
- usernames that do not match the institutional key format go directly to
Windows and are never sent to SGU or provisioned by the broker.
Redis is deliberately not used for password continuity. A second persistent Redis is deliberately not used for password continuity. A second persistent
password verifier duplicates attackable credential material, while a reversible password verifier duplicates attackable credential material, while a reversible
+3 -2
View File
@@ -97,8 +97,9 @@ usuario que cerró sesión y deshabilita la enumeración de usuarios locales en
equipo unido al dominio. No modifica ni oculta el proveedor de contraseña de equipo unido al dominio. No modifica ni oculta el proveedor de contraseña de
Microsoft; **Other user** permanece como ruta de recuperación. Microsoft; **Other user** permanece como ruta de recuperación.
Cerrar sesión o reiniciar el equipo. El acceso SGU debe quedar seleccionado por Cerrar sesión o reiniciar el equipo. **Acceso Institucional** debe quedar
defecto y el proveedor de contraseña de Microsoft debe permanecer disponible. seleccionado por defecto; el proveedor nativo de Microsoft permanece disponible
para recuperación.
## 5. Verificación ## 5. Verificación
+2 -5
View File
@@ -300,10 +300,7 @@ if ($PSCmdlet.ShouldProcess($installPath, 'Install and register the SGU Credenti
New-ItemProperty -Path $classRegistryPath -Name ThreadingModel -Value Both -PropertyType String -Force | Out-Null New-ItemProperty -Path $classRegistryPath -Name ThreadingModel -Value Both -PropertyType String -Force | Out-Null
New-Item -Path $providerRegistryPath -Force | Out-Null New-Item -Path $providerRegistryPath -Force | Out-Null
# Windows PowerShell 5.1 interprets an UTF-8 script without a BOM using the Set-Item -Path $providerRegistryPath -Value 'Acceso Institucional'
# current ANSI code page. Construct the middle dot from its Unicode value so
# the LogonUI registry label remains correct on every client locale.
Set-Item -Path $providerRegistryPath -Value ('La Salle {0} Acceso SGU' -f [char]0x00B7)
if (-not $DoNotSetAsDefaultCredentialProvider) { if (-not $DoNotSetAsDefaultCredentialProvider) {
if (-not (Test-Path -LiteralPath $defaultProviderPolicyPath)) { if (-not (Test-Path -LiteralPath $defaultProviderPolicyPath)) {
@@ -316,7 +313,7 @@ if ($PSCmdlet.ShouldProcess($installPath, 'Install and register the SGU Credenti
-Force | Out-Null -Force | Out-Null
} }
# Do not leave a signed-out SGU identity exposed as a persistent user tile. # Do not leave a signed-out domain identity exposed as a persistent user tile.
# The Microsoft password provider remains registered and supplies Other user. # The Microsoft password provider remains registered and supplies Other user.
if (-not (Test-Path -LiteralPath $interactiveLogonPolicyPath)) { if (-not (Test-Path -LiteralPath $interactiveLogonPolicyPath)) {
New-Item -Path $interactiveLogonPolicyPath -Force | Out-Null New-Item -Path $interactiveLogonPolicyPath -Force | Out-Null
@@ -0,0 +1,174 @@
[CmdletBinding(SupportsShouldProcess)]
param(
[string]$Version = '0.6.15',
[ValidatePattern('^https://')]
[string]$ClientPackageUri = 'https://gitea.lci.ulsa.mx/alexrg/SGU-CredentialProvider/releases/download/v0.6.15/sgu-windows-client-bootstrap-0.6.15.zip',
[ValidatePattern('^[0-9A-Fa-f]{64}$')]
[string]$ClientPackageSha256 = 'A5684FD1C196672F005517EB8E21D345BB0707091B59E203627995FF88001A11',
[string]$GpoName = 'SGU - Credential Provider update',
[string]$DomainController = $env:COMPUTERNAME
)
$ErrorActionPreference = 'Stop'
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]::new($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw 'Run this script from an elevated Windows PowerShell session on a domain controller or management host.'
}
Import-Module ActiveDirectory -ErrorAction Stop
Import-Module GroupPolicy -ErrorAction Stop
$domain = Get-ADDomain -Server $DomainController -ErrorAction Stop
$domainDnsRoot = $domain.DNSRoot
$domainDn = $domain.DistinguishedName
$gpo = Get-GPO -Name $GpoName -Domain $domainDnsRoot -Server $DomainController -ErrorAction SilentlyContinue
if (-not $gpo -and $PSCmdlet.ShouldProcess($GpoName, 'Create computer startup update policy')) {
$gpo = New-GPO -Name $GpoName -Domain $domainDnsRoot -Server $DomainController
}
if (-not $gpo) {
throw "The GPO '$GpoName' does not exist and was not created."
}
$existingLink = @(Get-GPInheritance -Target $domainDn -Domain $domainDnsRoot -Server $DomainController).GpoLinks |
Where-Object DisplayName -eq $GpoName |
Select-Object -First 1
if (-not $existingLink -and
$PSCmdlet.ShouldProcess($domainDn, "Link and enable '$GpoName'")) {
New-GPLink -Name $GpoName -Target $domainDn -Domain $domainDnsRoot -Server $DomainController -LinkEnabled Yes | Out-Null
}
elseif ($existingLink -and
$existingLink.Enabled -notin @($true, 'Yes') -and
$PSCmdlet.ShouldProcess($domainDn, "Enable '$GpoName'")) {
Set-GPLink -Name $GpoName -Target $domainDn -Domain $domainDnsRoot -Server $DomainController -LinkEnabled Yes | Out-Null
}
$systemPolicyKey = 'HKLM\Software\Policies\Microsoft\Windows\System'
$winlogonPolicyKey = 'HKLM\Software\Policies\Microsoft\Windows NT\CurrentVersion\Winlogon'
if ($PSCmdlet.ShouldProcess($GpoName, 'Make the computer startup script synchronous')) {
Set-GPRegistryValue -Name $GpoName -Domain $domainDnsRoot -Server $DomainController `
-Key $systemPolicyKey -ValueName 'RunStartupScriptSync' -Type DWord -Value 1
Set-GPRegistryValue -Name $GpoName -Domain $domainDnsRoot -Server $DomainController `
-Key $winlogonPolicyKey -ValueName 'SyncForegroundPolicy' -Type DWord -Value 1
}
$scriptName = "Update-SguCredentialProvider-$Version.ps1"
$gpoScriptsPath = Join-Path $env:WINDIR "SYSVOL\domain\Policies\{$($gpo.Id)}\Machine\Scripts"
$startupPath = Join-Path $gpoScriptsPath 'Startup'
$powershellScriptsIniPath = Join-Path $gpoScriptsPath 'psscripts.ini'
$scriptPath = Join-Path $startupPath $scriptName
$startupScript = @"
`$ErrorActionPreference = 'Stop'
`$version = '$Version'
`$packageUri = '$ClientPackageUri'
`$expectedSha256 = '$($ClientPackageSha256.ToUpperInvariant())'
`$computerSystem = Get-CimInstance Win32_ComputerSystem
if (-not `$computerSystem.PartOfDomain -or `$computerSystem.DomainRole -ge 4) {
exit 0
}
`$updateRoot = Join-Path `$env:ProgramData "SGU\CredentialProviderUpdates\`$version"
`$markerPath = Join-Path `$updateRoot 'complete.marker'
if (Test-Path -LiteralPath `$markerPath -PathType Leaf) {
exit 0
}
New-Item -ItemType Directory -Path `$updateRoot -Force | Out-Null
`$archivePath = Join-Path `$updateRoot 'client-bootstrap.zip'
`$stagePath = Join-Path `$updateRoot 'package'
if ((Test-Path -LiteralPath `$archivePath -PathType Leaf) -and
(Get-FileHash -LiteralPath `$archivePath -Algorithm SHA256).Hash -ne `$expectedSha256) {
Remove-Item -LiteralPath `$archivePath -Force
}
if (-not (Test-Path -LiteralPath `$archivePath -PathType Leaf)) {
Invoke-WebRequest -Uri `$packageUri -OutFile `$archivePath -UseBasicParsing -TimeoutSec 600
}
if ((Get-FileHash -LiteralPath `$archivePath -Algorithm SHA256).Hash -ne `$expectedSha256) {
throw 'The SGU Credential Provider update package did not match its expected SHA-256.'
}
`$installScript = Join-Path `$stagePath 'payload\scripts\Install-CredentialProvider.ps1'
if (-not (Test-Path -LiteralPath `$installScript -PathType Leaf)) {
if (Test-Path -LiteralPath `$stagePath -PathType Container) {
Remove-Item -LiteralPath `$stagePath -Recurse -Force
}
Expand-Archive -LiteralPath `$archivePath -DestinationPath `$stagePath -Force
}
if (-not (Test-Path -LiteralPath `$installScript -PathType Leaf)) {
throw 'The verified update package did not contain Install-CredentialProvider.ps1.'
}
`$settingsPath = Join-Path `$env:ProgramData 'SGU\CredentialProvider\settings.json'
`$settings = Get-Content -LiteralPath `$settingsPath -Raw | ConvertFrom-Json
`$installParameters = @{
PublishPath = (Join-Path `$stagePath 'payload\credential-provider')
BrokerEndpoint = [string]`$settings.BrokerEndpoint
ClientCertificateThumbprint = [string]`$settings.ClientCertificateThumbprint
ServerCertificateThumbprint = [string]`$settings.ServerCertificateThumbprint
DomainNetbios = [string]`$settings.DomainNetbios
TimeoutSeconds = [int]`$settings.TimeoutSeconds
}
`$dotnet = Get-Command dotnet -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source -ErrorAction SilentlyContinue
`$runtimeInstalled = `$dotnet -and (& `$dotnet --list-runtimes | Select-String '^Microsoft\.NETCore\.App 10\.')
if (-not `$runtimeInstalled) {
`$runtimeInstaller = Get-ChildItem -LiteralPath (Join-Path `$stagePath 'payload\prerequisites') -Filter '*x64*.exe' -File |
Select-Object -First 1
if (-not `$runtimeInstaller) {
throw 'The update package does not contain the required .NET x64 runtime installer.'
}
`$installParameters.InstallDotNetRuntime = `$true
`$installParameters.DotNetRuntimeInstallerPath = `$runtimeInstaller.FullName
}
& `$installScript @installParameters | Out-Null
[IO.File]::WriteAllText(`$markerPath, (Get-Date).ToUniversalTime().ToString('o'), [Text.UTF8Encoding]::new(`$false))
"@
if ($PSCmdlet.ShouldProcess($startupPath, "Install '$scriptName' as a computer startup script")) {
New-Item -ItemType Directory -Path $startupPath -Force | Out-Null
[IO.File]::WriteAllText($scriptPath, $startupScript, [Text.UTF8Encoding]::new($false))
$scriptsIni = "[Startup]`r`n0CmdLine=$scriptName`r`n0Parameters=`r`n"
# Windows' Scripts CSE requires UTF-16LE with a BOM for psscripts.ini.
[IO.File]::WriteAllText($powershellScriptsIniPath, $scriptsIni, [Text.Encoding]::Unicode)
# Writing SYSVOL directly does not register the Scripts CSE in the GPO's
# Active Directory object. Without it, gpresult lists the GPO but the
# client never executes its startup script.
$gpoDn = "CN={$($gpo.Id)},CN=Policies,CN=System,$domainDn"
$gpoObject = Get-ADObject -Identity $gpoDn -Server $DomainController `
-Properties gPCMachineExtensionNames,versionNumber
$scriptExtension = '[{42B5FAAE-6536-11D2-AE5A-0000F87571E3}{40B6664F-4972-11D1-A7CA-0000F87571E3}]'
$extensionNames = [string]$gpoObject.gPCMachineExtensionNames
if ($extensionNames.IndexOf($scriptExtension, [StringComparison]::OrdinalIgnoreCase) -lt 0) {
Set-ADObject -Identity $gpoDn -Server $DomainController `
-Replace @{gPCMachineExtensionNames = "$extensionNames$scriptExtension"}
}
# Keep the AD and SYSVOL computer versions synchronized and force clients
# to process this corrected script registration on their next refresh.
$gptIniPath = Join-Path (Split-Path (Split-Path $gpoScriptsPath -Parent) -Parent) 'GPT.ini'
$gptIni = Get-Content -LiteralPath $gptIniPath -Raw
$gptVersion = [int]([regex]::Match($gptIni, '(?m)^Version=(\d+)\r?$').Groups[1].Value)
$adVersion = [int]$gpoObject.versionNumber
$baseVersion = [Math]::Max($gptVersion, $adVersion)
$nextVersion = ($baseVersion -band -65536) -bor (($baseVersion + 1) -band 65535)
$updatedGptIni = [regex]::Replace($gptIni, '(?m)^Version=\d+\r?$', "Version=$nextVersion")
[IO.File]::WriteAllText($gptIniPath, $updatedGptIni, [Text.Encoding]::ASCII)
Set-ADObject -Identity $gpoDn -Server $DomainController -Replace @{versionNumber = $nextVersion}
}
[pscustomobject]@{
GpoName = $gpo.DisplayName
GpoId = $gpo.Id
LinkedTarget = $domainDn
StartupScript = $scriptPath
Version = $Version
PackageSha256 = $ClientPackageSha256.ToUpperInvariant()
}
+1 -1
View File
@@ -161,7 +161,7 @@ app.MapPost("/v1/authenticate", async (
AuthenticationFlowOutcome.InvalidCredentials => Results.Json( AuthenticationFlowOutcome.InvalidCredentials => Results.Json(
new ErrorResponse( new ErrorResponse(
result.ErrorCode ?? "INVALID_INSTITUTIONAL_CREDENTIALS", result.ErrorCode ?? "INVALID_INSTITUTIONAL_CREDENTIALS",
"Credenciales institucionales inválidas."), "Usuario o contraseña incorrectos."),
statusCode: StatusCodes.Status401Unauthorized), statusCode: StatusCodes.Status401Unauthorized),
_ => Unavailable(context, result.ErrorCode) _ => Unavailable(context, result.ErrorCode)
@@ -16,12 +16,12 @@ public sealed class SguCredentialProvider : CredentialProviderBase
{ {
yield return new CredentialProviderLabelControl( yield return new CredentialProviderLabelControl(
ControlKeys.ProviderLabel, ControlKeys.ProviderLabel,
"La Salle · Acceso SGU"); "Acceso Institucional");
yield return new CredentialProviderLogoControl( yield return new CredentialProviderLogoControl(
ControlKeys.ProviderLogo, ControlKeys.ProviderLogo,
"Acceso institucional SGU", "Acceso Institucional",
ProviderTileIcon.Create()); ProviderTileIcon.Create());
yield return new LargeLabelControl(ControlKeys.Heading, "Acceso institucional SGU") yield return new LargeLabelControl(ControlKeys.Heading, "Iniciar sesión")
{ {
// Isolate the CPFT_LARGE_TEXT heading from the compact provider tile // Isolate the CPFT_LARGE_TEXT heading from the compact provider tile
// for the selected-layout variant. LogonUI still owns the typography. // for the selected-layout variant. LogonUI still owns the typography.
@@ -29,8 +29,8 @@ public sealed class SguCredentialProvider : CredentialProviderBase
}; };
yield return new SmallLabelControl( yield return new SmallLabelControl(
ControlKeys.InformationLabel, ControlKeys.InformationLabel,
"Usa tu clave institucional (DO, AL o AD + 6 dígitos) y contraseña."); "Escribe tu usuario institucional o de dominio y contraseña.");
yield return new TextboxControl(ControlKeys.UserName, "Clave institucional"); yield return new TextboxControl(ControlKeys.UserName, "Usuario");
SecurePasswordTextboxControl password = new(ControlKeys.Password, "Contraseña"); SecurePasswordTextboxControl password = new(ControlKeys.Password, "Contraseña");
yield return password; yield return password;
yield return new SubmitButtonControl(ControlKeys.Submit, "Iniciar sesión", password); yield return new SubmitButtonControl(ControlKeys.Submit, "Iniciar sesión", password);
@@ -43,7 +43,12 @@ public sealed class SguCredentialProvider : CredentialProviderBase
public override bool ShouldIncludeGenericTile() => true; public override bool ShouldIncludeGenericTile() => true;
public override CredentialTile CreateGenericTile() => new SguCredentialTile(this); public override CredentialTile CreateGenericTile()
{
SguCredentialTile tile = new(this);
DefaultTile = tile;
return tile;
}
public override CredentialTile2 CreateUserTile(CredentialProviderUser user) => public override CredentialTile2 CreateUserTile(CredentialProviderUser user) =>
new SguCredentialTile(this, user); new SguCredentialTile(this, user);
+72 -24
View File
@@ -34,9 +34,14 @@ internal sealed class SguCredentialTile : CredentialTile3
protected override CredentialResponseBase GetCredentials() protected override CredentialResponseBase GetCredentials()
{ {
if (!UserIdentityClassifier.TryParse(userNameControl.Text, out UserIdentity? identity) || identity is null) ProviderSettings settings = TryLoadDomainOnlySettings();
if (!TryGetWindowsLogonName(
userNameControl.Text,
settings.DomainNetbios,
out string domain,
out string userName))
{ {
return Failure("La clave debe usar DO, AL o AD seguido de seis dígitos."); return Failure("Escribe un usuario válido.");
} }
SecureString securePassword = passwordControl.Password; SecureString securePassword = passwordControl.Password;
@@ -45,10 +50,16 @@ internal sealed class SguCredentialTile : CredentialTile3
return Failure("La contraseña es requerida."); 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); string plainTextPassword = CopyToManagedString(securePassword);
try try
{ {
ProviderSettings settings;
BrokerDecision decision; BrokerDecision decision;
try try
{ {
@@ -61,33 +72,25 @@ internal sealed class SguCredentialTile : CredentialTile3
} }
catch catch
{ {
settings = TryLoadDomainOnlySettings();
decision = BrokerDecision.Unavailable("LOCAL_CONFIGURATION_OR_TLS_ERROR"); decision = BrokerDecision.Unavailable("LOCAL_CONFIGURATION_OR_TLS_ERROR");
} }
if (decision.Kind == BrokerDecisionKind.InvalidCredentials) if (decision.Kind == BrokerDecisionKind.Authorized)
{ {
return Failure("Credenciales institucionales inválidas."); return DomainCredential(decision.Domain!, decision.UserName!, securePassword);
} }
string domain = decision.Kind == BrokerDecisionKind.Authorized // An SGU rejection does not create an account. Pass the unchanged
? decision.Domain! // credential to Windows so an existing AD account with the same
: settings.DomainNetbios; // name can still authenticate. A non-existent account is rejected
string userName = decision.Kind == BrokerDecisionKind.Authorized // by the domain controller.
? decision.UserName! return DomainCredential(
: identity.UserName; domain,
userName,
return new CredentialResponseSecure securePassword,
{ decision.Kind == BrokerDecisionKind.Unavailable
IsSuccess = true, ? "El servicio institucional no está disponible; Windows validará la contraseña guardada en el dominio."
StatusIcon = decision.Kind == BrokerDecisionKind.Unavailable ? StatusIcon.Warning : StatusIcon.None, : null);
StatusText = decision.Kind == BrokerDecisionKind.Unavailable
? "Servicio institucional no disponible; Windows validará la última contraseña de dominio registrada."
: null,
Domain = domain,
Username = userName,
Password = securePassword
};
} }
finally finally
{ {
@@ -111,6 +114,51 @@ internal sealed class SguCredentialTile : CredentialTile3
} }
} }
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() private static CredentialResponseSecure Failure(string message) => new()
{ {
IsSuccess = false, IsSuccess = false,
@@ -69,6 +69,29 @@ public sealed class AuthenticationWorkflowTests
Assert.Null(directory.Password); Assert.Null(directory.Password);
} }
[Fact]
public async Task EverySuccessfulSignInSynchronizesTheLatestPassword()
{
CapturingDirectorySynchronizer directory = new();
AuthenticationWorkflow workflow = new(
new CapturingNtlmValidator(NtlmValidationResult.Valid()),
directory);
_ = await workflow.AuthenticateAsync(
"AL123456",
"Contraseña-anterior-27!",
TestContext.Current.CancellationToken);
AuthenticationFlowResult result = await workflow.AuthenticateAsync(
"AL123456",
"Contraseña-nueva-28!",
TestContext.Current.CancellationToken);
Assert.Equal(AuthenticationFlowOutcome.Authorized, result.Outcome);
Assert.Equal(
["Contraseña-anterior-27!", "Contraseña-nueva-28!"],
directory.Passwords);
}
private sealed class CapturingNtlmValidator(NtlmValidationResult result) : INtlmCredentialValidator private sealed class CapturingNtlmValidator(NtlmValidationResult result) : INtlmCredentialValidator
{ {
public UserIdentity? Identity { get; private set; } public UserIdentity? Identity { get; private set; }
@@ -92,6 +115,8 @@ public sealed class AuthenticationWorkflowTests
public string? Password { get; private set; } public string? Password { get; private set; }
public List<string> Passwords { get; } = [];
public InstitutionalProfile? Profile { get; private set; } public InstitutionalProfile? Profile { get; private set; }
public Task<DirectorySyncResult> SynchronizeAsync( public Task<DirectorySyncResult> SynchronizeAsync(
@@ -103,6 +128,7 @@ public sealed class AuthenticationWorkflowTests
Identity = identity; Identity = identity;
Profile = profile; Profile = profile;
Password = password; Password = password;
Passwords.Add(password);
return Task.FromResult(new DirectorySyncResult( return Task.FromResult(new DirectorySyncResult(
"LCI", "LCI",
identity.UserName, identity.UserName,
@@ -14,11 +14,11 @@ internal static class Program
private static readonly string[] ExpectedLabels = private static readonly string[] ExpectedLabels =
[ [
"La Salle · Acceso SGU", "Acceso Institucional",
"Acceso institucional SGU", "Acceso Institucional",
"Acceso institucional SGU", "Iniciar sesión",
"Usa tu clave institucional (DO, AL o AD + 6 dígitos) y contraseña.", "Escribe tu usuario institucional o de dominio y contraseña.",
"Clave institucional", "Usuario",
"Contraseña", "Contraseña",
"Iniciar sesión" "Iniciar sesión"
]; ];
@@ -89,6 +89,8 @@ internal static class Program
bool passed = fieldCount == ExpectedLabels.Length && bool passed = fieldCount == ExpectedLabels.Length &&
credentialCount == 1 && credentialCount == 1 &&
defaultIndex == 0 &&
autoLogon == 0 &&
credential != IntPtr.Zero && credential != IntPtr.Zero &&
providerLogoPresent && providerLogoPresent &&
!userTilePresent && !userTilePresent &&
@@ -146,7 +148,7 @@ internal static class Program
private static int RunSerializationProbe(string mode, IntPtr credential, IReadOnlyList<string> labels) private static int RunSerializationProbe(string mode, IntPtr credential, IReadOnlyList<string> labels)
{ {
string[] labelArray = labels.ToArray(); string[] labelArray = labels.ToArray();
uint userNameFieldId = checked((uint)Array.IndexOf(labelArray, "Clave institucional")); uint userNameFieldId = checked((uint)Array.IndexOf(labelArray, "Usuario"));
uint passwordFieldId = checked((uint)Array.IndexOf(labelArray, "Contraseña")); uint passwordFieldId = checked((uint)Array.IndexOf(labelArray, "Contraseña"));
string userName = mode == "online-success" string userName = mode == "online-success"
? Environment.GetEnvironmentVariable("SGU_TEST_USERNAME") ? Environment.GetEnvironmentVariable("SGU_TEST_USERNAME")
@@ -184,7 +186,7 @@ internal static class Program
bool rejectionPassed = response == (int)SerializationResponse.NoCredentialNotFinished && bool rejectionPassed = response == (int)SerializationResponse.NoCredentialNotFinished &&
serialization.SerializationData == IntPtr.Zero && serialization.SerializationData == IntPtr.Zero &&
statusIcon == (int)StatusIcon.Error && statusIcon == (int)StatusIcon.Error &&
statusText == "Credenciales institucionales inválidas."; statusText == "Usuario o contraseña incorrectos.";
Console.WriteLine(JsonSerializer.Serialize(new Console.WriteLine(JsonSerializer.Serialize(new
{ {
passed = rejectionPassed, passed = rejectionPassed,
@@ -216,7 +218,7 @@ internal static class Program
? serializedCredentialPassed && statusIcon == (int)StatusIcon.None && string.IsNullOrEmpty(statusText) ? serializedCredentialPassed && statusIcon == (int)StatusIcon.None && string.IsNullOrEmpty(statusText)
: serializedCredentialPassed && : serializedCredentialPassed &&
statusIcon == (int)StatusIcon.Warning && statusIcon == (int)StatusIcon.Warning &&
statusText == "Servicio institucional no disponible; Windows validará la última contraseña de dominio registrada."; statusText == "El servicio de autenticación no está disponible; Windows validará la última contraseña de dominio registrada.";
Console.WriteLine(JsonSerializer.Serialize(new Console.WriteLine(JsonSerializer.Serialize(new
{ {
passed, passed,
@@ -55,8 +55,8 @@ public sealed class ProviderTileIconTests
LargeLabelControl heading = Assert.Single(controls.OfType<LargeLabelControl>()); LargeLabelControl heading = Assert.Single(controls.OfType<LargeLabelControl>());
SguCredentialTile tile = Assert.IsType<SguCredentialTile>(provider.CreateGenericTile()); SguCredentialTile tile = Assert.IsType<SguCredentialTile>(provider.CreateGenericTile());
Assert.Equal("La Salle · Acceso SGU", providerLabel.Label); Assert.Equal("Acceso Institucional", providerLabel.Label);
Assert.Equal("Acceso institucional SGU", heading.Label); Assert.Equal("Iniciar sesión", heading.Label);
Assert.Equal(FieldState.DisplayInSelectedTile, heading.State); Assert.Equal(FieldState.DisplayInSelectedTile, heading.State);
Assert.Equal(GenericTileDisplayMode.DisplayAsDedicatedTile, tile.GenericTileDisplayMode); Assert.Equal(GenericTileDisplayMode.DisplayAsDedicatedTile, tile.GenericTileDisplayMode);
Assert.IsAssignableFrom<CredentialTile3>(tile); Assert.IsAssignableFrom<CredentialTile3>(tile);