-1

I am using the below to impersonate users on Windows 7. This code is compiled into a dll and called from python. Generally it works, but recently we have been seeing the main execution fail and have traced it back to the "WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle());" method. When this gets called, it does not impersonate the user, no error is thrown, and execution stops immediately (the Console.WriteLine() right after does not get called).

Any ideas? Please? I do not want to admit how much time I have spent trying to troubleshoot this.

Thanks!

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
using System.Security;

namespace PEServ.DataIntegration.Utilities
{
    public class WindowsCredentialHelper
    {

        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);



        public WindowsCredentialHelper()
        {
            Console.WriteLine("CS: WindowsCredentialHelper instance created successfully");
        }

        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        public WindowsImpersonationContext LogonAsUser(string username, string password, string domain)
        {
            SafeTokenHandle safeTokenHandle;

            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token. 
            const int LOGON32_LOGON_INTERACTIVE = 2;

            Console.WriteLine("DotNet: Attempting to Logon user: {0}", username);
            // Call LogonUser to obtain a handle to an access token. 
            bool returnValue = LogonUser(username, domain, password,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                out safeTokenHandle);

            if (returnValue)
            {
                Console.WriteLine("DotNet: Successfully logged on as user: {0}", username);
            }
            else
            {
                Console.WriteLine("DotNet: Failed to create a user");

                int err = Marshal.GetLastWin32Error();
                if (err == 1909 || err == 1331)
                {
                    Console.WriteLine("Logon user failed because account is currently locked/disabled");
                }
                else
                {
                    Console.WriteLine("Logon user failed with error code: {0}", err);
                }

                throw new System.ComponentModel.Win32Exception(err);
            }


            //Console.WriteLine("DotNet: About to create a windows identity");
            //WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
            //Console.WriteLine("New windows identity is: {0}", newId.Name);

            //Console.WriteLine("Attempting to imperonate user: {0}", newId.Name);
            //WindowsImpersonationContext impersonatedUser = newId.Impersonate();
            //Console.WriteLine("DotNet: Impersonation of user: {0} was successful", newId.Name);

            Console.WriteLine("DotNet: Attempting to impersonate the user");
            WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle());
            Console.WriteLine("DotNet: Impersonated the user");

            return impersonatedUser;

        }

        public void Undo(WindowsImpersonationContext impersonatedUser)
        {
            impersonatedUser.Undo();
        }

        public string GetCurrentUser()
        {
            return WindowsIdentity.GetCurrent().Name;

        }

        public string GetCurrentUserNameOnly()
        {
            return this.GetCurrentUser().Split(new char[] { '\\' })[1];

        }  
    }

    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true)
        {
        }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }
}

Changed to python based on Ben's recommendation:

    def impersonate_user(self, user_name, password, domain):
        handel=win32security.LogonUser(user_name, domain, password, win32con.LOGON32_LOGON_INTERACTIVE,win32con.LOGON32_PROVIDER_DEFAULT)
        win32security.ImpersonateLoggedOnUser(handel)
    print "Hello"

    return True
3
  • 1
    Why are you using C# from Python just to call the Win32 API? Just call the damn API from Python.
    – Ben
    Jul 17, 2012 at 19:34
  • Whoever voted my question down, I would like to understand why that is...
    – dashstar
    Aug 6, 2012 at 21:46
  • You need to get the error code. Try catching the exception and looking at the related message. What error message does it give in the debug output? If you cannot see any debug output, you need to show that window in your IDE. If you don't know how, you need to name your IDE and tool set.
    – Ben
    Aug 8, 2012 at 12:14

2 Answers 2

0

You can do this directly from Python, using LogonUser, ImpersonateLoggedOnUser and RevertToSelf.

Just do that and cut out the C# which is just complicating matters.

Starting point:

6
  • Thanks for the advice and the link Ben. We were originally doing some stuff in .net which is why we had it there, but after your comment I thought about it more and determined it was fine to move it to python... however, it still fails silently, now on the ImpersonateLoggedOnUser method.
    – dashstar
    Jul 17, 2012 at 20:02
  • BOOL ImpersonateLoggedOnUser returns false and sets the thread last error if it fails, which you can check with GetLastError.
    – Ben
    Jul 17, 2012 at 21:08
  • Hi @Ben ImpersoanteLoggedOnUser doesn't return a value though according to the document I have: win32security
    – dashstar
    Jul 18, 2012 at 13:18
  • @dashstar, can you elaborate on "fails silently". How do you know it fails if it is silent - what are the symptoms?
    – Ben
    Jul 18, 2012 at 14:39
  • Because if I step through the code it gets to the ImpersonateLoggedOnUser method and when I run it, it doesn't execute the next line and exits. I posted the amended python code, you'll notice the print statement after that method (this does not get called).
    – dashstar
    Jul 18, 2012 at 15:03
0

Late to answer, but just came across this issue. Change LOGON32_LOGON_INTERACTIVE to LOGON32_LOGON_BATCH (4)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.