Inheritance: System.Runtime.InteropServices.SafeHandle
コード例 #1
0
 private static extern bool LogonUser(
     string username,
     string domain,
     string password,
     LogonType logonType,
     LogonProvider logonProvider,
     out SafeTokenHandle token);
コード例 #2
0
ファイル: Win32.cs プロジェクト: dotnet/corefx
 internal static int SetThreadToken(SafeTokenHandle hToken)
 {
     int hr = 0;
     if (!Interop.Advapi32.SetThreadToken(IntPtr.Zero, hToken))
     {
         hr = Marshal.GetHRForLastWin32Error();
     }
     return hr;
 }
 internal WindowsImpersonationContext(SafeTokenHandle safeTokenHandle, WindowsIdentity wi, bool isImpersonating, FrameSecurityDescriptor fsd)
 {
     this.m_safeTokenHandle = SafeTokenHandle.InvalidHandle;
     if (safeTokenHandle.IsInvalid)
     {
         throw new ArgumentException(Environment.GetResourceString("Argument_InvalidImpersonationToken"));
     }
     if (isImpersonating)
     {
         if (!Win32Native.DuplicateHandle(Win32Native.GetCurrentProcess(), safeTokenHandle, Win32Native.GetCurrentProcess(), ref this.m_safeTokenHandle, 0, true, 2))
         {
             throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
         }
         this.m_wi = wi;
     }
     this.m_fsd = fsd;
 }
コード例 #4
0
        internal WindowsImpersonationContext (SafeTokenHandle safeTokenHandle, WindowsIdentity wi, bool isImpersonating, FrameSecurityDescriptor fsd) {
            if (safeTokenHandle.IsInvalid)
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidImpersonationToken"));
            Contract.EndContractBlock();

            if (isImpersonating) {
                if (!Win32Native.DuplicateHandle(Win32Native.GetCurrentProcess(),
                                                 safeTokenHandle,
                                                 Win32Native.GetCurrentProcess(),
                                                 ref m_safeTokenHandle,
                                                 0,
                                                 true,
                                                 Win32Native.DUPLICATE_SAME_ACCESS))
                    throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
                m_wi = wi;
            }
            m_fsd = fsd;
        }
コード例 #5
0
ファイル: Win32.cs プロジェクト: dotnet/corefx
        internal static int OpenThreadToken(TokenAccessLevels dwDesiredAccess, WinSecurityContext dwOpenAs, out SafeTokenHandle phThreadToken)
        {
            int hr = 0;
            bool openAsSelf = true;
            if (dwOpenAs == WinSecurityContext.Thread)
                openAsSelf = false;

            if (!Interop.Advapi32.OpenThreadToken((IntPtr)(-2), dwDesiredAccess, openAsSelf, out phThreadToken))
            {
                if (dwOpenAs == WinSecurityContext.Both)
                {
                    openAsSelf = false;
                    hr = 0;
                    if (!Interop.Advapi32.OpenThreadToken((IntPtr)(-2), dwDesiredAccess, openAsSelf, out phThreadToken))
                        hr = Marshal.GetHRForLastWin32Error();
                }
                else
                {
                    hr = Marshal.GetHRForLastWin32Error();
                }
            }
            if (hr != 0) phThreadToken = null;
            return hr;
        }
