# ============================================================================= # LOI Monitrack Windows Agent - MSI 설치 스크립트 (관리자 권한) # # - 코드서명 인증서를 신뢰 등록(스크립트가 자동) → 서버별 백신 예외 불필요 # - MSI 무인 설치: msiexec /i LoiAgent.msi /qn SERVER=.. NAME=.. # - 기존(구버전) 설치는 MSI 가 서비스를 재구성한다(수동 정리 불필요) # # 사용법 (관리자 PowerShell): # powershell -ExecutionPolicy Bypass -File install_agent_msi.ps1 # powershell -ExecutionPolicy Bypass -File install_agent_msi.ps1 -Name "MyHost" -Server "monitrack.loict.co.kr" # ============================================================================= [CmdletBinding()] param( [string] $Server = "monitrack.loict.co.kr", [string] $Name = $env:COMPUTERNAME, [string] $MsiUrl = "https://monitrack.loict.co.kr/downloads/LoiAgent.msi", [string] $CertUrl = "https://monitrack.loict.co.kr/downloads/LoiCodeSign.cer", # ※ DNS 가 안 되는 서버는 -MsiUrl/-CertUrl 로 IP 대체 가능: # https://monitrack.loict.co.kr/downloads/LoiAgent.msi (인증서 고정 적용됨) [string] $CertThumbprint = "5078E8621C7D5374CA983218AD18F22D3ECF342C", # 서버 TLS 인증서 고정(DNS 없이 IP 접속 → 이름 불일치만 허용) [string] $TlsThumbprint = "74C1EA36332A485B362C33F201CEBFFFD59609E0", [string] $TlsCn = "monitrack.loict.co.kr" ) # HTTPS 인증서 고정 콜백(.NET 콜백은 PowerShell 스크립트블록이 스레드 문제로 실패할 수 있어 C# 로 컴파일) if (-not ("LoiTlsPin" -as [type])) { Add-Type @" using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; public class LoiTlsPin { public static void Apply(string thumb, string cn) { try { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; } catch {} try { ServicePointManager.CheckCertificateRevocationList = false; } catch {} ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, err) => { if (err == SslPolicyErrors.None) return true; var fatal = SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNotAvailable; if ((err & fatal) != 0) return false; var c2 = cert as X509Certificate2; if (c2 == null) return false; if (!string.IsNullOrEmpty(thumb) && string.Equals(c2.Thumbprint, thumb, System.StringComparison.OrdinalIgnoreCase)) return true; if (!string.IsNullOrEmpty(cn) && (c2.Subject ?? "").IndexOf("CN=" + cn, System.StringComparison.OrdinalIgnoreCase) >= 0) return true; return false; }; } } "@ } [LoiTlsPin]::Apply($TlsThumbprint, $TlsCn) $ErrorActionPreference = 'Stop' function Step($t) { Write-Host ("[*] " + $t) -ForegroundColor Cyan } function Ok($t) { Write-Host (" [OK] " + $t) -ForegroundColor Green } function Warn($t) { Write-Host (" [!] " + $t) -ForegroundColor Yellow } Write-Host "===== LOI Monitrack Agent MSI 설치 =====" -ForegroundColor White # 0) 관리자 권한 if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw "관리자 권한으로 실행하세요." } # 1) 코드서명 인증서 신뢰 등록 (Root + TrustedPublisher) Step "코드서명 인증서 신뢰 등록" $have = Get-ChildItem "Cert:\LocalMachine\TrustedPublisher" -ErrorAction SilentlyContinue | Where-Object { $_.Thumbprint -eq $CertThumbprint } if ($have) { Ok "이미 등록됨" } else { $cer = Join-Path $env:TEMP "LoiCodeSign.cer" Invoke-WebRequest -Uri $CertUrl -OutFile $cer -UseBasicParsing $c = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($cer) if ($c.Thumbprint -ne $CertThumbprint) { throw ("인증서 지문 불일치 (실제 {0})" -f $c.Thumbprint) } Import-Certificate -FilePath $cer -CertStoreLocation "Cert:\LocalMachine\Root" | Out-Null Import-Certificate -FilePath $cer -CertStoreLocation "Cert:\LocalMachine\TrustedPublisher" | Out-Null Ok ("등록 완료 ({0})" -f $c.Subject) } # 2) MSI 다운로드 + 무결성/서명 검증 Step "MSI 다운로드 및 검증" $msi = Join-Path $env:TEMP "LoiAgent.msi" Invoke-WebRequest -Uri $MsiUrl -OutFile $msi -UseBasicParsing $expected = "" try { $md5txt = (Invoke-WebRequest -Uri ($MsiUrl + ".md5") -UseBasicParsing).Content $m = [regex]::Match([string]$md5txt, '[0-9a-fA-F]{32}') if ($m.Success) { $expected = $m.Value.ToUpper() } } catch { Warn "사이드카 해시를 못 받았습니다." } $got = (Get-FileHash $msi -Algorithm MD5).Hash Write-Host (" MD5: {0}" -f $got) if ($expected -and $got -ne $expected) { throw ("MD5 불일치! 기대={0} 실제={1}" -f $expected, $got) } $sig = Get-AuthenticodeSignature $msi if ($sig.Status -eq 'Valid') { Ok ("서명 검증: Valid ({0})" -f $sig.SignerCertificate.Subject) } else { Warn ("서명 검증: {0}" -f $sig.Status) } # 3) 설치 (이미 설치돼 있으면 재설치 모드로) Step "MSI 설치 (서비스 재구성 포함)" $log = Join-Path $env:TEMP "loi_agent_msi.log" $installed = $false try { $installed = [bool](Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall","HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall" -ErrorAction SilentlyContinue | ForEach-Object { (Get-ItemProperty $_.PSPath -ErrorAction SilentlyContinue).DisplayName } | Where-Object { $_ -eq 'LOI Monitrack Agent' }) } catch { } $msiArgs = "/i `"$msi`" /qn /norestart /L*v `"$log`" SERVER=`"$Server`" NAME=`"$Name`"" if ($installed) { $msiArgs += " REINSTALL=ALL REINSTALLMODE=amus"; Write-Host " (이미 설치됨 → 재설치 모드)" } $p = Start-Process msiexec.exe -ArgumentList $msiArgs -Wait -PassThru if ($p.ExitCode -ne 0) { if (Get-Service LOI_Zabbix -ErrorAction SilentlyContinue) { Warn ("msiexec 코드 {0} 이지만 서비스가 이미 정상입니다(설치 유지)" -f $p.ExitCode) } else { Warn ("msiexec 종료코드 {0}. 로그: {1}" -f $p.ExitCode, $log) throw "MSI 설치 실패" } } # 4) 확인 Step "설치 확인" Start-Sleep -Seconds 3 $svc = Get-CimInstance Win32_Service -Filter "Name='LOI_Zabbix'" -ErrorAction SilentlyContinue if ($svc) { Ok ("서비스: {0} ({1})" -f $svc.State, $svc.PathName) } else { Warn "서비스를 찾지 못했습니다." } Ok ("exe 버전: {0}" -f (Get-Item "C:\LoiAgent\LoiAgent.exe").VersionInfo.FileVersion) Write-Host "===== DONE (완료) =====" -ForegroundColor White