mscorlib(4.0.0.0) API with additions
WindowsIdentity.cs
1 using Microsoft.Win32;
2 using Microsoft.Win32.SafeHandles;
5 using System.Reflection;
11 using System.Security.Claims;
13 using System.Text;
14 using System.Threading;
15 
17 {
19  [Serializable]
20  [ComVisible(true)]
22  {
23  [SecurityCritical]
24  private static SafeAccessTokenHandle s_invalidTokenHandle;
25 
26  private string m_name;
27 
28  private SecurityIdentifier m_owner;
29 
30  private SecurityIdentifier m_user;
31 
32  private object m_groups;
33 
34  [SecurityCritical]
35  private SafeAccessTokenHandle m_safeTokenHandle = SafeAccessTokenHandle.InvalidHandle;
36 
37  private string m_authType;
38 
39  private int m_isAuthenticated = -1;
40 
41  private volatile TokenImpersonationLevel m_impersonationLevel;
42 
43  private volatile bool m_impersonationLevelInitialized;
44 
45  private static RuntimeConstructorInfo s_specialSerializationCtor;
46 
48  [NonSerialized]
49  public new const string DefaultIssuer = "AD AUTHORITY";
50 
51  [NonSerialized]
52  private string m_issuerName = "AD AUTHORITY";
53 
54  [NonSerialized]
55  private object m_claimsIntiailizedLock = new object();
56 
57  [NonSerialized]
58  private volatile bool m_claimsInitialized;
59 
60  [NonSerialized]
61  private List<Claim> m_deviceClaims;
62 
63  [NonSerialized]
64  private List<Claim> m_userClaims;
65 
71  public sealed override string AuthenticationType
72  {
73  [SecuritySafeCritical]
74  get
75  {
76  if (m_safeTokenHandle.IsInvalid)
77  {
78  return string.Empty;
79  }
80  if (m_authType == null)
81  {
82  Win32Native.LUID LogonId = GetLogonAuthId(m_safeTokenHandle);
83  if (LogonId.LowPart == 998)
84  {
85  return string.Empty;
86  }
87  SafeLsaReturnBufferHandle ppLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle;
88  try
89  {
90  int num = Win32Native.LsaGetLogonSessionData(ref LogonId, ref ppLogonSessionData);
91  if (num < 0)
92  {
93  throw GetExceptionFromNtStatus(num);
94  }
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);
97  return Marshal.PtrToStringUni(sECURITY_LOGON_SESSION_DATA.AuthenticationPackage.Buffer);
98  }
99  finally
100  {
101  if (!ppLogonSessionData.IsInvalid)
102  {
103  ppLogonSessionData.Dispose();
104  }
105  }
106  }
107  return m_authType;
108  }
109  }
110 
113  [ComVisible(false)]
115  {
116  [SecuritySafeCritical]
117  get
118  {
119  if (!m_impersonationLevelInitialized)
120  {
121  TokenImpersonationLevel tokenImpersonationLevel = TokenImpersonationLevel.None;
122  if (m_safeTokenHandle.IsInvalid)
123  {
124  tokenImpersonationLevel = TokenImpersonationLevel.Anonymous;
125  }
126  else
127  {
128  TokenType tokenInformation = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType);
129  if (tokenInformation == TokenType.TokenPrimary)
130  {
131  tokenImpersonationLevel = TokenImpersonationLevel.None;
132  }
133  else
134  {
135  int tokenInformation2 = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel);
136  tokenImpersonationLevel = (TokenImpersonationLevel)(tokenInformation2 + 1);
137  }
138  }
139  m_impersonationLevel = tokenImpersonationLevel;
140  m_impersonationLevelInitialized = true;
141  }
142  return m_impersonationLevel;
143  }
144  }
145 
149  public override bool IsAuthenticated
150  {
151  get
152  {
153  if (m_isAuthenticated == -1)
154  {
155  m_isAuthenticated = (CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[1]
156  {
157  11
158  })) ? 1 : 0);
159  }
160  return m_isAuthenticated == 1;
161  }
162  }
163 
167  public virtual bool IsGuest
168  {
169  [SecuritySafeCritical]
170  get
171  {
172  if (m_safeTokenHandle.IsInvalid)
173  {
174  return false;
175  }
176  return CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[2]
177  {
178  32,
179  546
180  }));
181  }
182  }
183 
187  public virtual bool IsSystem
188  {
189  [SecuritySafeCritical]
190  get
191  {
192  if (m_safeTokenHandle.IsInvalid)
193  {
194  return false;
195  }
196  SecurityIdentifier right = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[1]
197  {
198  18
199  });
200  return User == right;
201  }
202  }
203 
207  public virtual bool IsAnonymous
208  {
209  [SecuritySafeCritical]
210  get
211  {
212  if (m_safeTokenHandle.IsInvalid)
213  {
214  return true;
215  }
216  SecurityIdentifier right = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[1]
217  {
218  7
219  });
220  return User == right;
221  }
222  }
223 
226  public override string Name
227  {
228  [SecuritySafeCritical]
229  get
230  {
231  return GetName();
232  }
233  }
234 
237  [ComVisible(false)]
239  {
240  [SecuritySafeCritical]
241  get
242  {
243  if (m_safeTokenHandle.IsInvalid)
244  {
245  return null;
246  }
247  if (m_owner == null)
248  {
249  using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenOwner))
250  {
251  m_owner = new SecurityIdentifier(safeLocalAllocHandle.Read<IntPtr>(0uL), noDemand: true);
252  }
253  }
254  return m_owner;
255  }
256  }
257 
260  [ComVisible(false)]
261  public SecurityIdentifier User
262  {
263  [SecuritySafeCritical]
264  get
265  {
266  if (m_safeTokenHandle.IsInvalid)
267  {
268  return null;
269  }
270  if (m_user == null)
271  {
272  using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenUser))
273  {
274  m_user = new SecurityIdentifier(safeLocalAllocHandle.Read<IntPtr>(0uL), noDemand: true);
275  }
276  }
277  return m_user;
278  }
279  }
280 
284  {
285  [SecuritySafeCritical]
286  get
287  {
288  if (m_safeTokenHandle.IsInvalid)
289  {
290  return null;
291  }
292  if (m_groups == null)
293  {
294  IdentityReferenceCollection identityReferenceCollection = new IdentityReferenceCollection();
295  using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenGroups))
296  {
297  if (safeLocalAllocHandle.Read<uint>(0uL) != 0)
298  {
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)
304  {
305  uint num = 3221225492u;
306  if ((sID_AND_ATTRIBUTES.Attributes & num) == 4)
307  {
308  identityReferenceCollection.Add(new SecurityIdentifier(sID_AND_ATTRIBUTES.Sid, noDemand: true));
309  }
310  }
311  }
312  }
313  Interlocked.CompareExchange(ref m_groups, identityReferenceCollection, null);
314  }
315  return m_groups as IdentityReferenceCollection;
316  }
317  }
318 
321  public virtual IntPtr Token
322  {
323  [SecuritySafeCritical]
324  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
325  get
326  {
327  return m_safeTokenHandle.DangerousGetHandle();
328  }
329  }
330 
333  public SafeAccessTokenHandle AccessToken
334  {
335  [SecurityCritical]
336  get
337  {
338  return m_safeTokenHandle;
339  }
340  }
341 
344  public virtual IEnumerable<Claim> UserClaims
345  {
346  get
347  {
348  InitializeClaims();
349  return m_userClaims.AsReadOnly();
350  }
351  }
352 
355  public virtual IEnumerable<Claim> DeviceClaims
356  {
357  get
358  {
359  InitializeClaims();
360  return m_deviceClaims.AsReadOnly();
361  }
362  }
363 
366  public override IEnumerable<Claim> Claims
367  {
368  get
369  {
370  if (!m_claimsInitialized)
371  {
372  InitializeClaims();
373  }
374  foreach (Claim claim in base.Claims)
375  {
376  yield return claim;
377  }
378  foreach (Claim userClaim in m_userClaims)
379  {
380  yield return userClaim;
381  }
382  foreach (Claim deviceClaim in m_deviceClaims)
383  {
384  yield return deviceClaim;
385  }
386  }
387  }
388 
389  [SecuritySafeCritical]
390  static WindowsIdentity()
391  {
392  s_invalidTokenHandle = SafeAccessTokenHandle.InvalidHandle;
393  s_specialSerializationCtor = (typeof(WindowsIdentity).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[1]
394  {
395  typeof(SerializationInfo)
396  }, null) as RuntimeConstructorInfo);
397  }
398 
399  [SecurityCritical]
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")
402  {
403  }
404 
405  [SecurityCritical]
406  internal WindowsIdentity(SafeAccessTokenHandle safeTokenHandle)
407  : this(safeTokenHandle.DangerousGetHandle(), null, -1)
408  {
409  GC.KeepAlive(safeTokenHandle);
410  }
411 
418  [SecuritySafeCritical]
419  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
420  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
421  public WindowsIdentity(IntPtr userToken)
422  : this(userToken, null, -1)
423  {
424  }
425 
433  [SecuritySafeCritical]
434  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
435  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
436  public WindowsIdentity(IntPtr userToken, string type)
437  : this(userToken, type, -1)
438  {
439  }
440 
449  [SecuritySafeCritical]
450  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
451  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
452  public WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType)
453  : this(userToken, type, -1)
454  {
455  }
456 
467  [SecuritySafeCritical]
468  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
469  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
470  public WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType, bool isAuthenticated)
471  : this(userToken, type, isAuthenticated ? 1 : 0)
472  {
473  }
474 
475  [SecurityCritical]
476  private WindowsIdentity(IntPtr userToken, string authType, int isAuthenticated)
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")
478  {
479  CreateFromToken(userToken);
480  m_authType = authType;
481  m_isAuthenticated = isAuthenticated;
482  }
483 
484  [SecurityCritical]
485  private void CreateFromToken(IntPtr userToken)
486  {
487  if (userToken == IntPtr.Zero)
488  {
489  throw new ArgumentException(Environment.GetResourceString("Argument_TokenZero"));
490  }
491  uint ReturnLength = (uint)Marshal.SizeOf(typeof(uint));
492  bool tokenInformation = Win32Native.GetTokenInformation(userToken, 8u, SafeLocalAllocHandle.InvalidHandle, 0u, out ReturnLength);
493  if (Marshal.GetLastWin32Error() == 6)
494  {
495  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidImpersonationToken"));
496  }
497  if (!Win32Native.DuplicateHandle(Win32Native.GetCurrentProcess(), userToken, Win32Native.GetCurrentProcess(), ref m_safeTokenHandle, 0u, bInheritHandle: true, 2u))
498  {
499  throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
500  }
501  }
502 
508  [SecuritySafeCritical]
509  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
510  public WindowsIdentity(string sUserPrincipalName)
511  : this(sUserPrincipalName, null)
512  {
513  }
514 
521  [SecuritySafeCritical]
522  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
523  public WindowsIdentity(string sUserPrincipalName, string type)
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")
525  {
526  KerbS4ULogon(sUserPrincipalName, ref m_safeTokenHandle);
527  }
528 
534  [SecuritySafeCritical]
535  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
536  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.SerializationFormatter)]
538  : this(info)
539  {
540  }
541 
542  [SecurityCritical]
543  private WindowsIdentity(SerializationInfo info)
544  : base(info)
545  {
546  m_claimsInitialized = false;
547  IntPtr intPtr = (IntPtr)info.GetValue("m_userToken", typeof(IntPtr));
548  if (intPtr != IntPtr.Zero)
549  {
550  CreateFromToken(intPtr);
551  }
552  }
553 
557  [SecurityCritical]
559  {
560  base.GetObjectData(info, context);
561  info.AddValue("m_userToken", m_safeTokenHandle.DangerousGetHandle());
562  }
563 
566  void IDeserializationCallback.OnDeserialization(object sender)
567  {
568  }
569 
573  [SecuritySafeCritical]
574  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
575  public static WindowsIdentity GetCurrent()
576  {
577  return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, threadOnly: false);
578  }
579 
584  [SecuritySafeCritical]
585  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
586  public static WindowsIdentity GetCurrent(bool ifImpersonating)
587  {
588  return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, ifImpersonating);
589  }
590 
594  [SecuritySafeCritical]
595  [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
596  public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess)
597  {
598  return GetCurrentInternal(desiredAccess, threadOnly: false);
599  }
600 
603  [SecuritySafeCritical]
605  {
606  return new WindowsIdentity();
607  }
608 
609  [SecuritySafeCritical]
610  [ComVisible(false)]
611  private bool CheckNtTokenForSid(SecurityIdentifier sid)
612  {
613  if (m_safeTokenHandle.IsInvalid)
614  {
615  return false;
616  }
617  SafeAccessTokenHandle phNewToken = SafeAccessTokenHandle.InvalidHandle;
618  TokenImpersonationLevel impersonationLevel = ImpersonationLevel;
619  bool IsMember = false;
620  try
621  {
622  if (impersonationLevel == TokenImpersonationLevel.None && !Win32Native.DuplicateTokenEx(m_safeTokenHandle, 8u, IntPtr.Zero, 2u, 2u, ref phNewToken))
623  {
624  throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
625  }
626  if (!Win32Native.CheckTokenMembership((impersonationLevel != 0) ? m_safeTokenHandle : phNewToken, sid.BinaryForm, ref IsMember))
627  {
628  throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
629  }
630  return IsMember;
631  }
632  finally
633  {
634  if (phNewToken != SafeAccessTokenHandle.InvalidHandle)
635  {
636  phNewToken.Dispose();
637  }
638  }
639  }
640 
641  [MethodImpl(MethodImplOptions.NoInlining)]
642  [SecurityCritical]
643  internal string GetName()
644  {
645  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
646  if (m_safeTokenHandle.IsInvalid)
647  {
648  return string.Empty;
649  }
650  if (m_name == null)
651  {
652  using (SafeRevertToSelf(ref stackMark))
653  {
654  NTAccount nTAccount = User.Translate(typeof(NTAccount)) as NTAccount;
655  m_name = nTAccount.ToString();
656  }
657  }
658  return m_name;
659  }
660 
664  [MethodImpl(MethodImplOptions.NoInlining)]
665  [SecuritySafeCritical]
666  public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
667  {
668  if (action == null)
669  {
670  throw new ArgumentNullException("action");
671  }
672  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
673  WindowsIdentity wi = null;
674  if (!safeAccessTokenHandle.IsInvalid)
675  {
676  wi = new WindowsIdentity(safeAccessTokenHandle);
677  }
678  using (SafeImpersonate(safeAccessTokenHandle, wi, ref stackMark))
679  {
680  action();
681  }
682  }
683 
689  [MethodImpl(MethodImplOptions.NoInlining)]
690  [SecuritySafeCritical]
691  public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func)
692  {
693  if (func == null)
694  {
695  throw new ArgumentNullException("func");
696  }
697  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
698  WindowsIdentity wi = null;
699  if (!safeAccessTokenHandle.IsInvalid)
700  {
701  wi = new WindowsIdentity(safeAccessTokenHandle);
702  }
703  T val = default(T);
704  using (SafeImpersonate(safeAccessTokenHandle, wi, ref stackMark))
705  {
706  return func();
707  }
708  }
709 
714  [MethodImpl(MethodImplOptions.NoInlining)]
715  [SecuritySafeCritical]
717  {
718  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
719  return Impersonate(ref stackMark);
720  }
721 
728  [MethodImpl(MethodImplOptions.NoInlining)]
729  [SecuritySafeCritical]
730  [SecurityPermission(SecurityAction.Demand, Flags = (SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.ControlPrincipal))]
732  {
733  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
734  if (userToken == IntPtr.Zero)
735  {
736  return SafeRevertToSelf(ref stackMark);
737  }
738  WindowsIdentity windowsIdentity = new WindowsIdentity(userToken, null, -1);
739  return windowsIdentity.Impersonate(ref stackMark);
740  }
741 
742  [SecurityCritical]
743  internal WindowsImpersonationContext Impersonate(ref StackCrawlMark stackMark)
744  {
745  if (m_safeTokenHandle.IsInvalid)
746  {
747  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AnonymousCannotImpersonate"));
748  }
749  return SafeImpersonate(m_safeTokenHandle, this, ref stackMark);
750  }
751 
755  [SecuritySafeCritical]
756  [ComVisible(false)]
757  protected virtual void Dispose(bool disposing)
758  {
759  if (disposing && m_safeTokenHandle != null && !m_safeTokenHandle.IsClosed)
760  {
761  m_safeTokenHandle.Dispose();
762  }
763  m_name = null;
764  m_owner = null;
765  m_user = null;
766  }
767 
769  [ComVisible(false)]
770  public void Dispose()
771  {
772  Dispose(disposing: true);
773  }
774 
775  [SecurityCritical]
776  internal static WindowsImpersonationContext SafeRevertToSelf(ref StackCrawlMark stackMark)
777  {
778  return SafeImpersonate(s_invalidTokenHandle, null, ref stackMark);
779  }
780 
781  [SecurityCritical]
782  internal static WindowsImpersonationContext SafeImpersonate(SafeAccessTokenHandle userToken, WindowsIdentity wi, ref StackCrawlMark stackMark)
783  {
784  int hr = 0;
785  bool isImpersonating;
786  SafeAccessTokenHandle currentToken = GetCurrentToken(TokenAccessLevels.MaximumAllowed, threadOnly: false, out isImpersonating, out hr);
787  if (currentToken == null || currentToken.IsInvalid)
788  {
789  throw new SecurityException(Win32Native.GetMessage(hr));
790  }
791  FrameSecurityDescriptor securityObjectForFrame = SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, create: true);
792  if (securityObjectForFrame == null)
793  {
794  throw new SecurityException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
795  }
796  WindowsImpersonationContext windowsImpersonationContext = new WindowsImpersonationContext(currentToken, GetCurrentThreadWI(), isImpersonating, securityObjectForFrame);
797  if (userToken.IsInvalid)
798  {
799  hr = Win32.RevertToSelf();
800  if (hr < 0)
801  {
802  Environment.FailFast(Win32Native.GetMessage(hr));
803  }
804  UpdateThreadWI(wi);
805  securityObjectForFrame.SetTokenHandles(currentToken, wi?.AccessToken);
806  }
807  else
808  {
809  hr = Win32.RevertToSelf();
810  if (hr < 0)
811  {
812  Environment.FailFast(Win32Native.GetMessage(hr));
813  }
814  hr = Win32.ImpersonateLoggedOnUser(userToken);
815  if (hr < 0)
816  {
817  windowsImpersonationContext.Undo();
818  throw new SecurityException(Environment.GetResourceString("Argument_ImpersonateUser"));
819  }
820  UpdateThreadWI(wi);
821  securityObjectForFrame.SetTokenHandles(currentToken, wi?.AccessToken);
822  }
823  return windowsImpersonationContext;
824  }
825 
826  [SecurityCritical]
827  internal static WindowsIdentity GetCurrentThreadWI()
828  {
829  return SecurityContext.GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader());
830  }
831 
832  [SecurityCritical]
833  internal static void UpdateThreadWI(WindowsIdentity wi)
834  {
835  Thread currentThread = Thread.CurrentThread;
836  if (currentThread.GetExecutionContextReader().SecurityContext.WindowsIdentity != wi)
837  {
838  ExecutionContext mutableExecutionContext = currentThread.GetMutableExecutionContext();
839  SecurityContext securityContext = mutableExecutionContext.SecurityContext;
840  if (wi != null && securityContext == null)
841  {
842  securityContext = (mutableExecutionContext.SecurityContext = new SecurityContext());
843  }
844  if (securityContext != null)
845  {
846  securityContext.WindowsIdentity = wi;
847  }
848  }
849  }
850 
851  [SecurityCritical]
852  internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess, bool threadOnly)
853  {
854  int hr = 0;
855  bool isImpersonating;
856  SafeAccessTokenHandle currentToken = GetCurrentToken(desiredAccess, threadOnly, out isImpersonating, out hr);
857  if (currentToken == null || currentToken.IsInvalid)
858  {
859  if (threadOnly && !isImpersonating)
860  {
861  return null;
862  }
863  throw new SecurityException(Win32Native.GetMessage(hr));
864  }
865  WindowsIdentity windowsIdentity = new WindowsIdentity();
866  windowsIdentity.m_safeTokenHandle.Dispose();
867  windowsIdentity.m_safeTokenHandle = currentToken;
868  return windowsIdentity;
869  }
870 
871  internal static RuntimeConstructorInfo GetSpecialSerializationCtor()
872  {
873  return s_specialSerializationCtor;
874  }
875 
876  private static int GetHRForWin32Error(int dwLastError)
877  {
878  if ((dwLastError & 2147483648u) == 2147483648u)
879  {
880  return dwLastError;
881  }
882  return (dwLastError & 0xFFFF) | -2147024896;
883  }
884 
885  [SecurityCritical]
886  private static Exception GetExceptionFromNtStatus(int status)
887  {
888  switch (status)
889  {
890  case -1073741790:
891  return new UnauthorizedAccessException();
892  case -1073741801:
893  case -1073741670:
894  return new OutOfMemoryException();
895  default:
896  {
897  int errorCode = Win32Native.LsaNtStatusToWinError(status);
898  return new SecurityException(Win32Native.GetMessage(errorCode));
899  }
900  }
901  }
902 
903  [SecurityCritical]
904  private static SafeAccessTokenHandle GetCurrentToken(TokenAccessLevels desiredAccess, bool threadOnly, out bool isImpersonating, out int hr)
905  {
906  isImpersonating = true;
907  SafeAccessTokenHandle safeAccessTokenHandle = GetCurrentThreadToken(desiredAccess, out hr);
908  if (safeAccessTokenHandle == null && hr == GetHRForWin32Error(1008))
909  {
910  isImpersonating = false;
911  if (!threadOnly)
912  {
913  safeAccessTokenHandle = GetCurrentProcessToken(desiredAccess, out hr);
914  }
915  }
916  return safeAccessTokenHandle;
917  }
918 
919  [SecurityCritical]
920  private static SafeAccessTokenHandle GetCurrentProcessToken(TokenAccessLevels desiredAccess, out int hr)
921  {
922  hr = 0;
923  if (!Win32Native.OpenProcessToken(Win32Native.GetCurrentProcess(), desiredAccess, out SafeAccessTokenHandle TokenHandle))
924  {
925  hr = GetHRForWin32Error(Marshal.GetLastWin32Error());
926  }
927  return TokenHandle;
928  }
929 
930  [SecurityCritical]
931  internal static SafeAccessTokenHandle GetCurrentThreadToken(TokenAccessLevels desiredAccess, out int hr)
932  {
933  hr = Win32.OpenThreadToken(desiredAccess, WinSecurityContext.Both, out SafeAccessTokenHandle phThreadToken);
934  return phThreadToken;
935  }
936 
937  [SecurityCritical]
938  private T GetTokenInformation<T>(TokenInformationClass tokenInformationClass) where T : struct
939  {
940  using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, tokenInformationClass))
941  {
942  return safeLocalAllocHandle.Read<T>(0uL);
943  }
944  }
945 
946  [SecurityCritical]
947  internal static ImpersonationQueryResult QueryImpersonation()
948  {
949  SafeAccessTokenHandle phThreadToken = null;
950  int num = Win32.OpenThreadToken(TokenAccessLevels.Query, WinSecurityContext.Thread, out phThreadToken);
951  if (phThreadToken != null)
952  {
953  phThreadToken.Close();
954  return ImpersonationQueryResult.Impersonated;
955  }
956  if (num == GetHRForWin32Error(5))
957  {
958  return ImpersonationQueryResult.Impersonated;
959  }
960  if (num == GetHRForWin32Error(1008))
961  {
962  return ImpersonationQueryResult.NotImpersonated;
963  }
964  return ImpersonationQueryResult.Failed;
965  }
966 
967  [SecurityCritical]
968  private static Win32Native.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle)
969  {
970  using (SafeLocalAllocHandle safeLocalAllocHandle = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics))
971  {
972  Win32Native.TOKEN_STATISTICS tOKEN_STATISTICS = safeLocalAllocHandle.Read<Win32Native.TOKEN_STATISTICS>(0uL);
973  return tOKEN_STATISTICS.AuthenticationId;
974  }
975  }
976 
977  [SecurityCritical]
978  private static SafeLocalAllocHandle GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass)
979  {
980  SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle;
981  uint ReturnLength = (uint)Marshal.SizeOf(typeof(uint));
982  bool tokenInformation = Win32Native.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, invalidHandle, 0u, out ReturnLength);
983  int lastWin32Error = Marshal.GetLastWin32Error();
984  switch (lastWin32Error)
985  {
986  case 24:
987  case 122:
988  {
989  UIntPtr sizetdwBytes = new UIntPtr(ReturnLength);
990  invalidHandle.Dispose();
991  invalidHandle = Win32Native.LocalAlloc(0, sizetdwBytes);
992  if (invalidHandle == null || invalidHandle.IsInvalid)
993  {
994  throw new OutOfMemoryException();
995  }
996  invalidHandle.Initialize(ReturnLength);
997  if (!Win32Native.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, invalidHandle, ReturnLength, out ReturnLength))
998  {
999  throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
1000  }
1001  return invalidHandle;
1002  }
1003  case 6:
1004  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidImpersonationToken"));
1005  default:
1006  throw new SecurityException(Win32Native.GetMessage(lastWin32Error));
1007  }
1008  }
1009 
1010  [SecurityCritical]
1011  [HandleProcessCorruptedStateExceptions]
1012  private unsafe static SafeAccessTokenHandle KerbS4ULogon(string upn, ref SafeAccessTokenHandle safeTokenHandle)
1013  {
1014  byte[] array = new byte[3]
1015  {
1016  67,
1017  76,
1018  82
1019  };
1020  UIntPtr sizetdwBytes = new UIntPtr((uint)(array.Length + 1));
1021  using (SafeLocalAllocHandle safeLocalAllocHandle = Win32Native.LocalAlloc(64, sizetdwBytes))
1022  {
1023  if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid)
1024  {
1025  throw new OutOfMemoryException();
1026  }
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;
1032  try
1033  {
1034  Privilege privilege = null;
1036  int num;
1037  try
1038  {
1039  try
1040  {
1041  privilege = new Privilege("SeTcbPrivilege");
1042  privilege.Enable();
1043  }
1045  {
1046  }
1047  IntPtr SecurityMode = IntPtr.Zero;
1048  num = Win32Native.LsaRegisterLogonProcess(ref LogonProcessName, ref LsaHandle, ref SecurityMode);
1049  if (5 == Win32Native.LsaNtStatusToWinError(num))
1050  {
1051  num = Win32Native.LsaConnectUntrusted(ref LsaHandle);
1052  }
1053  }
1054  catch
1055  {
1056  privilege?.Revert();
1057  throw;
1058  }
1059  finally
1060  {
1061  privilege?.Revert();
1062  }
1063  if (num < 0)
1064  {
1065  throw GetExceptionFromNtStatus(num);
1066  }
1067  byte[] array2 = new byte["Kerberos".Length + 1];
1068  Encoding.ASCII.GetBytes("Kerberos", 0, "Kerberos".Length, array2, 0);
1069  sizetdwBytes = new UIntPtr((uint)array2.Length);
1070  using (SafeLocalAllocHandle safeLocalAllocHandle2 = Win32Native.LocalAlloc(0, sizetdwBytes))
1071  {
1072  if (safeLocalAllocHandle2 == null || safeLocalAllocHandle2.IsInvalid)
1073  {
1074  throw new OutOfMemoryException();
1075  }
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);
1081  if (num < 0)
1082  {
1083  throw GetExceptionFromNtStatus(num);
1084  }
1085  Win32Native.TOKEN_SOURCE SourceContext = default(Win32Native.TOKEN_SOURCE);
1086  if (!Win32Native.AllocateLocallyUniqueId(ref SourceContext.SourceIdentifier))
1087  {
1088  throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
1089  }
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);
1097  int SubStatus = 0;
1098  byte[] bytes = Encoding.Unicode.GetBytes(upn);
1099  uint num2 = (uint)(Marshal.SizeOf(typeof(Win32Native.KERB_S4U_LOGON)) + bytes.Length);
1100  using (SafeLocalAllocHandle safeLocalAllocHandle3 = Win32Native.LocalAlloc(64, new UIntPtr(num2)))
1101  {
1102  if (safeLocalAllocHandle3 == null || safeLocalAllocHandle3.IsInvalid)
1103  {
1104  throw new OutOfMemoryException();
1105  }
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;
1111  try
1112  {
1113  safeLocalAllocHandle3.AcquirePointer(ref pointer);
1114  Win32Native.KERB_S4U_LOGON value = default(Win32Native.KERB_S4U_LOGON);
1115  value.MessageType = 12u;
1116  value.Flags = 0u;
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)
1121  {
1122  num = SubStatus;
1123  }
1124  if (num < 0)
1125  {
1126  throw GetExceptionFromNtStatus(num);
1127  }
1128  if (SubStatus < 0)
1129  {
1130  throw GetExceptionFromNtStatus(SubStatus);
1131  }
1132  }
1133  finally
1134  {
1135  if (pointer != null)
1136  {
1137  safeLocalAllocHandle3.ReleasePointer();
1138  }
1139  }
1140  }
1141  return safeTokenHandle;
1142  }
1143  }
1144  finally
1145  {
1146  if (!LsaHandle.IsInvalid)
1147  {
1148  LsaHandle.Dispose();
1149  }
1150  if (!ProfileBuffer.IsInvalid)
1151  {
1152  ProfileBuffer.Dispose();
1153  }
1154  }
1155  }
1156  }
1157 
1160  [SecuritySafeCritical]
1161  protected WindowsIdentity(WindowsIdentity identity)
1162  : base(identity, null, identity.m_authType, null, null, checkAuthType: false)
1163  {
1164  if (identity == null)
1165  {
1166  throw new ArgumentNullException("identity");
1167  }
1168  bool success = false;
1170  try
1171  {
1172  if (!identity.m_safeTokenHandle.IsInvalid && identity.m_safeTokenHandle != SafeAccessTokenHandle.InvalidHandle && identity.m_safeTokenHandle.DangerousGetHandle() != IntPtr.Zero)
1173  {
1174  identity.m_safeTokenHandle.DangerousAddRef(ref success);
1175  if (!identity.m_safeTokenHandle.IsInvalid && identity.m_safeTokenHandle.DangerousGetHandle() != IntPtr.Zero)
1176  {
1177  CreateFromToken(identity.m_safeTokenHandle.DangerousGetHandle());
1178  }
1179  m_authType = identity.m_authType;
1180  m_isAuthenticated = identity.m_isAuthenticated;
1181  }
1182  }
1183  finally
1184  {
1185  if (success)
1186  {
1187  identity.m_safeTokenHandle.DangerousRelease();
1188  }
1189  }
1190  }
1191 
1192  [SecurityCritical]
1193  internal IntPtr GetTokenInternal()
1194  {
1195  return m_safeTokenHandle.DangerousGetHandle();
1196  }
1197 
1198  [SecurityCritical]
1199  internal WindowsIdentity(ClaimsIdentity claimsIdentity, IntPtr userToken)
1200  : base(claimsIdentity)
1201  {
1202  if (userToken != IntPtr.Zero && userToken.ToInt64() > 0)
1203  {
1204  CreateFromToken(userToken);
1205  }
1206  }
1207 
1208  internal ClaimsIdentity CloneAsBase()
1209  {
1210  return base.Clone();
1211  }
1212 
1215  public override ClaimsIdentity Clone()
1216  {
1217  return new WindowsIdentity(this);
1218  }
1219 
1220  [SecuritySafeCritical]
1221  private void InitializeClaims()
1222  {
1223  if (!m_claimsInitialized)
1224  {
1225  lock (m_claimsIntiailizedLock)
1226  {
1227  if (!m_claimsInitialized)
1228  {
1229  m_userClaims = new List<Claim>();
1230  m_deviceClaims = new List<Claim>();
1231  if (!string.IsNullOrEmpty(Name))
1232  {
1233  m_userClaims.Add(new Claim(base.NameClaimType, Name, "http://www.w3.org/2001/XMLSchema#string", m_issuerName, m_issuerName, this));
1234  }
1235  AddPrimarySidClaim(m_userClaims);
1236  AddGroupSidClaims(m_userClaims);
1237  if (Environment.IsWindows8OrAbove)
1238  {
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");
1242  }
1243  m_claimsInitialized = true;
1244  }
1245  }
1246  }
1247  }
1248 
1249  [SecurityCritical]
1250  private void AddDeviceGroupSidClaims(List<Claim> instanceClaims, TokenInformationClass tokenInformationClass)
1251  {
1252  if (!m_safeTokenHandle.IsInvalid)
1253  {
1254  SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
1255  try
1256  {
1257  safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, tokenInformationClass);
1258  int num = Marshal.ReadInt32(safeLocalAllocHandle.DangerousGetHandle());
1259  IntPtr intPtr = new IntPtr((long)safeLocalAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(Win32Native.TOKEN_GROUPS), "Groups"));
1260  string text = null;
1261  for (int i = 0; i < num; i++)
1262  {
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)
1267  {
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));
1270  claim.Properties.Add(text, "");
1271  instanceClaims.Add(claim);
1272  }
1273  else if ((sID_AND_ATTRIBUTES.Attributes & num2) == 16)
1274  {
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));
1277  claim2.Properties.Add(text, "");
1278  instanceClaims.Add(claim2);
1279  }
1280  intPtr = new IntPtr((long)intPtr + Win32Native.SID_AND_ATTRIBUTES.SizeOf);
1281  }
1282  }
1283  finally
1284  {
1285  safeLocalAllocHandle.Close();
1286  }
1287  }
1288  }
1289 
1290  [SecurityCritical]
1291  private void AddGroupSidClaims(List<Claim> instanceClaims)
1292  {
1293  if (!m_safeTokenHandle.IsInvalid)
1294  {
1295  SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
1296  SafeLocalAllocHandle safeLocalAllocHandle2 = SafeLocalAllocHandle.InvalidHandle;
1297  try
1298  {
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);
1302  bool flag = false;
1303  safeLocalAllocHandle = GetTokenInformation(m_safeTokenHandle, TokenInformationClass.TokenGroups);
1304  int num = Marshal.ReadInt32(safeLocalAllocHandle.DangerousGetHandle());
1305  IntPtr intPtr = new IntPtr((long)safeLocalAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(Win32Native.TOKEN_GROUPS), "Groups"));
1306  for (int i = 0; i < num; i++)
1307  {
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)
1312  {
1313  if (!flag && StringComparer.Ordinal.Equals(securityIdentifier2.Value, securityIdentifier.Value))
1314  {
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)));
1316  flag = true;
1317  }
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)));
1319  }
1320  else if ((sID_AND_ATTRIBUTES.Attributes & num2) == 16)
1321  {
1322  if (!flag && StringComparer.Ordinal.Equals(securityIdentifier2.Value, securityIdentifier.Value))
1323  {
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)));
1325  flag = true;
1326  }
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)));
1328  }
1329  intPtr = new IntPtr((long)intPtr + Win32Native.SID_AND_ATTRIBUTES.SizeOf);
1330  }
1331  }
1332  finally
1333  {
1334  safeLocalAllocHandle.Close();
1335  safeLocalAllocHandle2.Close();
1336  }
1337  }
1338  }
1339 
1340  [SecurityCritical]
1341  private void AddPrimarySidClaim(List<Claim> instanceClaims)
1342  {
1343  if (!m_safeTokenHandle.IsInvalid)
1344  {
1345  SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
1346  try
1347  {
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));
1350  uint num = 16u;
1351  SecurityIdentifier securityIdentifier = new SecurityIdentifier(sID_AND_ATTRIBUTES.Sid, noDemand: true);
1352  if (sID_AND_ATTRIBUTES.Attributes == 0)
1353  {
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)));
1355  }
1356  else if ((sID_AND_ATTRIBUTES.Attributes & num) == 16)
1357  {
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)));
1359  }
1360  }
1361  finally
1362  {
1363  safeLocalAllocHandle.Close();
1364  }
1365  }
1366  }
1367 
1368  [SecurityCritical]
1369  private void AddTokenClaims(List<Claim> instanceClaims, TokenInformationClass tokenInformationClass, string propertyValue)
1370  {
1371  if (!m_safeTokenHandle.IsInvalid)
1372  {
1373  SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
1374  try
1375  {
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));
1379  long num = 0L;
1380  for (int i = 0; i < cLAIM_SECURITY_ATTRIBUTES_INFORMATION.AttributeCount; i++)
1381  {
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)
1385  {
1386  case 3:
1387  {
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++)
1391  {
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));
1393  }
1394  break;
1395  }
1396  case 1:
1397  {
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++)
1401  {
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));
1403  }
1404  break;
1405  }
1406  case 2:
1407  {
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++)
1411  {
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));
1413  }
1414  break;
1415  }
1416  case 6:
1417  {
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++)
1421  {
1422  instanceClaims.Add(new Claim(cLAIM_SECURITY_ATTRIBUTE_V.Name, (array[j] == 0L) ? Convert.ToString(value: false, CultureInfo.InvariantCulture) : Convert.ToString(value: true, CultureInfo.InvariantCulture), "http://www.w3.org/2001/XMLSchema#boolean", m_issuerName, m_issuerName, this, propertyValue, string.Empty));
1423  }
1424  break;
1425  }
1426  }
1427  num += Marshal.SizeOf(cLAIM_SECURITY_ATTRIBUTE_V);
1428  }
1429  }
1430  finally
1431  {
1432  safeLocalAllocHandle.Close();
1433  }
1434  }
1435  }
1436  }
1437 }
Represents a character encoding.To browse the .NET Framework source code for this type,...
Definition: Encoding.cs:15
static Thread CurrentThread
Gets the currently running thread.
Definition: Thread.cs:134
static CultureInfo InvariantCulture
Gets the T:System.Globalization.CultureInfo object that is culture-independent (invariant).
Definition: CultureInfo.cs:263
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 ...
Definition: Encoding.cs:1576
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.
Definition: Marshal.cs:241
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...
Definition: List.cs:553
static Encoding Unicode
Gets an encoding for the UTF-16 format using the little endian byte order.
Definition: Encoding.cs:975
Provides a mechanism for releasing unmanaged resources.To browse the .NET Framework source code for t...
Definition: IDisposable.cs:8
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...
Definition: BindingFlags.cs:10
Definition: __Canon.cs:3
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.
Definition: IntPtr.cs:147
static int SizeOf(object structure)
Returns the unmanaged size of an object in bytes.
Definition: Marshal.cs:159
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...
Definition: GC.cs:267
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.
Definition: Encoding.cs:920
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.
void Add(T item)
Adds an object to the end of the T:System.Collections.Generic.List`1.
Definition: List.cs:510
SecurityAction
Specifies the security actions that can be performed using declarative security.
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
IDictionary< string, string > Properties
Gets a dictionary that contains additional properties associated with this claim.
Definition: Claim.cs:61
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...
Definition: Marshal.cs:301
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.
Represents a claim.
Definition: Claim.cs:10
A platform-specific type that is used to represent a pointer or a handle.
Definition: IntPtr.cs:14
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...
Definition: Marshal.cs:123
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.
Definition: IntPtr.cs:135
Represents type declarations: class types, interface types, array types, value types,...
Definition: Type.cs:18
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks,...
Definition: Marshal.cs:15
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.
Definition: GC.cs:11
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...
Definition: Marshal.cs:103
Allows an object to control its own serialization and deserialization.
Definition: ISerializable.cs:8
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.
Definition: Marshal.cs:1198
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.
Definition: IntPtr.cs:20
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)....
Definition: CultureInfo.cs:16
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.
Definition: Interlocked.cs:10
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.
Definition: Thread.cs:18