How to remotely register static ETW manifests as part of a website deployment? - powershell

I'm doing a pilot effort to use the new EventSource (Microsoft.Diagnostics.Tracing.EventSource from nuget) and its new support for ETW channels in order to write to the windows event log. The code is in place, and it writes properly to my workstations event log. I'm thrilled.
Now comes the difficult part. The application that's taking advantage of this capability is a web service, and we deploy it with webdeploy as part of a build-deploy-test system. Because usage of ETW channels requires static registration of provider manifests via wevtutil.exe. The EventSource documentation states that this is best done as part of an installer, but this seems a bit out of webdeploy's capabilities.
Our aim is that we would be able to automatically uninstall the manifest resident on the target server immediately before executing the webdeploy package, and then to import the new manifest after the webdeploy sync has completed. We're not set on this, but it seems like the most sensible way.
For that reason, it seems like maybe this is something that powershell remoting might be able to solve, but it's not an area I know much about.
Has anyone done something like this? Is there a better or simpler way?

There are only a few requirements here. A) the remote machine must have PowerShell remoting enable which also means it must have PowerShell 2.0 or higher B) the script running on the local machine must be able to run as administrator and the credentials used must have admin privileges on the remote machine. If you can meet those requirements then this should be cake.
On the remote machine you need to execute two commands to enable remoting:
Set-ExecutionPolicy RemoteSigned
Enable-PSRemoting -Force
Then on the local machine from an elevated prompt you should be able to execute something like this from a script:
# these two paths assume these files have been copied to the remote computer and to a directory
# in which the service account has privileges to read i.e. not under a userprofile dir.
$etwDllPath = c:\somepath\myassembly.mysourcename.etwManifest.dll
$etwManPath = c:\somepath\myassembly.mysourcename.etwManifest.man
$s = New-PSSession -ComputerName <remoteComputerName>
Invoke-Command -Session $s {param($man) wevtutil.exe um $man} -arg $etwManPath
Invoke-Command -Session $s {param($man,$dll) wevutil.exe im $man /rf:$dll /mf:$dll} -arg $etwManPath, $etwDllPath
Remove-PSSession $s
If you can avoid a remote path with spaces, try to. It will make this easier. :-)

Related

PowerShell - ActiveDirectory Module

I need the ability to have users run a script that requires the ActiveDirectory module. I copied over the following:
"C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ActiveDirectory", "Microsoft.ActiveDirectory.Management.resources.dll", "Microsoft.ActiveDirectory.Management.dll".
The script runs two Get-ADUser commands, 1 without the -Server parameter and the other with. The issue is that the former is working but the latter is not.
Is there another module that I need to copy over?
I don't like the idea of installing administrative tools for non-admins. Even if you could get away with copying files and not doing the full-blown RSAT installation. Not the least of reasons is you are dramatically increasing the attack surface for malicious actors. The better solution is (Just Enough Administration) JEA, or a philosophically similar approach.
JEA / Contrained endpoints can get complicated, but a summary of what you can do looks something like this:
New-PSSessionConfigurationFile -Path 'C:\PSSessionConfigs\DemoPSEndpointConfig.pssc' -ModulesToImport ActiveDirectory -VisibleCmdlets "Get-ADUser"
Register-PSSessionConfiguration -Path 'C:\PSSessionConfigs\DemoPSEndpointConfig.pssc' -ShowSecurityDescriptorUI -Name DemoPSEndPoint
Run these commands on a system that has the ActiveDirectory module (likely the whole RSAT component) installed, it doesn't need to be a Domain Controller. It will create a new PowerShell remoting endpoint configuration that exposes only the commands you wish. The Register-PSSessionConfiguration command will display a security dialog where you can permission which users you want to allow to connect, you want to grant them read & execute permission. Once that's done, you can get the results with an Invoke-Command command like this:
Invoke-Command -ComputerName <ServerName> -ConfigurationName DemoPSEndPoint -ScriptBlock { Get-ADUser <UserName> }
You can add the -Server parameter in the command without issue. You can expand the cmdlets you are allowing in the New-PSSessionConfiguration command.
Again this is very much a summary of a more complex topic but should be enough to get what you want.
Personally, I don't use configuration files as much as I use startup scripts. I think the latter is more flexible. You can get some information about that here. If you really want to dig into this there are references at the end of the article including a link to the PowerShell JEA documentation. There's also a link to some of the MVP articles I used to develop my own endpoints.
The ActiveDirectory module is dependent on the RSAT (remote server administration tool). This is avalible to install/activate through powershell: https://mikefrobbins.com/2018/10/03/use-powershell-to-install-the-remote-server-administration-tools-rsat-on-windows-10-version-1809/
With this installed you automatically also get the Activedirectory module installed.

Double-Hop Errors when running Skype for Business Cmdlets

I am attempting to automate the Skype for Business Server installation process in Powershell, I have a script that remotes into specified machines and begins preparing them as Front-End servers. The problem lies when certain SfB cmdlets (SfB commands are all of the form "verb-Cs...", ex. Get-CsUser or Get-CsPool) are run in remote sessions, they throw the double-hop error:
Exception: Active Directory error "-2147016672" occurred while searching for domain controllers in domain...
This is after running Enable-CsComputer, which enables the computer's role-based off its definition in the topology (topology was published successfully). The user object is in all required groups (RTCUniversalServerAdmins, Schema Admins, CsAdministrators & Local Admin rights on all SfB Servers). Oddly enough, the command 'Import-CsConfiguration -localstore" does not throw errors, and it's in the same remote session. There may be other local or domain groups that I need to be in, but I cannot pinpoint exactly which and have not seen them documented in the Skype build guides. Skype commands that have parameters to specify targets or just pull data, such as Get-CsPool or Get-CsAdForest, do not have errors because they are run in the local scope. The Enable-CsComputer has no parameter for the computer name, it has to be executed from that machine itself.
Enabling CredSSP delegation on each server is not an option, and I'm not understanding why there is a "second hop" in this command! If the second hop was a resource on a file server or database, that would make sense, and be easy to solve, but in this case, I can't track it. Can anyone tell me what I may be missing?
Here's a code sample to try and illustrate. From the jumbox I get the pool data to create an array, and a session is opened to each machine:
$ServerArray =get-cspool -identity $poolName
$i=0
$SessionArray = #{}
foreach($server in $ServerArray.Computers){$SessionArray[$i] = new-PsSession -ComputerName $server}
foreach($session in $SessionArray.values){
invoke-Command -session $session -scriptBlock {
#remote commands:
import-csConfiguration -<config file path> -localstore; #no errors
enable-CsReplica; #no errors
enable-cscomputer; #double hop error here
}}
If I log into that machine and run the same command, it executes fine but the intention of the project is to automate it on an arbitrary number of machines.
It looks like it's just trying to authenticate to a domain controller, which is reasonable. You'll have to approach this like any other double-hop issue.
Microsoft has an article dedicated to the double hop issue, and has a few solutions other than CredSSP that you can look at: Making the second hop in PowerShell Remoting

vNext Work Around for Second Hop Issue on NonDomain Machines

I've asked the Microsoft Developer Community this question but I haven't had much success.
I am trying to create some automation tests with a vNext Build Definition in which the build agent RemotePSSession into a non-domain virtual machine (the test machine) and runs a batch file that can take several arguments. This batch file may read (installer files) or write (reports) to a network share that is on the domain. The issue that I am coming across is the second hop issue. Here is an article about it: https://blogs.technet.microsoft.com/ashleymcglone/2016/08/30/powershell-remoting-kerberos-double-hop-solved-securely/
In my instance, the PowerShell Remote Session is not able to pass the credentials we have authenticated previously in the test machine to access the network share’s resources. We have tried using CredSSP authentication on both the agent and the test machine to enable access but that has failed. The Net Use and other commands which call domain resources have also failed. We’ve even tried modifying the custom task PowerShell on Target Machines task and did not have much luck with it.
From what we have discovered is that there is no way to access the domain network shares with RemotePSSession with the following topology: Server A (which is in the domain or workgroup) ⇒ RemotePSSession + CredSSP into Server B (which is non-domain), using a local admin Server B account ⇒ Calls the network shares, with Net Use using some domain account.
It seems that the second hop only works for domain-joined machines (we have been testing it CredSSP using as well).
Let us know if there is a solution or workaround that we can implement.
Their response was >> If you can make sure the method is correct and the issue is caused by DevOps, we will be happy to help you with your issues about DevOps. Here are some documents might be helpful: https://learn.microsoft.com/en-us/powershell/scripting/learn/remoting/ps-remoting-second-hop?view=powershell-6.
I've looked at this documentation before and I haven't had much success, does anyone else have any suggestions?
Here is a code snippet:
#serverA - local machine
#serverB - $remoteServer
#serverC - DFS namespace server
$session = New-PSSession -ComputerName $remoteServer -Credential $credential -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck) -Authentication Credssp
$scriptBlock_runFile = {
#Scenario 0 which works:
#ipconfig
#Scenario 1 which doesn't work:
#& dir \\contoso.com\departments\folder"
#Scenario 2 which doesn't work:
#& net use x: \\contoso.com\departments\folder /user:CONTOSO\user "password"
}
Invoke-Command -Session $session -ScriptBlock $scriptBlock_runFile

Powershell remoting - cannot execute an exe as another user

