Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Runtime.InteropServices;
- using System.Security.Principal;
- using System.Security.Permissions;
- using Microsoft.Win32.SafeHandles;
- using System.Runtime.ConstrainedExecution;
- using System.Security;
- namespace FetchFile
- {
- class Program
- {
- [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, password;
- domainName = "domain";
- userName = "username";
- password = "password";
- const int LOGON32_PROVIDER_WINNT50 = 3;
- const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
- bool returnValue = LogonUser(userName, domainName, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, 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("Value of Windows NT token: " + safeTokenHandle);
- Console.WriteLine("Before impersonation: "
- + WindowsIdentity.GetCurrent().Name);
- using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
- {
- string src = @"\serversharedfile.txt";
- string dest = @"c:file.txt";
- File.Copy(dest, src);
- Console.WriteLine("After impersonation: "+ WindowsIdentity.GetCurrent().Name);
- }
- 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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement