2 using Microsoft.Win32.SafeHandles;
24 private static SafeAccessTokenHandle s_invalidTokenHandle;
26 private string m_name;
32 private object m_groups;
35 private SafeAccessTokenHandle m_safeTokenHandle = SafeAccessTokenHandle.InvalidHandle;
37 private string m_authType;
39 private int m_isAuthenticated = -1;
43 private volatile bool m_impersonationLevelInitialized;
45 private static RuntimeConstructorInfo s_specialSerializationCtor;
52 private string m_issuerName =
"AD AUTHORITY";
55 private object m_claimsIntiailizedLock =
new object();
58 private volatile bool m_claimsInitialized;
73 [SecuritySafeCritical]
76 if (m_safeTokenHandle.IsInvalid)
80 if (m_authType ==
null)
82 Win32Native.LUID LogonId = GetLogonAuthId(m_safeTokenHandle);
83 if (LogonId.LowPart == 998)
87 SafeLsaReturnBufferHandle ppLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle;
90 int num = Win32Native.LsaGetLogonSessionData(ref LogonId, ref ppLogonSessionData);
93 throw GetExceptionFromNtStatus(num);
95 ppLogonSessionData.Initialize((uint)
Marshal.
SizeOf(typeof(Win32Native.SECURITY_LOGON_SESSION_DATA)));
96 Win32Native.SECURITY_LOGON_SESSION_DATA sECURITY_LOGON_SESSION_DATA = ppLogonSessionData.Read<Win32Native.SECURITY_LOGON_SESSION_DATA>(0uL);
101 if (!ppLogonSessionData.IsInvalid)
103 ppLogonSessionData.Dispose();
116 [SecuritySafeCritical]
119 if (!m_impersonationLevelInitialized)
122 if (m_safeTokenHandle.IsInvalid)
128 TokenType tokenInformation = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType);
129 if (tokenInformation == TokenType.TokenPrimary)
135 int tokenInformation2 = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel);
139 m_impersonationLevel = tokenImpersonationLevel;
140 m_impersonationLevelInitialized =
true;
142 return m_impersonationLevel;
153 if (m_isAuthenticated == -1)
155 m_isAuthenticated = (CheckNtTokenForSid(
new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[1]
160 return m_isAuthenticated == 1;
169 [SecuritySafeCritical]
172 if (m_safeTokenHandle.IsInvalid)
176 return CheckNtTokenForSid(
new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[2]
189 [SecuritySafeCritical]
192 if (m_safeTokenHandle.IsInvalid)
200 return User == right;
209 [SecuritySafeCritical]
212 if (m_safeTokenHandle.IsInvalid)
220 return User == right;
226 public override string Name 228 [SecuritySafeCritical]
240 [SecuritySafeCritical]
243 if (m_safeTokenHandle.IsInvalid)
249 using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenOwner))
263 [SecuritySafeCritical]
266 if (m_safeTokenHandle.IsInvalid)
272 using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenUser))
285 [SecuritySafeCritical]
288 if (m_safeTokenHandle.IsInvalid)
292 if (m_groups ==
null)
295 using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenGroups))
297 if (safeLocalAllocHandle.Read<uint>(0uL) != 0)
299 Win32Native.TOKEN_GROUPS tOKEN_GROUPS = safeLocalAllocHandle.Read<Win32Native.TOKEN_GROUPS>(0uL);
300 Win32Native.SID_AND_ATTRIBUTES[] array =
new Win32Native.SID_AND_ATTRIBUTES[tOKEN_GROUPS.GroupCount];
301 safeLocalAllocHandle.ReadArray((uint)
Marshal.
OffsetOf(typeof(Win32Native.TOKEN_GROUPS),
"Groups").
ToInt32(), array, 0, array.Length);
302 Win32Native.SID_AND_ATTRIBUTES[] array2 = array;
303 foreach (Win32Native.SID_AND_ATTRIBUTES sID_AND_ATTRIBUTES in array2)
305 uint num = 3221225492u;
306 if ((sID_AND_ATTRIBUTES.Attributes & num) == 4)
323 [SecuritySafeCritical]
327 return m_safeTokenHandle.DangerousGetHandle();
338 return m_safeTokenHandle;
370 if (!m_claimsInitialized)
374 foreach (
Claim claim
in base.Claims)
378 foreach (
Claim userClaim
in m_userClaims)
380 yield
return userClaim;
382 foreach (
Claim deviceClaim
in m_deviceClaims)
384 yield
return deviceClaim;
389 [SecuritySafeCritical]
392 s_invalidTokenHandle = SafeAccessTokenHandle.InvalidHandle;
395 typeof(SerializationInfo)
396 },
null) as RuntimeConstructorInfo);
400 private WindowsIdentity()
401 : base(null, null, null,
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
"http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid")
406 internal WindowsIdentity(SafeAccessTokenHandle safeTokenHandle)
407 : this(safeTokenHandle.DangerousGetHandle(), null, -1)
418 [SecuritySafeCritical]
422 : this(userToken, null, -1)
433 [SecuritySafeCritical]
437 : this(userToken, type, -1)
449 [SecuritySafeCritical]
453 : this(userToken, type, -1)
467 [SecuritySafeCritical]
471 : this(userToken, type, isAuthenticated ? 1 : 0)
477 : base(null, null, null,
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
"http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid")
479 CreateFromToken(userToken);
480 m_authType = authType;
481 m_isAuthenticated = isAuthenticated;
485 private void CreateFromToken(
IntPtr userToken)
492 bool tokenInformation = Win32Native.GetTokenInformation(userToken, 8u, SafeLocalAllocHandle.InvalidHandle, 0u, out ReturnLength);
497 if (!Win32Native.DuplicateHandle(Win32Native.GetCurrentProcess(), userToken, Win32Native.GetCurrentProcess(), ref m_safeTokenHandle, 0u, bInheritHandle:
true, 2u))
508 [SecuritySafeCritical]
511 : this(sUserPrincipalName, null)
521 [SecuritySafeCritical]
524 : base(null, null, null,
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
"http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid")
526 KerbS4ULogon(sUserPrincipalName, ref m_safeTokenHandle);
534 [SecuritySafeCritical]
546 m_claimsInitialized =
false;
550 CreateFromToken(intPtr);
560 base.GetObjectData(info, context);
561 info.AddValue(
"m_userToken", m_safeTokenHandle.DangerousGetHandle());
573 [SecuritySafeCritical]
584 [SecuritySafeCritical]
594 [SecuritySafeCritical]
598 return GetCurrentInternal(desiredAccess, threadOnly:
false);
603 [SecuritySafeCritical]
609 [SecuritySafeCritical]
613 if (m_safeTokenHandle.IsInvalid)
617 SafeAccessTokenHandle phNewToken = SafeAccessTokenHandle.InvalidHandle;
619 bool IsMember =
false;
622 if (impersonationLevel == TokenImpersonationLevel.None && !Win32Native.DuplicateTokenEx(m_safeTokenHandle, 8u,
IntPtr.
Zero, 2u, 2u, ref phNewToken))
626 if (!Win32Native.CheckTokenMembership((impersonationLevel != 0) ? m_safeTokenHandle : phNewToken, sid.BinaryForm, ref IsMember))
634 if (phNewToken != SafeAccessTokenHandle.InvalidHandle)
636 phNewToken.Dispose();
643 internal string GetName()
645 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
646 if (m_safeTokenHandle.IsInvalid)
652 using (SafeRevertToSelf(ref stackMark))
654 NTAccount nTAccount =
User.
Translate(typeof(NTAccount)) as NTAccount;
665 [SecuritySafeCritical]
672 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
674 if (!safeAccessTokenHandle.IsInvalid)
678 using (SafeImpersonate(safeAccessTokenHandle, wi, ref stackMark))
690 [SecuritySafeCritical]
697 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
699 if (!safeAccessTokenHandle.IsInvalid)
704 using (SafeImpersonate(safeAccessTokenHandle, wi, ref stackMark))
715 [SecuritySafeCritical]
718 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
729 [SecuritySafeCritical]
733 StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
736 return SafeRevertToSelf(ref stackMark);
745 if (m_safeTokenHandle.IsInvalid)
749 return SafeImpersonate(m_safeTokenHandle,
this, ref stackMark);
755 [SecuritySafeCritical]
757 protected virtual void Dispose(
bool disposing)
759 if (disposing && m_safeTokenHandle !=
null && !m_safeTokenHandle.IsClosed)
761 m_safeTokenHandle.Dispose();
778 return SafeImpersonate(s_invalidTokenHandle,
null, ref stackMark);
782 internal static WindowsImpersonationContext SafeImpersonate(SafeAccessTokenHandle userToken, WindowsIdentity wi, ref StackCrawlMark stackMark)
785 bool isImpersonating;
786 SafeAccessTokenHandle currentToken = GetCurrentToken(
TokenAccessLevels.MaximumAllowed, threadOnly:
false, out isImpersonating, out hr);
787 if (currentToken ==
null || currentToken.IsInvalid)
791 FrameSecurityDescriptor securityObjectForFrame = SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, create:
true);
792 if (securityObjectForFrame ==
null)
794 throw new SecurityException(
Environment.GetResourceString(
"ExecutionEngine_MissingSecurityDescriptor"));
796 WindowsImpersonationContext windowsImpersonationContext =
new WindowsImpersonationContext(currentToken, GetCurrentThreadWI(), isImpersonating, securityObjectForFrame);
797 if (userToken.IsInvalid)
799 hr = Win32.RevertToSelf();
802 Environment.FailFast(Win32Native.GetMessage(hr));
805 securityObjectForFrame.SetTokenHandles(currentToken, wi?.
AccessToken);
809 hr = Win32.RevertToSelf();
812 Environment.FailFast(Win32Native.GetMessage(hr));
814 hr = Win32.ImpersonateLoggedOnUser(userToken);
817 windowsImpersonationContext.Undo();
818 throw new SecurityException(Environment.GetResourceString(
"Argument_ImpersonateUser"));
821 securityObjectForFrame.SetTokenHandles(currentToken, wi?.
AccessToken);
823 return windowsImpersonationContext;
827 internal static WindowsIdentity GetCurrentThreadWI()
833 internal static void UpdateThreadWI(WindowsIdentity wi)
836 if (currentThread.GetExecutionContextReader().SecurityContext.WindowsIdentity != wi)
838 ExecutionContext mutableExecutionContext = currentThread.GetMutableExecutionContext();
839 SecurityContext securityContext = mutableExecutionContext.SecurityContext;
840 if (wi !=
null && securityContext ==
null)
842 securityContext = (mutableExecutionContext.SecurityContext =
new SecurityContext());
844 if (securityContext !=
null)
846 securityContext.WindowsIdentity = wi;
852 internal static WindowsIdentity GetCurrentInternal(
TokenAccessLevels desiredAccess,
bool threadOnly)
855 bool isImpersonating;
856 SafeAccessTokenHandle currentToken = GetCurrentToken(desiredAccess, threadOnly, out isImpersonating, out hr);
857 if (currentToken ==
null || currentToken.IsInvalid)
859 if (threadOnly && !isImpersonating)
863 throw new SecurityException(Win32Native.GetMessage(hr));
865 WindowsIdentity windowsIdentity =
new WindowsIdentity();
866 windowsIdentity.m_safeTokenHandle.Dispose();
867 windowsIdentity.m_safeTokenHandle = currentToken;
868 return windowsIdentity;
871 internal static RuntimeConstructorInfo GetSpecialSerializationCtor()
873 return s_specialSerializationCtor;
876 private static int GetHRForWin32Error(
int dwLastError)
878 if ((dwLastError & 2147483648u) == 2147483648u)
882 return (dwLastError & 0xFFFF) | -2147024896;
886 private static Exception GetExceptionFromNtStatus(
int status)
891 return new UnauthorizedAccessException();
894 return new OutOfMemoryException();
897 int errorCode = Win32Native.LsaNtStatusToWinError(status);
898 return new SecurityException(Win32Native.GetMessage(errorCode));
904 private static SafeAccessTokenHandle GetCurrentToken(
TokenAccessLevels desiredAccess,
bool threadOnly, out
bool isImpersonating, out
int hr)
906 isImpersonating =
true;
907 SafeAccessTokenHandle safeAccessTokenHandle = GetCurrentThreadToken(desiredAccess, out hr);
908 if (safeAccessTokenHandle ==
null && hr == GetHRForWin32Error(1008))
910 isImpersonating =
false;
913 safeAccessTokenHandle = GetCurrentProcessToken(desiredAccess, out hr);
916 return safeAccessTokenHandle;
920 private static SafeAccessTokenHandle GetCurrentProcessToken(
TokenAccessLevels desiredAccess, out
int hr)
923 if (!Win32Native.OpenProcessToken(Win32Native.GetCurrentProcess(), desiredAccess, out SafeAccessTokenHandle TokenHandle))
931 internal static SafeAccessTokenHandle GetCurrentThreadToken(
TokenAccessLevels desiredAccess, out
int hr)
933 hr = Win32.OpenThreadToken(desiredAccess, WinSecurityContext.Both, out SafeAccessTokenHandle phThreadToken);
934 return phThreadToken;
938 private T GetTokenInformation<T>(TokenInformationClass tokenInformationClass) where
T :
struct 940 using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, tokenInformationClass))
942 return safeLocalAllocHandle.Read<
T>(0uL);
947 internal static ImpersonationQueryResult QueryImpersonation()
949 SafeAccessTokenHandle phThreadToken =
null;
950 int num = Win32.OpenThreadToken(
TokenAccessLevels.Query, WinSecurityContext.Thread, out phThreadToken);
951 if (phThreadToken !=
null)
953 phThreadToken.Close();
954 return ImpersonationQueryResult.Impersonated;
956 if (num == GetHRForWin32Error(5))
958 return ImpersonationQueryResult.Impersonated;
960 if (num == GetHRForWin32Error(1008))
962 return ImpersonationQueryResult.NotImpersonated;
964 return ImpersonationQueryResult.Failed;
968 private static Win32Native.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle)
970 using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics))
972 Win32Native.TOKEN_STATISTICS tOKEN_STATISTICS = safeLocalAllocHandle.Read<Win32Native.TOKEN_STATISTICS>(0uL);
973 return tOKEN_STATISTICS.AuthenticationId;
978 private static SafeLocalAllocHandle GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass)
980 SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle;
982 bool tokenInformation = Win32Native.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, invalidHandle, 0u, out ReturnLength);
984 switch (lastWin32Error)
989 UIntPtr sizetdwBytes =
new UIntPtr(ReturnLength);
990 invalidHandle.Dispose();
991 invalidHandle = Win32Native.LocalAlloc(0, sizetdwBytes);
992 if (invalidHandle ==
null || invalidHandle.IsInvalid)
994 throw new OutOfMemoryException();
996 invalidHandle.Initialize(ReturnLength);
997 if (!Win32Native.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, invalidHandle, ReturnLength, out ReturnLength))
1001 return invalidHandle;
1004 throw new ArgumentException(Environment.GetResourceString(
"Argument_InvalidImpersonationToken"));
1006 throw new SecurityException(Win32Native.GetMessage(lastWin32Error));
1011 [HandleProcessCorruptedStateExceptions]
1012 private unsafe
static SafeAccessTokenHandle KerbS4ULogon(
string upn, ref SafeAccessTokenHandle safeTokenHandle)
1014 byte[] array =
new byte[3]
1020 UIntPtr sizetdwBytes =
new UIntPtr((uint)(array.Length + 1));
1021 using (SafeLocalAllocHandle safeLocalAllocHandle = Win32Native.LocalAlloc(64, sizetdwBytes))
1023 if (safeLocalAllocHandle ==
null || safeLocalAllocHandle.IsInvalid)
1025 throw new OutOfMemoryException();
1027 safeLocalAllocHandle.Initialize((ulong)((
long)array.Length + 1L));
1028 safeLocalAllocHandle.WriteArray(0uL, array, 0, array.Length);
1029 Win32Native.UNICODE_INTPTR_STRING LogonProcessName =
new Win32Native.UNICODE_INTPTR_STRING(array.Length, safeLocalAllocHandle);
1030 SafeLsaLogonProcessHandle LsaHandle = SafeLsaLogonProcessHandle.InvalidHandle;
1031 SafeLsaReturnBufferHandle ProfileBuffer = SafeLsaReturnBufferHandle.InvalidHandle;
1034 Privilege privilege =
null;
1041 privilege =
new Privilege(
"SeTcbPrivilege");
1047 IntPtr SecurityMode = IntPtr.Zero;
1048 num = Win32Native.LsaRegisterLogonProcess(ref LogonProcessName, ref LsaHandle, ref SecurityMode);
1049 if (5 == Win32Native.LsaNtStatusToWinError(num))
1051 num = Win32Native.LsaConnectUntrusted(ref LsaHandle);
1056 privilege?.Revert();
1061 privilege?.Revert();
1065 throw GetExceptionFromNtStatus(num);
1067 byte[] array2 =
new byte[
"Kerberos".Length + 1];
1069 sizetdwBytes =
new UIntPtr((uint)array2.Length);
1070 using (SafeLocalAllocHandle safeLocalAllocHandle2 = Win32Native.LocalAlloc(0, sizetdwBytes))
1072 if (safeLocalAllocHandle2 ==
null || safeLocalAllocHandle2.IsInvalid)
1074 throw new OutOfMemoryException();
1076 safeLocalAllocHandle2.Initialize((uint)array2.Length);
1077 safeLocalAllocHandle2.WriteArray(0uL, array2, 0, array2.Length);
1078 Win32Native.UNICODE_INTPTR_STRING PackageName =
new Win32Native.UNICODE_INTPTR_STRING(
"Kerberos".Length, safeLocalAllocHandle2);
1079 uint AuthenticationPackage = 0u;
1080 num = Win32Native.LsaLookupAuthenticationPackage(LsaHandle, ref PackageName, ref AuthenticationPackage);
1083 throw GetExceptionFromNtStatus(num);
1085 Win32Native.TOKEN_SOURCE SourceContext =
default(Win32Native.TOKEN_SOURCE);
1086 if (!Win32Native.AllocateLocallyUniqueId(ref SourceContext.SourceIdentifier))
1090 SourceContext.Name =
new char[8];
1091 SourceContext.Name[0] =
'C';
1092 SourceContext.Name[1] =
'L';
1093 SourceContext.Name[2] =
'R';
1094 uint ProfileBufferLength = 0u;
1095 Win32Native.LUID LogonId =
default(Win32Native.LUID);
1096 Win32Native.QUOTA_LIMITS Quotas =
default(Win32Native.QUOTA_LIMITS);
1099 uint num2 = (uint)(
Marshal.
SizeOf(typeof(Win32Native.KERB_S4U_LOGON)) + bytes.Length);
1100 using (SafeLocalAllocHandle safeLocalAllocHandle3 = Win32Native.LocalAlloc(64,
new UIntPtr(num2)))
1102 if (safeLocalAllocHandle3 ==
null || safeLocalAllocHandle3.IsInvalid)
1104 throw new OutOfMemoryException();
1106 safeLocalAllocHandle3.Initialize(num2);
1107 ulong num3 = (ulong)
Marshal.
SizeOf(typeof(Win32Native.KERB_S4U_LOGON));
1108 safeLocalAllocHandle3.WriteArray(num3, bytes, 0, bytes.Length);
1109 byte* pointer =
null;
1113 safeLocalAllocHandle3.AcquirePointer(ref pointer);
1114 Win32Native.KERB_S4U_LOGON value =
default(Win32Native.KERB_S4U_LOGON);
1115 value.MessageType = 12u;
1117 value.ClientUpn =
new Win32Native.UNICODE_INTPTR_STRING(bytes.Length,
new IntPtr(pointer + num3));
1118 safeLocalAllocHandle3.Write(0uL, value);
1119 num = Win32Native.LsaLogonUser(LsaHandle, ref LogonProcessName, 3u, AuthenticationPackage,
new IntPtr(pointer), (uint)safeLocalAllocHandle3.ByteLength, IntPtr.Zero, ref SourceContext, ref ProfileBuffer, ref ProfileBufferLength, ref LogonId, ref safeTokenHandle, ref Quotas, ref SubStatus);
1120 if (num == -1073741714 && SubStatus < 0)
1126 throw GetExceptionFromNtStatus(num);
1130 throw GetExceptionFromNtStatus(SubStatus);
1135 if (pointer !=
null)
1137 safeLocalAllocHandle3.ReleasePointer();
1141 return safeTokenHandle;
1146 if (!LsaHandle.IsInvalid)
1148 LsaHandle.Dispose();
1150 if (!ProfileBuffer.IsInvalid)
1152 ProfileBuffer.Dispose();
1160 [SecuritySafeCritical]
1162 : base(identity, null, identity.m_authType, null, null, checkAuthType: false)
1164 if (identity ==
null)
1168 bool success =
false;
1172 if (!identity.m_safeTokenHandle.IsInvalid && identity.m_safeTokenHandle != SafeAccessTokenHandle.InvalidHandle && identity.m_safeTokenHandle.DangerousGetHandle() !=
IntPtr.
Zero)
1174 identity.m_safeTokenHandle.DangerousAddRef(ref success);
1175 if (!identity.m_safeTokenHandle.IsInvalid && identity.m_safeTokenHandle.DangerousGetHandle() !=
IntPtr.
Zero)
1177 CreateFromToken(identity.m_safeTokenHandle.DangerousGetHandle());
1179 m_authType = identity.m_authType;
1180 m_isAuthenticated = identity.m_isAuthenticated;
1187 identity.m_safeTokenHandle.DangerousRelease();
1193 internal IntPtr GetTokenInternal()
1195 return m_safeTokenHandle.DangerousGetHandle();
1200 : base(claimsIdentity)
1204 CreateFromToken(userToken);
1210 return base.
Clone();
1220 [SecuritySafeCritical]
1221 private void InitializeClaims()
1223 if (!m_claimsInitialized)
1225 lock (m_claimsIntiailizedLock)
1227 if (!m_claimsInitialized)
1231 if (!
string.IsNullOrEmpty(
Name))
1233 m_userClaims.
Add(
new Claim(base.NameClaimType,
Name,
"http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName,
this));
1235 AddPrimarySidClaim(m_userClaims);
1236 AddGroupSidClaims(m_userClaims);
1239 AddDeviceGroupSidClaims(m_deviceClaims, TokenInformationClass.TokenDeviceGroups);
1240 AddTokenClaims(m_userClaims, TokenInformationClass.TokenUserClaimAttributes,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsuserclaim");
1241 AddTokenClaims(m_deviceClaims, TokenInformationClass.TokenDeviceClaimAttributes,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdeviceclaim");
1243 m_claimsInitialized =
true;
1250 private void AddDeviceGroupSidClaims(
List<Claim> instanceClaims, TokenInformationClass tokenInformationClass)
1252 if (!m_safeTokenHandle.IsInvalid)
1254 SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
1257 safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, tokenInformationClass);
1259 IntPtr intPtr =
new IntPtr((
long)safeLocalAllocHandle.DangerousGetHandle() + (long)
Marshal.
OffsetOf(typeof(Win32Native.TOKEN_GROUPS),
"Groups"));
1261 for (
int i = 0; i < num; i++)
1263 Win32Native.SID_AND_ATTRIBUTES sID_AND_ATTRIBUTES = (Win32Native.SID_AND_ATTRIBUTES)
Marshal.
PtrToStructure(intPtr, typeof(Win32Native.SID_AND_ATTRIBUTES));
1264 uint num2 = 3221225492u;
1265 SecurityIdentifier securityIdentifier =
new SecurityIdentifier(sID_AND_ATTRIBUTES.Sid, noDemand:
true);
1266 if ((sID_AND_ATTRIBUTES.Attributes & num2) == 4)
1268 text =
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsdevicegroup";
1269 Claim claim =
new Claim(text, securityIdentifier.Value,
"http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName,
this,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority",
Convert.ToString(securityIdentifier.IdentifierAuthority,
CultureInfo.
InvariantCulture));
1271 instanceClaims.
Add(claim);
1273 else if ((sID_AND_ATTRIBUTES.Attributes & num2) == 16)
1275 text =
"http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlywindowsdevicegroup";
1276 Claim claim2 =
new Claim(text, securityIdentifier.Value,
"http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName,
this,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority",
Convert.ToString(securityIdentifier.IdentifierAuthority,
CultureInfo.
InvariantCulture));
1278 instanceClaims.
Add(claim2);
1280 intPtr =
new IntPtr((
long)intPtr + Win32Native.SID_AND_ATTRIBUTES.SizeOf);
1285 safeLocalAllocHandle.Close();
1291 private void AddGroupSidClaims(
List<Claim> instanceClaims)
1293 if (!m_safeTokenHandle.IsInvalid)
1295 SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
1296 SafeLocalAllocHandle safeLocalAllocHandle2 = SafeLocalAllocHandle.InvalidHandle;
1299 safeLocalAllocHandle2 = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenPrimaryGroup);
1300 Win32Native.TOKEN_PRIMARY_GROUP tOKEN_PRIMARY_GROUP = (Win32Native.TOKEN_PRIMARY_GROUP)
Marshal.
PtrToStructure(safeLocalAllocHandle2.DangerousGetHandle(), typeof(Win32Native.TOKEN_PRIMARY_GROUP));
1301 SecurityIdentifier securityIdentifier =
new SecurityIdentifier(tOKEN_PRIMARY_GROUP.PrimaryGroup, noDemand:
true);
1303 safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenGroups);
1305 IntPtr intPtr =
new IntPtr((
long)safeLocalAllocHandle.DangerousGetHandle() + (long)
Marshal.
OffsetOf(typeof(Win32Native.TOKEN_GROUPS),
"Groups"));
1306 for (
int i = 0; i < num; i++)
1308 Win32Native.SID_AND_ATTRIBUTES sID_AND_ATTRIBUTES = (Win32Native.SID_AND_ATTRIBUTES)
Marshal.
PtrToStructure(intPtr, typeof(Win32Native.SID_AND_ATTRIBUTES));
1309 uint num2 = 3221225492u;
1310 SecurityIdentifier securityIdentifier2 =
new SecurityIdentifier(sID_AND_ATTRIBUTES.Sid, noDemand:
true);
1311 if ((sID_AND_ATTRIBUTES.Attributes & num2) == 4)
1313 if (!flag && StringComparer.Ordinal.Equals(securityIdentifier2.Value, securityIdentifier.Value))
1315 instanceClaims.
Add(
new Claim(
"http://schemas.microsoft.com/ws/2008/06/identity/claims/primarygroupsid", securityIdentifier2.Value,
"http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName,
this,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority",
Convert.ToString(securityIdentifier2.IdentifierAuthority,
CultureInfo.
InvariantCulture)));
1318 instanceClaims.
Add(
new Claim(
"http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid", securityIdentifier2.Value,
"http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName,
this,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority",
Convert.ToString(securityIdentifier2.IdentifierAuthority,
CultureInfo.
InvariantCulture)));
1320 else if ((sID_AND_ATTRIBUTES.Attributes & num2) == 16)
1322 if (!flag && StringComparer.Ordinal.Equals(securityIdentifier2.Value, securityIdentifier.Value))
1324 instanceClaims.
Add(
new Claim(
"http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarygroupsid", securityIdentifier2.Value,
"http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName,
this,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority",
Convert.ToString(securityIdentifier2.IdentifierAuthority,
CultureInfo.
InvariantCulture)));
1327 instanceClaims.
Add(
new Claim(
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/denyonlysid", securityIdentifier2.Value,
"http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName,
this,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority",
Convert.ToString(securityIdentifier2.IdentifierAuthority,
CultureInfo.
InvariantCulture)));
1329 intPtr =
new IntPtr((
long)intPtr + Win32Native.SID_AND_ATTRIBUTES.SizeOf);
1334 safeLocalAllocHandle.Close();
1335 safeLocalAllocHandle2.Close();
1341 private void AddPrimarySidClaim(
List<Claim> instanceClaims)
1343 if (!m_safeTokenHandle.IsInvalid)
1345 SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
1348 safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenUser);
1349 Win32Native.SID_AND_ATTRIBUTES sID_AND_ATTRIBUTES = (Win32Native.SID_AND_ATTRIBUTES)
Marshal.
PtrToStructure(safeLocalAllocHandle.DangerousGetHandle(), typeof(Win32Native.SID_AND_ATTRIBUTES));
1351 SecurityIdentifier securityIdentifier =
new SecurityIdentifier(sID_AND_ATTRIBUTES.Sid, noDemand:
true);
1352 if (sID_AND_ATTRIBUTES.Attributes == 0)
1354 instanceClaims.
Add(
new Claim(
"http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid", securityIdentifier.Value,
"http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName,
this,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority",
Convert.ToString(securityIdentifier.IdentifierAuthority,
CultureInfo.
InvariantCulture)));
1356 else if ((sID_AND_ATTRIBUTES.Attributes & num) == 16)
1358 instanceClaims.
Add(
new Claim(
"http://schemas.microsoft.com/ws/2008/06/identity/claims/denyonlyprimarysid", securityIdentifier.Value,
"http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName,
this,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/windowssubauthority",
Convert.ToString(securityIdentifier.IdentifierAuthority,
CultureInfo.
InvariantCulture)));
1363 safeLocalAllocHandle.Close();
1369 private void AddTokenClaims(
List<Claim> instanceClaims, TokenInformationClass tokenInformationClass,
string propertyValue)
1371 if (!m_safeTokenHandle.IsInvalid)
1373 SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
1376 SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle;
1377 safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, tokenInformationClass);
1378 Win32Native.CLAIM_SECURITY_ATTRIBUTES_INFORMATION cLAIM_SECURITY_ATTRIBUTES_INFORMATION = (Win32Native.CLAIM_SECURITY_ATTRIBUTES_INFORMATION)
Marshal.
PtrToStructure(safeLocalAllocHandle.DangerousGetHandle(), typeof(Win32Native.CLAIM_SECURITY_ATTRIBUTES_INFORMATION));
1380 for (
int i = 0; i < cLAIM_SECURITY_ATTRIBUTES_INFORMATION.AttributeCount; i++)
1382 IntPtr ptr =
new IntPtr(cLAIM_SECURITY_ATTRIBUTES_INFORMATION.Attribute.pAttributeV1.ToInt64() + num);
1383 Win32Native.CLAIM_SECURITY_ATTRIBUTE_V1 cLAIM_SECURITY_ATTRIBUTE_V = (Win32Native.CLAIM_SECURITY_ATTRIBUTE_V1)
Marshal.
PtrToStructure(ptr, typeof(Win32Native.CLAIM_SECURITY_ATTRIBUTE_V1));
1384 switch (cLAIM_SECURITY_ATTRIBUTE_V.ValueType)
1388 IntPtr[] array4 =
new IntPtr[cLAIM_SECURITY_ATTRIBUTE_V.ValueCount];
1389 Marshal.
Copy(cLAIM_SECURITY_ATTRIBUTE_V.Values.ppString, array4, 0, (
int)cLAIM_SECURITY_ATTRIBUTE_V.ValueCount);
1390 for (
int m = 0; m < cLAIM_SECURITY_ATTRIBUTE_V.ValueCount; m++)
1392 instanceClaims.
Add(
new Claim(cLAIM_SECURITY_ATTRIBUTE_V.Name,
Marshal.
PtrToStringAuto(array4[m]),
"http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName,
this, propertyValue,
string.Empty));
1398 long[] array2 =
new long[cLAIM_SECURITY_ATTRIBUTE_V.ValueCount];
1399 Marshal.
Copy(cLAIM_SECURITY_ATTRIBUTE_V.Values.pInt64, array2, 0, (
int)cLAIM_SECURITY_ATTRIBUTE_V.ValueCount);
1400 for (
int k = 0; k < cLAIM_SECURITY_ATTRIBUTE_V.ValueCount; k++)
1402 instanceClaims.
Add(
new Claim(cLAIM_SECURITY_ATTRIBUTE_V.Name,
Convert.ToString(array2[k],
CultureInfo.
InvariantCulture),
"http://www.w3.org/2001/XMLSchema#integer64", m_issuerName, m_issuerName,
this, propertyValue,
string.Empty));
1408 long[] array3 =
new long[cLAIM_SECURITY_ATTRIBUTE_V.ValueCount];
1409 Marshal.
Copy(cLAIM_SECURITY_ATTRIBUTE_V.Values.pUint64, array3, 0, (
int)cLAIM_SECURITY_ATTRIBUTE_V.ValueCount);
1410 for (
int l = 0; l < cLAIM_SECURITY_ATTRIBUTE_V.ValueCount; l++)
1412 instanceClaims.
Add(
new Claim(cLAIM_SECURITY_ATTRIBUTE_V.Name,
Convert.ToString((ulong)array3[l],
CultureInfo.
InvariantCulture),
"http://www.w3.org/2001/XMLSchema#uinteger64", m_issuerName, m_issuerName,
this, propertyValue,
string.Empty));
1418 long[] array =
new long[cLAIM_SECURITY_ATTRIBUTE_V.ValueCount];
1419 Marshal.
Copy(cLAIM_SECURITY_ATTRIBUTE_V.Values.pUint64, array, 0, (
int)cLAIM_SECURITY_ATTRIBUTE_V.ValueCount);
1420 for (
int j = 0; j < cLAIM_SECURITY_ATTRIBUTE_V.ValueCount; j++)
1432 safeLocalAllocHandle.Close();
Represents a character encoding.To browse the .NET Framework source code for this type,...
static Thread CurrentThread
Gets the currently running thread.
static CultureInfo InvariantCulture
Gets the T:System.Globalization.CultureInfo object that is culture-independent (invariant).
TokenImpersonationLevel ImpersonationLevel
Gets the impersonation level for the user.
static int ReadInt32([In] [MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
Reads a 32-bit signed integer at a given offset from unmanaged memory.
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
Describes a set of security permissions applied to code. This class cannot be inherited.
WindowsIdentity(IntPtr userToken, string type)
Initializes a new instance of the T:System.Security.Principal.WindowsIdentity class for the user repr...
virtual byte [] GetBytes(char[] chars)
When overridden in a derived class, encodes all the characters in the specified character array into ...
virtual WindowsImpersonationContext Impersonate()
Impersonates the user represented by the T:System.Security.Principal.WindowsIdentity object.
WindowsAccountType
Specifies the type of Windows account used.
static IntPtr OffsetOf(Type t, string fieldName)
Returns the field offset of the unmanaged form of the managed class.
override bool? IsAuthenticated
Gets a value indicating whether the user has been authenticated by Windows.
void Add(IdentityReference identity)
Adds an T:System.Security.Principal.IdentityReference object to the T:System.Security....
ReadOnlyCollection< T > AsReadOnly()
Returns a read-only T:System.Collections.ObjectModel.ReadOnlyCollection`1 wrapper for the current col...
static Encoding Unicode
Gets an encoding for the UTF-16 format using the little endian byte order.
Provides a mechanism for releasing unmanaged resources.To browse the .NET Framework source code for t...
Indicates that a class is to be notified when deserialization of the entire object graph has been com...
BindingFlags
Specifies flags that control binding and the way in which the search for members and types is conduct...
static WindowsIdentity GetCurrent()
Returns a T:System.Security.Principal.WindowsIdentity object that represents the current Windows user...
unsafe long ToInt64()
Converts the value of this instance to a 64-bit signed integer.
static int SizeOf(object structure)
Returns the unmanaged size of an object in bytes.
TokenImpersonationLevel
Defines security impersonation levels. Security impersonation levels govern the degree to which a ser...
static void KeepAlive(object obj)
References the specified object, which makes it ineligible for garbage collection from the start of t...
new const string DefaultIssuer
Identifies the name of the default T:System.Security.Claims.ClaimsIdentity issuer.
WindowsIdentity(IntPtr userToken)
Initializes a new instance of the T:System.Security.Principal.WindowsIdentity class for the user repr...
virtual bool IsGuest
Gets a value indicating whether the user account is identified as a F:System.Security....
static WindowsIdentity GetAnonymous()
Returns a T:System.Security.Principal.WindowsIdentity object that you can use as a sentinel value in ...
static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess)
Returns a T:System.Security.Principal.WindowsIdentity object that represents the current Windows user...
delegate void Action()
Encapsulates a method that has no parameters and does not return a value.
Describes the source and destination of a given serialized stream, and provides an additional caller-...
IdentityReferenceCollection Groups
Gets the groups the current Windows user belongs to.
WindowsIdentity(WindowsIdentity identity)
Initializes a new instance of the T:System.Security.Principal.WindowsIdentity class by using the spec...
override ClaimsIdentity Clone()
Creates a new object that is a copy of the current instance.
static Encoding ASCII
Gets an encoding for the ASCII (7-bit) character set.
virtual IEnumerable< Claim > UserClaims
Gets claims that have the F:System.Security.Claims.ClaimTypes.WindowsUserClaim property key.
sealed override string AuthenticationType
Gets the type of authentication used to identify the user.
Represents a Windows user.
void Add(T item)
Adds an object to the end of the T:System.Collections.Generic.List`1.
SecurityAction
Specifies the security actions that can be performed using declarative security.
Provides information about, and means to manipulate, the current environment and platform....
IDictionary< string, string > Properties
Gets a dictionary that contains additional properties associated with this claim.
Manages the execution context for the current thread. This class cannot be inherited.
static void Copy(int[] source, int startIndex, IntPtr destination, int length)
Copies data from a one-dimensional, managed 32-bit signed integer array to an unmanaged memory pointe...
virtual bool IsAnonymous
Gets a value that indicates whether the user account is identified as an anonymous account by the sys...
static T RunImpersonated< T >(SafeAccessTokenHandle safeAccessTokenHandle, Func< T > func)
Runs the specified function as the impersonated Windows identity. Instead of using an impersonated me...
A cast or conversion operation, such as (SampleType)obj in C::or CType(obj, SampleType) in Visual Bas...
abstract override string ToString()
Returns the string representation of the identity represented by the T:System.Security....
void OnDeserialization(object sender)
Runs when the entire object graph has been deserialized.
static int CompareExchange(ref int location1, int value, int comparand)
Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.
virtual ClaimsIdentity Clone()
Returns a new T:System.Security.Claims.ClaimsIdentity copied from this claims identity.
virtual IntPtr Token
Gets the Windows account token for the user.
A platform-specific type that is used to represent a pointer or a handle.
void Dispose()
Releases all resources used by the T:System.Security.Principal.WindowsIdentity.
Represents a claims-based identity.
static void PrepareConstrainedRegions()
Designates a body of code as a constrained execution region (CER).
static string PtrToStringAuto(IntPtr ptr, int len)
Allocates a managed T:System.String and copies the specified number of characters from a string store...
SafeAccessTokenHandle AccessToken
Gets this T:Microsoft.Win32.SafeHandles.SafeAccessTokenHandle for this T:System.Security....
unsafe int ToInt32()
Converts the value of this instance to a 32-bit signed integer.
Represents type declarations: class types, interface types, array types, value types,...
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks,...
WindowsIdentity(string sUserPrincipalName)
Initializes a new instance of the T:System.Security.Principal.WindowsIdentity class for the user repr...
MethodImplOptions
Defines the details of how a method is implemented.
Represents a collection of T:System.Security.Principal.IdentityReference objects and provides a means...
virtual IEnumerable< Claim > DeviceClaims
Gets claims that have the F:System.Security.Claims.ClaimTypes.WindowsDeviceClaim property key.
override string Name
Gets the user's Windows logon name.
Stores all the data needed to serialize or deserialize an object. This class cannot be inherited.
Controls the system garbage collector, a service that automatically reclaims unused memory.
WindowsIdentity(SerializationInfo info, StreamingContext context)
Initializes a new instance of the T:System.Security.Principal.WindowsIdentity class for the user repr...
The exception that is thrown when one of the arguments provided to a method is not valid.
WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType)
Initializes a new instance of the T:System.Security.Principal.WindowsIdentity class for the user repr...
static unsafe string PtrToStringUni(IntPtr ptr, int len)
Allocates a managed T:System.String and copies a specified number of characters from an unmanaged Uni...
Allows an object to control its own serialization and deserialization.
override IEnumerable< Claim > Claims
Gets all claims for the user represented by this Windows identity.
static void PtrToStructure(IntPtr ptr, object structure)
Marshals data from an unmanaged block of memory to a managed object.
Represents a security identifier (SID) and provides marshaling and comparison operations for SIDs.
static readonly IntPtr Zero
A read-only field that represents a pointer or handle that has been initialized to zero.
WindowsIdentity(string sUserPrincipalName, string type)
Initializes a new instance of the T:System.Security.Principal.WindowsIdentity class for the user repr...
Specifies that the class can be serialized.
void Add(TKey key, TValue value)
Adds an element with the provided key and value to the T:System.Collections.Generic....
The exception that is thrown when a method call is invalid for the object's current state.
static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
Runs the specified action as the impersonated Windows identity. Instead of using an impersonated meth...
Provides information about a specific culture (called a locale for unmanaged code development)....
static int GetLastWin32Error()
Returns the error code returned by the last unmanaged function that was called using platform invoke ...
The exception that is thrown when a method in the N:System.Security.AccessControl namespace attempts ...
SecurityIdentifier User
Gets the security identifier (SID) for the user.
SecurityPermissionFlag
Specifies access flags for the security permission object.
static WindowsIdentity GetCurrent(bool ifImpersonating)
Returns a T:System.Security.Principal.WindowsIdentity object that represents the Windows identity for...
SecurityIdentifier Owner
Gets the security identifier (SID) for the token owner.
void GetObjectData(SerializationInfo info, StreamingContext context)
Populates a T:System.Runtime.Serialization.SerializationInfo with the data needed to serialize the ta...
Provides atomic operations for variables that are shared by multiple threads.
The exception that is thrown when a security error is detected.
TokenAccessLevels
Defines the privileges of the user account associated with the access token.
virtual void Dispose(bool disposing)
Releases the unmanaged resources used by the T:System.Security.Principal.WindowsIdentity and optional...
virtual bool IsSystem
Gets a value indicating whether the user account is identified as a F:System.Security....
Represents the Windows user prior to an impersonation operation.
Provides a set of static methods and properties that provide support for compilers....
static WindowsImpersonationContext Impersonate(IntPtr userToken)
Impersonates the user represented by the specified user token.
override IdentityReference Translate(Type targetType)
Translates the account name represented by the T:System.Security.Principal.SecurityIdentifier object ...
Creates and controls a thread, sets its priority, and gets its status.