How to Installing Sysmon with Config file on Remote Machine - powershell

Task I'm trying to accomplish
a program that copies Sysmon to remote machines and installs it with a given configuration file that catches all the events listed in the specifications.
I am able to copy all the files successfully. But when I try to run installer sysmon64.exe at a remote machine, it gives me an error.
PS C:\Users\Administrator> C:\Users\Administrator\Documents\Sysmon.ps1
Error:
System Monitor v12.0 - System activity monitor
Copyright (C) 2014-2020 Mark Russinovich and Thomas Garnier
Sysinternals - www.sysinternals.com
NotSpecified: (:String) [], RemoteException
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : 192.168.0.5
Usage:
Install: c:\windows\cpsysmon\Sysmon64.exe -i [<configfile>]
Update configuration: c:\windows\cpsysmon\Sysmon64.exe -c [<configfile>]
Install event manifest: c:\windows\cpsysmon\Sysmon64.exe -m
Print schema: c:\windows\cpsysmon\Sysmon64.exe -s
Uninstall: c:\windows\cpsysmon\Sysmon64.exe -u [force]
-c Update configuration of an installed Sysmon driver or dump the
current configuration if no other argument is provided. Optionally
take a configuration file.
-i Install service and driver. Optionally take a configuration file.
-m Install the event manifest (done on service install as well).
-s Print configuration schema definition of the specified version.
Specify 'all' to dump all schema versions (default is latest).
-u Uninstall service and driver. Adding force causes uninstall to proceed
even when some components are not installed.
The service logs events immediately and the driver installs as a boot-start driver to capture activity from early in the boot that the service will write to the event
log when it starts.
On Vista and higher, events are stored in "Applications and Services Logs/Microsoft/Windows/Sysmon/Operational". On older systems, events are written to the System
event log.
Use the '-? config' command for configuration file documentation.More examples are available on the Sysinternals website.
Specify -accepteula to automatically accept the EULA on installation, otherwise you will be interactively prompted to accept it.
Neither install nor uninstall requires a reboot.
Script
$Session = New-PSSession -ComputerName 192.168.0.5 -Credential "Study\Administrator"
Copy-Item "C:\Users\Administrator\Desktop\Sysmon\*.*" -ToSession $Session -Destination C:\Windows\cpsysmon\ -Recurse
Invoke-Command -Session $session -ScriptBlock {cmd.exe /C "c:\windows\cpsysmon\Sysmon64.exe" /silent -Wait}

I think you just need replace
cmd.exe /C "c:\windows\cpsysmon\Sysmon64.exe" /silent -Wait
by
cmd.exe /C "c:\windows\cpsysmon\Sysmon64.exe" -i -n -accepteula

Related

Is it possible to start a process as "nt authority\system" over Powershell remoting?

I'm automating the testing of the installation, detection, and uninstallation of some Windows applications. In order to run most of those installers silently, they must be run as nt authority\system. That is easy enough to accomplish on a local machine by invoking psexec something like this:
psexec -s setup.exe /S
I need to be able to automatically roll back the test target computer to known-good states, so I'm using another computer to orchestrate all this. Ideally I could use PowerShell remoting to start the installer on the target computer. I haven't yet found a way to achieve that.
Attempt 1: psexec from a Remote Session
The most obvious thing to do is to connect to the target computer using remoting and invoke psexec -s. Here's what that looks like:
[target.ad.example.com]: PS C:\Users\un1\Documents> C:\PsTools\PsExec.exe -s whoami
C:\PsTools\PsExec.exe :
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com
The problem is, the process just hangs at that point.
Attempt 2: Start-Process with -Verb RunAs
Using the RunAs verb with Start-Process may well run a process elevated, but it doesn't seem to run it as nt authority\system:
whoami-to-file.bat
whoami > out.txt
PowerShell Session
[target.ad.example.com]: PS C:\> Start-Process .\whoami-to-file.bat -Verb RunAs -WorkingDirectory
[target.ad.example.com]: PS C:\> Get-Contents out.txt
example\un1
The process is not started as nt authority\system.
The Question
Is it possible to start a process as nt authority\system over PowerShell remoting? If so, how?
Note: I'm no expert at Windows security and credentials, so I don't understand the exact security implications of this technique. In my case the only credentials in question are those a temporary test computer, so there isn't much risk. I doubt this technique is a good idea for production.
It's a Double-Hop (I think)
clymb3r's article about CredSSP I think explains why psexec -s fails over PowerShell remoting. I think that PowerShell remoting counts as one hop and invoking psexec -s counts as a second hop. If that's the case we have a manifestation of the double-hop authentication problem.
Use CredSSP
I suppose there are a variety of ways to overcome the double-hop problem. This being a testing scenario, CredSSP seems appropriate (beware the security risk). Here's the proof of concept.
First you have to enable CredSSP on both computers:
PS C:\> Enable-WSManCredSSP Client -DelegateComputer target.ad.example.com
PS C:\> Invoke-Command { Enable-WSManCredSSP Server} -ComputerName target.ad.example.com
Then you can remote to the target using CredSSP:
PS C:\> $credential = Get-Credential example\target-admin
PS C:\> Enter-PSSession target.ad.example.com -Credential $credential -Authentication CredSSP
[target.ad.example.com]: PS C:\>
And psexec -s works:
[target.ad.example.com]: PS C:\> psexec -s whoami
C:\PsTools\PsExec.exe :
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com
Connecting to local system...Starting PSEXESVC service on local system...Connecting with PsExec service on
target...Starting whoami on target...
whoami exited on target with error code 0.
nt authority\system
https://github.com/mkellerman/Invoke-CommandAs
Made a function to Invoke-Command as SYSTEM, or provided credential, against local/remote computer. Returns PSObjects, handles network interruptions and resolves any Double-Hop issues.
Try it out let me know if this resolves your issues.

PowerShell - Remote Start-Process - "This command cannot be run due to the error: This operation requires an interactive window station."

I am trying to start SmartBear's TestExecute program remotely through PowerShell and I'm getting an error when trying to call Start-Process.
This command cannot be run due to the error: The requested operation requires elevation.
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
+ PSComputerName : myClient.ourDomain.local
I can't figure out how to get around this. How do I make this work?
Here's my script:
# $TestExecuteLocalSource is the directory of TestExecute.exe on the remote machine
# $TestProjectSuite is the directory of project suite on the remote machine
# These paths are local (relative to the remote machine)
Function StartTestExecute
{
$rs = Get-PSSession
$script = {param($TestExecuteLocalSource, $TestProjectSuite);
cd $TestExecuteLocalSource
Start-Process .\TestExecute.exe -NoNewWindow -ArgumentList $TestProjectSuite, '/r', '/p:eSignRegression', '/e'
}
Invoke-Command -Session $rs -ScriptBlock $script -ArgumentList ($TestExecuteLocalSource, $TestProjectSuite)
When running tests, TestComplete/TestExecute must have access to the system GUI. When you are running test on a remote machine using this approach, GUI is not accessible and TestExecute cannot work. The best way to run a test remotely is using the Network Suite feature of TestComplete. It will automatically create a GUI session on a remote machine and run the test within it.

Running a Setup.exe from a network share, via Invoke-Command in Powershell

PSEXEC started to give me some trouble, and I decided to recode in PowerShell.
This batch command used to work for me, before PSEXEC started messing things up:
psexec -accepteula \\<ServerToBeUpdated> -u <User> -p <Password> cmd /c "\\<ServerWithInstallationFile>\SystemEnv\Bin\Setup.exe /silent /Update"
I'm trying to do this with Invoke-Command in Powershell, but with no luck so far.
I've tried many combinations, and googled a lot, and overall it seems that PowerShell is not fond of the UNC path I'm trying to install from.
Here is what I've got:
Invoke-Command -ComputerName <ServerToBeUpdated> -ScriptBlock { Start-Process -FilePath "\\<ServerWithInstallationFile>\SystemEnv\Bin\Setup.exe" -ArgumentList "/update /silent" -wait }
I get this error message:
This command cannot be run due to the error: Access is denied.
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
+ PSComputerName : DE5441
Some people say that the setup.exe has be copied locally on the remote server. But this does not seem to be an option for me, mainly for two reasons.
My setup.exe identifies that it is not in the right path, then it kills the local the setup.exe process, and automatically starts a new setup.exe from the UNC path.
I also need the ExitCode from my setup.exe, which gets lost when the "killing" starts as mentioned in reason number 1.
As a final note, I did grant access for PowerShell to run remotely with the Enable-PSRemoting command, and I also get expected results from this simple test:
Invoke-Command -ComputerName <ServerToBeUpdated> -ScriptBlock { Hostname }
You are experiencing a so called double-hop authentication issue. If using normal authentication you will not be able to authenticate to a second computer from the machine you are invoking the command on.
To solve this you can use CredSSP.
To enable CredSSP on the machine that is being called:
Enable-WSManCredSSP -Role Server -force
To enable CredSSP on the client:
Enable-WSManCredSSP -Role Client -DelegateComputer server.domain.com -force
The -delegateComputer parameter expects a FQDN but also takes wildcards.
After enabling CredSSP you can use it to invoke your command with the parameter -authentication CredSSP

Powershell remote execution not writing log on remote machine

I am currently stuck with an installation issue using a powershell script. I can run the script without any problem on Host B from command line. But when I attempt to launch it remotely, the script is not able to create the log file (which I monitor to see when I need to send the password to the command line). The error is at very bottom...
I launch the installer from Host A (see commands below). It remotely executes the powershell script cognosInstall.ps1 on Host B. The script code is at bottom. It begins to copy files over and kick-off the installation, but for some reason it has a problem with creating the log file. I check local directory on HostB and do not find the file either.
Host A (data collector): Triggers remote execution of powershell script which installs IBM Cognos.
$s=new-pssession -computername HostB -credential $creds
invoke-command -session $s {$filename=Split-Path c:\temp\auto-install\*stats*.iso -leaf -resolve;echo $filename;}
invoke-command -session $s {c:\temp\auto-install\cognosInstall.ps1 $filename;}
Host B (Cognos is being installed on):
#Open a command window
invoke-item C:\Windows\System32\cmd.exe
start-sleep -s 2
# Write output of install command to file
select-window cmd |send-keys "c:\temp\cognos-install\cognos_install.bat c:\temp\cognos-install\cognos_mssql.ini C:\temp\IBM_Cognos_10.1.1_and_FP1 > c:\temp\Cognos_Install_log 2>&1 {ENTER}"
#check file for password prompt
do {
Start-Sleep -s 8;
write-output "Waiting for Password Prompt"
}
until (Select-string -Path c:\temp\Cognos_Install_Log -pattern Password )
select-window cmd |send-keys "Passwd123{ENTER}"
Error I am getting:
Install starts to run..... then hits this issue.....
Copying install config file to cognos-install directory
C:\temp\auto-install\cognos_mssql.ini
1 File(s) copied
Beginning of Cognos Install - wait for completion
Waiting for Password Prompt
Cannot find path 'C:\temp\Cognos_Install_Log' because it does not exist.
+ CategoryInfo : ObjectNotFound: (C:\temp\Cognos_Install_Log:Stri
ng) [Select-String], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.Selec
tStringCommand

Intermittent errors with automation of virtual machines using Powershell

I have an intermittent problem with Powershell when automating some tests on a virtual machine.
The scenario and set up is as follows:
Server running HyperV
One virtual machine with multiple snapshots
Powershell script that restores a given snapshot, copies files over, runs a test and retrieves log files
Batch file that calls the Powershell script multiple times with different parameters
The batch file parameters specify things like which snapshot to use, which test to run, etc.
The problem is as follows:
I can run the batch and some of the tests will fail to copy files / fail to create a scheduled task / fail to retrieve log files / etc. It varies which if any (or all) sections fail. Some of the tests will work completely. If I re-run the same batch file, again some tests may fail and others will work; there is no consistency in terms of which fail and which run. Sometimes I have two adjacent tests that use the same snapshot, 1 will work and 1 won’t (see errors below).
To restore the snapshots I am using the “PowerShell Management Library for Hyper-V” from: (http://pshyperv.codeplex.com/releases)
Below is some of the code:
Powershell (minus a few functions / variable declarations / reading xml config file / reading and validating command line inputs / and other non-relevant sections):
Function ApplySnapshot
{
LogAction "Starting apply snapshot"
LogAction $("Restoring snapshot {0}" -f $ss)
#Stop a running VM, restore snapshot, start it up and connect to it
$vmstate = get-vmstate $vmname
$vmstate = $vmstate.EnabledState
if ($vmstate -ne "Stopped")
{
stop-vm $vmname -force
Start-Sleep -Second 15
}
get-vmsnapshot $vmname | where {$_.ElementName -eq $ss} | Restore-VMSnapshot -force
start-vm $vmname -force
Start-Sleep -Second 20
LogAction $("Snapshot {0} restored" -f $ss)
LogAction "End apply snapshot"
}
Function CopyFiles
{
LogAction "Start copy installation files"
$from = "\\server\folderx"
$to = "\\" + $hostname + "\C$\test"
Enter-PSSession -ComputerName $hostname -Credential $cred
Copy-Item $from $to -Recurse
LogAction "End copy installation files"
}
Function CreateSchedule ($hn, $tn, $tr, $sd, $st, $un, $pw)
{
LogAction "Starting create schedule"
Invoke-Command -ComputerName $hn -ScriptBlock {
param($hn, $tn, $tr, $sd, $st, $un, $pw)
Write-Host $("Host name: [{0}]" -f $hn);
$cmd = $("schtasks.exe /create /S ""{0}"" /tn ""{1}"" /tr ""{2}"" /sc once /sd {3} /st {4} /ru ""{5}"" /rp ""{6}"" /rl highest /V1" -f $hn, $tn, $tr, $sd, $st, $un, $pw);
Invoke-Expression $cmd;
} -ArgumentList #($hn, $tn, $tr, $sd, $st, $un, $pw)
LogAction "End create schedule"
}
...setting variables etc...
ApplySnapshot
CopyFiles
CreateSchedule -hn $hostname -tn $taskname -tr $taskrun -sd $setdate -st $settime -un $username -pw $password
Batch file:
PowerShell -Command "& C:\Auto.ps1" <...params...>
PowerShell -Command "& C:\Auto.ps1" <...params...>
PowerShell -Command "& C:\Auto.ps1" <...params...>
PowerShell -Command "& C:\Auto.ps1" <...params...>
pause
Example output:
C:\Auto>PowerShell -Command "& C:\Auto.ps1" <...params...>
WARNING: The job to Change state of VM TestVM to Stopped is still
running in the background.
You can check its progress with Test-wmiJob or Test-wmiJob -statusOnly using
the following job id:
\\Server\root\virtualization:Msvm_ConcreteJob.InstanceID="A207CEBA-F582-4A42-
BCDE-3312C7FB6DCC"
JobStarted
WARNING: The job to Change state of VM TestVM to Running is still
running in the background.
You can check its progress with Test-wmiJob or Test-wmiJob -statusOnly using
the following job id:
\\Server\root\virtualization:Msvm_ConcreteJob.InstanceID="42C31CEF-00E2-40A7-
AF70-578B0B91B05D"
JobStarted
Enter-PSSession : Connecting to remote server failed with the following error m
essage : The WinRM client cannot complete the operation within the time specifi
ed. Check if the machine name is valid and is reachable over the network and fi
rewall exception for Windows Remote Management service is enabled. For more inf
ormation, see the about_Remote_Troubleshooting Help topic.
At C:\Auto.ps1:192 char:18
+ Enter-PSSession <<<< -ComputerName $hostname -Credential $cred
+ CategoryInfo : InvalidArgument: (TestVM:String) [Enter-PSS
ession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
[TestVM] Connecting to remote server failed with the following error messa
ge : The WinRM client cannot complete the operation within the time specified.
Check if the machine name is valid and is reachable over the network and firewa
ll exception for Windows Remote Management service is enabled. For more informa
tion, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (:) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionStateBroken
So, in this example, the snapshot has been successfully applied (despite the warnings). The “Enter-PSSession” error appears after the files have been copied to the virtual machine.
As a test, I tried this on a different server (also running HyperV etc etc), and I found that I still get the initial error (after the file copying stage) but I do not get the error creating the scheduled task.
All my efforts to search for information on the “Connecting to remote server failed with the following error message : The WinRM client cannot complete the operation within the time specified.” Error seem to say “make sure the machine is set up for remote use”; well I know it is because sometimes it works and if I run just an “Enter-PSSession” command by itself, I can connect.
The server(s) and virtual machine(s) are on the same domain.
I know there’s a lot to take in here, but I would really appreciate some help in how to troubleshoot / fix this problem.
Thank you
Maybe the targets are not always up when the connection attempts are being made.