Automating OSSEC Agent Deployment on Windows Using CloudFormation, SSM, PowerShell, and Python
Automating OSSEC Agent Installation on Windows with PowerShell

Automating OSSEC Agent Deployment on Windows Using CloudFormation, SSM, PowerShell, and Python

Cloud security is increasingly vital, and automating and standardizing the deployment of security agents is crucial. To efficiently install OSSEC (a widely-used Host Intrusion Detection System - HIDS) on Windows EC2 instances in a scalable, repeatable, and automated manner, we leveraged AWS CloudFormation, AWS Systems Manager (SSM), PowerShell, and Python.

Our Infrastructure-as-Code (IaC) solution ensures that OSSEC agents are installed consistently across Windows EC2 instances by retrieving scripts from an S3 bucket, executing them using SSM, and automating the full setup with PowerShell and Python.


Challenges with OSSEC Installation

When deploying OSSEC, we had to overcome several challenges:

Managing OSSEC Installations

  • Ensuring no conflicting versions exist.
  • Uninstalling any previous OSSEC installation if necessary.

Handling OSSEC Configuration Files

  • Dynamically setting up configurations based on the local instance's network information.
  • Replacing default configuration files with custom ones for seamless integration.

Ensuring OSSEC Agent Operation

  • Automating the start of the agent after installation.
  • Verifying successful communication with the OSSEC server.

Without an automated approach, these tasks would be error-prone, time-consuming, and difficult to scale across multiple instances.


The Solution: CloudFormation, SSM, PowerShell, and Python Automation

Our Infrastructure-as-Code (IaC) approach simplifies OSSEC agent deployment by using:

  • CloudFormation to define the infrastructure and automation steps.
  • AWS Systems Manager (SSM) Associations to download and execute scripts automatically.
  • PowerShell & Python to install, configure, and verify OSSEC.


1. Automating Deployment with CloudFormation and SSM

To deploy OSSEC automatically across multiple Windows EC2 instances, we used AWS Systems Manager (SSM) Associations in our CloudFormation template. This ensures that each instance executes the OSSEC installation and configuration script at scale.

CloudFormation SSM Association for OSSEC Installation

The following CloudFormation resource defines an SSM Association that:

  1. Downloads the OSSEC installation script from an S3 bucket.
  2. Executes the script on Windows EC2 instances.
  3. Ensures all instances tagged with "Platform: Windows" receive the agent.

"InstallOssecAgentWindowsAssociation": {
    "Type": "AWS::SSM::Association",
    "DependsOn": [
        "InstallOssecServerAssociation"
    ],
    "Properties": {
        "AssociationName": "Install-OSSec-Agent-Windows",
        "Name": "AWS-RunPowerShellScript",
        "Parameters": {
            "commands": [
                {
                    "Fn::Sub": "aws s3 cp s3://${DeploymentBucketName}/${DeploymentBucketPath}Scripts/ossec/InstallOssecAgentWindows.ps1 C:\\Setup\\ossec\\"
                },
                {
                    "Fn::Sub": "powershell -ExecutionPolicy Bypass -File C:\\Setup\\ossec\\InstallOssecAgentWindows.ps1 --DeploymentBucketName ${DeploymentBucketName} --DeploymentBucketPath ${DeploymentBucketPath}"
                }
            ],
            "executionTimeout": ["900"]
        },
        "Targets": [
            {
                "Key": "tag:Platform",
                "Values": ["Windows"]
            }
        ]
    }
}        

What This Does

  • Automatically copies the OSSEC installation script (InstallOssecAgentWindows.ps1 and InstallOssecWindowsAgent.py) from S3.
  • Executes the PowerShell script, which then invokes a Python script to handle installation.
  • Ensures only Windows EC2 instances (tagged as Platform: Windows) execute the process.


2. OSSEC Installation Workflow

Once the CloudFormation template provisions the infrastructure, the SSM Association executes the PowerShell script, which then runs a Python script to install and configure OSSEC.

Step 1: Gathering System Information

Before installing the OSSEC agent, the python script retrieves the local IPv4 address of the instance:

import socket

