Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions Extensions/HttpContextBaseExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,20 @@ public static CacheAdapter GetCacheAdapter(this HttpContextBase httpContext)
return new CacheAdapter(httpContext);
}

public static bool HasApiUnreachableFlag(this HttpContextBase httpContext)
public static bool HasApiUnreachableFlag(this HttpContextBase httpContext, bool trimName = true)
{
var name = httpContext?.User?.Identity?.Name;
if (string.IsNullOrEmpty(name))
{
return false;
}

return httpContext.GetCacheAdapter().GetApiUnreachable(Util.CanonicalizeUserName(name));
// for owa we dont want trim username, because owa send netbiosname
// but for compatibility with Ms365 we use flag
if (trimName)
return httpContext.GetCacheAdapter().GetApiUnreachable(Util.CanonicalizeUserName(name));
else
return httpContext.GetCacheAdapter().GetApiUnreachable(name);
}
}
}
60 changes: 60 additions & 0 deletions Interop/NameTranslator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using MultiFactor.IIS.Adapter.Services;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using static MultiFactor.IIS.Adapter.Interop.NativeMethods;

namespace MultiFactor.IIS.Adapter.Interop
{
public class NameTranslator : IDisposable
{
private readonly SafeDsHandle _handle;
private readonly Logger _logger;
private readonly string _domain;

public NameTranslator(string domain, Logger logger)
{
_domain = domain;
_logger = logger;
uint res = DsBind(domain, null, out _handle);
if (res != (uint)DS_NAME_ERROR.DS_NAME_NO_ERROR)
{
_logger.Warn($"Failed to bind to: {domain}");
throw new Win32Exception((int)res);
}
}

public UserSearchContext Translate(string netbiosName)
{
uint err = DsCrackNames(_handle, DS_NAME_FLAGS.DS_NAME_FLAG_EVAL_AT_DC | DS_NAME_FLAGS.DS_NAME_FLAG_TRUST_REFERRAL, DS_NAME_FORMAT.DS_NT4_ACCOUNT_NAME, DS_NAME_FORMAT.DS_USER_PRINCIPAL_NAME, 1, new[] { netbiosName }, out IntPtr pResult);
if (err != (uint)DS_NAME_ERROR.DS_NAME_NO_ERROR)
{
_logger.Warn($"Failed to translate {netbiosName} in {_domain}");
throw new Win32Exception((int)err);
}

try
{
// Next convert the returned structure to managed environment
DS_NAME_RESULT Result = (DS_NAME_RESULT)Marshal.PtrToStructure(pResult, typeof(DS_NAME_RESULT));
var res = Result.Items;
if (res == null || res.Length == 0 || (!res[0].status.HasFlag(DS_NAME_ERROR.DS_NAME_ERROR_TRUST_REFERRAL) && !res[0].status.HasFlag(DS_NAME_ERROR.DS_NAME_NO_ERROR)))
{
_logger.Warn($"Unexpected result of translation {netbiosName} in {_domain}");
throw new System.Security.SecurityException("Unable to resolve user name.");
}
return new UserSearchContext(res[0].pDomain, res[0].pName, netbiosName);
}
finally
{
DsFreeNameResult(pResult);
}

}

public void Dispose()
{
_handle.Dispose();
}
}
}
160 changes: 160 additions & 0 deletions Interop/NativeMethods.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
using System;
using System.Runtime.InteropServices;

namespace MultiFactor.IIS.Adapter.Interop
{
internal static class NativeMethods
{
private const string NTDSAPI = "ntdsapi.dll";

[DllImport(NTDSAPI, CharSet = CharSet.Auto)]
public static extern uint DsBind(
string DomainControllerName, // in, optional
string DnsDomainName, // in, optional
out SafeDsHandle phDS);

[DllImport(NTDSAPI, CharSet = CharSet.Auto)]
public static extern uint DsCrackNames(
SafeDsHandle hDS,
DS_NAME_FLAGS flags,
DS_NAME_FORMAT formatOffered,
DS_NAME_FORMAT formatDesired,
uint cNames,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPTStr, SizeParamIndex = 4)]
string[] rpNames,
out IntPtr ppResult);

[DllImport(NTDSAPI, CharSet = CharSet.Auto)]
public static extern void DsFreeNameResult(IntPtr pResult /* DS_NAME_RESULT* */);

