Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use RBAC support from DirectoryServices.Protocols for Role claim resolution on Linux for Negotiate #25075

Merged
merged 19 commits into from
Aug 25, 2020
Merged
1 change: 1 addition & 0 deletions eng/Dependencies.props
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ and are generated based on the last package release.
<LatestPackageReference Include="System.ComponentModel.Annotations" />
<LatestPackageReference Include="System.Diagnostics.DiagnosticSource" />
<LatestPackageReference Include="System.Diagnostics.EventLog" />
<LatestPackageReference Include="System.DirectoryServices.Protocols" />
<LatestPackageReference Include="System.Drawing.Common" />
<LatestPackageReference Include="System.IO.Pipelines" />
<LatestPackageReference Include="System.Net.Http" />
Expand Down
4 changes: 4 additions & 0 deletions eng/Version.Details.xml
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,10 @@
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>0862d48a9c9fbda879206b194a16d8e607deac42</Sha>
</Dependency>
<Dependency Name="System.DirectoryServices.Protocols" Version="5.0.0-rc.1.20416.7">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>0862d48a9c9fbda879206b194a16d8e607deac42</Sha>
</Dependency>
<Dependency Name="System.Drawing.Common" Version="5.0.0-rc.1.20416.7">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>0862d48a9c9fbda879206b194a16d8e607deac42</Sha>
Expand Down
1 change: 1 addition & 0 deletions eng/Versions.props
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
<SystemComponentModelAnnotationsPackageVersion>5.0.0-rc.1.20416.7</SystemComponentModelAnnotationsPackageVersion>
<SystemDiagnosticsDiagnosticSourcePackageVersion>5.0.0-rc.1.20416.7</SystemDiagnosticsDiagnosticSourcePackageVersion>
<SystemDiagnosticsEventLogPackageVersion>5.0.0-rc.1.20416.7</SystemDiagnosticsEventLogPackageVersion>
<SystemDirectoryServicesProtocolsPackageVersion>5.0.0-rc.1.20416.7</SystemDirectoryServicesProtocolsPackageVersion>
<SystemDrawingCommonPackageVersion>5.0.0-rc.1.20416.7</SystemDrawingCommonPackageVersion>
<SystemIOPipelinesPackageVersion>5.0.0-rc.1.20416.7</SystemIOPipelinesPackageVersion>
<SystemNetHttpJsonPackageVersion>5.0.0-rc.1.20416.7</SystemNetHttpJsonPackageVersion>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Negotiate;
using Microsoft.AspNetCore.Builder;
Expand All @@ -22,6 +23,17 @@ public void ConfigureServices(IServiceCollection services)
services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate(options =>
{
/*
var ldapOptions = options.LdapOptions;
// Mandatory settings
ldapOptions.EnableLdapRoleClaimResolution = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
ldapOptions.Domain = "DOMAIN.com";
// Optional settings
ldapOptions.MachineAccountName = "machineName";
ldapOptions.MachineAccountPassword = "PassW0rd";
ldapOptions.ResolveNestedGroups = true;
*/

options.Events = new NegotiateEvents()
{
OnAuthenticationFailed = context =>
Expand Down
104 changes: 104 additions & 0 deletions src/Security/Authentication/Negotiate/src/Internal/LdapAdapter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.DirectoryServices.Protocols;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Authentication.Negotiate
{
internal static class LdapAdapter
{
public static async Task RetrieveClaimsAsync(LdapOptions options, AuthenticatedContext context, ILogger logger)
{
if (!options.EnableLdapRoleClaimResolution)
{
return;
}

var user = context.Principal.Identity.Name;
var userAccountName = user.Substring(0, user.IndexOf('@'));
var distinguishedName = options.Domain.Split('.').Select(name => $"dc={name}").Aggregate((a, b) => $"{a},{b}");

var filter = $"(&(objectClass=user)(sAMAccountName={userAccountName}))"; // This is using ldap search query language, it is looking on the server for someUser
var searchRequest = new SearchRequest(distinguishedName, filter, SearchScope.Subtree, null);
var searchResponse = (SearchResponse) await Task<DirectoryResponse>.Factory.FromAsync(
options.LdapConnection.BeginSendRequest,
options.LdapConnection.EndSendRequest,
searchRequest,
PartialResultProcessing.NoPartialResultSupport,
null);

if (searchResponse.Entries.Count > 0)
{
if (searchResponse.Entries.Count > 1)
{
logger.LogWarning($"More than one response received for query: {filter} with distinguished name: {distinguishedName}");
}

var userFound = searchResponse.Entries[0]; //Get the object that was found on ldap
var memberof = userFound.Attributes["memberof"]; // You can access ldap Attributes with Attributes property

var claimsIdentity = context.Principal.Identity as ClaimsIdentity;

foreach (var group in memberof)
{
// Example distinguished name: CN=TestGroup,DC=KERB,DC=local
var groupDN = $"{Encoding.UTF8.GetString((byte[])group)}";
var groupCN = groupDN.Split(',')[0].Substring("CN=".Length);

if (options.ResolveNestedGroups)
{
GetNestedGroups(options.LdapConnection, claimsIdentity, distinguishedName, groupCN, logger);
}
else
{
AddRole(claimsIdentity, groupCN);
}
}
}
else
{
logger.LogWarning($"No response received for query: {filter} with distinguished name: {distinguishedName}");
}
}

private static void GetNestedGroups(LdapConnection connection, ClaimsIdentity principal, string distinguishedName, string groupCN, ILogger logger)
{
var filter = $"(&(objectClass=group)(sAMAccountName={groupCN}))"; // This is using ldap search query language, it is looking on the server for someUser
var searchRequest = new SearchRequest(distinguishedName, filter, System.DirectoryServices.Protocols.SearchScope.Subtree, null);
var searchResponse = (SearchResponse)connection.SendRequest(searchRequest);

if (searchResponse.Entries.Count > 0)
{
if (searchResponse.Entries.Count > 1)
{
logger.LogWarning($"More than one response received for query: {filter} with distinguished name: {distinguishedName}");
}

var group = searchResponse.Entries[0]; //Get the object that was found on ldap
string name = group.DistinguishedName;
AddRole(principal, name);

var memberof = group.Attributes["memberof"]; // You can access ldap Attributes with Attributes property
if (memberof != null)
{
foreach (var member in memberof)
{
var groupDN = $"{Encoding.UTF8.GetString((byte[])member)}";
var nestedGroupCN = groupDN.Split(',')[0].Substring("CN=".Length);
GetNestedGroups(connection, principal, distinguishedName, nestedGroupCN, logger);
}
}
}
}

private static void AddRole(ClaimsIdentity identity, string role)
{
identity.AddClaim(new Claim(identity.RoleClaimType, role));
}
}
}
75 changes: 75 additions & 0 deletions src/Security/Authentication/Negotiate/src/LdapOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.DirectoryServices.Protocols;

namespace Microsoft.AspNetCore.Authentication.Negotiate
{
/// <summary>
/// Options class for configuring LDAP connections on Linux
/// </summary>
public class LdapOptions
{
/// <summary>
/// Configure whether LDAP connection should be used to resolve role claims.
/// This is mainly used on Linux.
/// </summary>
public bool EnableLdapRoleClaimResolution { get; set; }

/// <summary>
/// The domain to use for the LDAP connection. This is a mandatory setting.
/// </summary>
/// <example>
/// DOMAIN.com
/// </example>
public string Domain { get; set; }

/// <summary>
/// The machine account name to use when opening the LDAP connection.
/// If this is not provided, the machine wide credentials of the
/// domain joined machine will be used.
/// </summary>
public string MachineAccountName { get; set; }

/// <summary>
/// The machine account password to use when opening the LDAP connection.
/// This must be provided if a <see cref="MachineAccountName"/> is provided.
/// </summary>
public string MachineAccountPassword { get; set; }

/// <summary>
/// This option indicates whether nested groups should be examined when
/// resolving AD Roles.
/// </summary>
public bool ResolveNestedGroups { get; set; } = true;

/// <summary>
/// The <see cref="LdapConnection"/> to be used to retrieve role claims.
/// If no explicit connection is provided, an LDAP connection will be
/// automatically created based on the <see cref="Domain"/>,
/// <see cref="MachineAccountName"/> and <see cref="MachineAccountPassword"/>
/// options. If provided, this connection will be used and the
/// <see cref="Domain"/>, <see cref="MachineAccountName"/> and
/// <see cref="MachineAccountPassword"/> options will not be used to create
/// the <see cref="LdapConnection"/>.
/// </summary>
public LdapConnection LdapConnection { get; set; }

public void Validate()
{
if (EnableLdapRoleClaimResolution)
{
if (string.IsNullOrEmpty(Domain))
{
throw new ArgumentException($"{nameof(EnableLdapRoleClaimResolution)} is set to true but {nameof(Domain)} is not set.");
}

if (string.IsNullOrEmpty(MachineAccountName) && !string.IsNullOrEmpty(MachineAccountPassword))
{
throw new ArgumentException($"{nameof(MachineAccountPassword)} should only be specified when {nameof(MachineAccountName)} is configured.");
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<Reference Include="Microsoft.AspNetCore.Authentication" />
<Reference Include="Microsoft.AspNetCore.Connections.Abstractions" />
<Reference Include="Microsoft.AspNetCore.Hosting.Server.Abstractions" />
<Reference Include="System.DirectoryServices.Protocols" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Security.Principal;
using System.Text.Encodings.Web;
Expand Down Expand Up @@ -328,6 +329,9 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
Principal = user
};

await LdapAdapter.RetrieveClaimsAsync(Options.LdapOptions, authenticatedContext, Logger);

await Events.Authenticated(authenticatedContext);

if (authenticatedContext.Result != null)
Expand Down
24 changes: 24 additions & 0 deletions src/Security/Authentication/Negotiate/src/NegotiateOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,30 @@ public class NegotiateOptions : AuthenticationSchemeOptions
/// </summary>
public bool PersistNtlmCredentials { get; set; } = true;

/// <summary>
/// Configuration settings for LDAP connections used to retrieve AD Role claims.
/// This is only used on Linux systems.
/// </summary>
public LdapOptions LdapOptions { get; } = new LdapOptions();

/// <summary>
/// Checks that the options are valid for a specific scheme
/// </summary>
/// <param name="scheme">The scheme being validated.</param>
public override void Validate(string scheme)
{
Validate();
}

/// <summary>
/// Check that the options are valid. Should throw an exception if things are not ok.
/// </summary>
public override void Validate()
{
base.Validate();
LdapOptions.Validate();
}

/// <summary>
/// Indicates if integrated server Windows Auth is being used instead of this handler.
/// See <see cref="PostConfigureNegotiateOptions"/>.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.DirectoryServices.Protocols;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
Expand Down Expand Up @@ -59,6 +61,34 @@ public void PostConfigure(string name, NegotiateOptions options)
+ " Enable Windows Authentication for the server and the Negotiate Authentication handler will defer to it.");
}
}

var ldapOptions = options.LdapOptions;

if (ldapOptions.EnableLdapRoleClaimResolution)
{
if (ldapOptions.LdapConnection == null)
{
var di = new LdapDirectoryIdentifier(server: ldapOptions.Domain, fullyQualifiedDnsHostName: true, connectionless: false);

if (string.IsNullOrEmpty(ldapOptions.MachineAccountName))
{
// Use default credentials
ldapOptions.LdapConnection = new LdapConnection(di);
}
else
{
// Use specific specific machine account
var machineAccount = ldapOptions.MachineAccountName + "@" + ldapOptions.Domain;
var credentials = new NetworkCredential(machineAccount, ldapOptions.MachineAccountPassword);
ldapOptions.LdapConnection = new LdapConnection(di, credentials);
}

ldapOptions.LdapConnection.SessionOptions.ProtocolVersion = 3; //Setting LDAP Protocol to latest version
ldapOptions.LdapConnection.Timeout = TimeSpan.FromMinutes(1);
}

ldapOptions.LdapConnection.Bind(); // This line actually makes the connection.
}
}
}
}