def get_local_ipv4():
    """Retrieves the local IPv4 address of the machine."""
    try:
        hostname = socket.gethostname()
        ip_address = socket.gethostbyname(hostname)
        return ip_address
    except socket.error as e:
        print(f"Error getting local IPv4 address: {e}")
        return None

local_ip = get_local_ipv4()
print(f"Local IPv4 Address: {local_ip}")        

This IP address determines the correct OSSEC configuration files for that instance.


Step 2: Handling Existing OSSEC Installations

Before installing, the PowerShell script removes any existing OSSEC installation to prevent conflicts:

Stop-Service -Name "OSSEC HIDS" -Force -ErrorAction SilentlyContinue
Stop-Process -Name "ossec-agent-win32-3.7.0-24343" -Force -ErrorAction SilentlyContinue

$uninstallPath = "C:\Program Files (x86)\ossec-agent\uninstall.exe"
if (Test-Path $uninstallPath) {
    Start-Process -FilePath $uninstallPath -ArgumentList "/S" -NoNewWindow -Wait
}

Remove-Item -Path 'C:\Program Files (x86)\ossec-agent\ossec.conf' -Force -ErrorAction SilentlyContinue
Remove-Item -Path 'C:\Program Files (x86)\ossec-agent\client.keys' -Force -ErrorAction SilentlyContinue        

Step 3: Downloading and Installing OSSEC

The PowerShell script also uses S3 to retrieve the required files such as the Python script, ossec.conf, and client.keys, before the installation begins:

aws s3 cp s3://${DeploymentBucketName}/${DeploymentBucketPath}Packages/ossec/ 'C:\Setup\ossec\' --recursive
aws s3 cp s3://${DeploymentBucketName}/${DeploymentBucketPath}Scripts/ossec/ 'C:\Setup\ossec\' --recursive        

Then, the Python script runs the OSSEC installer:

import subprocess
import os

setup_dir = r'C:\Setup\ossec'
ossec_exe = os.path.join(setup_dir, 'ossec-agent-win32-3.7.0-24343.exe')

subprocess.run(["powershell", "-Command", f'& "{ossec_exe}" /S /U'], capture_output=True, text=True)
print("OSSEC installation initiated.")        

Step 4: Configuring OSSEC

After installation, the Python script applies custom configuration files (ossec.conf, client.keys) which were copied from S3, based on the instance’s IP:

import shutil

ossec_conf_src = os.path.join(setup_dir, f'{local_ip}_ossec.conf')
client_keys_src = os.path.join(setup_dir, f'{local_ip}_client.keys')

ossec_conf_dest = r'C:\Program Files (x86)\ossec-agent\ossec.conf'
client_keys_dest = r'C:\Program Files (x86)\ossec-agent\client.keys'

if os.path.exists(ossec_conf_src) and os.path.exists(client_keys_src):
    shutil.copyfile(ossec_conf_src, ossec_conf_dest)
    shutil.copyfile(client_keys_src, client_keys_dest)
    print("OSSEC configuration files updated successfully.")        

Step 5: Starting and Verifying OSSEC

The OSSEC service is started and verified by the Python script:

# Start OSSEC service
subprocess.run(["powershell", "-Command", 'net start "OSSEC HIDS"'], capture_output=True, text=True)

# Check service status
service_status = subprocess.run(["powershell", "-Command", 'Get-Service -Name "OSSEC HIDS"'], capture_output=True, text=True)
if "Running" in service_status.stdout:
    print("OSSEC agent is running.")
else:
    print("OSSEC agent failed to start.")        

Conclusion

This CloudFormation-based automation ensures a scalable, consistent, and error-free OSSEC deployment across Windows EC2 instances:

  • IaC with CloudFormation simplifies deployment across environments.
  • SSM Associations ensure automated script execution on Windows instances.
  • PowerShell & Python automate installation, configuration, and verification.
  • S3 Integration ensures centrally managed scripts and configuration.

This approach reduces manual effort, enhances security posture, and ensures all instances are properly monitored using OSSEC. 🚀

To view or add a comment, sign in

More articles by Glenn G.

Explore content categories