none
Impersonation problem - access denied

    Question

  • Hello, I have problem with this: https://msdn.microsoft.com/en-us/library/w070t6ka(v=vs.110).aspx

    I successfully impersonate other account (admin account), but I dont have permissions.

    My code:

    using System;
    using System.ComponentModel;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.Principal;
    using Microsoft.Win32;
    using Microsoft.Win32.SafeHandles;
    using System.Runtime.ConstrainedExecution;
    using System.Security.Permissions;
    
    namespace ConsoleApplication1
    {
        public class Program
        {
            private static void Action()
            {
                File.AppendAllText("C:\\Users\\kkoncar\\Desktop\\Temp.txt", "some text...");
            }
    
            [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);
    
            [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
            public static void Main(string[] args)
            {
                SafeTokenHandle safeTokenHandle;
                try
                {
                    string userName, domainName;
    
                    domainName = "KRISTIJANK";
                    userName = "John";
    
                    const int LOGON32_PROVIDER_DEFAULT = 0;
                    const int LOGON32_LOGON_INTERACTIVE = 2;
    
                    bool returnValue = LogonUser(userName, domainName, "SmartRGS15",
                        LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                        out safeTokenHandle);
    
                    Console.WriteLine("LogonUser called.");
    
                    if (false == returnValue)
                    {
                        int ret = Marshal.GetLastWin32Error();
                        Console.WriteLine("LogonUser failed with error code : {0}", ret);
                        throw new System.ComponentModel.Win32Exception(ret);
                    }
                    using (safeTokenHandle)
                    {
                        Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                        Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name);
                        using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                        {
                            using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                            {
                                Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);
    
                                Action();
                            }
                        }
                        Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception occurred. " + ex.Message);
                }
            }
        }
    
        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);
            }
        }
    }


    Console output:

    LogonUser called.
    Did LogonUser Succeed? Yes
    Before impersonation: SMART\kkoncar
    After impersonation: KRISTIJANK\John
    Exception occurred. Access to the path 'C:\Users\kkoncar\Desktop\Temp.txt' is de
    nied.
    Press any key to continue . . .
    


    • Edited by KKristijan Wednesday, September 09, 2015 10:17 AM not complete post
    Wednesday, September 09, 2015 10:16 AM

Answers

All replies

  • It looks like you are trying to access file on someone elses (kkoncar) Desktop. Remember after impersonation ,you are no longer kkoncar.

    Happy Coding.

    • Proposed as answer by Andy ONeillModerator Wednesday, September 09, 2015 12:53 PM
    • Unproposed as answer by KKristijan Wednesday, September 09, 2015 2:07 PM
    Wednesday, September 09, 2015 11:11 AM
  • This is my situation:
    kkoncar is my user account. I'm dont have admin privilegies.

    John is admin account. John has no restrictions - he can access to all my files, settings itd... When he tries to access my home folder, UAC ask for confirmation, and his access is granted.

    Then, why my program cannot access to these things?



    • Edited by KKristijan Wednesday, September 09, 2015 2:08 PM
    Wednesday, September 09, 2015 2:07 PM
  • Can you do this and let us know the result. It is for indicating that the application requires elevated privileges.

    https://msdn.microsoft.com/en-us/library/bb756929.aspx?f=255&MSPPError=-2147217396


    Happy Coding.

    Wednesday, September 09, 2015 2:20 PM
  • Can you do this and let us know the result. It is for indicating that the application requires elevated privileges.

    https://msdn.microsoft.com/en-us/library/bb756929.aspx?f=255&MSPPError=-2147217396


    Happy Coding.

    Still getting error... :/

    Idk... When I logged in John account, and try to access kkoncar home folder, UAC ask for confirmation, and I can access to all files. But, my program cant...

    p.s. Sorry, my english is not so great


    • Edited by KKristijan Wednesday, September 09, 2015 2:29 PM
    Wednesday, September 09, 2015 2:25 PM
  • ok, are you impersonating John just to access the file in your Desktop?

    Happy Coding.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.


    Wednesday, September 09, 2015 2:28 PM
  • yes - to access files, open program (as admin). this app is going to elevate privilegiest beacause kkoncar is not admin.
    Wednesday, September 09, 2015 2:32 PM
  • ok,

    Without impersonating can you try specify your FilePath as follows.

    string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    strig filePath = path + @"\Temp.txt"


    Happy Coding. 

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

    Wednesday, September 09, 2015 2:35 PM
  • Sorry for delay; internet issues. 

    Path is the same when use Enviroment.SpecialFolder.

    Without elevation (from kkoncar user account), app can add text

    • Edited by KKristijan Wednesday, September 09, 2015 3:16 PM
    Wednesday, September 09, 2015 3:14 PM
  • There is *A LOT* of code involved in doing what explorer does when asking you if you want to grant yourself access to files that you don't have access to when you're logged in as admin.  I'd recommend starting with checking the existing DACL on the file and verify that your user context should have access to it.  

    WinSDK Support Team Blog: http://blogs.msdn.com/b/winsdk/

    Wednesday, September 09, 2015 5:18 PM
  • Hi KKristijan,

    Here is a complete demo about Impersonation in C#.NET

    http://www.codeproject.com/Articles/124981/Impersonating-user-accessing-files-and-HKCU

    Hope you'll get some hints form above article.

    Best regards,

    Kristin


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by KKristijan Thursday, September 10, 2015 6:22 PM
    Thursday, September 10, 2015 7:30 AM
    Moderator
  • Thanks guys :)
    • Marked as answer by KKristijan Thursday, September 10, 2015 6:21 PM
    Thursday, September 10, 2015 8:39 AM