Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2682
  • Last Modified:

Take ownership of a folder with C# 1.1

I need to be able to take control of a folder while using C#.

I have found an example using WMI in Win32 at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/takeownership_method_in_class_win32_directory.asp

There is an example of how to do it in .NET 2.0 at:
http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_21823904.html

Can somebody provide an example of how to do this in .NET 1.0 or 1.1?

Thanks
0
TAMUQITS
Asked:
TAMUQITS
  • 5
  • 5
  • 4
2 Solutions
 
gregoryyoungCommented:
That code should work in 1.1 as well (except the using generics part)
0
 
gregoryyoungCommented:
using System;
      using System.Management;
namespace ConsoleApplication6
{


      class Program {
                  static void Main(string[] args) {

                        string path = @"c:\test";
                        string dirObject = String.Format("win32_Directory.Name='{0}'", path);
                        using (ManagementObject dir = new ManagementObject(dirObject)) {
                              dir.Get();
                              dir.InvokeMethod("TakeOwnerShip", null);
                        }

                  }
            }
      }
0
 
TAMUQITSAuthor Commented:
Thanks for the response. I added the code to my app and it runs up until "dir.Get()" and then it throws a "Access is denied." Exception.

I'm not sure where to start with this so I gave everybody full access to the test folder and I still get this message. That leads me to believe it is not an NTFS issue.

Details:
=== Access is denied ===
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.UnauthorizedAccessException: Access is denied.

=== The stack trace is ===
[UnauthorizedAccessException: Access is denied.]
   System.Management.ManagementScope.InitializeGuts(Object o) +47
   System.Management.ManagementScope.Initialize() +187
   System.Management.ManagementObject.Initialize(Boolean getObject) +620
   System.Management.ManagementObject.InvokeMethod(String methodName, Object[] args) +94
   tamuq.ad.ADUser.renameProfile() +360
   tamuq.ad.ADUser.resetProfile(Boolean deletArchivedProfiles) +170
   ASP.editUser_resetProfile_aspx.btnResetProfile_Click(Object Src, EventArgs E) in C:\UserMgmt\editUser_resetProfile.aspx:37
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain() +1281

=== MORE INFO ===

When I tried to add a reference to the system.management.dll I got the error:
A reference to 'I:\WINDOWS\MICROSOFT.NET\Framework\v1.1.4322\System.Management.dll' could not be added. Error parsing application configuration file at line 11. Type '{http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/configuration}ReadOnlyConfigurationSectionData' is not found in Schema.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
gregoryyoungCommented:
"A reference to 'I:\WINDOWS\MICROSOFT.NET\Framework\v1.1.4322\System.Management.dll' could not be added. Error parsing application configuration file at line 11. Type '{http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/configuration}ReadOnlyConfigurationSectionData' is not found in Schema."

sounds like you are having an app config problem for one ...

For the second bit .. what user are you running as (yourself?)

0
 
TAMUQITSAuthor Commented:
At this point in the App I've impersonated an admin account.

"sounds like you are having an app config problem for one ..."
Where would be a good place to start looking for a solution. Are you talking about machine.config, web.config or something else?

Thanks
0
 
gregoryyoungCommented:
sounds like its having issues with an application block for your app.
0
 
Bob LearnedCommented:
You might be able to use impersonation with WMI instead:

  ConnectionOptions options = new ConnectionOptions();
  options.Username = userName;
  options.Password = userPassword;

  ManagementPath path = new ManagementPath();
  path.Server = @"\\<machine name goes here>\root\cimv2";

  string filePath = @"c:\test";
  string dirObject = String.Format("Win32_Directory.Name='{0}'", path);
  using (ManagementObject dir = new ManagementObject(dirObject, path, options);
  {
     dir.Get();
     dir.InvokeMethod("TakeOwnerShip", null);
  }

Bob
0
 
TAMUQITSAuthor Commented:
The Learned One I wasn't able to get the above code to work.

I modified it to compile but still no luck:
              LogonUtility logon = new LogonUtility();
                    logon.ImpersonateUser(TQDelAcct, TQDelPass);
                    System.Web.HttpContext.Current.Trace.Warn("BBB0");
                   
                    System.Web.HttpContext.Current.Trace.Warn("BBB1");

                    /////////////////////////////////////////////////////
                    /////////////////////////////////////////////////////

                    //Define ManagementScope
                    ConnectionOptions options = new ConnectionOptions();
                    options.Username = TQDelAcct;
                    options.Password = TQDelPass;
           
                    //Define ManagementPath
                    ManagementPath path = new ManagementPath();
                    path.Server = @"\\mail\root\cimv2";

                    ManagementScope scope = new ManagementScope(profileStart, options);

                    string dirObject = String.Format("win32_Directory.Name='{0}'", profileStart);
                    //Define ManagementObject
                    using (ManagementObject dir = new ManagementObject(dirObject, path, null))
                    {
                        System.Web.HttpContext.Current.Trace.Warn("BBB2");
                        dir.Get();
                        System.Web.HttpContext.Current.Trace.Warn("BBB3");
                        dir.InvokeMethod("TakeOwnerShip", null);
                        System.Web.HttpContext.Current.Trace.Warn("BBB4");
                    }

I'm going to open an MSDN ticket on this and once I get a solution I will post and award points
0
 
Bob LearnedCommented:
What is happening with that code?

Bob
0
 
TAMUQITSAuthor Commented:
I submitted a ticket with MSDN and they provided me with the following class that did the trick.
It came in the form of a windows form app with the below namespaces. I believe you only need System since it imports all the .dlls but I'm a web guy so here is all of them

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

    public class ACLUtil
    {
        public enum SE_OBJECT_TYPE : uint
        {
            SE_UNKNOWN_OBJECT_TYPE = 0,
            SE_FILE_OBJECT,
            SE_SERVICE,
            SE_PRINTER,
            SE_REGISTRY_KEY,
            SE_LMSHARE,
            SE_KERNEL_OBJECT,
            SE_WINDOW_OBJECT,
            SE_DS_OBJECT,
            SE_DS_OBJECT_ALL,
            SE_PROVIDER_DEFINED_OBJECT,
            SE_WMIGUID_OBJECT,
            SE_REGISTRY_WOW64_32KEY
        }

        [Flags]
        public enum SECURITY_INFORMATION : uint
        {
            OWNER_SECURITY_INFORMATION = 0x00000001,
            GROUP_SECURITY_INFORMATION = 0x00000002,
            DACL_SECURITY_INFORMATION = 0x00000004,
            SACL_SECURITY_INFORMATION = 0x00000008,

            // Win2k only
            PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000,
            // Win2k only
            PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000,
            // Win2k only
            UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000,
            // Win2k only
            UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000,
        }

        public const string SE_RESTORE_NAME = "SeRestorePrivilege";

        [StructLayout(LayoutKind.Sequential)]
        public struct LUID
        {
            public uint lowpart;
            public uint highpart;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct LUID_AND_ATTRIBUTES
        {
            public LUID pLuid;
            public uint Attributes;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct TOKEN_PRIVILEGES
        {
            public int PrivilegeCount;
            public LUID_AND_ATTRIBUTES privileges;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct TRUSTEE
        {
            public uint pMultipleTrustee;
            public uint MultipleTrusteeOperation;
            public uint TrusteeForm;
            public uint TrusteeType;
            public uint ptstrName;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct EXPLICIT_ACCESS
        {
            public uint grfAccessPermissions;
            public uint grfAccessMode;
            public uint grfInheritance;
            public TRUSTEE pTRUSTEE;
        }

        // Generic access rights extracted from WinNT.h
        public const uint GENERIC_ALL = 0x10000000;
        public const uint GENERIC_EXECUTE = 0x20000000;
        public const uint GENERIC_READ = 0x80000000;
        public const uint GENERIC_WRITE = 0x40000000;

        public const uint SET_ACCESS = 2;

        // Inheritance Flags
        public const uint CONTAINER_INHERIT_ACE = 2;
        public const uint OBJECT_INHERIT_ACE = 1;

        // Error codes
        public const int ERROR_SUCCESS = 0;
        public const int ERROR_INSUFFICIENT_BUFFER = 122;
        public const int ERROR_NONE_MAPPED = 1332;

        private const uint MAXIMUM_ALLOWED = 0x02000000;
        private const uint TOKEN_QUERY = 0x0008;
        private const uint TOKEN_ADJUST_PRIVILEGES = 0x0020;
        private const uint SE_PRIVILEGE_ENABLED = 2;

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool OpenThreadToken(
            uint ThreadHandle,
            uint DesiredAccess,
            bool OpenAsSelf,
            ref uint TokenHandle);

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool OpenProcessToken(
            uint ThreadHandle,
            uint DesiredAccess,
            ref uint TokenHandle);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool CloseHandle(uint handle);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern uint GetCurrentThread();

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern uint GetCurrentProcess();

        public static uint GetCurrentToken(uint accessMask)
        {
            uint hToken = 0;

            if (!OpenThreadToken(GetCurrentThread(), accessMask, true, ref hToken))
            {
                if (!OpenProcessToken(GetCurrentProcess(), accessMask, ref hToken))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                    //throw new ApplicationException("OpenProcessToken failed with error code : " + Marshal.GetLastWin32Error().ToString());
                }
            }
            return hToken;
        }

        [DllImport("Kernel32.dll",
             CallingConvention = CallingConvention.Winapi,
             SetLastError = true)]
        public static extern uint LocalFree(uint hMem);

        [DllImport("Advapi32.dll",
             EntryPoint = "BuildExplicitAccessWithNameA",
             CallingConvention = CallingConvention.Winapi,
             SetLastError = true, CharSet = CharSet.Ansi)]
        public static extern void BuildExplicitAccessWithName(
            ref EXPLICIT_ACCESS ea,
            IntPtr TrusteeName,
            uint AccessPermissions,
            uint AccessMode,
            uint Inheritance);

        [DllImport("Advapi32.dll",
             EntryPoint = "SetEntriesInAclA",
             CallingConvention = CallingConvention.Winapi,
             SetLastError = true, CharSet = CharSet.Ansi)]
        public static extern uint SetEntriesInAcl(
            int CountofExplicitEntries,
            ref EXPLICIT_ACCESS ea,
            uint OldAcl,
            ref uint NewAcl);

        [DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Ansi)]
        public static extern uint SetNamedSecurityInfo(
            [MarshalAs(UnmanagedType.LPStr)] string pObjectName,
            SE_OBJECT_TYPE ObjectType,
            SECURITY_INFORMATION SecurityInfo,
            IntPtr psidOwner,
            uint psidGroup,
            uint pDacl,
            uint pSacl);

        [DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Ansi)]
        public static extern bool LookupAccountName(
            [MarshalAs(UnmanagedType.LPStr)] string lpSystemName,
            [MarshalAs(UnmanagedType.LPStr)] string lpAccountName,
            IntPtr Sid,
            ref int cbSid,
            IntPtr DomainName,
            ref int cbDomainName,
            ref uint peUse
            );

        [DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Ansi)]
        public static extern bool LookupPrivilegeValue(
            [MarshalAs(UnmanagedType.LPStr)] string lpSystemName,
            [MarshalAs(UnmanagedType.LPStr)] string lpName,
            ref LUID Luid);
        [DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Ansi)]
        public static extern bool AdjustTokenPrivileges(
            uint TokenHandle,
            bool DisableAllPrivileges,
            ref TOKEN_PRIVILEGES NewState,
            int BufferLength,
            uint PreviousState,
            uint ReturnLength);

        static bool AddFullControlToFolder(string FolderName, string[] accountNames, string ownerName)
        {
            int x;
            int i;
            bool bReturn;

            bReturn = false;

            x = accountNames.Length;
            EXPLICIT_ACCESS[] ea = new EXPLICIT_ACCESS[x];
            IntPtr[] accountNamePtrs = new IntPtr[x];
            IntPtr sidPtr = IntPtr.Zero;
            IntPtr domainNamePtr = IntPtr.Zero;
            uint pDacl = 0;
            uint hToken = 0;

            try
            {
                int sidSize;
                int domainNameSize;
                bool bResult;
                uint status;
                uint eUse;
                LUID luid = new LUID();
                TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();

                sidSize = 0;
                domainNameSize = 0;
                eUse = 0;

                bResult = LookupAccountName(null, ownerName,
                                sidPtr, ref sidSize,
                                domainNamePtr, ref domainNameSize, ref eUse);
                if (bResult == false &&
                    Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)
                    throw new ApplicationException("LookupAccountName failed with error code : " + Marshal.GetLastWin32Error().ToString());

                sidPtr = Marshal.AllocHGlobal(sidSize);
                domainNamePtr = Marshal.AllocHGlobal(domainNameSize);

                bResult = LookupAccountName(null, ownerName,
                    sidPtr, ref sidSize,
                    domainNamePtr, ref domainNameSize, ref eUse);
                if (bResult == false)
                    throw new ApplicationException("LookupAccountName failed with error code : " + Marshal.GetLastWin32Error().ToString());

                for (i = 0; i < x; i++)
                {
                    accountNamePtrs[i] = Marshal.StringToHGlobalAnsi(accountNames[i]);
                    BuildExplicitAccessWithName(ref ea[i],
                        accountNamePtrs[i],
                        GENERIC_ALL,
                        SET_ACCESS,
                        CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE);
                }

                status = SetEntriesInAcl(x, ref ea[0], 0, ref pDacl);
                if (status != ERROR_SUCCESS)
                    throw new ApplicationException("SetEntriesInAcl failed with error code : " + status.ToString());

                hToken = GetCurrentToken(TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES);

                bResult = LookupPrivilegeValue(null, SE_RESTORE_NAME, ref luid);
                if (bResult == false)
                    throw new ApplicationException("LookupPrivilegeValue failed with error code : " + Marshal.GetLastWin32Error().ToString());

                tp.PrivilegeCount = 1;
                tp.privileges.pLuid = luid;
                tp.privileges.Attributes = SE_PRIVILEGE_ENABLED;

                bResult = AdjustTokenPrivileges(hToken, false, ref tp, Marshal.SizeOf(tp), 0, 0);
                if (bResult == false)
                    throw new ApplicationException("AdjustTokenPrivileges failed with error code : " + Marshal.GetLastWin32Error().ToString());

                status = SetNamedSecurityInfo(FolderName, SE_OBJECT_TYPE.SE_FILE_OBJECT,
                    SECURITY_INFORMATION.DACL_SECURITY_INFORMATION |
                    SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION |
                    SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION,
                    sidPtr,
                    0,
                    pDacl,
                    0);
                if (status != ERROR_SUCCESS)
                    throw new ApplicationException("SetNamedSecurityInfo failed with error code : " + status.ToString());

                bReturn = true;
            }
            finally
            {
                for (i = 0; i < x; i++)
                {
                    if (accountNamePtrs[i] != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(accountNamePtrs[i]);
                    }
                }
                if (sidPtr != IntPtr.Zero)
                    Marshal.FreeHGlobal(sidPtr);
                if (domainNamePtr != IntPtr.Zero)
                    Marshal.FreeHGlobal(domainNamePtr);
                if (pDacl != 0)
                    LocalFree(pDacl);
                if (hToken != 0)
                    CloseHandle(hToken);
            }

            return bReturn;
        }



        public static bool SetOwner(string FolderName, string ownerName, string adminAcct, string adminPass)
        {
            bool bReturn = false;
            IntPtr sidPtr = IntPtr.Zero;
            IntPtr domainNamePtr = IntPtr.Zero;
            uint hToken = 0;
            LogonUtility logon = new LogonUtility(); //custom class - used to access impersonation function

            try
            {
                int sidSize;
                int domainNameSize;
                bool bResult;
                uint status;
                uint eUse;
                LUID luid = new LUID();
                TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();

                sidSize = 0;
                domainNameSize = 0;
                eUse = 0;

                bResult = LookupAccountName(
                                null, ownerName,
                                sidPtr, ref sidSize,
                                domainNamePtr, ref domainNameSize, ref eUse);
                if (bResult == false && Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER)
                System.Web.HttpContext.Current.Trace.Warn("1 LookupAccountName failed with error code : " + Marshal.GetLastWin32Error().ToString());

                sidPtr = Marshal.AllocHGlobal(sidSize);
                domainNamePtr = Marshal.AllocHGlobal(domainNameSize);
                bResult = LookupAccountName(null, ownerName,
                                            sidPtr, ref sidSize,
                                            domainNamePtr, ref domainNameSize, ref eUse);
                if (bResult == false)
                System.Web.HttpContext.Current.Trace.Warn("2 LookupAccountName failed with error code : " + Marshal.GetLastWin32Error().ToString());

                hToken = GetCurrentToken(TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES);
                bResult = LookupPrivilegeValue(null, SE_RESTORE_NAME, ref luid);
                if (bResult == false)
                System.Web.HttpContext.Current.Trace.Warn("3 LookupPrivilegeValue failed with error code : " + Marshal.GetLastWin32Error().ToString());

                tp.PrivilegeCount = 1;
                tp.privileges.pLuid = luid;
                tp.privileges.Attributes = SE_PRIVILEGE_ENABLED;

                bResult = AdjustTokenPrivileges(hToken, false, ref tp, Marshal.SizeOf(tp), 0, 0);
                if (bResult == false)
                System.Web.HttpContext.Current.Trace.Warn("4 AdjustTokenPrivileges failed with error code : " + Marshal.GetLastWin32Error().ToString());

                logon.ImpersonateUser(adminAcct, adminPass);//impersonate the admin account

                status = SetNamedSecurityInfo(FolderName, SE_OBJECT_TYPE.SE_FILE_OBJECT,
                                                SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, sidPtr, 0, 0, 0);
                if (status != ERROR_SUCCESS)
                {
                    System.Web.HttpContext.Current.Trace.Warn("5 SetNamedSecurityInfo failed with error code : " + status.ToString());
                }
                else
                    bReturn = true;
            }
            finally
            {
                if (sidPtr != IntPtr.Zero)
                    Marshal.FreeHGlobal(sidPtr);
                if (domainNamePtr != IntPtr.Zero)
                    Marshal.FreeHGlobal(domainNamePtr);
                if (hToken != 0)
                    CloseHandle(hToken);
            }

            return bReturn;
        }


        /*
                [STAThread]
                static void Main(string[] args)
                {
                    string[] accountNames = { "Administrators", "SYSTEM", "testuser" };

                    if (AddFullControlToFolder("C:\\TEST\\TEST", accountNames, "REDMOND\\prabagar"))
                    {
                        Console.WriteLine("Permissions set successfully");
                    }
                    else
                        Console.WriteLine("Unable to set permissions");
                }
        */

    }
0
 
Bob LearnedCommented:
Nice class, but I don't see LogonUtility anywhere.

Bob
0
 
TAMUQITSAuthor Commented:
I forgot about that one here it is:
//////////////////////////////////////////////////////////
 public class LogonUtility
    {
        private static string IMPERSONATED_USER;
        private static string IMPERSONATED_PASS;
        public LogonUtility()
        {
            IMPERSONATED_USER = IMPERSONATED_PASS = "";
        }
        public LogonUtility(string user, string pass)
        {
            IMPERSONATED_USER = user;
            IMPERSONATED_PASS = pass;
        }
         //import LSA functions
        [DllImport("advapi32.dll")]
        private static extern bool LogonUser(
            String lpszUsername,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken
            );

        [DllImport("advapi32.dll")]
        private static extern bool DuplicateToken(
            IntPtr ExistingTokenHandle,
            int ImpersonationLevel,
            ref IntPtr DuplicateTokenHandle
            );

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);

        [DllImport("advapi32.dll")]
        private static extern bool ImpersonateLoggedOnUser(IntPtr hToken);

        [DllImport("kernel32.dll")]
        private static extern int GetLastError();

        //enum impersonation levels an logon types

        private enum SecurityImpersonationLevel
        {
            SecurityAnonymous,
            SecurityIdentification,
            SecurityImpersonation,
            SecurityDelegation
        }

        private enum LogonTypes
        {
            LOGON32_PROVIDER_DEFAULT = 0,
            LOGON32_LOGON_INTERACTIVE = 2,
            LOGON32_LOGON_NETWORK = 3,
            LOGON32_LOGON_BATCH = 4,
            LOGON32_LOGON_SERVICE = 5,
            LOGON32_LOGON_UNLOCK = 7,
            LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
            LOGON32_LOGON_NEW_CREDENTIALS = 9
        }

        public WindowsImpersonationContext ImpersonateUser()
        {
            //define the handles
            IntPtr existingTokenHandle = IntPtr.Zero;
            IntPtr duplicateTokenHandle = IntPtr.Zero;

            string domain = "yourDomain";
            string username = IMPERSONATED_USER;
            string password = IMPERSONATED_PASS;

            bool isOkay = true;

            try
            {
                //get a security token

                isOkay = LogonUser(username, domain, password,
                    (int)LogonTypes.LOGON32_LOGON_INTERACTIVE, (int)LogonTypes.LOGON32_PROVIDER_DEFAULT,
                    ref existingTokenHandle);

                if (!isOkay)
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    int lastError = GetLastError();

                    throw new Exception("LogonUser Failed: " + lastWin32Error + " - " + lastError);
                }

                // copy the token

                isOkay = DuplicateToken(existingTokenHandle,
                    (int)SecurityImpersonationLevel.SecurityImpersonation,
                    ref duplicateTokenHandle);

                if (!isOkay)
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    int lastError = GetLastError();
                    CloseHandle(existingTokenHandle);
                    throw new Exception("DuplicateToken Failed: " + lastWin32Error + " - " + lastError);
                }
                else
                {

                    // create an identity from the token

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

                    return impersonatedUser;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //free all handles
                if (existingTokenHandle != IntPtr.Zero)
                {
                    CloseHandle(existingTokenHandle);
                }
                if (duplicateTokenHandle != IntPtr.Zero)
                {
                    CloseHandle(duplicateTokenHandle);
                }
            }
        }

        /// <summary>impersonates a user</summary>
        /// <param name="sUsername">domain\name of the user account</param>
        /// <param name="sPassword">the user's password</param>
        /// <returns>the new WindowsImpersonationContext</returns>
        public WindowsImpersonationContext ImpersonateUser(String username, String password)
        {
            //define the handles
            IntPtr existingTokenHandle = IntPtr.Zero;
            IntPtr duplicateTokenHandle = IntPtr.Zero;

            String domain;
            if (username.IndexOf("\\") > 0)
            {
                //split domain and name
                String[] splitUserName = username.Split('\\');
                domain = splitUserName[0];
                username = splitUserName[1];
            }
            else
            {
                //domain = String.Empty;
                domain = "qatar";
            }

            bool isOkay = true;
            try
            {
                //get a security token
                isOkay = LogonUser(username, domain, password,
                    (int)LogonTypes.LOGON32_LOGON_INTERACTIVE, (int)LogonTypes.LOGON32_PROVIDER_DEFAULT,
                    ref existingTokenHandle);
                if (!isOkay)
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    int lastError = GetLastError();
                    throw new Exception("LogonUser Failed: " + lastWin32Error + " - " + lastError);
                }
                // copy the token

                isOkay = DuplicateToken(existingTokenHandle,
                    (int)SecurityImpersonationLevel.SecurityImpersonation,
                    ref duplicateTokenHandle);

                if (!isOkay)
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    int lastError = GetLastError();
                    CloseHandle(existingTokenHandle);
                    throw new Exception("DuplicateToken Failed: " + lastWin32Error + " - " + lastError);
                }
                else
                {
                    // create an identity from the token

                    WindowsIdentity newId = new WindowsIdentity(duplicateTokenHandle);
                    WindowsImpersonationContext impersonatedUser = newId.Impersonate();
                    return impersonatedUser;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //free all handles
                if (existingTokenHandle != IntPtr.Zero)
                {
                    CloseHandle(existingTokenHandle);
                }
                if (duplicateTokenHandle != IntPtr.Zero)
                {
                    CloseHandle(duplicateTokenHandle);
                }
            }
        }
    }
0
 
Bob LearnedCommented:
Cool b-)  Thanks :D

Bob
0
 
gregoryyoungCommented:
I am curious if they are saying the WMI methodology does not work. I am also curious of any code access implications for all of these pinvokes.

btw: you might want to "adjust" that logon utility class ... it has some problems (try the following)

LogonUtility foo = new LogonUtility("test", "test");
LogonUtility bar = new LogonUtility("test2", "test2");
foo.ImpersonateUser(); //logs in as test2
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 5
  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now