Logstash-forwarder as Windows Service - elasticsearch

I'm struggling to create a Windows Service for a logstash forwarder on Windows 2008 R2 Server.
My setup looks as follows:
Ubuntu Server 14.04 LTS
Elasticsearch
Logstash
Kibana
Windows Server 2008 R2:
Application logging to a certain path.
Ship logs to the ELK Stack via Logstash-forwarder
I'm currently shipping logs successfully to the ELK-Stack via Logstash forwarder compiled for Windows using the instructions here... https://github.com/elastic/logstash-forwarder. The only problem is, that I have to run the logstash forwarder in a CLI window, and I'm not able to set it up as a Windows Service.
I've tryed the following SC command, the service is created but the service will not start at all. Just returning the following error: The service did not respond to the start or control request in a timely fashion.
sc create LogstashForwarder binpath= "\"C:\_Logstash\logstash-forwarder.exe\" -config=\"C:\_Logstash\logstash-forwarder.conf\"" start= Auto displayname= "Logstash forwarder"
Unfortunately Google does not know any answer either.
Does anyone have been able to start the logstash forwarder on Windows as a Windows Service with the SC command? Some good advice will be very appreciated.

If your logstash configuration is correct try these steps.
Get nssm soft
Decompress the nssm zip in the bin folder of logstash
Excecute from command line nssm install logstash
Add the path to your bat on the launched config screen
Add your startup directory too.
Here you can get some more help
https://blog.basefarm.com/blog/how-to-install-logstash-on-windows-server-2012-with-kibana-in-iis/
https://github.com/verbosemode/public-notes/blob/master/logstash-windows.md
Hope this help

To Add to Rys' answer, Logstash-Forwarder doesn't natively read the Windows Event log. Whilst looking into how to get around this I came across this gist by Sean-M.
I modified his original script so that the Powershell script starts LSF and then pipes the event log into the stdin. I then point NSSM at the script and run that as a service. If you have your configuration file setup like this:
{
"network": {
"servers": [ "<logstash IP>:5000" ],
"timeout": 15,
"ssl ca": "C:/path/to/logstash-forwarder.crt"
},
"files": [
{
"paths": [
"C:/inetpub/logs/LogFiles/W3SVC*/*.log"
],
"fields": { "type": "iis-w3svc" }
},
{
"paths": [
"-"
],
"fields": { "type": "windows-event" }
}
]
}
LSF will capture the JSON input and send it to Logstash. Powershell code below**:
#Requires -Version 3
param (
[string]$lognames
)
#reading security log requires elevated privileges so only read Application and System for now
[string[]]$logname = $("Application", "System" )
if ($lognames)
{
[string[]]$logname = $lognames -split ", "
}
##################################
# Functions #
##################################
function EvenSpace{
param ($word)
$tabWidth = 48
$wordTabs = $tabWidth - $word.Length
$tabNum = [Math]::Floor($($wordTabs/4)) / 2
("`t" * $tabNum)
}
## Read events, write to file
function ReadEvents {
param ([hashtable]$filter, [string]$OutFile=[String]::Empty)
## Make it look pretty if writting to stdout
try {
[object[]]$data = Get-WinEvent -FilterHashtable $filter -ErrorAction SilentlyContinue | sort RecordId
[int]$count = 0
if ((-not $data -eq $null) -or ($data.Count -gt 0)) {
$count = $data.Count
}
Write-Verbose ("Log: $($filter["LogName"])" + (EvenSpace -word $filter["LogName"]) + "Count: $count")
}
catch {
$Error[0]
Write-Verbose ""
Write-Verbose "Filter:"
$filter
return
}
if ($data.Count -gt 0) {
foreach ($event in $data) {
$json = $event | ConvertTo-Json -Compress
#$jsonbytes = #($json)
#$process.StandardInput.BaseStream.Write($jsonbytes,0,$jsonbytes.Count)
Write-Verbose $json
$process.StandardInput.WriteLine($json)
}
}
}
## Use a try/catch/finally to allow for the inputs to be closed and the process stopped
[System.Diagnostics.Process]$process = $null
$endTime = Get-Date
try
{
## Prepare to invoke the process
$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$processStartInfo.FileName = (Get-Command .\logstash-forwarder.exe).Definition
$processStartInfo.WorkingDirectory = (Get-Location).Path
$processStartInfo.Arguments = "-config logstash-forwarder.conf"
$processStartInfo.UseShellExecute = $false
## Always redirect the input and output of the process.
## Sometimes we will capture it as binary, other times we will
## just treat it as strings.
$processStartInfo.RedirectStandardOutput = $true
$processStartInfo.RedirectStandardInput = $true
$process = [System.Diagnostics.Process]::Start($processStartInfo)
##################################
# Main Logic #
##################################
## Loop to capture events
while ($true) {
[String]::Empty | Write-Verbose
Start-Sleep -Seconds 5
$startTime = $endTime
[TimeSpan]$diff = (Get-Date) - $startTime
if ($diff.TotalHours -gt 1) {
$endTime = $startTime + (New-TimeSpan -Minutes 30)
}
else {
$endTime = Get-Date
}
Write-Verbose "Starting timespan $($startTime) -> $($endTime)"
## Supports reading multiple logs
if ($logname.Count -gt 1) {
foreach ($log in $logname) {
ReadEvents -filter #{LogName=$log; StartTime=$startTime; EndTime=$endTime} -OutFile $output
}
}
else {
ReadEvents -filter #{LogName=$logname; StartTime=$startTime; EndTime=$endTime} -OutFile $output
}
}
}
catch
{
Write-Error $error[0]|format-list -force
throw $_.Exception
}
finally
{
if($process)
{
$process.StandardInput.Close()
$process.Close()
}
}
** The script doesn't really handle LSF failing, but it serves my purposes for now.

