After a bit of reading, this question can be reduced to Impersonating a domain user on a host in Powershell non-interactively.
Impersonating a domain user on a host in Powershell non-interactively
To impersonate a user in powershell non-interactively you must do the following:
- Enable Powershell Remoting
- Add User to PowerShell PSSessionConfiguration
- Enable CredSSP on Host (As client and server)
- Export Asymmetrical Key of Domain user
- Initiate session with Credssp authentication
Enable Powershell Remoting
The host we will use needs to have Windows Remote Management enabled, there is a powershell command to do all the work for you.
Enable-PSRemoting -Force
Add User to PowerShell PSSessionConfiguration
If the user is not an administrator on the host, you must add it to the Powershell Session Configuration. You can then control what kind of access you would like to give to the user on that host.
Set-PSSessionConfiguration Microsoft.PowerShell -ShowSecurityDescriptorUI
Enable CredSSP on Host (As client and server)
Credssp deals with the double-hop or second-hop issue on Microsoft products.
This allows credential forwarding to occur for users to access services that may not be on the local host, such as network shares.
In many cases, this is an issue when logging into machine B from machine A and needing a resource on machine C.
In this case, machine A and B are the same host, so we enable Credssp on the host as both the Client
and Server
roles.
Enable-WSManCredSSP -Role Client -Delegate $env:COMPUTERNAME
Enable-WSManCredSSP -Role Server
Export Asymmetrical Key of Domain user
This is mentioned in one of the answers by 'noam'.
An asymmetrical key can be used by exporting the domain user's password to a file.
Then, the file can be read and a new powershell session can be started on the host.
Read-Host -AsSecureString "Write the password: " | ConvertFrom-SecureString | Out-File C:\somelocation\users-pass-key-file.txt
Initiate session with Credssp authentication
Now you can initiate a non-interactive login session in Powershell by reading the file with the key, and logging into the host.
$user = "DOMAIN\username"
$passkey = Get-Content C:\somelocation\users-pass-key-file.txt | ConvertTo-SecureString
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user,$passkey
Invoke-Command -ComputerName $env:COMPUTERNAME -ScriptBlock { Write-Output $env:USERNAME } -Credential $credential -Authentication Credssp
Using Jenkins with impersonated user
After doing the previous steps you can use your Jenkins slaves or master to execute Powershell commands on behalf of another user.
This will have to be done by running Invoke-Command
with the appropriate preface using the credentials stored on the host in question.