################################### CONFIGURE VARS ################################### #openNac Core (AGENT PAYLOAD) Domain/IP (Without HTTP/S protocol) #NOTE: This will be the site where openNAC agent will send the payloads (Computer information retrieved by agent). Should be a domain or an IP #Examples: 10.10.0.50 or core.client.com $agentPayloadHost = "" #openNac Core (DOWNLOAD) Domain/IP (Without HTTP/S protocol) #NOTE: The script will download the openNAC Agent installer from this openNAC Core. MUST be an IP #Examples: 10.10.0.50 $agentDownloadHost = "" #Install openVPN to enable VPN Agent Feature - 1: YES, 0: NO #NOTE: openVPN Certificate should be installed as TrustedPublisher in the computer (Check doc) # If openvpn certificate is not installed and this option is activated the installation will get blocked. $INSTALL_OPENVPN = "1" #Install WinPCAP to give the possibility of enable agent visibility - 1: YES, 0: NO $INSTALL_WINPCAP = "0" #Create Agent Taskbar shortcut on desktop (Only valid if $INSTALL_OPENVPN = 1 ) - 1: YES, 0: NO $CREATE_SHORTCUT = "1" #Start Agent Taskbar with Windows - 1: YES, 0: NO $AGENT_AUTOSTART = "1" ################################### CONFIGURE VARS ################################### ###################################################################################### $signature = @" [DllImport("Crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool CryptStringToBinary( string pszString, int cchString, int dwFlags, byte[] pbBinary, ref int pcbBinary, int pdwSkip, ref int pdwFlags ); [DllImport("Crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool CryptBinaryToString( byte[] pbBinary, int cbBinary, int dwFlags, StringBuilder pszString, ref int pcchString ); "@ Add-Type -MemberDefinition $signature -Namespace PKI -Name Crypt32 -UsingNamespace "System.Text" Function Get-StringHash([String] $String,$HashName = "MD5") { $StringBuilder = New-Object System.Text.StringBuilder [System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String))|%{ [Void]$StringBuilder.Append($_.ToString("x2")) } $StringBuilder.ToString() } ###################################################################################### $appBeforeInstall = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -match "OpenNAC Agent*" } if(![string]::IsNullOrEmpty($appBeforeInstall)){ throw "openNac agent is installed. To update the agent check check de openNac doc." } if(!$agentPayloadHost){ throw " openNac core Domain/IP not configured" } $agentPayloadHost = $agentPayloadHost.Replace('"',"").Trim() $agentPayloadHostHex = "" $agentPayloadHost.ToCharArray() | foreach-object -process { $agentPayloadHostHex += '{0:X}' -f [int][char]$_ } $agentPayloadHostHex=$agentPayloadHostHex.ToLower(); $installerOptions = -join ($CREATE_SHORTCUT, $INSTALL_WINPCAP,$INSTALL_OPENVPN,$AGENT_AUTOSTART) [Byte[]]$installerOptionsArray = [convert]::ToInt32($installerOptions,2) $pcchString = 0 if ([PKI.Crypt32]::CryptBinaryToString($installerOptionsArray,$installerOptionsArray.Length,12,$null,[ref]$pcchString)) { $SB = New-Object Text.StringBuilder $pcchString # call the function again and pass StringBuilder into pszString parameter [void][PKI.Crypt32]::CryptBinaryToString($installerOptionsArray,$installerOptionsArray.Length,12,$SB,[ref]$pcchString) $installerOptionsHex = $SB.ToString().Trim() } else { Write-Warning $((New-Object ComponentModel.Win32Exception ([Runtime.InteropServices.Marshal]::GetLastWin32Error())).Message) } $url = "https://$agentDownloadHost/win-agent-download?type=bundle" $bundleFileName = -join("opennac-Installer_55ff_",$installerOptionsHex,"_",$agentPayloadHostHex) $hash = Get-StringHash $bundleFileName "SHA1" $hashLastBytes = ($hash).substring($hash.length-2) $outpath = -join($env:TEMP,"\",$bundleFileName,"_",$hashLastBytes,".exe") try { try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 }catch [exception]{ try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls11 }catch [exception]{ try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls }catch [exception]{ Write-Output $_.Exception|format-list -force } } } [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} $client = New-Object -TypeName System.Net.WebClient $client.DownloadFile($url,$outpath) }catch [Exception]{ Write-Output $_.Exception|format-list -force } if(Test-Path $outpath){ $arg = "/quiet /norestart" Start-Process -Wait -Filepath "$outpath" -ArgumentList $arg $app = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -match "OpenNAC Agent*" } $openNacTaskbar = Get-Process "opennac-taskbar" -ErrorAction SilentlyContinue if (!$openNacTaskbar){ $U = Get-WmiObject -Class win32_computersystem | Select-Object -ExpandProperty username $TaskName = "RunOpenNacAgentTaskbar" $TaskDescr = "Run openNac Agent taskbar to finish update" $TaskCommand = "$env:ProgramFiles\opennac-agent\taskbar\opennac-taskbar.exe" $TaskStartTime = [datetime]::Now.AddMinutes(1) $service = new-object -ComObject("Schedule.Service") $service.Connect() $rootFolder = $service.GetFolder("\") $TaskDefinition = $service.NewTask(0) $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" $TaskDefinition.Settings.Enabled = $true $TaskDefinition.Settings.AllowDemandStart = $true $TaskDefinition.Settings.DisallowStartIfOnBatteries = $false $TaskDefinition.Settings.StopIfGoingOnBatteries = $false $triggers = $TaskDefinition.Triggers $trigger = $triggers.Create(1) $trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") $trigger.Enabled = $true $Action = $TaskDefinition.Actions.Create(0) $action.Path = "$TaskCommand" $action.Arguments = "$TaskArg" $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,$U,$null,3) do{ $openNacTaskbar = Get-Process "opennac-taskbar" -ErrorAction SilentlyContinue }until ($openNacTaskbar) Start-Service -name "OpenNAC Agent" } Remove-Item -path $outpath -ErrorAction SilentlyContinue Remove-Item -path "$env:windir\Install_Agent.ps1" -ErrorAction SilentlyContinue if([string]::IsNullOrEmpty($app)){ Write-Output "Failed installing openNac agent" } }else{ Write-Output "Failed downloading openNac agent" }