0

I have a C# winform application which I want to impersonate with a local window user. I can run the exe run as different user and can send the local user credential,

 static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

enter image description here

Question - how to send the credential for local user through code so that whenever the application runs, it's should run with that user context? Any example code appreciate. Thanks!

user584018
  • 10,186
  • 15
  • 74
  • 160

2 Answers2

1

I dont know a direct way to do this, i found a solution though, it isnt really pretty but it would do the job

You would need 2 main things to pull this off. First to install psexec and secondly to create a console app with this code in mind. You would run the program you like as the user you like

using System.Diagnostics;

// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = \\computername -u user -p password "PathToYourProgram"; 
// Enter the executable to run, including the complete path
start.FileName = psexec.exe; 
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;

// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
     proc.WaitForExit();

     // Retrieve the app's exit code
     exitCode = proc.ExitCode;
}

this code is taken from Launching an application (.EXE) from C#?

nalnpir
  • 1,167
  • 6
  • 14
0

I'm able to run the winform in local user context, here I did impersonate code. Refer this article, https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsimpersonationcontext?redirectedfrom=MSDN&view=netframework-4.7.2

and here is my code, running Form1() under impersonation,

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
using System.Security;

namespace WindowsFormsApp1
{
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    /// 
    [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);

    // Test harness.
    // If you incorporate this code into a DLL, be sure to demand FullTrust.
    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    [STAThread]
    static void Main()
    {
        try
        {
            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;

            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(PUT_YUR_LOCAL_USER_NAME, PUT_YOUR_MACHINE_HOST_NAME_OR_DOMAIN_NAME, PUT_YOUR_PASSWORD, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out SafeTokenHandle safeTokenHandle);

            //Console.WriteLine("LogonUser called.");

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                MessageBox.Show(string.Format("LogonUser failed with error code : {0}", ret));
                throw new System.ComponentModel.Win32Exception(ret);
            }
            using (safeTokenHandle)
            {
                // Use the token handle returned by LogonUser.
                using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                {
                    using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new Form1());
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("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);
}
}
user584018
  • 10,186
  • 15
  • 74
  • 160