-
-
Save secure-77/2b91bc1f2d0f8e2a410d58ca0a798d43 to your computer and use it in GitHub Desktop.
Impersonate a user and execute a script block as that user
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ToExecute | |
$userName = "user" | |
$domain = "domain" | |
$password = '<<<PASS>>>' | |
$Path = '\\some\path\here' | |
.\Use-Impersonation.ps1 $userName $domain $password {Get-ChildItem $Path | Foreach { Write-Host $_.Name }} | |
#Use-Impersonation.ps1 | |
param( $userName, $domain, $password, [ScriptBlock] $scriptBlock ) | |
function GetCurrentPrincipal | |
{ | |
return [System.Security.Principal.WindowsIdentity]::GetCurrent().Name | |
} | |
$logonUserSignature = | |
@' | |
[DllImport( "advapi32.dll" )] | |
public static extern bool LogonUser( String lpszUserName, | |
String lpszDomain, | |
String lpszPassword, | |
int dwLogonType, | |
int dwLogonProvider, | |
ref IntPtr phToken ); | |
'@ | |
$AdvApi32 = Add-Type -MemberDefinition $logonUserSignature -Name "AdvApi32" -Namespace "PsInvoke.NativeMethods" -PassThru | |
$closeHandleSignature = | |
@' | |
[DllImport( "kernel32.dll", CharSet = CharSet.Auto )] | |
public static extern bool CloseHandle( IntPtr handle ); | |
'@ | |
$Kernel32 = Add-Type -MemberDefinition $closeHandleSignature -Name "Kernel32" -Namespace "PsInvoke.NativeMethods" -PassThru | |
try | |
{ | |
$Logon32ProviderDefault = 0 | |
$Logon32LogonInteractive = 2 | |
$tokenHandle = [IntPtr]::Zero | |
$success = $AdvApi32::LogonUser($userName, $domain, $password, $Logon32LogonInteractive, $Logon32ProviderDefault, [Ref] $tokenHandle) | |
if (!$success ) | |
{ | |
$retVal = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() | |
Write-Host "LogonUser was unsuccessful. Error code: $retVal" | |
return | |
} | |
Write-Host "LogonUser was successful." | |
Write-Host "Value of Windows NT token: $tokenHandle" | |
$identityName = GetCurrentPrincipal | |
Write-Host "Current Identity: $identityName" | |
$newIdentity = New-Object System.Security.Principal.WindowsIdentity( $tokenHandle ) | |
$context = $newIdentity.Impersonate() | |
$identityName = GetCurrentPrincipal | |
Write-Host "Impersonating: $identityName" | |
Write-Host "Executing custom script" | |
& $scriptBlock | |
} | |
catch [System.Exception] | |
{ | |
Write-Host $_.Exception.ToString() | |
} | |
finally | |
{ | |
if ( $context -ne $null ) | |
{ | |
$context.Undo() | |
} | |
if ( $tokenHandle -ne [System.IntPtr]::Zero ) | |
{ | |
$Kernel32::CloseHandle( $tokenHandle ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment