Azure VM пытается олицетворять и получить доступ к файлу - PullRequest
0 голосов
/ 21 февраля 2019

Вот мой интерфейс.У меня есть 2 пользователя, первый «admin», а другой «user» в виртуальной машине Azure.Мой «пользователь» не имеет доступа к моему файлу C: /direc/test.txt, но у моего «администратора» есть все разрешения.

Поэтому я пытаюсь выдать себя за моего администратора, чтобы я могдоступ к моему C: /direc/test.txt как «пользователь».

Но, это дает мне эту сумасшедшую ошибку:
But, it give me this crazy error:

Выражение: [ошибка рекурсивного поиска ресурсов в mscorlib]
Описание: бесконечная рекурсия во время поиска ресурсов в mscorlib.
Это может быть ошибка в mscorlib или, возможно, в определенных точках расширения, таких как события разрешения сборки или имена CultureInfo.Имя ресурса: UnknownError_Num

Вот мой класс для подражания

public class CodeImpersonate : IDisposable
    {
        /// <summary>
        /// This logon type is intended for users who will be interactively using the computer, such as a user being logged on by a terminal server, 
        /// remote shell, or similar process. This logon type has the additional expense of caching logon information for disconnected operations; therefore,
        /// it is inappropriate for some client/server applications, such as a mail server.
        /// </summary>
        public const int LOGON32_LOGON_INTERACTIVE = 9;

        /// <summary>
        /// Use the standard logon provider for the system. The default security provider is negotiate, 
        /// unless you pass NULL for the domain name and the user name is not in UPN format. In this case, the default provider is NTLM.
        /// Windows 2000: The default security provider is NTLM.
        /// </summary>
        public const int LOGON32_PROVIDER_DEFAULT = 0;

        WindowsImpersonationContext impersonationContext;

        [DllImport("advapi32.dll")]
        public static extern int LogonUserA(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();

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

        public bool ImpersonateValidUser(String userName, String domain, String password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            // Console.WriteLine("Before impersonation: "
            //+ WindowsIdentity.GetCurrent().Name);
            try
            {
                if (RevertToSelf())
                {
                    if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                            ref token) != 0)
                    {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);


                            impersonationContext = tempWindowsIdentity.Impersonate();
                            if (impersonationContext != null)
                            {
                                Console.WriteLine("After impersonation: "+
                                WindowsIdentity.GetCurrent().Name);
                                CloseHandle(token);
                                CloseHandle(tokenDuplicate);
                                return true;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occurred. " + e.Message);
            }


            if (token != IntPtr.Zero)
                CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;
        }

        public void UndoImpersonation()
        {
            if (impersonationContext != null)
                impersonationContext.Undo();
        }

        public void printContext()
        {
            Console.WriteLine(impersonationContext.ToString());
            Console.ReadLine();
        }
        public void Dispose()
        {
            impersonationContext.Dispose();
        }
    }

Вот мой код в моей основной:

string currentPath = @"C:\direc";
            string currentFileName = "test";
            string currentFileExt = ".txt";

            try
            {
                FileOnDesktop = OpenFileFromCMS(currentPath, currentFileName, currentFileExt);
            }catch(Exception e)
            {
                Console.WriteLine(e);
            }



 private static bool OpenFileFromCMS(string currentPath, string currentFileName, string currentFileExt)
            {


                Byte[] arrayByte = null;
                CodeImpersonate impersonationDemo = new CodeImpersonate();

                    bool a = impersonationDemo.ImpersonateValidUser(user, domain, pwd);
                using (new Impersonation("domain", "admin", "123456"))
                {
                    string ActiveUser = WindowsIdentity.GetCurrent().Name;
                        string[] fileArray = Directory.GetFiles(currentPath);
                }
...