Tried to add this under the Answer using nssm. You can also use the following to create the service from commandline without the UI.
Just ensure that nssm.exe is in the same directory and you run the script from there (or just edit the script).
#echo off
set BASE_DIR=C:\temp\logstash-forwarder
nssm install Logstash-Forwarder "%BASE_DIR%\logstash-forwarder.exe"
nssm set Logstash-Forwarder AppDirectory "%BASE_DIR%"
nssm set Logstash-Forwarder AppStopMethodSkip "6"
nssm set Logstash-Forwarder AppParameters "-config %BASE_DIR%\logstash-forwarder.conf"

Related

mount.exe in powershell service not mounting NFS for the user, only current process

I'm using winsw to run a powershell 7 service with user credentials, in order to automatically mount an NFS volume. I can verify the service is running as that user since $env:UserName shows up correctly in the log.
Strangely, when the service runs this command:
mount.exe -o anon,nolock,hard 10.1.132.244:/rendering.dev.firehawkvfx.com X:
The service script can see the contents of the mounted path and that works, but the user in the windows UI session cannot, and the mount doesn't arrive in windows explorer at all. It appears the mount only exists for the process. This must have something to do with the way processes are isolated in windows is my guess.
There are a few components involved in doing this, but at the risk of being verbose the winsw service looks like this:
<service>
<id>myservice</id>
<name>MyService</name>
<description>This service updates Deadline Certificates with Firehawk.</description>
<serviceaccount>
<username>.\REPLACE_WITH_DEADLINE_USER_NAME</username>
<password>REPLACE_WITH_DEADLINE_USER_PASS</password>
<allowservicelogon>true</allowservicelogon>
</serviceaccount>
<env name="FH_DEADLINE_CERTS_HOME" value="%BASE%"/>
<executable>C:\Program Files\PowerShell\7\pwsh.exe</executable>
<startarguments>-NoLogo -ExecutionPolicy Bypass -File c:\AppData\myservice.ps1</startarguments>
<log mode="roll"></log>
</service>
and myservice.ps1 wrapper that runs the NFS mount.exe command (in aws-auth-deadline-pwsh-cert.ps1) looks like this:
#Requires -Version 7.0
Write-Host "Start Service"
# $ErrorActionPreference = "Stop"
function Main {
$Timer = New-Object Timers.Timer
$Timer.Interval = 10000
$Timer.Enabled = $True
$Timer.AutoReset = $True
$objectEventArgs = #{
InputObject = $Timer
EventName = 'Elapsed'
SourceIdentifier = 'myservicejob'
Action = {
try {
$resourcetier = "dev"
Write-Host "Run aws-auth-deadline-cert`nCurent user: $env:UserName"
Set-strictmode -version latest
if (Test-Path -Path C:\AppData\myservice-config.ps1) {
. C:\AppData\myservice-config.ps1
C:\AppData\aws-auth-deadline-pwsh-cert.ps1 -resourcetier $resourcetier -deadline_user_name $deadline_user_name -aws_region $aws_region -aws_access_key $aws_access_key -aws_secret_key $aws_secret_key
}
else {
Write-Warning "C:\AppData\myservice-config.ps1 does not exist. Install the service again and do not use the -skip_configure_aws argument"
}
Write-Host "Finished running aws-auth-deadline-cert"
}
catch {
Write-Warning "Error in service Action{} block"
Write-Warning "Message: $_"
exit(1)
}
}
}
$Job = Register-ObjectEvent #objectEventArgs
Wait-Event
}
try {
Main
}
catch {
Write-Warning "Error running Main in: $PSCommandPath"
exit(1)
}
In case its of interest, I maintain this work ongoing at this github repo - https://github.com/firehawkvfx/firehawk-auth-scripts

Powershell - Loop Install of Available Software Updates (SCCM)

I have the below script which I am using to run on critical desktop clients to install all available updates (quarterly) that have been deployed by SCCM.
As some deployed updates only become available when other dependent updates have been installed the script is stopping before the reboot.
I ideally want it to loop and continue to install all available updates until all have installed and then proceed to automatically reboot.
Any ideas?
Add-Type -AssemblyName PresentationCore, PresentationFramework
switch (
[System.Windows.MessageBox]::Show(
'This action will download and install critical Microsoft updates and may invoke an automatic reboot. Do you want to continue?',
'WARNING',
'YesNo',
'Warning'
)
) {
'Yes'
{
Start-Process -FilePath "C:\Windows\CCM\ClientUX\scclient.exe" "softwarecenter:Page=InstallationStatus"
$installUpdateParam = #{
NameSpace = 'root/ccm/ClientSDK'
ClassName = 'CCM_SoftwareUpdatesManager'
MethodName = 'InstallUpdates'
}
$getUpdateParam = #{
NameSpace = 'root/ccm/ClientSDK'
ClassName = 'CCM_SoftwareUpdate'
Filter = 'EvaluationState < 8'
}
[ciminstance[]]$updates = Get-CimInstance #getUpdateParam
if ($updates) {
Invoke-CimMethod #installUpdateParam -Arguments #{ CCMUpdates = $updates }
while(Get-CimInstance #getUpdateParam){
Start-Sleep -Seconds 30
}
}
$rebootPending = Invoke-CimMethod -Namespace root/ccm/ClientSDK -ClassName CCM_ClientUtilities -MethodName DetermineIfRebootPending
if ($rebootPending.RebootPending){
Invoke-CimMethod -Namespace root/ccm/ClientSDK -ClassName CCM_ClientUtilities -MethodName RestartComputer
}
'No'
# Exit-PSSession
}
}
You may loop indefinitely to start the process and stop only when $updates is $null or empty.
while($true) {
Start-Process ...
[ciminstance[]]$updates = Get-CimInstance #getUpdateParam
if ($updates) {
Invoke-CimMethod #installUpdateParam -Arguments #{ CCMUpdates = $updates }
while(Get-CimInstance #getUpdateParam){
Start-Sleep -Seconds 30
}
}
else {
break;
}
}

Downloading certain files using powershell produce corrupt files

