Phase 1 WP-2–10: Repositories, audit service, security & auth (LDAP, JWT, roles, policies, data protection)
- WP-2: SecurityRepository + CentralUiRepository with audit log queries - WP-3: AuditService with transactional guarantee (same SaveChangesAsync) - WP-4: Optimistic concurrency tests (deployment records vs template last-write-wins) - WP-5: Seed data (SCADA-Admins → Admin role mapping) - WP-6: LdapAuthService (direct bind, TLS enforcement, group query) - WP-7: JwtTokenService (HMAC-SHA256, 15-min refresh, 30-min idle timeout) - WP-8: RoleMapper (LDAP groups → roles with site-scoped deployment) - WP-9: Authorization policies (Admin/Design/Deployment + site scope handler) - WP-10: Shared Data Protection keys via EF Core 141 tests pass, zero warnings.
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Novell.Directory.Ldap;
|
||||
|
||||
namespace ScadaLink.Security;
|
||||
|
||||
public class LdapAuthService
|
||||
{
|
||||
private readonly SecurityOptions _options;
|
||||
private readonly ILogger<LdapAuthService> _logger;
|
||||
|
||||
public LdapAuthService(IOptions<SecurityOptions> options, ILogger<LdapAuthService> logger)
|
||||
{
|
||||
_options = options?.Value ?? throw new ArgumentNullException(nameof(options));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public async Task<LdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(username))
|
||||
return new LdapAuthResult(false, null, null, null, "Username is required.");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(password))
|
||||
return new LdapAuthResult(false, null, null, null, "Password is required.");
|
||||
|
||||
// Enforce TLS unless explicitly allowed for dev/test
|
||||
if (!_options.LdapUseTls && !_options.AllowInsecureLdap)
|
||||
{
|
||||
return new LdapAuthResult(false, null, null, null,
|
||||
"Insecure LDAP connections are not allowed. Enable TLS or set AllowInsecureLdap for dev/test.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = new LdapConnection();
|
||||
|
||||
if (_options.LdapUseTls)
|
||||
{
|
||||
connection.SecureSocketLayer = true;
|
||||
}
|
||||
|
||||
await Task.Run(() => connection.Connect(_options.LdapServer, _options.LdapPort), ct);
|
||||
|
||||
if (_options.LdapUseTls && !connection.SecureSocketLayer)
|
||||
{
|
||||
await Task.Run(() => connection.StartTls(), ct);
|
||||
}
|
||||
|
||||
// Direct bind with user credentials
|
||||
var bindDn = BuildBindDn(username);
|
||||
await Task.Run(() => connection.Bind(bindDn, password), ct);
|
||||
|
||||
// Query for user attributes and group memberships
|
||||
var displayName = username;
|
||||
var groups = new List<string>();
|
||||
|
||||
try
|
||||
{
|
||||
var searchFilter = $"(uid={EscapeLdapFilter(username)})";
|
||||
var searchResults = await Task.Run(() =>
|
||||
connection.Search(
|
||||
_options.LdapSearchBase,
|
||||
LdapConnection.ScopeSub,
|
||||
searchFilter,
|
||||
new[] { _options.LdapDisplayNameAttribute, _options.LdapGroupAttribute },
|
||||
false), ct);
|
||||
|
||||
while (searchResults.HasMore())
|
||||
{
|
||||
try
|
||||
{
|
||||
var entry = searchResults.Next();
|
||||
var dnAttr = entry.GetAttribute(_options.LdapDisplayNameAttribute);
|
||||
if (dnAttr != null)
|
||||
displayName = dnAttr.StringValue;
|
||||
|
||||
var groupAttr = entry.GetAttribute(_options.LdapGroupAttribute);
|
||||
if (groupAttr != null)
|
||||
{
|
||||
foreach (var groupDn in groupAttr.StringValueArray)
|
||||
{
|
||||
groups.Add(ExtractCn(groupDn));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
// No more results
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (LdapException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to query LDAP attributes for user {Username}; authentication succeeded but group lookup failed", username);
|
||||
// Auth succeeded even if attribute lookup failed
|
||||
}
|
||||
|
||||
connection.Disconnect();
|
||||
|
||||
return new LdapAuthResult(true, displayName, username, groups, null);
|
||||
}
|
||||
catch (LdapException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "LDAP authentication failed for user {Username}", username);
|
||||
return new LdapAuthResult(false, null, username, null, "Invalid username or password.");
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogError(ex, "Unexpected error during LDAP authentication for user {Username}", username);
|
||||
return new LdapAuthResult(false, null, username, null, "An unexpected error occurred during authentication.");
|
||||
}
|
||||
}
|
||||
|
||||
private string BuildBindDn(string username)
|
||||
{
|
||||
// If username already looks like a DN, use it as-is
|
||||
if (username.Contains('='))
|
||||
return username;
|
||||
|
||||
// Build DN from username and search base
|
||||
return string.IsNullOrWhiteSpace(_options.LdapSearchBase)
|
||||
? $"cn={username}"
|
||||
: $"cn={username},{_options.LdapSearchBase}";
|
||||
}
|
||||
|
||||
private static string EscapeLdapFilter(string input)
|
||||
{
|
||||
return input
|
||||
.Replace("\\", "\\5c")
|
||||
.Replace("*", "\\2a")
|
||||
.Replace("(", "\\28")
|
||||
.Replace(")", "\\29")
|
||||
.Replace("\0", "\\00");
|
||||
}
|
||||
|
||||
private static string ExtractCn(string dn)
|
||||
{
|
||||
// Extract CN from a DN like "cn=GroupName,dc=example,dc=com"
|
||||
if (dn.StartsWith("cn=", StringComparison.OrdinalIgnoreCase) ||
|
||||
dn.StartsWith("CN=", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var commaIndex = dn.IndexOf(',');
|
||||
return commaIndex > 3 ? dn[3..commaIndex] : dn[3..];
|
||||
}
|
||||
return dn;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user