Skip to content

Instantly share code, notes, and snippets.

@jborean93
Created February 3, 2020 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jborean93/0cde95b055746294fb52ed6db3ac2840 to your computer and use it in GitHub Desktop.
Save jborean93/0cde95b055746294fb52ed6db3ac2840 to your computer and use it in GitHub Desktop.
Basic example of how to access network paths with custom credentials
# Copyright: (c) 2020, Jordan Borean (@jborean93) <jborean93@gmail.com>
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
Add-Type -Namespace LogonUtil -Name NativeMethods -MemberDefinition @'
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(
IntPtr hObject);
[DllImport("Advapi32.dll", SetLastError = true)]
public static extern bool ImpersonateLoggedOnUser(
IntPtr hToken);
[DllImport("Advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool LogonUserW(
string lpszUsername,
string lpszDomain,
IntPtr lpszPassword,
UInt32 dwLogonType,
UInt32 dwLogonProvider,
out IntPtr phToken);
[DllImport("Advapi32.dll", SetLastError = true)]
public static extern bool RevertToSelf();
'@
Function Get-ItemWithCredential {
<#
.SYNOPSIS
Basic framework that shows how to log on and impersonate a custom credential for network operations.
.DESCRIPTION
The actual command that is run can be anything as any operations by the thread are run under the context of the
impersonated token. All local actions continue to be done under the original process token's context but any
network sessions will use the credentials that are specified.
.PARAMETER Credential
The credential object that is used to log on user with LOGON32_LOGON_NEW_CREDENTIALS.
.EXAMPLE Access UNC path with custom credentials
$cred = Get-Credential
Get-ItemWithCredential -Path \\server\share\file.txt -Credential $cred
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[String]
$Path,
[PSCredential]
$Credential
)
$token = [IntPtr]::Zero
$impersonated = $false
if ($PSBoundParameters.ContainsKey('Credential')) {
$username = $Credential.UserName
$domain = [NullString]::Value # .NET string marshaling turns $null to "", use NullString instead.
if ($username.Contains('\')) {
# Get the domain part if the username is in the Netlogon format 'DOMAIN\username'.
$userSplit = $username.Split('\', 2)
$domain = $userSplit[0]
$username = $userSplit[1]
}
# Create a copy of the decrypted secure string in unmanaged memory for LogonUserW to read from.
$passwordPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($Credential.Password)
try {
$res = [LogonUtil.NativeMethods]::LogonUserW(
$username,
$domain,
$passwordPtr,
9, # LOGON32_LOGON_NEW_CREDENTIALS
3, # LOGON32_PROVIDER_WINNT50
[ref]$token
); $err = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
} finally {
# Make sure we always free the unmanaged memory as soon as we can to reduce the disclosure times of the
# secure string.
[System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($passwordPtr)
}
if (-not $res) {
$msg = "Failed to log the user '$($Credential.UserName) for impersonation"
$exception = [System.ComponentModel.Win32Exception]::new($err)
Write-Error -Message $msg -Exception $exception
return
}
}
try {
if ($token -ne [IntPtr]::Zero) {
# Set the thread token to the newly logged on NEW_CREDENTIALS logon, any subsequent network connections
# will use that context until RevertToSelf() is called.
$impersonated = [LogonUtil.NativeMethods]::ImpersonateLoggedOnUser(
$token
); $err = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
if (-not $impersonated) {
$exception = [System.ComponentModel.Win32Exception]::new($err)
Write-Error -Message "Failed to impersonate custom user" -Exception $exception
return
}
}
# Finally do you work here, any network operations will use the credentials that have been passed in. This can
# be anything but for this example only Get-Item is used.
Get-Item -Path $Path
} finally {
# We need to make sure we clean up the logon token and revert the thread's security context if set.
if ($token -ne [IntPtr]::Zero) {
$null = [LogonUtil.NativeMethods]::CloseHandle($token)
}
if ($impersonated) {
$res = [LogonUtil.NativeMethods]::RevertToSelf(); $err = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
if (-not $res) {
$exception = [System.ComponentModel.Win32Exception]::new($err)
Write-Error -Message "Failed to revert impersonation" -Exception $exception
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment