Skip to content

Instantly share code, notes, and snippets.

@johnallers
Forked from idavis/Use-Impersonation.ps1
Last active June 25, 2018 08:05
Show Gist options
  • Save johnallers/4548e4316deff13da00b to your computer and use it in GitHub Desktop.
Save johnallers/4548e4316deff13da00b to your computer and use it in GitHub Desktop.
param(
[String] $domain,
[String] $username,
[String] $password,
[ScriptBlock] $scriptBlock
)
<#
.SYNOPSIS
Impersonates a user and executes a script block as that user. This is an interactive script
and a window will open in order to securely capture credentials.
.EXAMPLE
Use-Impersonation.ps1 mydomain.com testuser testpassword {Get-ChildItem 'C:\' | Foreach { Write-Host $_.Name }}
This writes the contents of 'C:\' impersonating the user that is entered.
#>
$logonUserSignature =
@'
[DllImport( "advapi32.dll", SetLastError=true )]
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 = $false
try
{
$success = $AdvApi32::LogonUser($userName, $domain, $password, $Logon32LogonInteractive, $Logon32ProviderDefault, [Ref] $tokenHandle)
}
finally
{
}
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 = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-Host "Current Identity: $identityName"
$newIdentity = New-Object System.Security.Principal.WindowsIdentity( $tokenHandle )
$context = $newIdentity.Impersonate()
$identityName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
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 )
}
}
@johnallers
Copy link
Author

The script was updated to pass the credentials as parameters (I'm only using this to test the effects of running specific code with impersonation). In the original script, I received a 1326 error code every time. I'm guessing it was due to how the password was being passed into the LogonUser method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment