-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathInstallHuntress.powershellv2.ps1
More file actions
709 lines (623 loc) · 29.4 KB
/
InstallHuntress.powershellv2.ps1
File metadata and controls
709 lines (623 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
# Copyright (c) 2023 Huntress Labs, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Huntress Labs nor the names of its contributors may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL HUNTRESS LABS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Alan Bishop, John Ferrell, Dave Kleinatland, Cameron Granger
# The Huntress installer needs an Account Key and an Organization Key (a user specified name or description) which is used to affiliate an Agent with a
# specific Organization within the Huntress Partner's Account. These keys can be hard coded below or passed in when the script is run.
# For more details, see our KB article https://support.huntress.io/hc/en-us/articles/4404004936339-Deploying-Huntress-with-PowerShell
# Usage (remove brackets [] and substitute <variable> for your value):
# powershell -executionpolicy bypass -f ./InstallHuntress.powershellv2.ps1 [-acctkey <account_key>] [-orgkey <organization_key>] [-tags <tags>] [-reregister] [-reinstall] [-uninstall] [-repair]
#
# example:
# powershell -executionpolicy bypass -f ./InstallHuntress.powershellv2.ps1 -acctkey "0b8a694b2eb7b642069" -orgkey "Buzzword Company Name" -tags "production,US West"
# Optional command line params, this has to be the first line in the script.
param (
[string]$acctkey,
[string]$orgkey,
[string]$tags,
[switch]$reregister,
[switch]$reinstall,
[switch]$uninstall,
[switch]$repair
)
##############################################################################
## Begin user modified variables
##############################################################################
# Set to "Continue" to enable verbose logging.
$DebugPreference = "SilentlyContinue"
# Legacy, spinning HDD, or overloaded machines may require tuning this value. Most modern end points install in 10 seconds
# 3rd party security software (AV/EDR/etc) may significantly slow down the install if Huntress exclusions aren't properly put in!
$timeout = 120 # number of seconds to wait before continuing the install
##############################################################################
## Do not modify anything below this line
##############################################################################
# set defaults since we can't pass command line args
$reregister = $false
$TagsKey = ""
$reinstall = $false
$uninstall = $false
$repair = $false
# Find poorly written code faster with the most stringent setting.
Set-StrictMode -Version Latest
# Check for old outdated Windows PowerShell (script works as low as PoSh 2.0)
$oldOS = $false
if ($PsVersionTable.PsVersion.Major -lt 3){
$oldOS = $true
}
# Pull the kernel version so we know whether we need to check for EDR or not
$kernelVersion = [System.Environment]::OSVersion.Version
# These are used by the Huntress support team when troubleshooting.
$ScriptVersion = "Version 2, major revision 8, 2025 July 10, N-central specific"
$ScriptType = "PowerShell"
# Check for an account key specified on the command line.
if ( ! [string]::IsNullOrEmpty($acctkey) ) {
$AccountKey = $acctkey
}
# Check for an organization key specified on the command line.
if ( ! [string]::IsNullOrEmpty($orgkey) ) {
$OrganizationKey = $orgkey
}
# Check for tags specified on the command line.
if ( ! [string]::IsNullOrEmpty($tags) ) {
$TagsKey = $tags
}
# variables used throughout this script
$X64 = 64
$X86 = 32
$InstallerName = "HuntressInstaller.exe"
$InstallerPath = Join-Path $Env:TMP $InstallerName
$DebugLog = Join-Path $Env:TMP HuntressInstaller.log
$HuntressKeyPath = "HKLM:\SOFTWARE\Huntress Labs\Huntress"
$HuntressRegKey = "HKLM:\SOFTWARE\Huntress Labs"
# pick the appropriate file to download based on the OS version
if ($oldOS -eq $true) {
# For Windows Vista, Server 2008 (PoSh 2)
$DownloadURL = "https://update.huntress.io/legacy_download/" + $AccountKey + "/" + $InstallerName
} else {
# For Windows 7+, Server 2008 R2+ (PoSh 3+)
$DownloadURL = "https://update.huntress.io/download/" + $AccountKey + "/" + $InstallerName
}
# strings used throughout this script
$ScriptFailed = "Script Failed!"
$SupportMessage = "Please send the error message to support@huntress.com"
$HuntressAgentServiceName = "HuntressAgent"
$HuntressUpdaterServiceName = "HuntressUpdater"
$HuntressEDRServiceName = "HuntressRio"
# 32bit PoSh on 64bit Windows is unable to interact with certain assets, so we check for this condition
$PowerShellArch = $X86
# 8 byte pointer is 64bit
if ([IntPtr]::size -eq 8) {
$PowerShellArch = $X64
}
# time stamps for logging purposes
function Get-TimeStamp {
return "[{0:yyyy/MM/dd} {0:HH:mm:ss}]" -f (Get-Date)
}
# adds time stamp to a message and then writes that to the log file
function LogMessage ($msg) {
Add-Content $DebugLog "$(Get-TimeStamp) $msg"
Write-Host "$(Get-TimeStamp) $msg"
}
# test that all required parameters were passed, and that they are in the correct format
function Test-Parameters {
LogMessage "Verifying received parameters..."
# If reregister and reinstall were both flagged, just reregister as it is the more robust option
if ($reregister -and $reinstall) {
$err = "Specified -reregister and -reinstall, defaulting to reregister."
LogMessage $err
$reinstall = $false
}
# Ensure we have an account key (hard coded or passed params) and that it's in the correct form
if ($AccountKey -eq "__ACCOUNT_KEY__") {
$err = "AccountKey not set! Suggest using the -acctkey flag followed by your account key (you can find it in the Downloads section of your Huntress portal)."
LogMessage $err
Write-Host $err -ForegroundColor white -BackgroundColor red
throw $ScriptFailed + " " + $err
exit 1
} elseif ($AccountKey.length -ne 32) {
$err = "Invalid AccountKey specified (incorrect length)! Suggest double checking the key was copy/pasted in its entirety"
LogMessage $err
Write-Host $err -ForegroundColor white -BackgroundColor red
throw $ScriptFailed + " " + $err
exit 1
} elseif (($AccountKey -match '[^a-zA-Z0-9]')) {
$err = "Invalid AccountKey specified (invalid characters found)! Suggest double checking the key was copy/pasted fully"
LogMessage $err
Write-Host $err -ForegroundColor white -BackgroundColor red
throw $ScriptFailed + " " + $err
exit 1
}
# Ensure we have an organization key (hard coded or passed params).
if ($OrganizationKey -eq "__ORGANIZATION_KEY__") {
$err = "OrganizationKey not specified! This is a user defined identifier set by you (usually your customer's organization name)"
LogMessage $err
Write-Host $err -ForegroundColor white -BackgroundColor red
throw $ScriptFailed + " " + $err
exit 1
} elseif ($OrganizationKey.length -lt 1) {
$err = "Invalid OrganizationKey specified (length should be > 0)!"
LogMessage $err
Write-Host $err -ForegroundColor white -BackgroundColor red
throw $ScriptFailed + " " + $err
exit 1
}
}
# check to see if the Huntress service exists (agent or updater)
function Confirm-ServiceExists ($service) {
if (Get-Service $service -ErrorAction SilentlyContinue) {
return $true
}
return $false
}
# check to see if the Huntress service is running (agent or updater)
function Confirm-ServiceRunning ($service) {
$arrService = Get-Service $service
$status = $arrService.Status.ToString()
if ($status.ToLower() -eq 'running') {
return $true
}
return $false
}
# Stop the Agent and Updater services
function StopHuntressServices {
LogMessage "Stopping Huntress services..."
if (Confirm-ServiceExists($HuntressAgentServiceName)) {
Stop-Service -Name "$HuntressAgentServiceName"
} else {
LogMessage "$($HuntressAgentServiceName) not found, nothing to stop"
}
if (Confirm-ServiceExists($HuntressUpdaterServiceName)) {
Stop-Service -Name "$HuntressUpdaterServiceName"
} else {
LogMessage "$($HuntressUpdaterServiceName) not found, nothing to stop"
}
}
# return the architecture type (32 or 64 bit)
function Get-WindowsArchitecture {
if ($env:ProgramW6432) {
return $X64
} else {
return $X86
}
}
# Ensure the installer was not modified during download by validating the file signature.
function verifyInstaller ($file) {
$varChain = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Chain
try {
$varChain.Build((Get-AuthenticodeSignature -FilePath "$file").SignerCertificate) | out-null
} catch [System.Management.Automation.MethodInvocationException] {
$err = ( "ERROR: '$file' did not contain a valid digital certificate. " +
"Something may have corrupted/modified the file during the download process. " +
"Suggest trying again, contact support@huntress.com if it fails >2 times")
LogMessage $err
LogMessage $SupportMessage
Write-Host $err -ForegroundColor white -BackgroundColor red
throw $ScriptFailed + " " + $err + " " + $SupportMessage
}
}
# download the Huntress installer
function Get-Installer {
$msg = "Downloading installer to '$InstallerPath'..."
LogMessage $msg
# Ensure a secure TLS version is used.
$ProtocolsSupported = [enum]::GetValues('Net.SecurityProtocolType')
if ( ($ProtocolsSupported -contains 'Tls13') -and ($ProtocolsSupported -contains 'Tls12') ) {
# Use only TLS 1.3 or 1.2
LogMessage "Using TLS 1.3 or 1.2..."
[Net.ServicePointManager]::SecurityProtocol = (
[Enum]::ToObject([Net.SecurityProtocolType], 12288) -bOR [Enum]::ToObject([Net.SecurityProtocolType], 3072)
)
} else {
LogMessage "Using TLS 1.2..."
try {
# In certain .NET 4.0 patch levels, SecurityProtocolType does not have a TLS 1.2 entry.
# Rather than check for 'Tls12', we force-set TLS 1.2 and catch the error if it's truly unsupported.
[Net.ServicePointManager]::SecurityProtocol = [Enum]::ToObject([Net.SecurityProtocolType], 3072)
} catch {
$msg = $_.Exception.Message
$err = "ERROR: Unable to use a secure version of TLS. Please verify Hotfix KB3140245 is installed."
LogMessage $msg
LogMessage $err
throw $ScriptFailed + " " + $msg + " " + $err
}
}
# Attempt to download the correct installer for the given OS, throw error if it fails
$WebClient = New-Object System.Net.WebClient
try {
$WebClient.DownloadFile($DownloadURL, $InstallerPath)
} catch {
$msg = $_.Exception.Message
$err = "ERROR: Failed to download the Huntress Installer. Try accessing $($DownloadURL) from the host where the download failed. Contact support@huntress.io if the problem persists"
LogMessage $msg
LogMessage "$($err) Please contact support@huntress.io if the problem persists"
throw $ScriptFailed + " " + $err + " " + $msg
}
# Ensure the file downloaded correctly, if not, throw error
if ( ! (Test-Path $InstallerPath) ) {
$err = "ERROR: Failed to download the Huntress Installer from $DownloadURL. Suggest testing the URL in a browser."
LogMessage $err
LogMessage $SupportMessage
throw $ScriptFailed + " " + $err + " " + $SupportMessage
}
$msg = "Installer downloaded to '$InstallerPath'..."
LogMessage $msg
}
# check if the agent downloaded, is a valid install file, if those match up then run the installer
function Install-Huntress ($OrganizationKey) {
# check that the installer downloaded and wasn't quarantined
LogMessage "Checking for installer '$InstallerPath'..."
if ( ! (Test-Path $InstallerPath) ) {
$err = "ERROR: The installer was unexpectedly removed from $InstallerPath"
$msg = (
"A security product may have quarantined the installer. Please check " +
"your logs. If the issue continues to occur, please send the log to the Huntress " +
"Team for help at support@huntresslabs.com")
LogMessage $err
LogMessage $msg
Write-Host $err + $msg -ForegroundColor white -BackgroundColor red
throw $ScriptFailed + " " + $err + " " + $SupportMessage
}
# verify the installer's integrity
verifyInstaller($InstallerPath)
# execute the installer, stopping if it gets hung (security product interference)
$msg = "Executing installer..."
LogMessage $msg
# if $Tags value exists install using the provided tags, then check hardcoded, then set no tags
if (($Tags) -or ($TagsKey -ne "__TAGS__")) {
$process = Start-Process $InstallerPath "/ACCT_KEY=`"$AccountKey`" /ORG_KEY=`"$OrganizationKey`" /TAGS=`"$TagsKey`" /S" -PassThru
} else {
$process = Start-Process $InstallerPath "/ACCT_KEY=`"$AccountKey`" /ORG_KEY=`"$OrganizationKey`" /S" -PassThru
}
try {
$process | Wait-Process -Timeout $timeout -ErrorAction Stop
} catch {
$process | Stop-Process -Force
$err = "ERROR: Installer failed to complete in $timeout seconds. Possible interference from a security product?"
Write-Host $err -ForegroundColor white -BackgroundColor red
LogMessage $err
LogMessage $SupportMessage
throw $ScriptFailed + " " + $err + " " + $SupportMessage
}
}
# Test that the Huntress agent was able to install, register, and start service correctly
function Test-Installation {
LogMessage "Verifying installation..."
# Give the agent a few seconds to start and register.
Start-Sleep -Seconds 8
# Get the file locations of some of the Huntress executables
$HuntressDirectory = getAgentPath
$HuntressAgentPath = Join-Path $HuntressDirectory "HuntressAgent.exe"
$HuntressUpdaterPath = Join-Path $HuntressDirectory "HuntressUpdater.exe"
# Get the registry location, and store some strings for use in registry
$AgentIdKeyValueName = "AgentId"
$OrganizationKeyValueName = "OrganizationKey"
$TagsValueName = "Tags"
# Ensure the critical files were created.
foreach ( $file in ($HuntressAgentPath, $HuntressUpdaterPath) ) {
if ( ! (Test-Path $file) ) {
$err = "ERROR: $file did not exist. Check your AV/security software quarantine"
LogMessage $err
LogMessage $SupportMessage
throw $ScriptFailed + " " + $err + " " + $SupportMessage
}
LogMessage "'$file' is present."
}
# Check for Legacy OS, any kernel below 6.2 cannot run Huntress EDR (so we skip that check)
if ( ($kernelVersion.major -eq 6 -and $kernelVersion.minor -lt 2) -or ($kernelVersion.major -lt 6) ) {
$services = @($HuntressAgentServiceName, $HuntressUpdaterServiceName)
$err = "WARNING: Legacy OS detected, Huntress EDR will not be installed"
LogMessage $err
} else {
$services = @($HuntressAgentServiceName, $HuntressUpdaterServiceName, $HuntressEDRServiceName)
}
# Ensure the services are installed and running.
foreach ($svc in $services) {
# check if the service is installed?
if ( ! (Confirm-ServiceExists($svc))) {
$err = "ERROR: The $svc service is not installed. You may need to wait 20 minutes, reboot, or reinstall the agent."
LogMessage $err
if ($svc -eq "HuntressAgent") {
LogMessage $SupportMessage
throw $ScriptFailed + " " + $err + " " + $SupportMessage
}
}
# check if the service is running.
elseif ( ! (Confirm-ServiceRunning($svc)) ) {
$err = "ERROR: The $svc service is not running. You may need to manually start it for more info."
LogMessage $err
if ($svc -eq "HuntressAgent") {
LogMessage $SupportMessage
throw $ScriptFailed + " " + $err + " " + $SupportMessage
}
} else {
LogMessage "'$svc' is running."
}
}
# look for a condition that prevents checking registry keys, if not then check for registry keys
if ( ($PowerShellArch -eq $X86) -and ($WindowsArchitecture -eq $X64) ) {
LogMessage "WARNING: Can't verify registry settings due to 32bit PowerShell on 64bit host. Please run PowerShell in 64 bit mode"
} else {
# Ensure the Huntress registry key is present.
if ( ! (Test-Path $HuntressKeyPath) ) {
$err = "ERROR: The registry key '$HuntressKeyPath' did not exist. You may need to reinstall with the -reregister flag"
LogMessage $err
LogMessage $SupportMessage
throw $ScriptFailed + " " + $err + " " + $SupportMessage
}
# Ensure the Huntress registry values are present.
$HuntressKeyObject = Get-ItemProperty $HuntressKeyPath
foreach ( $value in ($AgentIdKeyValueName, $OrganizationKeyValueName, $TagsValueName) ) {
If ( ! (Get-Member -inputobject $HuntressKeyObject -name $value -Membertype Properties) ) {
$err = "ERROR: The registry value $value did not exist within $HuntressKeyPath. You may need to reinstall with the -reregister flag"
LogMessage $err
LogMessage $SupportMessage
throw $ScriptFailed + " " + $err + " " + $SupportMessage
}
}
}
# Verify the agent registered (if not blocked by 32/64 bit incompatibilities).
if ( ($PowerShellArch -eq $X86) -and ($WindowsArchitecture -eq $X64) ) {
LogMessage "WARNING: Can't verify agent registration due to 32bit PowerShell on 64bit host."
} else {
If ($HuntressKeyObject.$AgentIdKeyValueName -eq 0) {
$err = ("ERROR: The agent did not register. Check the log (%ProgramFiles%\Huntress\HuntressAgent.log) for errors.")
LogMessage $err
LogMessage $SupportMessage
throw $ScriptFailed + " " + $err + " " + $SupportMessage
}
LogMessage "Agent registered."
}
LogMessage "Installation verified!"
}
# prepare to reregister by stopping the Huntress service and deleting all the registry keys
function PrepReregister {
LogMessage "Preparing to re-register agent..."
StopHuntressServices
$HuntressKeyPath = "HKLM:\SOFTWARE\Huntress Labs\Huntress"
Remove-Item -Path "$HuntressKeyPath" -Recurse -ErrorAction SilentlyContinue
}
# looks at the Huntress log to return true if the agent is orphaned, false if the agent is active AB
function isOrphan {
# find the Huntress log file or state that it can't be found
if (Test-Path 'C:\Program Files\Huntress\HuntressAgent.log') {
$Path = 'C:\Program Files\Huntress\HuntressAgent.log'
} elseif (Test-Path 'C:\Program Files (x86)\Huntress\HuntressAgent.log') {
$Path = 'C:\Program Files (x86)\Huntress\HuntressAgent.log'
} else {
LogMessage "Unable to locate log file, thus unable to check if orphaned"
return $false
}
# if the log was found, look through the last 10 lines for the orphaned agent error code
if ($Path -match 'HuntressAgent.log') {
$linesFromLog = Get-Content $Path | Select -last 10
ForEach ($line in $linesFromLog) {
if ($line -like "*bad status code: 401*") {
return $true
}
}
}
return $false
}
# Check if the script is being run with admin access AB
function testAdministrator {
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
# Ensure the disk has enough space for the install files + agent, then write results to the log AB
function checkFreeDiskSpace {
# Using an older disk query to be backwards compatible with PoSh 2, catch WMI errors and check repository
try {
$freeSpace = (Get-WmiObject -query "Select * from Win32_LogicalDisk where DeviceID='c:'" | Select FreeSpace).FreeSpace
} catch {
LogMessage "WMI issues discovered (free space query), attempting to fix the repository"
winmgt -verifyrepository
$drives = get-psdrive
foreach ($drive in $drives) {
if ($drive.Name -eq "C") {
$freeSpace = $drive.Free
}
}
}
$freeSpaceNice = $freeSpace.ToString('N0')
$estimatedSpaceNeeded = 45123456
if ($freeSpace -lt $estimatedSpaceNeeded) {
$err = "Low disk space detected, you may have troubles completing this install. Only $($freeSpaceNice) bytes remaining (need about $($estimatedSpaceNeeded.ToString('N0'))."
Write-Host $err -ForegroundColor white -BackgroundColor red
LogMessage $err
} else {
LogMessage "Free disk space: $($freeSpaceNice)"
}
}
# determine the path in which Huntress is installed AB
function getAgentPath {
# Ensure we resolve the correct Huntress directory regardless of operating system or process architecture.
if (Get-WindowsArchitecture -eq $X64) {
return (Join-Path $Env:ProgramW6432 "Huntress")
} else {
return (Join-Path $Env:ProgramFiles "Huntress")
}
}
# attempt to run a process and log the results AB
function runProcess ($process, $flags, $name){
try {
Start-Process $process $flags | Wait-Process -Timeout $timeout -ErrorAction Stop
LogMessage "$($name) finished"
} catch {
Stop-Process $process -Force
$err = "ERROR: $($name) failed to complete in $timeout seconds."
Write-Host $err -ForegroundColor white -BackgroundColor red
LogMessage $err
exit 0
}
}
# Fully uninstall the agent AB
function uninstallHuntress {
$agentPath = getAgentPath
$updaterPath = Join-Path $agentPath "HuntressUpdater.exe"
$exeAgentPath = Join-Path $agentPath "HuntressAgent.exe"
$uninstallerPath = Join-Path $agentPath "Uninstall.exe"
# attempt to use the built in uninstaller, if not found use the uninstallers built into the Agent and Updater
if (Test-Path $agentPath) {
Write-Host "Uninstalling, please wait :) "
# run uninstaller.exe, if not found run the Agent's built in uninstaller and the Updater's built in uninstaller
if (Test-Path $uninstallerPath) {
runProcess "$($uninstallerPath)" "/S" "Uninstall.exe" -wait
Start-Sleep 15
} elseif (Test-Path $exeAgentPath) {
runProcess "$($exeAgentPath)" "/S" "Huntress Agent uninstaller" -wait
Start-Sleep 15
} elseif (Test-Path $updaterPath) {
runProcess "$($updaterPath)" "/S" "Updater uninstaller" -wait
Start-Sleep 15
} else {
LogMessage "Agent path found but no uninstallers found. Attempting to manually uninstall"
}
} else {
$err = "Note: unable to find Huntress install folder. Attempting to manually uninstall."
Write-Host $err -ForegroundColor white -BackgroundColor red
LogMessage $err
}
# look for the Huntress directory, if found then delete
if (Test-Path $agentPath) {
Remove-Item -LiteralPath $agentPath -Force -Recurse -ErrorAction SilentlyContinue
LogMessage "Manual cleanup of Huntress folder: success"
} else {
LogMessage "Manual cleanup of Huntress folder: folder not found"
}
# look for the registry keys, if exist then delete
if (Test-Path $HuntressRegKey) {
Get-Item -path $HuntressRegKey | Remove-Item -recurse
LogMessage "Manually deleted Huntress registry keys"
} else {
LogMessage "No registry keys found, uninstallation complete"
}
}
# grab the currently installed agent version AB
function getAgentVersion {
$exeAgentPath = Join-Path (getAgentPath) "HuntressAgent.exe"
$agentVersion = (Get-Item $exeAgentPath).VersionInfo.FileVersion
LogMessage "Agent version $($agentVersion) found"
return $agentVersion
}
# ensure all the Huntress services are running AB
function repairAgent {
Start-Service HuntressAgent
Start-Service HuntressUpdater
}
function main () {
# gather info on the host for logging purposes
LogMessage "Script type: '$ScriptType'"
LogMessage "Script version: '$ScriptVersion'"
LogMessage "Host name: '$env:computerName'"
try {
$os = (get-WMiObject -computername $env:computername -Class win32_operatingSystem).caption.Trim()
} catch {
LogMessage "WMI issues discovered (computer name query), attempting to fix the repository"
winmgt -verifyrepository
$os = (get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName
}
LogMessage "Host OS: '$os'"
LogMessage "Host Architecture: '$(Get-WindowsArchitecture)'"
if ($oldOS) {
LogMessage "Warning! Older version of PowerShell detected"
}
checkFreeDiskSpace
LogMessage "PowerShell Architecture: '$PowerShellArch'"
LogMessage "Installer location: '$InstallerPath'"
LogMessage "Installer log: '$DebugLog'"
LogMessage "Administrator access: $(testAdministrator)"
# if run with the uninstall flag, exit so we don't reinstall the agent after
if ($uninstall) {
LogMessage "Uninstalling Huntress agent"
uninstallHuntress
exit 0
}
# if the agent is orphaned, switch to the full uninstall/reinstall (reregister flag)
if ( !($reregister)) {
if (isOrphan) {
$err = 'Huntress Agent is orphaned, unable to use the provided flag. Switching to uninstall/reinstall (reregister flag)'
Write-Host $err -ForegroundColor white -BackgroundColor red
LogMessage "$err"
$reregister = $true
}
}
# if run with no flags and no account key, assume repair
if (!$repair -and !$reregister -and !$uninstall -and !$reinstall -and ($AccountKey -eq "__ACCOUNT_KEY__")) {
LogMessage "No flags or account key found! Defaulting to the -repair flag."
$repair = $true
}
# if run with the repair flag, check if installed (install if not), if ver < 0.13.16 apply the fix
if ($repair) {
if (Test-Path(getAgentPath)){
repairAgent
LogMessage "Repair complete!"
exit 0
} else {
LogMessage "Agent not found! Attempting to install"
$reregister = $true
}
}
# trim keys for blanks before use
$AccountKey = $AccountKey.Trim()
$OrganizationKey = $OrganizationKey.Trim()
# check that all the parameters that were passed are valid
Test-Parameters
# Hide most of the account key in the logs, keeping the front and tail end for troubleshooting
if ($AccountKey -ne "__Account_Key__") {
$masked = $AccountKey.Substring(0,4) + "************************" + $AccountKey.SubString(28,4)
LogMessage "AccountKey: '$masked'"
LogMessage "OrganizationKey: '$OrganizationKey'"
LogMessage "Tags: $($Tags)"
}
# reregister > reinstall > uninstall > install (in decreasing order of impact)
# reregister = reinstall + delete registry keys
# reinstall = install + stop Huntress service
if ($reregister) {
LogMessage "Re-register agent: '$reregister'"
if ( !(Confirm-ServiceExists($HuntressAgentServiceName))) {
LogMessage "Run with the -reregister flag but the service wasn't found. Attempting to install...."
}
PrepReregister
} elseif ($reinstall) {
LogMessage "Re-install agent: '$reinstall'"
if ( !(Confirm-ServiceExists($HuntressAgentServiceName)) ) {
$err = "Script was run w/ reinstall flag but there's nothing to reinstall. Attempting to clean remnants, then install the agent fresh."
LogMessage "$err"
uninstallHuntress
exit 0
}
StopHuntressServices
} else {
LogMessage "Checking for HuntressAgent service..."
if ( Confirm-ServiceExists($HuntressAgentServiceName) ) {
$err = "The Huntress Agent is already installed. Exiting with no changes. Suggest using -reregister or -reinstall flags"
LogMessage "$err"
Write-Host 'Huntress Agent is already installed. Suggest using the -reregister or -reinstall flags' -ForegroundColor white -BackgroundColor red
exit 0
}
}
Get-Installer
Install-Huntress $OrganizationKey
Test-Installation
LogMessage "Huntress Agent successfully installed!"
}
try {
main
} catch {
$ErrorMessage = $_.Exception.Message
LogMessage $ErrorMessage
exit 1
}