0

I am trying to impersonate a specific user to perform some sql operations in our server. This is not a ASP.Net application. I used the provided code before and it worked. But, recently we have upgraded our environment from windows server 2000 to windows server 2008 R2. After that upgrade this code is not working for me. I need some help in understanding this problem and help solving it. Any and every help will be appreciated. Thanks.

The provided code is a pseudo code, trying to write to a file and do a sql operation.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
using System.Security.Principal;
using System.Security.Permissions;

[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
public class Test
{
    const int LOGON32_LOGON_INTERACTIVE = 2;
    const int LOGON32_LOGON_NETWORK = 3;
    const int LOGON32_LOGON_BATCH = 4;
    const int LOGON32_LOGON_SERVICE = 5;
    const int LOGON32_LOGON_UNLOCK = 7;
    const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
    const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
    const int LOGON32_PROVIDER_DEFAULT = 0;
    const int SecurityImpersonation = 2;

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern int LogonUser(
        string lpszUsername,
        string lpszDomain,
        string lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        out IntPtr phToken
        );

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern int ImpersonateLoggedOnUser(
        IntPtr hToken
    );

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
      int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

    [DllImport("advapi32.dll", SetLastError = true)]
    static extern int RevertToSelf();

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern int CloseHandle(IntPtr hObject);

    public void TestImpersonation()
    {            
        IntPtr lnToken = new IntPtr(0);
        IntPtr dupeTokenHandle = new IntPtr(0);
        StringBuilder sb = new StringBuilder();

        int TResult = LogonUser("itservices", "DFC", "St4hls345t", LOGON32_LOGON_NETWORK,
                LOGON32_PROVIDER_DEFAULT, out lnToken);
        if (TResult > 0)
        {
            bool retVal = DuplicateToken(lnToken, SecurityImpersonation, ref dupeTokenHandle);
            if (false == retVal)
            {
                CloseHandle(lnToken);
                Console.WriteLine("Exception thrown in trying to duplicate token.");
                return;
            }

            WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
            WindowsImpersonationContext impersonatedUser = newId.Impersonate();

            writeLog(DateTime.Now.ToString(@"MM-dd-yyyy HH:mm:ss") + " - Impersonation Applied" + Environment.NewLine);
            runQuery();
            impersonatedUser.Undo();
            writeLog(DateTime.Now.ToString(@"MM-dd-yyyy HH:mm:ss") + " - Impersonation Reverted" + Environment.NewLine);
            runQuery();
            CloseHandle(lnToken);
        }
        else
        {
            writeLog(DateTime.Now.ToString(@"MM-dd-yyyy HH:mm:ss") + " - Impersonation not Applied" + Environment.NewLine);
        }

        return;
    }

    void writeLog(string message)
    {
        try
        {
            string filePath = @"E:\Impersonate\Testlog.txt";
            File.AppendAllText(filePath, message);
        }
        catch
        {
            Console.WriteLine();
        }
    }

    void runQuery()
    {
        SQLOperations sqlUtill = new SQLOperations();
        string cmdTxt = "SELECT * FROM [tblChildOrder] where [StahlsWorkOrderID] = 'DREAMFUL0015799'";
        DataTable dt = sqlUtill.executeQuery(cmdTxt);
        if (dt != null)
        {
            Console.WriteLine();
        }
        else
        {
            Console.WriteLine();
        }
    }
}
Teja
  • 1
  • 2

1 Answers1

0

Most upgrade that broke my code usually was caused by the upgrade changing permission to users. Double check the users, the permission they have and you should find the problem.

Rv3
  • 59
  • 6