I've a commandline program (c#) that encrypts config files based on machine key.
A powershell script copies the build to a Target Server, modifies configs accordingly and installs windows services.
All the windows services run as local system account (standard user, non-admin) - let's call this account "locuser".
The Target Server is a Win 2012 R2 Server. All of the above is achieved by PS remoting from the Build Server to this Target server.
Now, I need to run the encrypt commandline program as "locuser", so that the program can use the account specific key to do the encryption.
I know that this can be easily achieved by calling Start-Process cmdlet with -Credentials parameter. Well, here's the catch, the above works fine, if I remote in (RDP) to the Target Server and then run the Start-Process .... -Credential $cred from a Powershell Console.
However, I need this to be working while I remote-in (using my scripts) to the TargetServer whilst deploying. When I remote-in to the TargetServer I use credentials that has Admin privileges.
I've tried the following
I've granted "locuser" both "Full Control" and "Invoke (Execute)" permissions by using the Set-PSSessionConfiguration -Name Microsoft.PowerShell -ShowSecurityDescriptorUI command. I've run this command for both Microsoft.Powershell and Microsoft.Powershell32 - Still get Access Denied
I've edited the "Local Security Policy"->"Local Policies"->"User Rights Assignment"->Impersonate a client after authentication - and added both the Admin account (that I login with) and the "locuser" account - Still get Access Denied
I've also granted locuser admin rights - Still get Access Denied
I'm pretty sure, there is some configuration on the PS Remoting Side of things that I'm missing out but can't figure out what - because all Powershell throws me is a Access Denied error (see screenshot) with little to no useful information to troubleshoot further.
Also, checked Event logs for any traces but to no avail.
You've fallen prey to the dreaded Double Hop. Basically you're authenticating from computer A to computer B, then trying to authenticate again from computer B to computer C (which also happens to be B in this case).
If at all possible, you would be better off ending the session and starting a new one with the locuser credentials, then just calling Start-Process. Another, more messy approach is to use schtasks.
I can tell you how to do it in the same session but it's a bit messy and very complicated, and should only be a last resort:
On the originating server (Build Server):
Run the command Enable-WSManCredSSP -Role Client -Delegate [name] where [name] is an IP or DNS address / range including any target servers (eg "192.168.1.*")
Open GPEdit.msc, navigate to Computer Configuration\Administrative Templates\System\Credentials Delegation and check that the rules Allow delegating fresh credentials and Allow delegating fresh credentials with NTLM... are enabled and include [name]
On the Target Server:
Run the command Enable-WSManCredSSP -Role Server
Running the command:
Invoke-Command [targetserver] [-Credential $cred] -Scriptblock {
## do stuff
Invoke-Command . -Credential $locusercred -Authentication Credssp -ScriptBlock {
Start-Process -FilePath $sc #etc
}
}
Some things to be aware of:
Firstly I used this setup to create a local session, then remote from there (so A-A-B instead of A-B-B) so the Group Policy stuff might be in the wrong place but pretty sure it's right.
Secondly I found that credentials are a pain to get working in sessions (in this case $locusercred). I did get it going natively but weirdly it suddenly couldn't decrypt the securestring. I ended up saving a securestring with a defined key to the registry so it can always be decrypted from any account, you may need to come up with your own solution there.
All this stuff is explained in the free eBook "The Secrets of PowerShell Remoting", if you go for the double-hop approach I recommend giving it a read.

Powershell 3.0: Using my local profile and modules in remote PSSessions

I need my local $profile located on my local PC to be loaded automatically when I PSRemote into other computers. My $profile also imports a few local modules (available only on my local PC). So, I need my $profile to be enhanced so that my modules can be still be imported (regardless where my $profile is loaded).
I spent a lot of time trying to get this to work; but see a lot of inconsistent information posted (probably because the differences between PS2 and PS3). Everything I tried, resulted in some kind of error.
I was hoping someone would help me with a dummy-proof working example of how to do this. The only thing that actually works is a basic: enter-pssession -ComputerName RemoteServerName. I did try to at least get my local profile to load in a remote session (see below), but that didn't work either; let alone loading the modules imported in the profile file.
Register-PSSessionConfiguration -Name MyLocalProfile -StartupScript $Profile
Enter-PSSession -ComputerName REMOTESERVERNAME -ConfigurationName 'MyLocalProfile'
Gives error:
Enter-PSSession : Connecting to remote server REMOTESERVERNAME failed with the following error message : The WS-Management service cannot process the request. Cannot find the MyLocalProfile session configuration in the WSMan: drive on the REMOTESERVERNAME computer.
I even tried:
Register-PSSessionConfiguration -Name MyLocalProfile `
-StartupScript \\MYLocalPC\profile$\Microsoft.PowerShell_profile.ps1
But, but it still produced the same error. Not sure why it should be this hard to do something that most people would most likely want to happen by default.
Short answer: You're doing it incorrectly, and it's impossible to do it that way.
Long Answer:
From the Enter-PSSession page on MSDN, a line stands out:
The session configuration for a session is located on the remote computer. If the specified session configuration does not exist on the remote computer, the command fails.
Therefor you will have to Invoke-Command the Register-PSSessionConfiguration before creating the new session.