So I have a powershell script that I wrote which crawls through a particular website and downloads all of the software hosted on the site to my local machine. The website in question is nirsoft.net, and I will include the full script below. Anyway, so I have this script that downloads all of the application files hosted on the website, when I notice something odd: while most of the file downloads completed successfully, there are several files that were not downloaded successfully, resulting in a corrupt file of 4KB:
For those of you who are familiar with Nirsoft's software, the tools are very powerful, but also constantly misidentified as dangerous because of the password cracking tools, so my guess as to why this is happening is that, since powershell's If I were to guess as to why this was happening, I would guess that, due to the fact that powershell's "Invoke-webrequest cmdlet" uses Internet Explorer's engine for its core functionality, Internet Explorer is flagging the files as dangerous and refusing to download them, thus causing powershell to fail to download the file. I confirmed this by trying to manually download each of the corrupt files using internet explorer, which marked them all as malicious. However, this is where things get strange. In order to bypass this limitation, I attempted a variety of other methods to download the file within my script, like using a pure dotnet object ( (New-object System.Net.WebClient).DownloadFile("url","file") ) and even some third party command line tools (wget for windows, wget in cygwin, etc), but no matter what I tried, not a single alternative method I used was able to download a non-corrupt file. So what I want to know is if there is a way around this, and I want to know why even third party tools are affected by this. Is there some kind of rule that any scripting tool has to use Internet Explorer's engine in order to connect to the internet or something? Thanks in advance. Oh, and one last thing before I post the script. Below is the url to one of the files that I am having difficulty in downloading via powershell, which you can use to run individual tests rather than the whole script:
enter link description here
And without further ado, here is the script. Thank again:
$VerbosePreference = "Continue"
$DebugPreference = "Continue"
$present = $true
$subdomain = $null
$prods = (Invoke-WebRequest "https://www.nirsoft.net/utils/index.html").links
Foreach ($thing in $prods)
{
If ($thing.Innertext -match "([A-Za-z]|\s)+v\d{1,3}\.\d{1,3}(.)*")
{
If ($thing.href.Contains("/"))
{
}
$page = Invoke-WebRequest "https://www.nirsoft.net/utils/$($thing.href)"
If ($thing.href -like "*dot_net_tools*")
{
$prodname = $thing.innerText.Trim().Split(" ")
}
Else
{
$prodname = $thing.href.Trim().Split(".")
}
$newlinks = $page.links | Where-Object {$_.Innertext -like "*Download*" -and ($_.href.endswith("zip") -or $_.href.endswith("exe"))}
# $page.ParsedHtml.title
#$newlinks.href
Foreach ($item in $newlinks)
{
$split = $item.href.Split("/")
If ($item.href -like "*toolsdownload*")
{
Try
{
Write-host "https://www.nirsoft.net$($item.href)"
Invoke-WebRequest "https://www.nirsoft.net$($item.href)" -OutFile "$env:DOWNLOAD\test\$($split[-1])" -ErrorAction Stop
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
elseif ($item.href.StartsWith("http") -and $item.href.Contains(":"))
{
Try
{
Write-host "$($item.href)"
Invoke-WebRequest $item.href -OutFile "$env:DOWNLOAD\test\$($split[-1])" -ErrorAction Stop
}
Catch
{
Write-Host "$($item.href)" -ForegroundColor Red
}
}
Elseif ($thing.href -like "*/dot_net_tools*")
{
Try
{
Invoke-WebRequest "https://www.nirsoft.net/dot_net_tools/$($item.href)" -OutFile "$env:DOWNLOAD\test\$($split[-1])" -ErrorAction Stop
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
Else
{
Try
{
Write-Host "https://www.nirsoft.net/utils/$($item.href)"
Invoke-WebRequest "https://www.nirsoft.net/utils/$($item.href)" -OutFile "$env:DOWNLOAD\test\$($item.href)" -ErrorAction Stop
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
If ($item.href.Contains("/"))
{
If (!(Test-Path "$env:DOWNLOAD\test\$($split[-1])"))
{
$present = $false
}
}
Else
{
If (!(Test-Path "$env:DOWNLOAD\test\$($item.href)"))
{
$present = $false
}
}
}
}
}
If ($present)
{
Write-Host "All of the files were downloaded!!!" -ForegroundColor Green
}
Else
{
Write-Host "Not all of the files downloaded. Something went wrong." -ForegroundColor Red
}
You have two separate issues.
For anything Defender flags, it doesn't matter if you save it to disk with this or that. You could simply add an exclusion for the directory in Defender.
The other issue is pointed out by Guenther, you need to provide a referrer at least on some of the downloads. With the following changes I was able to download them all.
$VerbosePreference = "Continue"
$DebugPreference = "Continue"
$present = $true
$subdomain = $null
$path = c:\temp\downloadtest\
New-Item $path -ItemType Directory -ErrorAction SilentlyContinue | Out-Null
Add-MpPreference -ExclusionPath $path
$prods = (Invoke-WebRequest "https://www.nirsoft.net/utils/index.html").links
Foreach ($thing in $prods)
{
If ($thing.Innertext -match "([A-Za-z]|\s)+v\d{1,3}\.\d{1,3}(.)*")
{
If ($thing.href.Contains("/"))
{
}
$page = Invoke-WebRequest "https://www.nirsoft.net/utils/$($thing.href)"
If ($thing.href -like "*dot_net_tools*")
{
$prodname = $thing.innerText.Trim().Split(" ")
}
Else
{
$prodname = $thing.href.Trim().Split(".")
}
$newlinks = $page.links | Where-Object {$_.Innertext -like "*Download*" -and ($_.href.endswith("zip") -or $_.href.endswith("exe"))}
# $page.ParsedHtml.title
#$newlinks.href
Foreach ($item in $newlinks)
{
$split = $item.href.Split("/")
If ($item.href -like "*toolsdownload*")
{
Try
{
Write-host "https://www.nirsoft.net$($item.href)"
Invoke-WebRequest "https://www.nirsoft.net$($item.href)" -OutFile "$path\$($split[-1])" -ErrorAction Stop -Headers #{Referer="https://www.nirsoft.net$($item.href)"}
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
elseif ($item.href.StartsWith("http") -and $item.href.Contains(":"))
{
Try
{
Write-host "$($item.href)"
Invoke-WebRequest $item.href -OutFile "$path\$($split[-1])" -ErrorAction Stop -Headers #{Referer="$($item.href)"}
}
Catch
{
Write-Host "$($item.href)" -ForegroundColor Red
}
}
Elseif ($thing.href -like "*/dot_net_tools*")
{
Try
{
Invoke-WebRequest "https://www.nirsoft.net/dot_net_tools/$($item.href)" -OutFile "$path\$($split[-1])" -ErrorAction Stop -Headers #{Referer="https://www.nirsoft.net/dot_net_tools/$($item.href)"}
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
Else
{
Try
{
Write-Host "https://www.nirsoft.net/utils/$($item.href)"
Invoke-WebRequest "https://www.nirsoft.net/utils/$($item.href)" -OutFile "$path\$($item.href)" -ErrorAction Stop -Headers #{Referer="https://www.nirsoft.net/utils/$($item.href)"}
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
If ($item.href.Contains("/"))
{
If (!(Test-Path "$path\$($split[-1])"))
{
$present = $false
}
}
Else
{
If (!(Test-Path "$path\$($item.href)"))
{
$present = $false
}
}
}
}
}
If ($present)
{
Write-Host "All of the files were downloaded!!!" -ForegroundColor Green
}
Else
{
Write-Host "Not all of the files downloaded. Something went wrong." -ForegroundColor Red
}
I'd also recommend you turn the download routine into a function that you can pass the relative URL portion so you don't have to repeat code several times.

Adding a deployment step to call a http endpoint in Octopus Deploy

I am trying to create a new Octopus deploy step, which will call a http endpoint.
I have found the following step type that seems promising, but can get any documentation on it:
"Http Json Value Check
Gets json from http endpoint, looks-up a value by key and checks that it matches a predefined value. If value matches then script exists with a success code, if value does not match then script exists with a failure code."
I am not sure what to enter for the:
"Json Key" and the "Expected Value"
Has anyone done this? have an example or suggest a different method to achieve what I am trying?
Here is a PowerShell script I use to get the JSON from an endpoint and check for a valid Value. If I could remember where I got the code base before I modified it a little I would give credit to the original author. It will work with either a string or a regex.
#-------------------------------------------------------------------------
# Warmup.ps1
#-------------------------------------------------------------------------
[int]$returnme = 0
[int]$SleepTime = 5
[string]$regex = '[>"]?[aA]vailable["<]?'
[string]$strContains = $regex
# [string]$strContains = "log in"
[string]$hostName = hostname
[string]$domainName = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .).DNSDomain
[string]$warmMeUp = "http://$hostName.$domainName/endpoint"
[string]$html = "Will Be Set Later"
#-------------------------------------------------------------------------
# Get-WebPage
#-------------------------------------------------------------------------
function Get-WebPage([string]$url)
{
try
{
$wc = new-object net.webclient;
$wc.credentials = [System.Net.CredentialCache]::DefaultCredentials;
[string]$pageContents = $wc.DownloadString($url);
$wc.Dispose();
}
catch
{
Write-Host "First Try Failed. Second Try in $SleepTime Seconds."
try
{
Start-Sleep -s $SleepTime
$wc = new-object net.webclient;
$wc.credentials = [System.Net.CredentialCache]::DefaultCredentials;
$pageContents = $wc.DownloadString($url);
$wc.Dispose();
}
catch
{
$pageContents = GetWebSiteStatusCode($url)
}
}
return $pageContents;
}
#-------------------------------------------------------------------------
# GetWebSiteStatusCode
#-------------------------------------------------------------------------
function GetWebSiteStatusCode
{
param (
[string] $testUri,
[int] $maximumRedirection = 5
)
$request = $null
try {
$request = Invoke-WebRequest -Uri $testUri -MaximumRedirection $maximumRedirection -ErrorAction SilentlyContinue
}
catch [System.Net.WebException] {
$request = $_.ErrorDetails.Message
}
catch {
Write-Error $_.Exception
return $null
}
return $request
}
#-------------------------------------------------------------------------
# Main Application Logic
#-------------------------------------------------------------------------
"Warming up '{0}'..." -F $warmMeUp;
$html = Get-WebPage -url $warmMeUp;
Write-Host "Looking for Pattern $strContains"
if ($html.ToLower().Contains("unavailable") -or !($html -match $strContains))
{
$returnme = -1
Write-Host "Warm Up Failed. html returned:`n" + $html
}
exit $returnme

Retrieve the Windows Identity of the AppPool running a WCF Service

I need to verify that the underlying server-side account running my WCF Service has correct ACL permissions to various points on the local file system. If I can get the underlying Windows Identity, I can take it from there. This folds into a larger Powershell script used after deployment.
Below is my powershell snippet, that get the ApplicationPoolSid, how do you map this to the AppPool's Windows Identity?
$mywcfsrv = Get-Item IIS:\AppPools\<MyWCFServiceName>;
Updated below to include Keith's snippet
For completeness, here's the solution:
Function Get-WebAppPoolAccount
{
param ( [Parameter(Mandatory = $true, Position = 0)]
[string]
$AppPoolName )
# Make sure WebAdmin module is loaded.
$module = (Get-Module -ListAvailable) | ForEach-Object { if ($_.Name -like 'WebAdministration') { $_ } };
if ($module -eq $null)
{
throw "WebAdministration PSSnapin module is not available. This module is required in order to interact with WCF Services.";
}
Import-Module $module;
# Get the service account.
try
{
$mywcfsrv = Get-Item (Join-Path "IIS:\AppPools" $AppPoolName);
}
catch [System.Exception]
{
throw "Unable to locate $AppPoolName in IIS. Verify it is installed and running.";
}
$accountType = $mywcfsrv.processModel.identityType;
$account = $null;
if ($accountType -eq 'LocalSystem')
{
$account = 'NT AUTHORITY\SYSTEM';
}
elseif ($accountType -eq 'LocalService')
{
$account = 'NT AUTHORITY\LOCAL SERVICE';
}
elseif ($accountType -eq 'NetworkService')
{
$account = 'NT AUTHORITY\NETWORK SERVICE';
}
elseif ($accountType -eq 'SpecificUser')
{
$account = $mywcfsrv.processModel.userName;
}
return $account;
}
Like so:
$mywcfsrv = Get-Item IIS:\AppPools\<MyWCFServiceName>
$mywcfsrv.processModel.identityType

Resources