コード例 #6
0
        [SecurityCritical]  // auto-generated
        private static SafeLocalAllocHandle GetTokenUserFromToken(SafeTokenHandle tokenHandle) {
            SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;
            uint dwLength = (uint)Marshal.SizeOf(typeof(uint));
            bool result = Win32Native.GetTokenInformation(tokenHandle,
                                                          1 /* TokenInformationClass.TokenUser */,
                                                          safeLocalAllocHandle,
                                                          0,
                                                          out dwLength);
            int dwErrorCode = Marshal.GetLastWin32Error();
            switch (dwErrorCode) {
                case Win32Native.ERROR_INSUFFICIENT_BUFFER:
                    // ptrLength is an [In] param to LocalAlloc 
                    UIntPtr ptrLength = new UIntPtr(dwLength);
                    safeLocalAllocHandle = Win32Native.LocalAlloc(Win32Native.LMEM_FIXED, ptrLength);
                    if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid)
                        throw new OutOfMemoryException();
                    safeLocalAllocHandle.Initialize(dwLength);

                    result = Win32Native.GetTokenInformation(tokenHandle,
                                                             1 /* TokenInformationClass.TokenUser */,
                                                             safeLocalAllocHandle,
                                                             dwLength,
                                                             out dwLength);
                    if (!result) {
                        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error(), new IntPtr(-1));
                    }
                    break;
                default:
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error(), new IntPtr(-1));
                    break;
            }
            return safeLocalAllocHandle;
        }
コード例 #7
0
 public static extern bool SetThreadToken(HANDLE Thread, SafeTokenHandle Token);
コード例 #8
0
 private void Dispose(bool disposing)
 {
     if (!this.disposed)
     {
         if (disposing && (this.threadHandle != null))
         {
             this.threadHandle.Dispose();
             this.threadHandle = null;
         }
         if (this.isImpersonating)
         {
             System.Security.Principal.Win32.RevertToSelf();
         }
         this.disposed = true;
     }
 }
コード例 #9
0
ファイル: Win32.cs プロジェクト: sjyanxin/WPFSource
 internal static extern int SetThreadToken(SafeTokenHandle hToken);
コード例 #10
0
ファイル: Win32.cs プロジェクト: sjyanxin/WPFSource
 internal static extern int ImpersonateLoggedOnUser (SafeTokenHandle hToken); 
 private WindowsImpersonationContext()
 {
     this.m_safeTokenHandle = SafeTokenHandle.InvalidHandle;
 }
コード例 #12
0
 [System.Security.SecurityCritical]  // auto-generated
 internal void SetTokenHandles (SafeTokenHandle callerToken, SafeTokenHandle impToken)
 {
     m_callerToken = callerToken;
     m_impToken = impToken;
 }
コード例 #13
0
ファイル: NativeMethods.cs プロジェクト: nithinphilips/SMOz
 public static extern bool GetTokenInformation(
     SafeTokenHandle hToken,
     TOKEN_INFORMATION_CLASS tokenInfoClass,
     IntPtr pTokenInfo,
     Int32 tokenInfoLength,
     out Int32 returnLength);
コード例 #14
0
ファイル: NativeMethods.cs プロジェクト: nithinphilips/SMOz
 public extern static bool DuplicateToken(
     SafeTokenHandle ExistingTokenHandle,
     SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
     out SafeTokenHandle DuplicateTokenHandle);
コード例 #15
0
ファイル: NativeMethods.cs プロジェクト: nithinphilips/SMOz
 public static extern bool OpenProcessToken(IntPtr hProcess,
     UInt32 desiredAccess, out SafeTokenHandle hToken);
コード例 #16
0
ファイル: Program.cs プロジェクト: oblivious/Oblivious
 public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLoginType, int dwLogonProvider, out SafeTokenHandle phToken);
コード例 #17
0
ファイル: Impersonation.cs プロジェクト: Healix/Gw2Launcher
 public ImpersonationToken(SafeTokenHandle token)
 {
     try
     {
         this.Token = token;
         this.Identity = new WindowsIdentity(token.DangerousGetHandle());
         this.Context = this.Identity.Impersonate();
     }
     catch (Exception e)
     {
         this.Dispose();
         throw e;
     }
 }
コード例 #18
0
            public TlsContents()
            {
                int error = 0;
                int cachingError = 0;
                bool success = true;

                if ( processHandle.IsInvalid)
                {
                    lock( syncRoot )
                    {
                        if ( processHandle.IsInvalid)
                        {
                            SafeTokenHandle localProcessHandle;
                            if ( false == Win32Native.OpenProcessToken(
                                            Win32Native.GetCurrentProcess(),
                                            TokenAccessLevels.Duplicate,
                                            out localProcessHandle))
                            {
                                cachingError = Marshal.GetLastWin32Error();
                                success = false;
                            }
                            processHandle = localProcessHandle;
                        }
                    }
                }

                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    // Make the sequence non-interruptible
                }
                finally
                {
                    try
                    {
                        //
                        // Open the thread token; if there is no thread token, get one from
                        // the process token by impersonating self.
                        //

                        SafeTokenHandle threadHandleBefore = this.threadHandle;
                        error = FCall.OpenThreadToken(
                                      TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
                                      WinSecurityContext.Process,
                                      out this.threadHandle );
                        unchecked { error &= ~(int)0x80070000; }

                        if ( error != 0 )
                        {
                            if ( success == true )
                            {
                                this.threadHandle = threadHandleBefore;

                                if ( error != Win32Native.ERROR_NO_TOKEN )
                                {
                                    success = false;
                                }

                                Contract.Assert( this.isImpersonating == false, "Incorrect isImpersonating state" );

                                if ( success == true )
                                {
                                    error = 0;
                                    if ( false == Win32Native.DuplicateTokenEx(
                                                    processHandle,
                                                    TokenAccessLevels.Impersonate | TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
                                                    IntPtr.Zero,
                                                    Win32Native.SECURITY_IMPERSONATION_LEVEL.Impersonation,
                                                    System.Security.Principal.TokenType.TokenImpersonation,
                                                    ref this.threadHandle ))
                                    {
                                        error = Marshal.GetLastWin32Error();
                                        success = false;
                                    }
                                }

                                if ( success == true )
                                {
                                    error = FCall.SetThreadToken( this.threadHandle );
                                    unchecked { error &= ~(int)0x80070000; }

                                    if ( error != 0 )
                                    {
                                        success = false;
                                    }
                                }

                                if ( success == true )
                                {
                                    this.isImpersonating = true;
                                }
                            }
                            else
                            {
                                error = cachingError;
                            }
                        }
                        else
                        {
                            success = true;
                        }
                    }
                    finally
                    {
                        if ( !success )
                        {
                            Dispose();
                        }
                    }
                }

                if ( error == Win32Native.ERROR_NOT_ENOUGH_MEMORY )
                {
                    throw new OutOfMemoryException();
                }
                else if ( error == Win32Native.ERROR_ACCESS_DENIED ||
                    error == Win32Native.ERROR_CANT_OPEN_ANONYMOUS )
                {
                    throw new UnauthorizedAccessException();
                }
                else if ( error != 0 )
                {
                    Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "WindowsIdentity.GetCurrentThreadToken() failed with unrecognized error code {0}", error ));
                    throw new InvalidOperationException();
                }
            }
コード例 #19
0
ファイル: Microsoft.Win32.cs プロジェクト: sebgod/userscripts
 internal static bool OpenProcessToken([In] IntPtr ProcessToken, [In] TokenAccessLevels DesiredAccess, out SafeTokenHandle TokenHandle);
コード例 #20
0
ファイル: ImpersonateUser.cs プロジェクト: victorxata/261120
 public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,int logonType, int logonProvider, out SafeTokenHandle token);
コード例 #21
0
ファイル: MainForm.cs プロジェクト: jsmurphy/randomcode
        /// <summary>
        /// The function checks whether the primary access token of the process belongs 
        /// to user account that is a member of the local Administrators group, even if 
        /// it currently is not elevated.
        /// </summary>
        /// <returns>
        /// Returns true if the primary access token of the process belongs to user 
        /// account that is a member of the local Administrators group. Returns false 
        /// if the token does not.
        /// </returns>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// When any native Windows API call fails, the function throws a Win32Exception 
        /// with the last error code.
        /// </exception>
        internal bool IsUserInAdminGroup()
        {
            bool fInAdminGroup = false;
            SafeTokenHandle hToken = null;
            SafeTokenHandle hTokenToCheck = null;
            IntPtr pElevationType = IntPtr.Zero;
            IntPtr pLinkedToken = IntPtr.Zero;
            int cbSize = 0;

            try
            {
                // Open the access token of the current process for query and duplicate.
                if (!NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle,
                    NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_DUPLICATE, out hToken))
                {
                    throw new Win32Exception();
                }

                // Determine whether system is running Windows Vista or later operating
                // systems (major version >= 6) because they support linked tokens, but
                // previous versions (major version < 6) do not.
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    // Running Windows Vista or later (major version >= 6).
                    // Determine token type: limited, elevated, or default.

                    // Allocate a buffer for the elevation type information.
                    cbSize = sizeof(TOKEN_ELEVATION_TYPE);
                    pElevationType = Marshal.AllocHGlobal(cbSize);
                    if (pElevationType == IntPtr.Zero)
                    {
                        throw new Win32Exception();
                    }

                    // Retrieve token elevation type information.
                    if (!NativeMethods.GetTokenInformation(hToken,
                        TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType,
                        cbSize, out cbSize))
                    {
                        throw new Win32Exception();
                    }

                    // Marshal the TOKEN_ELEVATION_TYPE enum from native to .NET.
                    TOKEN_ELEVATION_TYPE elevType = (TOKEN_ELEVATION_TYPE)
                        Marshal.ReadInt32(pElevationType);

                    // If limited, get the linked elevated token for further check.
                    if (elevType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
                    {
                        // Allocate a buffer for the linked token.
                        cbSize = IntPtr.Size;
                        pLinkedToken = Marshal.AllocHGlobal(cbSize);
                        if (pLinkedToken == IntPtr.Zero)
                        {
                            throw new Win32Exception();
                        }

                        // Get the linked token.
                        if (!NativeMethods.GetTokenInformation(hToken,
                            TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken,
                            cbSize, out cbSize))
                        {
                            throw new Win32Exception();
                        }

                        // Marshal the linked token value from native to .NET.
                        IntPtr hLinkedToken = Marshal.ReadIntPtr(pLinkedToken);
                        hTokenToCheck = new SafeTokenHandle(hLinkedToken);
                    }
                }

                // CheckTokenMembership requires an impersonation token. If we just got
                // a linked token, it already is an impersonation token.  If we did not
                // get a linked token, duplicate the original into an impersonation
                // token for CheckTokenMembership.
                if (hTokenToCheck == null)
                {
                    if (!NativeMethods.DuplicateToken(hToken,
                        SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                        out hTokenToCheck))
                    {
                        throw new Win32Exception();
                    }
                }

                // Check if the token to be checked contains admin SID.
                WindowsIdentity id = new WindowsIdentity(hTokenToCheck.DangerousGetHandle());
                WindowsPrincipal principal = new WindowsPrincipal(id);
                fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            finally
            {
                // Centralized cleanup for all allocated resources.
                if (hToken != null)
                {
                    hToken.Close();
                    hToken = null;
                }
                if (hTokenToCheck != null)
                {
                    hTokenToCheck.Close();
                    hTokenToCheck = null;
                }
                if (pElevationType != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pElevationType);
                    pElevationType = IntPtr.Zero;
                }
                if (pLinkedToken != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pLinkedToken);
                    pLinkedToken = IntPtr.Zero;
                }
            }

            return fInAdminGroup;
        }
コード例 #22
0
            private void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (this.threadHandle != null)
                    {
                        this.threadHandle.Dispose();
                        this.threadHandle = null;
                    }
                }

                if (this.isImpersonating)
                {
                    NativeMethods.RevertToSelf();
                    this.isImpersonating = false;
                }
            }
コード例 #23
0
            [System.Security.SecurityCritical]  // auto-generated
            private void Dispose( bool disposing )
            {
                if ( this.disposed ) return;

                if ( disposing )
                {
                    if ( this.threadHandle != null )
                    {
                        this.threadHandle.Dispose();
                        this.threadHandle = null;
                    }
                }

                if ( this.isImpersonating )
                {
                    FCall.RevertToSelf();
                }

                this.disposed = true;
            }
