From 5982955c8c394a0dd3de0481082956df3039afb2 Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 20 Oct 2017 17:40:24 -0500 Subject: [PATCH 1/2] Minor updates to readme. Rename internal variables in methods. --- README.md | 5 +-- WazuhOSSec.psm1 | 91 +++++++++++++++++++++++++------------------------ 2 files changed, 47 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index e3e23f7..ce35ffb 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ The **WazuhOSSec** DSC module contains the **WazuhAgentInstall** and **WazuhAgen * **Ensure** - Install or uninstall the agent. (Present/Absent) ### **WazuhAgentRegister** -* **AgentName** - The name you want to register for the Agent (Default to hostname $env:ComputerName) +* **AgentName** - The name you want to register for the Agent. * **WazuhServerApiFqdn** - The FQDN of the Wazuh Server. i.e. wazuh.domain.com * **WazuhServerApiPort** - The port the Wazuh server is listening on. Defaults to 55000 * **UseSelfSignedCerts** - Determines whether to use a self signed cert with the Wazuh server. Default is false. @@ -25,9 +25,6 @@ The **WazuhOSSec** DSC module contains the **WazuhAgentInstall** and **WazuhAgen * **Ensure** - Register the agent with the wazuh server. (Present/Absent) ## Versions -### 1.0.1 -* Included check for Service AND Package in Get() of WazuhAgentInstall -* More Verbose output in a couple of helper methods ### 1.0.0 * Initial commit of DSC resource diff --git a/WazuhOSSec.psm1 b/WazuhOSSec.psm1 index 44cf8f7..60eb8d9 100644 --- a/WazuhOSSec.psm1 +++ b/WazuhOSSec.psm1 @@ -108,14 +108,14 @@ class WazuhAgentInstall [bool] VersionUpgrade($CurrentVersion) { $this.ValidateInstallerPath() - $InstallerInfo = Get-ItemProperty -Path $this.InstallerPath - if (($CurrentVersion -eq $InstallerInfo.VersionInfo.Fileversion) -and ($InstallerInfo.VersionInfo.CompanyName -like "*Wazuh*")) + $_InstallerInfo = Get-ItemProperty -Path $this.InstallerPath + if (($CurrentVersion -eq $_InstallerInfo.VersionInfo.Fileversion) -and ($_InstallerInfo.VersionInfo.CompanyName -like "*Wazuh*")) { return $false } else { - Write-Verbose "New Version detected: $($InstallerInfo.VersionInfo.Fileversion)" + Write-Verbose "New Version detected: $($_InstallerInfo.VersionInfo.Fileversion)" return $true } } @@ -125,7 +125,7 @@ class WazuhAgentInstall try { Start-Process -NoNewWindow -ErrorAction stop -Filepath $AgentExePath -ArgumentList '/S' - Write-Verbose "Agent installation complete." + Write-Verbose "Agent installation/removal complete." } catch { @@ -141,6 +141,7 @@ class WazuhAgentInstall class WazuhAgentRegister { #region header + # Vast portions of this resource were taken/inspired by the script provided by Wazuh, Inc. ### # Powershell script for registering agents automatically with the API # Copyright (C) 2017 Wazuh, Inc. All rights reserved. @@ -158,7 +159,7 @@ class WazuhAgentRegister ### #endregion [DscProperty(Key)] - [String]$AgentName = $env:COMPUTERNAME + [String]$AgentName [DscProperty(Mandatory)] [String]$WazuhServerApiFqdn @@ -289,14 +290,14 @@ class WazuhAgentRegister Write-Verbose "Retrieving Agent Key from server" #$response = req -method "GET" -resource "/agents/$($agent_id)/key" | ConvertFrom-Json #ToDo: I think converFrom-Json on the call lilke above so we don't have to below. - $ApiResponse = $this.WazuhApiRequest("Get", "/agents/$($AgentId)/key") - If (($ApiResponse | ConvertFrom-Json).error -ne '0') + $_ApiResponse = $this.WazuhApiRequest("Get", "/agents/$($AgentId)/key") | ConvertFrom-Json + If ($_ApiResponse.error -ne '0') { - throw "ERROR: $($ApiResponse.message)" + throw "ERROR: $($_ApiResponse.message)" } else { - $AgentKey = ($ApiResponse | ConvertFrom-Json).data + $AgentKey = $_ApiResponse.data Write-Verbose "Key for agent '$($AgentId)' received." } return $AgentKey @@ -326,17 +327,17 @@ class WazuhAgentRegister [System.Net.ServicePointManager]::CertificatePolicy = new-object PolicyCert } - [string]WazuhApiRequest($Method, $resource, $params) + [string]WazuhApiRequest($Method, $Resource, $Params) { - $UserName = ($this.Credential).GetNetworkCredential().UserName - $PassWord = ($this.Credential).GetNetworkCredential().Password - $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $UserName, $PassWord))) + $_UserName = ($this.Credential).GetNetworkCredential().UserName + $_PassWord = ($this.Credential).GetNetworkCredential().Password + $_Base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $_UserName, $_PassWord))) $this.BaseUrl = "https://" + $this.WazuhServerApiFqdn + ":" + $this.WazuhServerApiPort - $Url = $this.BaseUrl + $resource; + $_Url = $this.BaseUrl + $Resource; try { - return Invoke-WebRequest -Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo)} -Method $Method -Uri $Url -Body $params -UseBasicParsing + return Invoke-WebRequest -Headers @{Authorization = ("Basic {0}" -f $_Base64AuthInfo)} -Method $Method -Uri $_Url -Body $Params -UseBasicParsing } catch { @@ -344,17 +345,17 @@ class WazuhAgentRegister } } - [string]WazuhApiRequest($Method, $resource) + [string]WazuhApiRequest($Method, $Resource) { - $UserName = ($this.Credential).GetNetworkCredential().UserName - $PassWord = ($this.Credential).GetNetworkCredential().Password - $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $UserName, $PassWord))) + $_UserName = ($this.Credential).GetNetworkCredential().UserName + $_PassWord = ($this.Credential).GetNetworkCredential().Password + $_Base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $_UserName, $_PassWord))) $this.BaseUrl = "https://" + $this.WazuhServerApiFqdn + ":" + $this.WazuhServerApiPort - $Url = $this.BaseUrl + $resource; + $_Url = $this.BaseUrl + $Resource; try { - return Invoke-WebRequest -Headers @{Authorization = ("Basic {0}" -f $base64AuthInfo)} -Method $Method -Uri $Url -UseBasicParsing + return Invoke-WebRequest -Headers @{Authorization = ("Basic {0}" -f $_Base64AuthInfo)} -Method $Method -Uri $_Url -UseBasicParsing } catch { @@ -364,13 +365,13 @@ class WazuhAgentRegister [string]GetAgentInfo() { - $QueryParameter = @{search = $This.AgentName} - return $this.WazuhApiRequest("GET", "/agents", $QueryParameter) + $_QueryParameter = @{search = $This.AgentName} + return $this.WazuhApiRequest("GET", "/agents", $_QueryParameter) } [void]AgentControl([AgentStatus]$AgentStatus) { - $ServiceName = "OssecSvc" + $_ServiceName = "OssecSvc" switch ($AgentStatus) { @@ -378,12 +379,12 @@ class WazuhAgentRegister { try { - if ((Get-Service -Name "$ServiceName").status -ne "Stopped") + if ((Get-Service -Name "$_ServiceName").status -ne "Stopped") { Write-Verbose "Stopping Agent" - Stop-Service -Name $ServiceName + Stop-Service -Name $_ServiceName Start-Sleep -Seconds 2 - if ((Get-Service -Name $ServiceName).Status -eq "Stopped") + if ((Get-Service -Name $_ServiceName).Status -eq "Stopped") { Write-Verbose "Agent Stopped" } @@ -403,12 +404,12 @@ class WazuhAgentRegister { try { - if ((Get-Service -Name "$ServiceName").status -ne "Running") + if ((Get-Service -Name "$_ServiceName").status -ne "Running") { Write-Verbose "Starting Agent" - Start-Service -Name $ServiceName + Start-Service -Name $_ServiceName Start-Sleep -Seconds 2 - if ((Get-Service -Name $ServiceName).Status -eq "Running") + if ((Get-Service -Name $_ServiceName).Status -eq "Running") { Write-Verbose "Agent Started" } @@ -433,54 +434,54 @@ class WazuhAgentRegister { # Check installed version because the default Config file changed starting with v2.1.0 # Do a String replpace for newer version vs the Add-Content - $AgentConfigFilePath = $this.GetAgentPath() + "\" + $this.AgentConfigFile - $InstalledAgentVersion = (Get-Package -Name "*Wazuh*" -ProviderName Programs).Version - $WazuhServerIP = $this.GetWazuhServeIP() - Write-Verbose "Updating Configuration File: $AgentConfigFilePath with Server IP: $WazuhServerIP" - if ($InstalledAgentVersion -ge "2.1.0") + $_AgentConfigFilePath = $this.GetAgentPath() + "\" + $this.AgentConfigFile + $_InstalledAgentVersion = (Get-Package -Name "*Wazuh*" -ProviderName Programs).Version + $_WazuhServerIP = $this.GetWazuhServeIP() + Write-Verbose "Updating Configuration File: $_AgentConfigFilePath with Server IP: $_WazuhServerIP" + if ($_InstalledAgentVersion -ge "2.1.0") { try { - (Get-Content $AgentConfigFilePath) -replace "0.0.0.0", $WazuhServerIP | Out-File $AgentConfigFilePath -Encoding ascii + (Get-Content $_AgentConfigFilePath) -replace "0.0.0.0", $_WazuhServerIP | Out-File $_AgentConfigFilePath -Encoding ascii } catch { - throw "ERROR: Could not write config file: $AgentConfigFilePath" + throw "ERROR: Could not write config file: $_AgentConfigFilePath" } } else { try { - Add-Content $AgentConfigFilePath "`n $($WazuhServerIP) " + Add-Content $_AgentConfigFilePath "`n $($_WazuhServerIP) " } catch { - throw "ERROR: Could not write config file: $AgentConfigFilePath" + throw "ERROR: Could not write config file: $_AgentConfigFilePath" } } } [bool] InitializePolling() { - $PollingLogFile = ($this.GetAgentPath()) + "\DSC_Polling.log" - if (!(Test-Path -Path $PollingLogFile)) + $_PollingLogFile = ($this.GetAgentPath()) + "\DSC_Polling.log" + if (!(Test-Path -Path $_PollingLogFile)) { #Polling file does not exist so lets create and write Date-Time, Return true Write-Verbose "Writing out DSC_Polling.log file" - (Get-Date).DateTime | Out-File -FilePath $PollingLogFile -NoNewline + (Get-Date).DateTime | Out-File -FilePath $_PollingLogFile -NoNewline Return $true } else { Write-Verbose "Checking timespan from last Poll" #File exists so lets do some Date Maths - [datetime] $LastPollTime = Get-Content $PollingLogFile - if (($_interval = New-TimeSpan -Start $LastPollTime).TotalMinutes -ge $($this.ApiPollingInterval)) + [datetime] $_LastPollTime = Get-Content $_PollingLogFile + if (($_interval = New-TimeSpan -Start $_LastPollTime).TotalMinutes -ge $($this.ApiPollingInterval)) { Write-Verbose "Polling interval of `"$([int]$($_interval).TotalMinutes)`" minutes exceeds defined value of $($this.ApiPollingInterval) minutes - Calling API" #Update the DSC_Polling.log file with a new time stamp - (Get-Date).DateTime | Out-File -FilePath $PollingLogFile -NoNewline -Force + (Get-Date).DateTime | Out-File -FilePath $_PollingLogFile -NoNewline -Force Return $true } else From 2731ee658bf993f772b0902bd766809b9d4b6057 Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 25 Oct 2017 10:55:23 -0500 Subject: [PATCH 2/2] Updates to WazuhAgentRegister resource --- .vscode/settings.json | 4 +- README.md | 12 +- WazuhOSSec.psd1 => WazuhOSSecDSC.psd1 | 8 +- WazuhOSSec.psm1 => WazuhOSSecDSC.psm1 | 191 ++++++++++++++++++++------ 4 files changed, 162 insertions(+), 53 deletions(-) rename WazuhOSSec.psd1 => WazuhOSSecDSC.psd1 (97%) rename WazuhOSSec.psm1 => WazuhOSSecDSC.psm1 (67%) diff --git a/.vscode/settings.json b/.vscode/settings.json index 470eddc..e53147f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,4 +1,6 @@ { // When enabled, will trim trailing whitespace when you save a file. - "files.trimTrailingWhitespace": true + "files.trimTrailingWhitespace": true, + "editor.formatOnSave": false, + "powershell.codeFormatting.preset": "Allman" } diff --git a/README.md b/README.md index ce35ffb..162c966 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,19 @@ -# WazuhOSSec +# WazuhOSSecDSC Powershell DSC Class based resource for installing and configuring the Wazuh Agent -The **WazuhOSSec** DSC resources allow you to install and register the Wazuh Ossec Agent with the defined Wazuh Server. +The **WazuhOSSecDSC** resources allow you to install and register the Wazuh Ossec Agent with the defined Wazuh Server. ## Description -The **WazuhOSSec** DSC module contains the **WazuhAgentInstall** and **WazuhAgentRegister** DSC Resources. These resources were built using PowerShell Classes and such will require Powershell 5.0 +. These DSC resources allow you to install the Wazuh agent and regster it with the Wazuh server. +The **WazuhOSSecDSC** module contains the **WazuhAgentInstall** and **WazuhAgentRegister** DSC Resources. These resources were built using PowerShell Classes and as such will require Powershell 5.0+. These DSC resources allow you to install the Wazuh agent and register it with the Wazuh server. ## Resources * **WazuhAgentInstall** Installs or Upgrades the Wazuh Agent from a path you provide. -* **WazuhAgentRegister** Registers an agent with the Wazuh server +* **WazuhAgentRegister** Registers or Deletes an agent on the Wazuh Manager. ### **WazuhAgentInstall** * **InstallerPath** - Path to the Wazuh Agent installer on the local server. -* **Ensure** - Install or uninstall the agent. (Present/Absent) +* **Ensure** - Install or uninstall the agent. (Present/Absent). ### **WazuhAgentRegister** * **AgentName** - The name you want to register for the Agent. @@ -22,7 +22,7 @@ The **WazuhOSSec** DSC module contains the **WazuhAgentInstall** and **WazuhAgen * **UseSelfSignedCerts** - Determines whether to use a self signed cert with the Wazuh server. Default is false. * **ApiPollingInterval** - Used to determine a polling interval for checking if the agent is registered. Default is 0 for no interval meaning the resource will poll the server everytime DSC is run. Specified in minutes. * **Credential** - PSCredential object passed into the rersource for authenticating to the Wazuh server -* **Ensure** - Register the agent with the wazuh server. (Present/Absent) +* **Ensure** - Registers or Deletes the agent on the Wazuh Manager. (Present/Absent) ## Versions diff --git a/WazuhOSSec.psd1 b/WazuhOSSecDSC.psd1 similarity index 97% rename from WazuhOSSec.psd1 rename to WazuhOSSecDSC.psd1 index dd89bbb..d28bacb 100644 --- a/WazuhOSSec.psd1 +++ b/WazuhOSSecDSC.psd1 @@ -1,7 +1,7 @@ # -# Module manifest for module 'MyModule' +# Module manifest for module 'WazuhOSSecDSC' # -# Generated by: Marco +# Generated by: Marco Crank # # Generated on: 10/4/2017 # @@ -9,7 +9,7 @@ @{ # Script module or binary module file associated with this manifest. - RootModule = 'WazuhOSSec.psm1' + RootModule = 'WazuhOSSecDSC.psm1' # Version number of this module. ModuleVersion = '1.0.0' @@ -101,7 +101,7 @@ # LicenseUri = '' # A URL to the main website for this project. - ProjectUri = 'https://github.com/LeanKit-Labs/WazuhOSSec' + ProjectUri = 'https://github.com/LeanKit-Labs/WazuhOSSecDSC' # A URL to an icon representing this module. # IconUri = '' diff --git a/WazuhOSSec.psm1 b/WazuhOSSecDSC.psm1 similarity index 67% rename from WazuhOSSec.psm1 rename to WazuhOSSecDSC.psm1 index 60eb8d9..583a45e 100644 --- a/WazuhOSSec.psm1 +++ b/WazuhOSSecDSC.psm1 @@ -194,9 +194,15 @@ class WazuhAgentRegister [DscProperty(NotConfigurable)] [bool]$AgentRegistered + [DscProperty(NotConfigurable)] + [bool]$AgentRegisterExisting + [DscProperty(NotConfigurable)] [AgentStatus]$AgentStatus + [DscProperty(NotConfigurable)] + [string]$AgentIDFromAPI + [WazuhAgentRegister] Get() { #Set Certificate policy to ignore Self Signed Certs, False by default. @@ -205,30 +211,47 @@ class WazuhAgentRegister Write-Verbose "Allowing Self Signed Certs" $this.IgnoreSelfSignedCerts() } - Write-Verbose "Agent Name: $($this.AgentName)" $this.BaseUrl = "https://" + $this.WazuhServerApiFqdn + ":" + $this.WazuhServerApiPort - Write-Verbose "Base URL: $($this.BaseUrl)" - $this.AgentPath = $this.GetAgentPath() - Write-Verbose "Agent Path: $($This.AgentPath)" - $this.AgentConfigFile = $this.AgentPath + "\" + $this.AgentConfigFile - Write-Verbose "OSSec Agent Config: $($This.AgentConfigFile)" - $this.WazuhServerApiIP = $this.GetWazuhServeIP() - Write-Verbose "Wazuh Server IP: $($This.WazuhServerApiIP)" - - # This block uses the ApiPollingInterval value to determine if it should poll for Agent Registration. - # We put this in to alleviate unnecessary API calls to the server. Other wise every time DSC ran this would make a call - # to the API to verify the Agent was registered. Most of which would return back $true. - # If no ApiPollingInterval is set it wll poll each time - if (($this.ApiPollingInterval -eq 0) -or (($this.InitializePolling()) -and ($this.ApiPollingInterval -ne 0))) - { - #If PollingInterval is 0 cleanup the polling file so we don't have any lingering data lying around should the interval change later - if (($this.ApiPollingInterval -eq 0) -and (Test-Path ($this.AgentPath + "\DSC_Polling.log") -PathType Leaf)) + + if ($this.Ensure -eq [Ensure]::Present) + { + $this.AgentPath = $this.GetAgentPath() + $this.AgentConfigFile = $this.AgentPath + "\" + $this.AgentConfigFile + $this.WazuhServerApiIP = $this.GetWazuhServeIP() + Write-Verbose "Agent Name: $($this.AgentName)" + Write-Verbose "Base URL: $($this.BaseUrl)" + Write-Verbose "Agent Path: $($This.AgentPath)" + Write-Verbose "OSSec Agent Config: $($This.AgentConfigFile)" + Write-Verbose "Wazuh Server IP: $($This.WazuhServerApiIP)" + + # This block uses the ApiPollingInterval value to determine if it should poll for Agent Registration. + # We put this in to alleviate unnecessary API calls to the server. Other wise every time DSC ran this would make a call + # to the API to verify the Agent was registered. Most of which would return back $true. + # If no ApiPollingInterval is set it wll poll each time + if (($this.ApiPollingInterval -eq 0) -or (($this.InitializePolling()) -and ($this.ApiPollingInterval -ne 0))) + { + #If PollingInterval is 0 cleanup the polling file so we don't have any lingering data lying around should the interval change later + if (($this.ApiPollingInterval -eq 0) -and (Test-Path ($this.AgentPath + "\DSC_Polling.log") -PathType Leaf)) + { + Write-Verbose "ApiPollingInterval set to 0, Cleaning up Polling Log File" + Remove-Item -Path ($this.AgentPath + "\DSC_Polling.log") -Force + } + $_RegistrationStatus = $this.RegistrationStatus() + $this.AgentRegistered = $_RegistrationStatus.AgentRegistered + $this.AgentRegisterExisting = $_RegistrationStatus.AgentRegisterExisting + } + else { - Remove-Item -Path ($this.AgentPath + "\DSC_Polling.log") -Force + #No need to poll for agent status so assume Registered with the server + $this.AgentRegistered = $true } - $AgentPollResult = $this.GetAgentInfo() + return $this + } + else + { + $_AgentMetaData = $this.GetAgentInfo() | ConvertFrom-Json #If Total Items greater than or equal to 1 the agent should be registered - if (($agentPollResult | ConvertFrom-Json).data.totalitems -ge 1) + if (($_AgentMetaData).data.totalitems -ge 1) { $this.AgentRegistered = $true } @@ -236,34 +259,54 @@ class WazuhAgentRegister { $this.AgentRegistered = $false } + return $this } - else - { - #No need to poll for agent status so assume Registered with the server - $this.AgentRegistered = $true - } - return $this } [bool] Test() { - $this.Get() - if (!($this.AgentRegistered)) + $_Get = $this.Get() + if ($this.Ensure -eq [Ensure]::Present) + { + if ($_Get.AgentRegistered) + { + Write-Verbose "Agent is registered. GOOD JOB!" + return $true + } + Write-Verbose "Agent is not registered, Begin registration process." + return $false + } + else # Ensure = Absent { + Write-Verbose "Ensure set to `"Absent`", Checking for existing Agent." + if (!($_Get.AgentRegistered)) + { + Write-Verbose "No Agent found on server." + return $true + } + Write-Verbose "Agent found on server, begin deletion process." return $false } - return $true } [void] Set() { - # Register the Agent, Get the Key from Wazuh Server, Import the Key, update ossec.conf, and restart the Agent service - $AgentRegisterResponse = $this.AgentRegisterNew() - $AgentKeyResponse = $this.GetAgentKey($AgentRegisterResponse) - $this.ImportAgentKey($AgentKeyResponse) - $this.AgentControl([AgentStatus]::Stop) - $this.UpdateConfigFile() - $this.AgentControl([AgentStatus]::Start) + $_Get = $this.RegistrationStatus() + + if ($_Get.AgentRegisterExisting -or ($this.Ensure -eq [Ensure]::Absent)) + { + # If there is an existing Agent, Deleted the old and Re-Register as a new agent + $this.AgentRegisterDelete($this.AgentIDFromAPI) + } + if ($this.Ensure -eq [Ensure]::Present) + { + $_AgentRegisterResponseId = $this.AgentRegisterNew() + $_AgentKeyResponse = $this.GetAgentKey($_AgentRegisterResponseId) + $this.ImportAgentKey($_AgentKeyResponse) + $this.AgentControl([AgentStatus]::Stop) + $this.UpdateConfigFile() + $this.AgentControl([AgentStatus]::Start) + } } #region Helper Methods @@ -284,12 +327,26 @@ class WazuhAgentRegister } } + [string]AgentRegisterDelete($AgentId) + { + Write-Verbose "Deleting Agent from server: $($This.AgentName)" + $ApiResponse = $this.WazuhApiRequest("DELETE", "/agents/$($AgentId)") | ConvertFrom-Json + If ($ApiResponse.error -ne '0') + { + throw "ERROR: $($ApiResponse.message)" + } + else + { + Write-Verbose "Agent Deleted: (Agent - $($this.AgentName)) / (ID - $($AgentId))" + return $AgentId + } + } + [string] GetAgentKey($AgentId) { - # Getting agent key from manager + # Small sleep, experienced a timing issue after registering + Start-Sleep -Seconds 2 Write-Verbose "Retrieving Agent Key from server" - #$response = req -method "GET" -resource "/agents/$($agent_id)/key" | ConvertFrom-Json - #ToDo: I think converFrom-Json on the call lilke above so we don't have to below. $_ApiResponse = $this.WazuhApiRequest("Get", "/agents/$($AgentId)/key") | ConvertFrom-Json If ($_ApiResponse.error -ne '0') { @@ -309,8 +366,9 @@ class WazuhAgentRegister Write-Output "y" | & "$($this.GetAgentPath())\manage_agents.exe" "-i $($AgentKey)" "y`r`n" } - # If UseSelfSignedCerts=$true modify Certificate Policy to allow + [void]IgnoreSelfSignedCerts() + # If UseSelfSignedCerts=$true modify Certificate Policy to allow { add-type @" using System.Net; @@ -492,7 +550,6 @@ class WazuhAgentRegister } } - #The following two methods are used in various other methods so we broke them out to reduce code and make it simpler...we hope. [string]GetWazuhServeIP() { Write-Verbose "Resolving Wazuh Server IP Address" @@ -508,8 +565,9 @@ class WazuhAgentRegister [string]GetAgentPath() { - if ($_AgentPath = (Get-Package -Name "*wazuh*").Meta.Attributes.Get_Item("UninstallString").trim([char]"`"") | Split-Path ) + if ($_AgentPath = (Get-Package -Name "*wazuh*" -ErrorAction SilentlyContinue)) { + $_AgentPath = $_AgentPath.Meta.Attributes.Get_Item("UninstallString").trim([char]"`"") | Split-Path return $_AgentPath } else @@ -518,5 +576,54 @@ class WazuhAgentRegister } } + [hashtable]RegistrationStatus() + { + $_RegistrationStatus = [Hashtable]::new() + $_AgentMetaData = $this.GetAgentInfo() | ConvertFrom-Json + #If Total Items greater than or equal to 1 the agent should be registered + if (($_AgentMetaData).data.totalitems -ge 1) + { + Write-Verbose "Existing Agent found" + # Setting this value here so we can use it in the Set() Method to pull back Keys + $this.AgentIDFromAPI = $_AgentMetaData.data.items.id + #We need Path to Client.keys File C:|Program FIles (x86)\Ossec-agent + if (Test-Path ($this.AgentPath + "\Client.keys")) + { + Write-Verbose "Existing Client.Keys file found" + $_clientKeyFilePath = $this.AgentPath + "\Client.keys" + $_currentID = ((Get-Content -Path $_clientKeyFilePath).Split(' '))[0] + $_currentStatus = ($_AgentMetaData).data.items.status + if ((($this.AgentIDFromAPI) -eq $_currentID) -and ($_currentStatus) -ne "Never connected" ) + { + Write-Verbose "Current Agent ID matches Manager Agent ID and Status is Active or Disconnected - Assuming Agent Registered" + #Total Items ge 1, There is a CLient.keys file, the Agent ID from API and Client.keys match, and the agent status is disconnected or active + $_RegistrationStatus.add('AgentRegistered', $true) + } + else + { + Write-Verbose "Client.Keys file exists but Agent IDs do not match or Status is `"Never Connected`"" + # Total Items ge 1, there is a CLient.keys file, and Status is "Never Connected" + # Use the "Insert" API to re-use the Agent ID + $_RegistrationStatus.add('AgentRegistered', $false) + $_RegistrationStatus.add('AgentRegisterExisting', $true) + } + } + else + { + Write-Verbose "No Client.Keys file exists, assuming not registered" + #Total Items ge 1, There is no CLient.keys file + # Use the "Insert" API to re-use the Agent ID + $_RegistrationStatus.add('AgentRegistered', $false) + $_RegistrationStatus.add('AgentRegisterExisting', $true) + } + } + else + { + Write-Verbose "No Agent found on Manager, Agent not registered" + $_RegistrationStatus.add('AgentRegistered', $false) + } + Return $_RegistrationStatus + } + #endregion } \ No newline at end of file