简体   繁体   English

使用模拟和 CopyFileEx 从 Kernel DLL 复制文件?

[英]Copy file using impersonation and CopyFileEx from Kernel DLL?

I am using the following code to copy a file to a directory where only one X user has access, I am using impersonation but when I use it the CopyFileEx does not work, but I don't know why.我正在使用以下代码将文件复制到只有一个 X 用户可以访问的目录,我正在使用模拟但是当我使用它时 CopyFileEx 不起作用,但我不知道为什么。 if I remove the part of the impersonation it works correctly but I need it to be copied with a user X since in production it has to be like that.如果我删除了模拟的一部分,它可以正常工作,但我需要将它与用户 X 一起复制,因为在生产中它必须是这样的。

                        ImpersonationUtils impersonation = new ImpersonationUtils();
                var token = impersonation.LogonAsUser("User", "Domain", "pwd");

                if (!IntPtr.Equals(token, IntPtr.Zero))
                {
                    System.Security.Principal.WindowsImpersonationContext impersonatedUser = null;
                    var newIdentity = new System.Security.Principal.WindowsIdentity(token);
                    impersonatedUser = newIdentity.Impersonate();

                    bool result = CopyFileEx(filename, tempFilepath, new CopyProgressRoutine(this.CopyProgressHandler), IntPtr.Zero, cancelp, 0);

                    if (impersonatedUser != null)
                        impersonatedUser.Undo();

                    impersonation.LogonAsUserEnd(token);
                }

Here is a class I wrote in the past to make operations under Impersonation , Check out how the token is created inside DoWorkUnderImpersonation() with the credentials and the required constants to LogonUser() of advapi32.dll .这是我过去编写的 class 以在Impersonation下进行操作,查看令牌是如何在DoWorkUnderImpersonation()中创建的,其中包含advapi32.dllLogonUser()的凭据和所需的常量
The required operation is made inside the DoWork() method, add your copy files logic there.所需的操作在DoWork()方法中进行,在那里添加您的复制文件逻辑。
Call the static method DoWorkUnderImpersonation() from out side从外部调用 static 方法DoWorkUnderImpersonation()

// Implementation of the Impersonation class
Impersonation.DoWorkUnderImpersonation("DOMAIN", "USER", "PASSWORD");


public static class Impersonation
{
    // obtains user token
    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    // closes open handes returned by LogonUser
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    public static void DoWorkUnderImpersonation(string _domain, string _userName, string _password)
    {
        //elevate privileges before doing file copy to handle domain security
        WindowsImpersonationContext impersonationContext = null;
        IntPtr userHandle = IntPtr.Zero;
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_INTERACTIVE = 2;
        string domain = _domain;
        string user = _userName;
        string password = _password;

        try
        {
            Debug.WriteLine("windows identify before impersonation: " + WindowsIdentity.GetCurrent().Name);

            // if domain name was blank, assume local machine
            if (domain == "")
                domain = System.Environment.MachineName;

            // Call LogonUser to get a token for the user
            bool loggedOn = LogonUser(user,
                                        domain,
                                        password,
                                        LOGON32_LOGON_INTERACTIVE,
                                        LOGON32_PROVIDER_DEFAULT,
                                        ref userHandle);

            if (!loggedOn)
            {
                Debug.WriteLine("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
                return;
            }

            // Begin impersonating the user
            using (impersonationContext = WindowsIdentity.Impersonate(userHandle))
            {
                Debug.WriteLine("Main() windows identify after impersonation: " + WindowsIdentity.GetCurrent().Name);
                //run the program with elevated privileges (like file copying from a domain server)
                DoWork();
            }

        }
        catch (Exception ex)
        {
            Console.Write("Exception impersonating user: " + ex.Message);
        }
        finally
        {
            // Clean up
            if (impersonationContext != null)
            {
                impersonationContext.Undo();
            }

            if (userHandle != IntPtr.Zero)
            {
                CloseHandle(userHandle);
            }
        }
    }


    private static void DoWork()
    {
        try
        {
            // MAKE YOUR REQUIRED TASK HERE UNDER IMPERSONATION
        }
        catch (Exception ex)
        {
            Console.Write("error in Impersonation.DoWork() executing a task: " + ex.Message);
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM