Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Runtime.InteropServices; // DllImport
- using System.Security.Principal; // WindowsImpersonationContext
- using System.Security.Permissions; // PermissionSetAttribute
- namespace Inpersonation
- {
- class Inpersonater
- {
- // Get Token
- [DllImport("advapi32.dll", SetLastError = true)]
- public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
- int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
- // Return from context
- [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
- public extern static bool CloseHandle(IntPtr handle);
- public static void DoWorkUnderImpersonation()
- {
- WindowsImpersonationContext impersonationContext = null;
- IntPtr userHandle = IntPtr.Zero;
- const int LOGON32_PROVIDER_DEFAULT = 0;
- const int LOGON32_LOGON_INTERACTIVE = 2;
- Console.Write("Domain: ");
- string domain = Console.ReadLine();
- Console.Write("Login: ");
- string user = Console.ReadLine();
- Console.Write("Password: ");
- string password = "";
- ConsoleKeyInfo key;
- do
- {
- key = Console.ReadKey(true);
- if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
- {
- password += key.KeyChar;
- Console.Write("*");
- }
- else
- {
- if (key.Key == ConsoleKey.Backspace && password.Length > 0)
- {
- password = password.Substring(0, (password.Length - 1));
- Console.Write("\b \b");
- }
- }
- }
- // Stops Receving Keys Once Enter is Pressed
- while (key.Key != ConsoleKey.Enter);
- Console.WriteLine("");
- try
- {
- if (domain == "")
- domain = System.Environment.MachineName;
- bool loggedOn = LogonUser(user,
- domain,
- password,
- LOGON32_LOGON_INTERACTIVE,
- LOGON32_PROVIDER_DEFAULT,
- ref userHandle);
- if (!loggedOn)
- {
- Console.WriteLine("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
- return;
- }
- impersonationContext = WindowsIdentity.Impersonate(userHandle);
- //(WindowsIdentity.GetCurrent().Name);
- string text = System.IO.File.ReadAllText(@"C:\secret.txt");
- Console.WriteLine(text);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Exception impersonating user: " + ex.Message);
- }
- finally
- {
- if (impersonationContext != null)
- {
- impersonationContext.Undo();
- }
- if (userHandle != IntPtr.Zero)
- {
- CloseHandle(userHandle);
- }
- }
- }
- public static void Main()
- {
- DoWorkUnderImpersonation();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement