mattjohnsonpint/SimpleImpersonation

More details about behaviors of various LogonType and LogonProvider could be documented.

ryancdotnet opened this issue · 2 comments

Based on the documentation for this project:

"If impersonation fails, it will throw a custom ImpersonationException, which has the following properties:..."

While attempting to debug an issue, I noticed that even passing in invalid credentials to RunAsUser, it would still execute the Action (as the current user) if LogonType was NewCredentials.

I tested this scenario in a simple ConsoleApp:

using System;

namespace SimpleImpersonationFailureTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // Change this to anything other than NewCredentials and it successfully throws an exception
            SimpleImpersonation.LogonType logonType = SimpleImpersonation.LogonType.NewCredentials;

            SimpleImpersonation.Impersonation.RunAsUser(new SimpleImpersonation.UserCredentials("baddomain", "badusername", "badpassword"), logonType, () =>
            {
                //If I get here, that's a problem...
                Console.WriteLine("Goodbye World!");
            });

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
    }
}

My gut says LOGON32_LOGON_NEW_CREDENTIALS is the core of the issue, and there may not be a reasonable solution for trapping invalid credentials with this one LogonType. If so, then the documentation should at least be updated to reflect that.

  • NOTE: LogonType.NewCredentials will not raise exceptions when invalid credentials are provided. See here why (...)

So with LOGON32_LOGON_NEW_CREDENTIALS, the impersonation happens at the time of a network-outbound connection, such as writing a file to a CIFS share or connecting to Sql Server.

I ran this test with the these two scenarios and it appears the new user context is created and used at the time of the outbound connection, as I was able to successfully get exceptions for each one. However, the exceptions are from the .NET operations themselves, not generated from SimpleImpersonation (ie, not an ImpersonationException type).

I think the documentation should include how NewCredentials operates differently when RunAsUser is called, that due to the delayed impersonation credential usage, SimpleImpersonation is not able to generate ImpersonationExceptions immediately when RunAsUser is called.

I haven't documented all the quirks of the different logon types, as I simply pass them along to Windows. I agree that much more could be said about each one. I'd be willing to take a docs PR for this if anyone is up for it. Thanks.