コード例 #24
0
 public static extern bool AdjustTokenPrivileges(
     SafeTokenHandle TokenHandle,
     [MarshalAs(UnmanagedType.Bool)]
     bool DisableAllPrivileges,
     ref TOKEN_PRIVILEGE NewState,
     uint BufferLength,
     ref TOKEN_PRIVILEGE PreviousState,
     ref uint ReturnLength);
コード例 #25
0
 public static extern bool OpenProcessToken(
     HANDLE ProcessToken,
     TokenAccessLevels DesiredAccess,
     ref SafeTokenHandle TokenHandle);
コード例 #26
0
 public static extern bool OpenThreadToken(
     HANDLE ThreadToken,
     TokenAccessLevels DesiredAccess,
     [MarshalAs(UnmanagedType.Bool)]
     bool OpenAsSelf,
     ref SafeTokenHandle TokenHandle);
コード例 #27
0
ファイル: Win32.cs プロジェクト: sjyanxin/WPFSource
 internal static extern int OpenThreadToken (TokenAccessLevels dwDesiredAccess, WinSecurityContext OpenAs, out SafeTokenHandle phThreadToken);
コード例 #28
0
 bool DuplicateTokenEx(
     SafeTokenHandle ExistingToken,
     TokenAccessLevels DesiredAccess,
     IntPtr TokenAttributes,
     TokenImpersonationLevel ImpersonationLevel,
     TokenType TokenType,
     ref SafeTokenHandle NewToken);
コード例 #29
0
 private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
コード例 #30
0
            public TlsContents()
            {
                int num = 0;
                int num2 = 0;
                bool flag = true;
                if (processHandle.IsInvalid)
                {
                    lock (syncRoot)
                    {
                        if (processHandle.IsInvalid)
                        {
                            SafeTokenHandle handle;
                            if (!Win32Native.OpenProcessToken(Win32Native.GetCurrentProcess(), TokenAccessLevels.Duplicate, out handle))
                            {
                                num2 = Marshal.GetLastWin32Error();
                                flag = false;
                            }
                            processHandle = handle;
                        }
                    }
                }
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                }
                finally
                {
                    try
                    {
                        SafeTokenHandle threadHandle = this.threadHandle;
                        num = System.Security.Principal.Win32.OpenThreadToken(TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query, WinSecurityContext.Process, out this.threadHandle);
                        num &= 0x7ff8ffff;
                        if (num != 0)
                        {
                            if (flag)
                            {
                                this.threadHandle = threadHandle;
                                if (num != 0x3f0)
                                {
                                    flag = false;
                                }
                                if (flag)
                                {
                                    num = 0;
                                    if (!Win32Native.DuplicateTokenEx(processHandle, TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query | TokenAccessLevels.Impersonate, IntPtr.Zero, Win32Native.SECURITY_IMPERSONATION_LEVEL.Impersonation, System.Security.Principal.TokenType.TokenImpersonation, ref this.threadHandle))
                                    {
                                        num = Marshal.GetLastWin32Error();
                                        flag = false;
                                    }
                                }
                                if (flag)
                                {
                                    num = System.Security.Principal.Win32.SetThreadToken(this.threadHandle);
                                    num &= 0x7ff8ffff;
                                    if (num != 0)
                                    {
                                        flag = false;
                                    }
                                }
                                if (flag)
                                {
                                    this.isImpersonating = true;
                                }
                            }
                            else
                            {
                                num = num2;
                            }
                        }
                        else
                        {
                            flag = true;
                        }
                    }
                    finally
                    {
                        if (!flag)
                        {
                            this.Dispose();
                        }
                    }
                }
                switch (num)
                {
                    case 8:
                        throw new OutOfMemoryException();

                    case 5:
                    case 0x543:
                        throw new UnauthorizedAccessException();
                }
                if (num != 0)
                {
                    throw new InvalidOperationException();
                }
            }