[DllImport(NTDSAPI, CharSet = CharSet.Auto)]
public static extern uint DsUnBind(ref IntPtr phDS);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DS_NAME_RESULT
{
public uint cItems;
internal IntPtr rItems; // PDS_NAME_RESULT_ITEM
public DS_NAME_RESULT_ITEM[] Items
{
get
{
if (rItems == IntPtr.Zero)
{
return new DS_NAME_RESULT_ITEM[0];
}

var ResultArray = new DS_NAME_RESULT_ITEM[cItems];
Type strType = typeof(DS_NAME_RESULT_ITEM);
int stSize = Marshal.SizeOf(strType);
IntPtr curptr;

for (uint i = 0; i < cItems; i++)
{
curptr = new IntPtr(rItems.ToInt64() + (i * stSize));
ResultArray[i] = (DS_NAME_RESULT_ITEM)Marshal.PtrToStructure(curptr, strType);
}
return ResultArray;
}
}
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DS_NAME_RESULT_ITEM
{
public DS_NAME_ERROR status;
public string pDomain;
public string pName;
public override string ToString()
{
if (status == DS_NAME_ERROR.DS_NAME_NO_ERROR)
{
return pName;
}

return null;
}
}

public enum DS_NAME_ERROR
{
DS_NAME_NO_ERROR = 0,
// Generic processing error.
DS_NAME_ERROR_RESOLVING = 1,
// Couldn't find the name at all - or perhaps caller doesn't have
// rights to see it.
DS_NAME_ERROR_NOT_FOUND = 2,
// Input name mapped to more than one output name.
DS_NAME_ERROR_NOT_UNIQUE = 3,
// Input name found, but not the associated output format.
// Can happen if object doesn't have all the required attributes.
DS_NAME_ERROR_NO_MAPPING = 4,
// Unable to resolve entire name, but was able to determine which
// domain object resides in. Thus DS_NAME_RESULT_ITEM?.pDomain
// is valid on return.
DS_NAME_ERROR_DOMAIN_ONLY = 5,
// Unable to perform a purely syntactical mapping at the client
// without going out on the wire.
DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 6,
// The name is from an external trusted forest.
DS_NAME_ERROR_TRUST_REFERRAL = 7
}

[Flags]
public enum DS_NAME_FLAGS
{
DS_NAME_NO_FLAGS = 0x0,
// Perform a syntactical mapping at the client (if possible) without
// going out on the wire. Returns DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING
// if a purely syntactical mapping is not possible.
DS_NAME_FLAG_SYNTACTICAL_ONLY = 0x1,
// Force a trip to the DC for evaluation, even if this could be
// locally cracked syntactically.
DS_NAME_FLAG_EVAL_AT_DC = 0x2,
// The call fails if the DC is not a GC
DS_NAME_FLAG_GCVERIFY = 0x4,
// Enable cross forest trust referral
DS_NAME_FLAG_TRUST_REFERRAL = 0x8
}

public enum DS_NAME_FORMAT
{
// unknown name type
DS_UNKNOWN_NAME = 0,
// eg: CN=User Name,OU=Users,DC=Example,DC=Microsoft,DC=Com
DS_FQDN_1779_NAME = 1,
// eg: Example\UserN
// Domain-only version includes trailing '\\'.
DS_NT4_ACCOUNT_NAME = 2,
// Probably "User Name" but could be something else. I.e. The
// display name is not necessarily the defining RDN.
DS_DISPLAY_NAME = 3,
// obsolete - see #define later
// DS_DOMAIN_SIMPLE_NAME = 4,
// obsolete - see #define later
// DS_ENTERPRISE_SIMPLE_NAME = 5,
// String-ized GUID as returned by IIDFromString().
// eg: {4fa050f0-f561-11cf-bdd9-00aa003a77b6}
DS_UNIQUE_ID_NAME = 6,
// eg: example.microsoft.com/software/user name
// Domain-only version includes trailing '/'.
DS_CANONICAL_NAME = 7,
// eg: usern@example.microsoft.com
DS_USER_PRINCIPAL_NAME = 8,
// Same as DS_CANONICAL_NAME except that rightmost '/' is
// replaced with '\n' - even in domain-only case.
// eg: example.microsoft.com/software\nuser name
DS_CANONICAL_NAME_EX = 9,
// eg: www/www.microsoft.com@example.com - generalized service principal
// names.
DS_SERVICE_PRINCIPAL_NAME = 10,
// This is the string representation of a SID. Invalid for formatDesired.
// See sddl.h for SID binary <--> text conversion routines.
// eg: S-1-5-21-397955417-626881126-188441444-501
DS_SID_OR_SID_HISTORY_NAME = 11,
// Pseudo-name format so GetUserNameEx can return the DNS domain name to
// a caller. This level is not supported by the DS APIs.
DS_DNS_DOMAIN_NAME = 12
}
}
}
28 changes: 28 additions & 0 deletions Interop/SafeDsHandle.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;

