@echo off
color 1F
cls
REM # Security Agent Installer
REM # Version 2.7
REM # Richard Westmoreland 2022-12-09
REM # SilverSky, All Rights Reserved

echo ^+------------------------------------------------------------------^+
echo ^|             outSOC LOGM -- Installing Security Agent             ^|
echo ^|------------------------------------------------------------------^|
echo ^|                                                                  ^|
echo ^|      Welcome to the agent setup.  This has 6 steps:              ^|
echo ^|                                                                  ^|
echo ^|      1. Check connectivity to Wazuh manager                      ^|
echo ^|      2. Prompt for "Portal Tag", e.g. "AB1234"                   ^|
echo ^|      3. Install Wazuh agent                                      ^|
echo ^|      4. Register the agent with the Wazuh manager                ^|
echo ^|      5. Start the Wazuh agent service                            ^|
echo ^|                                                                  ^|
echo ^+------------------------------------------------------------------^+
echo.

call :CHECK_ADMIN

REM ## Move back into main installer path to establish absolute paths
setlocal enabledelayedexpansion
cd %~dp0..\
set InstallDir=%cd%
if "%InstallDir:~-1%" == "\" set InstallDir=%InstallDir:~0,-1%

set IniPath="%InstallDir%\etc\settings.ini"
set LogPath="%InstallDir%\log\install.log"
set MsiPath="%InstallDir%\log\msi.log"

set InstallerVer=2.7
set MsiFile=wazuh-agent-4.3.9-1.msi

set TIMESTAMP=
call :FORMAT_TIMESTAMP
echo %TIMESTAMP%: Starting agent installation...>>%LogPath%

REM Loading init file
set WazuhManager=
set WazuhVersion=
set PortalTag=UL1001
set RegisterPass=
call :GET_INI cluster manager WazuhManager
call :GET_INI cluster version WazuhVersion
call :GET_INI registration passwd RegisterPass

echo Installer v%InstallerVer% loaded, proceeding.

echo 1. Checking connectivity...
for /f "tokens=2 delims=[]" %%r in ('tracert -d -h 1 %WazuhManager%') do set ResolvedHost=%%r
if "%ResolvedHost%"=="" (
  echo ^   Could not resolve %WazuhManager%, exiting.
  call :FORMAT_TIMESTAMP
  echo %TIMESTAMP%: Could not resolve %WazuhManager%, exiting.>>%LogPath%
  timeout /t 10
  exit /b 1
) else (
  echo ^   Resolved %WazuhManager% to %ResolvedHost%
  call :FORMAT_TIMESTAMP
  echo %TIMESTAMP%: Resolved %WazuhManager% to %ResolvedHost%>>%LogPath%
)

for /f %%p in ('powershell "$t = New-Object Net.Sockets.TcpClient;try{$t.Connect("""%ResolvedHost%""", 5514)}catch{};$t.Connected"') do set TestPort5514=%%p
if "%TestPort5514%"=="True" (
  echo ^   Connected to %ResolvedHost% on TCP 5514
  call :FORMAT_TIMESTAMP
  echo %TIMESTAMP%: Connected to %ResolvedHost% on TCP 5514>>%LogPath%
) else (
  echo ^   Could not connect to %ResolvedHost% on TCP 5514, exiting.
  call :FORMAT_TIMESTAMP
  echo %TIMESTAMP%: Could not connect to %ResolvedHost% on TCP 5514, exiting.>>%LogPath%
  timeout /t 10
  exit /b 1
)

for /f %%p in ('powershell "$t = New-Object Net.Sockets.TcpClient;try{$t.Connect("""%ResolvedHost%""", 5515)}catch{};$t.Connected"') do set TestPort5515=%%p
if "%TestPort5515%"=="True" (
  echo ^   Connected to %ResolvedHost% on TCP 5515
  call :FORMAT_TIMESTAMP
  echo %TIMESTAMP%: Connected to %ResolvedHost% on TCP 5515>>%LogPath%
) else (
  echo ^   Could not connect to %ResolvedHost% on TCP 5515, exiting.
  call :FORMAT_TIMESTAMP
  echo %TIMESTAMP%: Could not connect to %ResolvedHost% on TCP 5515, exiting.>>%LogPath%
  timeout /t 10
  exit /b 1
)



if "%PortalTag%"=="" (
  call :FORMAT_TIMESTAMP
  echo ^   Portal Tag not defined, exiting.
  echo %TIMESTAMP%: Portal Tag not defined, exiting.>>%LogPath%
  timeout /t 10
  exit /b 1
)

call :FORMAT_TIMESTAMP
call :TOUPPER PortalTag
echo ^   New agent will be assigned to %PortalTag% group
echo %TIMESTAMP%: New agent will be assigned to %PortalTag% group>>%LogPath%


REM ## Install the agent

set ProgramPath=%ProgramFiles(x86)%
set Sys32Path=%SystemRoot%\System32
set MsiExe="%Sys32Path%\msiexec.exe"

set AgentHostname=%COMPUTERNAME%
call :TOUPPER AgentHostname
set AgentSuffix=usb.com


call :TOLOWER AgentSuffix
set AgentName=%AgentHostname%.%AgentSuffix%

if not exist "%ProgramPath%\ossec-agent\client.keys" (
  echo 3. Installing Wazuh agent version %WazuhVersion%...
  
  if exist "%ProgramPath%\ossec-agent" (
    call :FORMAT_TIMESTAMP
    echo %TIMESTAMP%: Prior wazuh application directory found, deleting>>%LogPath%
    rmdir /S /Q "%ProgramPath%\ossec-agent"
  )
  
  call :FORMAT_TIMESTAMP
  echo %TIMESTAMP%: Installing Wazuh agent version %WazuhVersion%...>>%LogPath%
  %MsiExe% /package "%InstallDir%\msi\%MsiFile%" /passive /norestart WAZUH_MANAGER="%WazuhManager%" WAZUH_MANAGER_PORT=5514 WAZUH_AGENT_NAME="%AgentName%" /l %MsiPath%

  call :FORMAT_TIMESTAMP
  echo %TIMESTAMP%: Adjusting wazuh directory permissions>>%LogPath%
  icacls "%ProgramPath%\ossec-agent" /grant "Users:(OI)(CI)F" /T /Q >NUL

  REM ## Remove default active responses
  del "%ProgramPath%\ossec-agent\active-response\bin\netsh.exe"
  del "%ProgramPath%\ossec-agent\active-response\bin\route-null.exe"
  
  REM ## Register the agent
  call :FORMAT_TIMESTAMP
  echo 4. Registering %AgentName% with %WazuhManager%...
  echo %TIMESTAMP%: Registering %AgentName% with %WazuhManager%...>>%LogPath%
  
  "%ProgramPath%\ossec-agent\agent-auth.exe" -m %WazuhManager% -p 5515 -P %RegisterPass% -A %AgentName% -G default,%PortalTag%

  echo %TIMESTAMP%: Creating OutSOC directories>>%LogPath%
  if not exist "%SystemDrive%\OutSOC\" mkdir "%SystemDrive%\outSOC"

) else (
  call :FORMAT_TIMESTAMP
  echo 3. Wazuh agent is already installed.
  echo %TIMESTAMP%: Wazuh agent is already installed.>>%LogPath%

  REM ## Register the agent
  call :FORMAT_TIMESTAMP
  echo 4. Registering %AgentName% with %WazuhManager%...
  echo %TIMESTAMP%: Registering %AgentName% with %WazuhManager%...>>%LogPath%
  
  "%ProgramPath%\ossec-agent\agent-auth.exe" -m %WazuhManager% -p 5515 -P %RegisterPass% -A %AgentName% -G default,%PortalTag%
)

call :FORMAT_TIMESTAMP
echo %TIMESTAMP%: Adjusting outsoc directory permissions>>%LogPath%
icacls "%SystemDrive%\OutSOC" /grant "Users:(OI)(CI)F" /T /Q >NUL

if exist "%ProgramPath%\ossec-agent" (
  REM ## Start the agent
  call :FORMAT_TIMESTAMP
  echo 6. Starting the agent service...
  echo %TIMESTAMP%: Starting the agent service...>>%LogPath%

  for /F "tokens=3 delims=: " %%h in ('sc query "WazuhSvc" ^| findstr "STATE"') do (
    if /I "%%h"=="RUNNING" (
      echo ^   Service already running, restarting.
      net stop "WazuhSvc"
      net start "WazuhSvc"
    ) else (
      net start "WazuhSvc"
    )
  )  
) else (
  call :FORMAT_TIMESTAMP
  echo ^   Agent directory is missing, installation may not be completed.
  echo ^   To register, first complete the install successfully. Exiting.
  echo %TIMESTAMP%: Agent directory is missing, installation may not be completed.>>%LogPath%
)


timeout /t 50


goto :EOF

REM ###############################################################

:CHECK_ADMIN
net session >NUL 2>&1
if %ErrorLevel% == 0 (
  exit /b 0
) else (
  echo Must be Running as administrator. Exiting.
  timeout /t 10
  exit
)

:GET_INI
set %~3=
setlocal
set insection=
for /f "usebackq eol=; tokens=*" %%a in (%IniPath%) do (
  set line=%%a
  if defined insection (
    for /f "tokens=1,* delims==" %%b in ("!line!") do (
      if /i "%%b"=="%2" (
        endlocal
        set %~3=%%c
        exit /b 0
      )
    )
  )
  if "!line:~0,1!"=="[" (
    for /f "delims=[]" %%b in ("!line!") do (
      if /i "%%b"=="%1" (
        set insection=1
      ) else (
        endlocal
        if defined insection exit /b 0
      )
    )
  )
)
endlocal
exit /b 0

:FORMAT_TIMESTAMP
for /f "tokens=2 delims==" %%G in ('wmic os get localdatetime /value') do set timestring=%%G

set YEAR=%timestring:~0,4%
set MON=%timestring:~4,2%
set DAY=%timestring:~6,2%
set HOUR=%timestring:~8,2%
set MIN=%timestring:~10,2%
set SEC=%timestring:~12,2%
set MS=%timestring:~15,3%

set TIMESTAMP=%YEAR%-%MON%-%DAY% %HOUR%:%MIN%:%SEC%.%MS%
exit /b 0

:TOUPPER
for %%x in ("a=A" "b=B" "c=C" "d=D" "e=E" "f=F" "g=G" "h=H" "i=I" "j=J" "k=K" "l=L" "m=M" "n=N" "o=O" "p=P" "q=Q" "r=R" "s=S" "t=T" "u=U" "v=V" "w=W" "x=X" "y=Y" "z=Z") do call set "%1=%%%1:%%~x%%"
exit /b 0

:TOLOWER
for %%x in ("A=a" "B=b" "C=c" "D=d" "E=e" "F=f" "G=g" "H=h" "I=i" "J=j" "K=k" "L=l" "M=m" "N=n" "O=o" "P=p" "Q=q" "R=r" "S=s" "T=t" "U=u" "V=v" "W=w" "X=x" "Y=y" "Z=z") do call set "%1=%%%1:%%~x%%"
exit /b 0