namespace MultiFactor.IIS.Adapter.Interop
{
public class SafeDsHandle : SafeHandle
{
public SafeDsHandle() : base(IntPtr.Zero, true) { }

public override bool IsInvalid
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[PrePrepareMethod]
get { return (handle == IntPtr.Zero); }
}

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[PrePrepareMethod]

protected override bool ReleaseHandle()
{
uint ret = NativeMethods.DsUnBind(ref handle);
System.Diagnostics.Debug.WriteLineIf(ret != 0, "Error unbinding :\t" + ret.ToString());
return ret != 0;
}
}
}
23 changes: 23 additions & 0 deletions Interop/UserSearchContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using MultiFactor.IIS.Adapter.Services.Ldap;
using System;

namespace MultiFactor.IIS.Adapter.Interop
{
public class UserSearchContext
{
public string Domain { get; set; }
public LdapIdentity UserIdentity { get; set; }

public UserSearchContext(string domain, string upn, string rawUserName)
{
if (string.IsNullOrWhiteSpace(domain))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(domain));
if (string.IsNullOrWhiteSpace(upn))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(upn));
Domain = domain;
UserIdentity = LdapIdentity.Parse(upn).WithRawName(rawUserName);
}

public override string ToString() => $"User:{UserIdentity.RawName}, UPN:{UserIdentity.Name}, Domain:{Domain}";
}
}
12 changes: 6 additions & 6 deletions MsDynamics365/Module.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using MultiFactor.IIS.Adapter.Extensions;
using MultiFactor.IIS.Adapter.Owa;
using MultiFactor.IIS.Adapter.Services;
using MultiFactor.IIS.Adapter.Services.Ldap;
using System;
using System.Web;

Expand Down Expand Up @@ -49,9 +50,8 @@ public override void OnPostAuthorizeRequest(HttpContextBase context)
//not yet authenticated with login/pwd
return;
}
var user = context.User.Identity.Name;
var user = LdapIdentity.Parse(context.User.Identity.Name);

var canonicalUserName = Util.CanonicalizeUserName(user);

//process request or postback to/from MultiFactor
if (path.Contains(Constants.MULTIFACTOR_PAGE))
Expand All @@ -65,17 +65,17 @@ public override void OnPostAuthorizeRequest(HttpContextBase context)
}

var ad = new ActiveDirectoryService(context.GetCacheAdapter(), Logger.IIS);
var secondFactorRequired = new UserRequiredSecondFactor(ad);
if (!secondFactorRequired.Execute(canonicalUserName))
var secondFactorRequired = new UserRequiredSecondFactor(ad, Logger.IIS);
if (!secondFactorRequired.Execute(user))
{
//bypass 2fa
return;
}

//mfa
var valSrv = new TokenValidationService(Logger.IIS);
var checker = new AuthChecker(context, valSrv);
var isAuthenticatedByMultifactor = checker.IsAuthenticated(user);
var checker = new AuthChecker(context, valSrv, Logger.IIS);
var isAuthenticatedByMultifactor = checker.IsAuthenticated(user.RawName);
if (isAuthenticatedByMultifactor || context.HasApiUnreachableFlag())
{
return;
Expand Down
6 changes: 6 additions & 0 deletions MultiFactor.IIS.Adapter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@
<Compile Include="Configuration.cs" />
<Compile Include="ConfigurationKeys.cs" />
<Compile Include="Extensions\HttpContextBaseExtensions.cs" />
<Compile Include="Interop\NameTranslator.cs" />
<Compile Include="Interop\NativeMethods.cs" />
<Compile Include="Interop\SafeDsHandle.cs" />
<Compile Include="Interop\UserSearchContext.cs" />
<Compile Include="MsDynamics365\Module.cs" />
<Compile Include="Constants.cs" />
<Compile Include="Core\HttpModuleBase.cs" />
Expand All @@ -77,6 +81,8 @@
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Services\Ldap\LdapIdentity.cs" />
<Compile Include="Services\Ldap\NetbiosService.cs" />
<Compile Include="Services\Ldap\Profile\AttributeKeyComparer.cs" />
<Compile Include="Services\MfaApiRequestExecutor.cs" />
<Compile Include="Services\MfaApiRequestExecutorFactory.cs" />
Expand Down
Loading