-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathS1-AIO.ps1
More file actions
1029 lines (936 loc) · 52 KB
/
S1-AIO.ps1
File metadata and controls
1029 lines (936 loc) · 52 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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SentinelOne AIO Toolkit
# Author: quippy-dev
# Unified purge/install/rollback/clean/kill management script for SentinelOne Windows agents.
param (
[Parameter(Mandatory = $false)]
[bool]$AnyTarget = $false, # Allow running on non-default endpoints (Purge mode)
[ValidateSet('Purge','Install','Rollback','Clean','Unprotect','Kill','CleanTemp','OnlyMSI')]
[string]$Mode = 'Install',
# Common Parameters
[string]$CustomerSiteToken = "CHANGE_ME_IF_FRESH_INSTALL_OR_ROLLBACK", # Site Token for Install/Rollback modes
[string]$ApiToken = "CHANGE_ME", # Service User API Token
[string]$ConsoleUrl = "https://<agent-configured-console>/", # Management URL the agent is currently configured to use (legacy or current) for targeting
[string]$ApiConsoleUrl = $null, # Active console for API calls. Defaults to ConsoleUrl if not specified.
[string]$AgentPassphrase = $null,
[string]$TempDir = 'C:\Windows\SystemTemp\_S1-AIO\', # Temporary directory for downloads
[string]$ExitCodeFile = 'C:\Windows\Temp\SC-exit-code.txt', # File to store exit codes
[string]$ErrorOutFile = 'C:\Windows\Temp\SC-stderr.txt', # File to store stderr output
[string]$StdOutFile = 'C:\Windows\Temp\SC-stdout.txt', # File to store stdout output
[switch]$SkipCleanup, # Skip clean up of downloaded installers after execution
[switch]$SkipDownload, # Skip downloading installers if they already exist
[switch]$VerboseOutput, # Enable verbose logging
[switch]$UnattendedMode, # Enable unattended, minimal output mode
[switch]$Failsafe, # Use v23.x EXE and MSI
[switch]$Dynamic, # Enable retrieval of Site Token even in purge mode
[switch]$DynamicExe, # Use S1 API to find and download the latest installer package
# Installer Configuration
[switch]$SkipStateless, # Skip a stateless upgrade (Install mode)
[switch]$WithObliterator, # Include Obliterator in Purge/Cleaner
[switch]$ShowInstaller, # Show the installer UI instead of running silently
# Timeout Settings
[int]$InstallTimeoutSec = 600, # Timeout for Install mode installer process
[int]$CleanerTimeoutSec = 360, # Timeout for Cleaner process (Purge/Rollback)
[int]$RollbackTimeoutSec = 600 # Timeout for Rollback installer process (Rollback)
)
# Ensure script runs in 64-bit PowerShell on 64-bit systems for consistency
if ($env:PROCESSOR_ARCHITEW6432 -eq "AMD64") {
if ($myInvocation.Line) {
&"$env:systemroot\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile $myInvocation.Line
}
else {
&"$env:systemroot\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -file "$($myInvocation.InvocationName)" $args
}
exit $lastexitcode
}
Write-Host "SentinelOne Unified Management Script initialized in $Mode mode"
try {
# Set TLS 1.2 for modern security standards. This requires .NET Framework 4.5+.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
} catch {
Write-Warning "TLS 1.2 is not available on this system. Connectivity may be impacted. This is expected on systems with .NET Framework older than 4.5."
}
if (-not $ApiConsoleUrl) { $ApiConsoleUrl = $ConsoleUrl }
# Allow WebClient to use default credentials for proxy authentication
[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$wc = $null
try {
$wc = New-Object Net.WebClient
[void]$wc.DownloadData($ConsoleUrl)
} catch {
Write-Warning "Connection to ConsoleUrl failed. Investigate firewalls, cipher suite policies..."
} finally {
if ($wc) { $wc.Dispose() }
}
$Global:_tamperProtectionChanged = $false
#=== LOGGING AND UTILITY FUNCTIONS ===
function Write-Log {
param([string]$Message, [switch]$IsError)
# Timestamp should be present for errors and verbose output
$Timestamp = if ($VerboseOutput) { "[$((Get-Date).ToString('HH:mm:ss'))] " } else { "" }
if ($IsError) {
Write-Host "${Timestamp}ERROR: ${Message}"
} elseif (-not $UnattendedMode) { # If not unattended, then decide based on VerboseOutput
if ($VerboseOutput) {
Write-Host "${Timestamp}${Message}"
} else {
Write-Host $Message # Normal output
}
}
# If $UnattendedMode is true and it's not an error, nothing is printed.
}
function Write-VerboseLog {
param([string]$Message)
# Only write verbose logs if VerboseOutput is true AND UnattendedMode is false
if ($VerboseOutput -and -not $UnattendedMode) {
Write-Log "VERBOSE: $Message"
}
}
function Write-ExceptionLog {
param([string]$Message, $Exception)
Write-Log "$Message" -IsError
Write-Log "EXCEPTION: $($Exception.Exception.Message)" -IsError
if ($VerboseOutput) {
Write-Log "STACKTRACE: $($Exception.ScriptStackTrace)" -IsError
}
}
function Mask-Secret {
param([string]$Secret)
if (-not $Secret) { return "(empty)" }
return $Secret
if ($Secret.Length -le 4) { return "****" }
return ("********" + $Secret.Substring($Secret.Length - 4))
}
# Function to select the appropriate MSI based on conditions
function Select-Msi {
foreach ($Msi in $MsiVersions) {
if (& $Msi.Condition) { return $Msi }
}
return $null
}
# Get Local File Hash (PSv2 compatible)
function Get-LocalFileHash {
param([string]$Path, [string]$Algorithm = "SHA256")
$Stream = $null
$HashAlgorithm = $null
try {
$Stream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
switch ($Algorithm.ToUpper()) {
"SHA256" { $HashAlgorithm = New-Object System.Security.Cryptography.SHA256Managed }
"SHA1" { $HashAlgorithm = New-Object System.Security.Cryptography.SHA1Managed }
default { Write-Log "Unsupported hash algorithm {$Algorithm} for {$Path}" -IsError; return $null }
}
$HashBytes = $HashAlgorithm.ComputeHash($Stream)
return [System.BitConverter]::ToString($HashBytes).Replace('-', '')
} catch {
Write-ExceptionLog "Problem getting hash for '$($Path | Split-Path -Leaf)'" $_
return $null
} finally {
if ($Stream) { $Stream.Close(); $Stream.Dispose() }
if ($HashAlgorithm) { $HashAlgorithm.Clear() }
}
}
function Get-ValidUrl {
# Replace these with mirrors you control (self-hosted, object storage, CDN, etc.)
$Mirrors = @(
'https://mirror-primary.example.com/installers',
'https://mirror-backup.example.com/installers',
'https://mirror-edge.example.com/installers'
)
$Url = $null
# If skipping download, we don't need to test connectivity, but we need a valid URL structure for file paths.
if ($SkipDownload.IsPresent) { return $Mirrors[0] }
foreach($MirrorUrl in $Mirrors) {
$Host = $MirrorUrl.Split('/')[2]
Write-VerboseLog "Probing mirror: $Host"
$wc = $null
try {
$wc = New-Object Net.WebClient
# Use a lightweight check file to confirm reachability.
[void]$wc.DownloadData("${MirrorUrl}/chk")
$Url = $MirrorUrl
break # Found a working mirror
} catch {
Write-VerboseLog "Mirror probe failed for $Host"
} finally {
if ($wc) { $wc.Dispose() }
}
}
if ($Url) {
Write-Log "Using mirror: $($Url.Split('/')[2])"
return $Url
} else {
Write-Log "CRITICAL: No installer mirrors are reachable. Cannot download necessary files. Aborting." -IsError
Exit 1
}
}
# Download File with Hash Verification (PSv2 compatible)
function Get-OrDownload {
param([string]$Url, [string]$Dest, [string]$ExpectHash)
$FileExists = Test-Path $Dest
if ($FileExists -and ((Get-LocalFileHash -Path $Dest -EA 0) -eq $ExpectHash)) {
Write-VerboseLog "File '$($Dest | Split-Path -Leaf)' already present with matching hash"
return $true
}
if ($SkipDownload.IsPresent) {
if (-not $FileExists) {
Write-Log "SkipDownload is enabled, but the destination file '$($Dest | Split-Path -Leaf)' is missing. Aborting." -IsError
} else {
# This case implies the file exists but the hash mismatched from the check above.
Write-Log "SkipDownload is enabled, but the existing file '$($Dest | Split-Path -Leaf)' has an incorrect hash. Aborting." -IsError
}
return $false # Fail the operation
}
Write-Log "Downloading '$($Url.Split('/')[-1])' to '$($Dest | Split-Path -Leaf)'"
$RetVal = $true
try {
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile($Url, $Dest)
$ActualHash = Get-LocalFileHash -Path $Dest -EA 0
if ($ActualHash -ne $ExpectHash) {
Write-Log "Hash mismatch for '$($Dest | Split-Path -Leaf)'. Expected: $ExpectHash, Actual: $ActualHash" -IsError
Remove-Item $Dest -Force -EA 0
$RetVal = $false
}
Write-VerboseLog "Download complete and hash verified for '$($Dest | Split-Path -Leaf)'"
} catch {
Write-ExceptionLog "Critical: Download failed for '$($Url.Split('/')[-1])'" $_
$RetVal = $false
}
if ($WebClient) { $WebClient.Dispose() }
return $RetVal
}
# Robust process execution (PSv2 compatible)
function Invoke-Process {
param([string]$FilePath, [string]$ArgumentList, [int]$TimeoutSeconds)
Write-VerboseLog "Executing: $FilePath $ArgumentList"
$Process = New-Object System.Diagnostics.Process
$Process.StartInfo.FileName = $FilePath
$Process.StartInfo.Arguments = $ArgumentList
try {
if ($TimeoutSeconds -le 0 -and -not $Failsafe.IsPresent) { $Process.Start() }
else {
$Process.StartInfo.UseShellExecute = $false
$Process.StartInfo.RedirectStandardError = $true
$Process.StartInfo.RedirectStandardOutput = $true
$Process.StartInfo.CreateNoWindow = $true
$Process.Start() | Out-Null
if (-not $Process.Id) { Write-Log "Failed to start process: $FilePath" -IsError; return $null }
if (-not $Process.WaitForExit($TimeoutSeconds * 1000)) {
Write-Log "Process timed out after $TimeoutSeconds seconds. Forcibly terminating" -IsError
Stop-ProcessTree -ParentId $Process.Id
}
if ($StdOutOutput = $Process.StandardOutput.ReadToEnd().Trim()) {
Set-Content -Path $StdOutFile -Value $StdOutOutput -Force
Write-VerboseLog "Standard output: $StdOutOutput"
}
if ($StdErrOutput = $Process.StandardError.ReadToEnd().Trim()) {
Set-Content -Path $ErrorOutFile -Value $StdErrOutput -Force
Write-VerboseLog "Error output: $StdErrOutput"
}
Set-Content -Path $ExitCodeFile -Value $Process.ExitCode -Force
}
return $Process
} catch {
Write-ExceptionLog "Error executing process '$FilePath'" $_
} finally { if ($Process) { $Process.Dispose() } }
return $null
}
# Terminate running installers and their children
function Stop-ProcessTree {
param([int]$ParentId)
# Use taskkill with /T to recursively terminate the process tree. This avoids WMI.
Write-VerboseLog "Terminating process tree for PID: $ParentId"
try {
Stop-Process -Id $ParentId -Force -EA 0
} catch {}
(& taskkill /PID $ParentId /F /T 2>$null)
}
function Invoke-TaskKill {
if ($Failsafe.IsPresent) {
$ProcessTargets = @('msiexec', 'Sentinel*')
} else {
$ProcessTargets = @('msiexec', 'SentinelOneInstaller*', 'SentinelCleaner*','SentinelUI*')
}
foreach ($ProcessName in $ProcessTargets) {
$Processes = Get-Process -Name $ProcessName -EA 0
$DisplayName = $ProcessName.Replace('*','')
if ($Processes) {
foreach ($Process in $Processes) {
Write-Log "Terminating process $($Process.ProcessName) (PID: $($Process.Id))"
Stop-ProcessTree -ParentId $Process.Id
}
if ($Mode -eq "Kill") { Write-Host "Killed $DisplayName + child processes" }
} elseif ($Mode -eq "Kill") { Write-Host "No $DisplayName process to kill!" }
}
# Remove-Item 'HKLM:\SOFTWARE\SentinelOne\Setup\UninstallRebootMark' -Recurse -Force -EA 0
}
function Invoke-ServiceCleanup {
Write-Log "Stopping and removing SentinelOne services..."
$Services = @('SentinelAgent', 'SentinelHelperService', 'SentinelStaticEngine', 'LogProcessorService')
foreach ($Service in $Services) {
Stop-Service -Name $Service -Force -EA 0
}
# Give services a moment to stop before attempting deletion.
Start-Sleep -Seconds 3
foreach ($Service in $Services) {
try {
# Set to disabled as a fallback in case deletion fails or requires a reboot.
Set-Service -Name $Service -StartupType Disabled -EA 0
# Use sc.exe for reliable deletion.
$null = Invoke-Process -FilePath 'sc.exe' -ArgumentList "delete `"$Service`"" -TimeoutSeconds 10
} catch {}
}
Write-VerboseLog "Service cleanup commands issued."
}
function Get-SentinelOnePath {
if ($env:PROCESSOR_ARCHITECTURE -eq 'AMD64') {
return "${env:ProgramW6432}\SentinelOne"
}
return "${env:ProgramFiles}\SentinelOne"
} $SentinelOnePath = Get-SentinelOnePath
function Get-SentinelCtl {
foreach ($Ctl in (Get-ChildItem "${SentinelOnePath}\*\SentinelCtl.exe" -EA 0 | Where-Object { -not $Ctl.PSIsContainer } |
Sort-Object -Descending -Property CreationTime)) {
if ((Test-Path $Ctl.FullName) -and (& $Ctl -f agent_id 2>$null)) { return $Ctl.FullName }
}
return $null
} $CtlPath = Get-SentinelCtl
function Get-CtlConfig {
param([string]$Prop)
$CtlPath = Get-SentinelCtl
if (-not $CtlPath) { return $null }
return (& $CtlPath config `"$Prop`").Trim('"')
}
function Set-CtlConfig {
param([string]$Prop, [string]$Val, [string]$Key)
$CtlPath = Get-SentinelCtl
if (-not $CtlPath) { return $null }
try { & $CtlPath config -p `"$Prop`" -v `"$Val`" -k `"$Key`" } catch { return $null }
return ((Get-CtlConfig -Prop $Prop) -eq $Val)
}
function Get-SentinelAgentPath {
# Prefer registry-based discovery for reliability
$RegPath = "HKLM:\SYSTEM\CurrentControlSet\Services\SentinelAgent"
if (Test-Path $RegPath) {
$ImagePath = (Get-ItemProperty -Path $RegPath).ImagePath
if ($ImagePath) {
return (($ImagePath -replace '"', '') -replace "SentinelAgent.exe", "")
}
}
# Fallback to ctl-based discovery
$CtlPath = Get-SentinelCtl
if ($CtlPath) { return (Split-Path -Path $CtlPath -Parent -Resolve) }
# Fallback to directory enumeration
else {
return Get-ChildItem $(Get-SentinelOnePath) -EA 0 | Where-Object { $_.PSIsContainer } |
Sort-Object -Descending -Property CreationTime | Select-Object -First 1 -ExpandProperty FullName
}
return $null
} $AgentPath = Get-SentinelAgentPath
function Get-SentinelAgentVersion {
# Prefer ctl-based discovery for accuracy
$CtlPath = Get-SentinelCtl
if ($CtlPath) {
$StatusOutput = (& $CtlPath status 2>$null | Select-String -Pattern '^Monitor')
if ($StatusOutput -match 'Build id: (.+)\+') {
return $Matches[1]
}
}
# Fallback to registry-based discovery
$RegPath = "HKLM:\SYSTEM\CurrentControlSet\Services\SentinelDeviceControl"
if (Test-Path $RegPath) {
$Description = (Get-ItemProperty -Path $RegPath).Description
if ($Description -match 'Driver (\d+\.\d+\.\d+\.\d+)') {
return $Matches[1]
}
}
# Fallback to folder name if other methods fail
$AgentPath = Get-SentinelAgentPath
if ($AgentPath -and ($AgentPath | Split-Path -Leaf) -match '^Sentinel Agent (.+)$') {
return $Matches[1]
}
return $null
} $SentinelAgentVersion = Get-SentinelAgentVersion
function Get-SiteTokenFromEndpointId {
param ([bool]$Retried = $false)
if ($CustomerSiteToken -notlike "CHANGE*") { return $CustomerSiteToken }
# Public/GitHub build: dynamic token retrieval is intentionally stubbed to avoid org-specific integrations.
# Replace the block below with your RMM/ITSM API call if you want to fetch tokens on the fly.
Write-Warning "No site token provided. Set -CustomerSiteToken or customize Get-SiteTokenFromEndpointId for your environment."
return $CustomerSiteToken
}
function Get-AgentPassphrase {
Start-Sleep -MilliSeconds (Get-Random -Minimum 50 -Maximum 5000)
$CtlPath = Get-SentinelCtl
$WebClient = $null
$Passphrase = $null
if ($AgentPassphrase) {
Write-VerboseLog "Using provided AgentPassphrase: $(Mask-Secret $AgentPassphrase)"
$Passphrase = $AgentPassphrase
return $Passphrase
}
try {
$MgmtStatus = (& $CtlPath ever_connected_to_management).Trim()
if ($MgmtStatus -notlike "Mgmt key part*") { throw "Agent has never connected to $ApiConsoleUrl! Skipping passphrase" }
if (-not $ApiToken -or $ApiToken -like "CHANGE*") { throw "API token is not set, will not retrieve passphrase" }
$AgentUuid = (& $CtlPath agent_id).Trim()
if (-not $AgentUuid) { throw "Could not determine Agent UUID from SentinelCtl" }
Write-VerboseLog $MgmtStatus
$WebClient = New-Object System.Net.WebClient
$WebClient.Headers.Add("Authorization", "APIToken $ApiToken")
$ApiUrl = "$ApiConsoleUrl/web/api/v2.1/agents/passphrases?uuids=$AgentUuid"
Write-VerboseLog "Querying API for passphrase: $ApiUrl"
$ApiResponseJson = $WebClient.DownloadString($ApiUrl)
if ($ApiResponseJson -match '"passphrase":\s*"([^"]+)"') { $Passphrase = $Matches[1] }
if (-not $Passphrase) { throw "Warning: Agent Passphrase not retrieved from API (empty response value)" }
else {
Write-Log "Agent Passphrase successfully retrieved"
Write-VerboseLog ("Passphrase: " + (Mask-Secret $Passphrase))
}
} catch { Write-Log $_ } # Write-ExceptionLog "Failed to retrieve Agent Passphrase" $_; return $null
finally { if ($WebClient) { $WebClient.Dispose() } }
return $Passphrase
}
function Get-TamperPassphrase {
if (@('Unprotect','Rollback','Failsafe') -contains $Mode) {
if (-not $AgentPassphrase) { $AgentPassphrase = Get-AgentPassphrase }
}
if ((Get-CtlConfig -Prop "agent.allowUnprotectByApprovedProcess") -eq "false") {
Write-Log "Agent is tamper-protected. Attempting to retrieve passphrase via API..."
if (-not $AgentPassphrase) { $AgentPassphrase = Get-AgentPassphrase }
if ($AgentPassphrase) {
if (Set-CtlConfig -Prop "agent.allowUnprotectByApprovedProcess" -Val "true" -Key $AgentPassphrase) { $Global:_tamperProtectionChanged = $true
Write-Log "Successfully removed tamper protection"
} else {
Write-Log "Could not retrieve passphrase and agent is tamper-protected. Aborting." -IsError; Exit 1
}
} # else { $AgentPassphrase = $null }
} return $AgentPassphrase
}
function Get-LogAndCleanup {
param([string]$SafeExitCode = '0')
# Check exit code and error output
$ErrorLogContents = $null
$StdOutContents = $null
if (Test-Path $ErrorOutFile) {
try { $ErrorLogContents = [System.IO.File]::ReadAllText($ErrorOutFile).Trim() } catch { $ErrorLogContents = $null }
}
if (Test-Path $StdOutFile) {
try { $StdOutContents = [System.IO.File]::ReadAllText($StdOutFile).Trim() } catch { $StdOutContents = $null }
}
$ExitCodeVal = if (Test-Path $ExitCodeFile) { (Get-Content -Path $ExitCodeFile | Out-String).Trim() } else { 'N/A (Error retrieving)' }
$ErrorCode = $false
if ($StdOutContents -match 'Error:') {
Write-Host "Installer output indicates error: $StdOutContents"
# Synthesize an error code if the process returned 0 but logged an error
if ($ExitCodeVal -eq '0') { $ExitCodeVal = '2000' }
}
if ($ErrorLogContents -and ($ErrorLogContents -notlike "Failed to access Sentinel Agent registry*cannot find the file specified.]")) {
Write-Host "Error output: $ErrorLogContents"
}
# Final cleanup
Remove-Item -Path (Join-Path (Get-Location).Path "SentinelELAM.sys") -Force -EA 0
if ($Mode -eq 'CleanTemp') {
Remove-Item -Path "${TempDir}Sentinel*", "${TempDir}S1*" -Recurse -Force -EA 0
Write-Host "Finished cleaning up temporary directory"
} elseif ($ExitCodeVal -eq $SafeExitCode -and -not $SkipCleanup.IsPresent) {
Write-Host "$Mode process presumed successful [exit code: $ExitCodeVal], cleaning up temporary installers"
Remove-Item -Path "${TempDir}Sentinel*", "${TempDir}S1*" -Recurse -Force -EA 0
} elseif ($ExitCodeVal -ne $SafeExitCode) {
Write-Host "Process exit code: $ExitCodeVal"
switch ($ExitCodeVal) {
'0' { Write-Log "Install/Upgrade completed successfully" }
'12' { Write-Log "Upgrade completed successfully (no uninstall/re-install)" }
'100' { Write-Log "Reboot required to continue installation" -IsError; Remove-Item -Force -EA 0 'HKLM:\SOFTWARE\SentinelOne\Setup\UninstallRebootMark'; $ErrorCode = $true }
'101' { Write-Log "Reboot required to continue installation" -IsError; Remove-Item -Force -EA 0 'HKLM:\SOFTWARE\SentinelOne\Setup\UninstallRebootMark'; $ErrorCode = $true }
'103' { Write-Log "Reboot required to uninstall/install" -IsError; Remove-Item -Force -EA 0 'HKLM:\SOFTWARE\SentinelOne\Setup\UninstallRebootMark'; $ErrorCode = $true }
'104' { Write-Log "Reboot already pending from a previous run" -IsError; Remove-Item -Force -EA 0 'HKLM:\SOFTWARE\SentinelOne\Setup\UninstallRebootMark'; $ErrorCode = $true }
'200' { Write-Log "Reboot required to complete uninstall" -IsError; Remove-Item -Force -EA 0 'HKLM:\SOFTWARE\SentinelOne\Setup\UninstallRebootMark'; $ErrorCode = $true }
'205' { Write-Log "Install/Upgrade aborted by the user" -IsError; $ErrorCode = $true }
'206' { Write-Log "Install/Upgrade canceled due to a wrong argument" -IsError; $ErrorCode = $true }
'1000' { Write-Log "Upgrade canceled: Agent has the same version or higher" -IsError; $ErrorCode = $true }
'1001' { Write-Log "Downgrade canceled: The target version is too old" -IsError; $ErrorCode = $true }
'1002' { Write-Log "Install canceled: Another installer is already running" -IsError; $ErrorCode = $true }
'1003' { Write-Log "Install canceled: Another MSI installer is already running" -IsError; $ErrorCode = $true }
'1004' { Write-Log "Upgrade canceled: Invalid arguments given to the installer" -IsError; $ErrorCode = $true }
'1005' { Write-Log "Upgrade canceled: Invalid passphrase provided" -IsError; $ErrorCode = $true }
'1009' { Write-Log "Installation aborted: Sentinel/SentinelOne Task Scheduler folders are inaccessible" -IsError; $ErrorCode = $true }
'1603' { Write-Log "Fatal error during installation (Permissions error?)" -IsError; $ErrorCode = $true }
'2000' { Write-Log "Installation failed: General unexpected error" -IsError; $ErrorCode = $true }
'2001' { Write-Log "Upgrade failed: Cannot proceed with the uninstall and re-install" -IsError; $ErrorCode = $true }
'2002' { Write-Log "Installation failed: Previous agent uninstalled, but new agent failed to install" -IsError; $ErrorCode = $true }
'2003' { Write-Log "Upgrade failed: Failed to uninstall the old agent" -IsError; $ErrorCode = $true }
'2004' { Write-Log "Installation failed: Retry in Safe Mode" -IsError; $ErrorCode = $true }
'2005' { Write-Log "Upgrade failed: Authentication error with Management" -IsError; $ErrorCode = $true }
'2006' { Write-Log "Upgrade failed: Configuration not found" -IsError; $ErrorCode = $true }
'2007' { Write-Log "Upgrade failed: Unexpected error during uninstall/re-install" -IsError; $ErrorCode = $true }
'2008' { Write-Log "Installation failed: Missing site token" -IsError; $ErrorCode = $true }
'2009' { Write-Log "Upgrade failed: Failed to retrieve Agent UID" -IsError; $ErrorCode = $true }
'2010' { Write-Log "Upgrade failed: Interactive desktop required" -IsError; $ErrorCode = $true }
'2011' { Write-Log "Installation failed: The installer is not signed correctly" -IsError; $ErrorCode = $true }
'2012' { Write-Log "Upgrade failed: Could not determine the currently installed Agent version" -IsError; $ErrorCode = $true }
'2013' { Write-Log "Installation failed: Insufficient system resources" -IsError; $ErrorCode = $true }
'2014' { Write-Log "Installation failed: Extract resources general failure" -IsError; $ErrorCode = $true }
'2015' { Write-Log "Installation failed: System requirements not met" -IsError; $ErrorCode = $true }
'2016' { Write-Log "Installation failed: Microsoft KB2533623 is not installed" -IsError; $ErrorCode = $true }
'2017' { Write-Log "Installation failed: Failed to load DLLs safely" -IsError; $ErrorCode = $true }
'2018' { Write-Log "Downgrade failed" -IsError; $ErrorCode = $true }
'2019' { Write-Log "Upgrade failed: Authentication error (failed to get approval)" -IsError; $ErrorCode = $true }
'2020' { Write-Log "Installation failed: Not enough space on the system drive" -IsError; $ErrorCode = $true }
'2021' { Write-Log "Upgrade failed: Authentication error (failed to get approval)" -IsError; $ErrorCode = $true }
'2022' { Write-Log "Installation failed: Unable to create an App Container" -IsError; $ErrorCode = $true }
'2023' { Write-Log "Upgrade failed: Not enough space on the system drive" -IsError; $ErrorCode = $true }
'2024' { Write-Log "Upgrade failed: Cannot open signed message file" -IsError; $ErrorCode = $true }
'2025' { Write-Log "Upgrade failed: Offline signed message authentication error" -IsError; $ErrorCode = $true }
'2026' { Write-Log "Upgrade failed: ISAPI filter removal process failed" -IsError; $ErrorCode = $true }
'2027' { Write-Log "Agent was installed but is in Disabled mode" }
'2028' { Write-Log "Agent was upgraded but the new Agent is in Disabled mode" }
'2029' { Write-Log "Failed to create a working directory under %WINDIR%\\Temp" -IsError; $ErrorCode = $true }
'2030' { Write-Log "Installer failed to open a file under its own working directory" -IsError; $ErrorCode = $true }
'2031' { Write-Log "Upgrade aborted: Sentinel/SentinelOne Task Scheduler folders are inaccessible" -IsError; $ErrorCode = $true }
'2032' { Write-Log "The SentinelOne Installer log could not be opened" -IsError; $ErrorCode = $true }
'-2146232576' { Write-Log ".NET Framework Initialization Error. Requires .NET v4.0.30319 or higher." -IsError; $ErrorCode = $true }
default { Write-Log "Unknown/unexpected error code" }
}
} else { Write-Host "Exit code: $ExitCodeVal" }
if ($ErrorCode) { return }
Start-Sleep -Seconds 8
# Re-enable tamper protection if we disabled it earlier
if ($Global:_tamperProtectionChanged) {
Write-Log "Attempting to re-enable tamper protection..."
try {
if (-not $AgentPassphrase) { $AgentPassphrase = Get-AgentPassphrase }
if ($AgentPassphrase) {
if (Set-CtlConfig -Prop "agent.allowUnprotectByApprovedProcess" -Val "false" -Key $AgentPassphrase) {
Write-Log "Successfully re-enabled tamper protection"
} else {
Write-Log "Failed to re-enable tamper protection using the available passphrase." -IsError
}
} else {
Write-Log "Could not retrieve a passphrase to re-enable tamper protection." -IsError
}
} catch {
Write-ExceptionLog "An error occurred while trying to re-enable tamper protection." $_
}
}
}
#=== MODE IMPLEMENTATIONS ===
# Unprotect Mode Logic
function Invoke-UnprotectMode {
if (-not $AgentPassphrase) { $AgentPassphrase = Get-AgentPassphrase }
$CtlPath = Get-SentinelCtl
if (-not $CtlPath) { Write-Log "UnprotectMode: Cannot find SentinelCtl.exe!" -IsError; return }
if (-not $AgentPassphrase) { Write-Log "UnprotectMode: Passphrase is required but not available." -IsError; return }
Write-Log "Disabling agent and unloading components..."
$null = Set-CtlConfig -Prop "agent.antiTampering" -Val "false" -Key $AgentPassphrase
$null = Set-CtlConfig -Prop "agent.injectWhenModuleTamperingProtectionIsOn" -Val "false" -Key $AgentPassphrase
$null = Set-CtlConfig -Prop "agent.forkProcessFromKernel" -Val "false" -Key $AgentPassphrase
$null = Set-CtlConfig -Prop "agent.preventProtectedFilesKernelModification" -Val "false" -Key $AgentPassphrase
$null = Set-CtlConfig -Prop "agent.preventProtectedProcessesKernelTermination" -Val "false" -Key $AgentPassphrase
$null = Set-CtlConfig -Prop "agent.preventProtectedThreadsKernelTermination" -Val "false" -Key $AgentPassphrase
$null = Set-CtlConfig -Prop "agent.coreOsProcessMitigationConfig.coreOsProcessMitigation" -Val "0" -Key $AgentPassphrase
if (Set-CtlConfig -Prop "agent.allowUnprotectByApprovedProcess" -Val "true" -Key $AgentPassphrase) {
Write-Log "Successfully removed tamper protection"
}
# Use Invoke-Process to ensure commands run sequentially and have timeouts.
$null = Invoke-Process -FilePath $CtlPath -ArgumentList "unprotect -k `"$AgentPassphrase`"" -TimeoutSeconds 30
$null = Invoke-Process -FilePath $CtlPath -ArgumentList "disable_agent -k `"$AgentPassphrase`"" -TimeoutSeconds 30
# $null = Invoke-Process -FilePath $CtlPath -ArgumentList "unload -b --unload_monitor -k `"$AgentPassphrase`"" -TimeoutSeconds 30
# Call the normalized cleanup function & kill lingering processes.
Invoke-TaskKill
Invoke-ServiceCleanup
$null = Invoke-Process -FilePath $CtlPath -ArgumentList "unload -b -s -a -k `"$AgentPassphrase`"" -TimeoutSeconds 60
$null = Invoke-Process -FilePath $CtlPath -ArgumentList "unload -b --unload_helper -k `"$AgentPassphrase`"" -TimeoutSeconds 30
$null = Invoke-Process -FilePath $CtlPath -ArgumentList "unload -b --unload_log -k `"$AgentPassphrase`"" -TimeoutSeconds 30
if ($Failsafe.IsPresent) {
if ($CtlPath -and (Test-Path $CtlPath)) { Write-Warning "SentinelCtl.exe still present, not removing directory!"}
elseif (Test-Path ($SentinelOnePath)) {
Write-Log "Removing agent directory '$SentinelOnePath' post-cleaner"
Remove-Item $SentinelOnePath -Recurse -Force -EA 0
Write-Host "Agent directory removal $(if (Test-Path $SentinelOnePath){'incomplete'}else{'successful'})"
} else { Write-Host "Agent directory not present, nothing to remove!" }
Remove-Item "C:\Windows\system32\drivers\SentinelOne" -Recurse -Force -EA 0
Remove-Item "C:\ProgramData\Sentinel" -Recurse -Force -EA 0
}
# Again call the normalized cleanup function & kill lingering processes.
Invoke-TaskKill
Invoke-ServiceCleanup
Remove-Item 'HKLM:\SOFTWARE\SentinelOne\Setup\UninstallRebootMark' -Recurse -Force -EA 0
Write-Log "UnprotectMode finished."
}
# Cleaner Mode Logic
function Invoke-CleanerMode {
param([bool]$Retry = $true, [bool]$Obliterator = ($WithObliterator.IsPresent))
if ($Retry) { $AgentPassphrase = Get-AgentPassphrase }
$CleanerArgs = "-q -f -c -t $CustomerSiteToken --ignore_pending_reboot_request --without_obliterator"
if ($ShowInstaller.IsPresent) { $CleanerArgs = $CleanerArgs.Replace("-q ", "") }
if ($Obliterator) { $CleanerArgs = $CleanerArgs.Replace(" --without_obliterator", "") }
if ($AgentPassphrase) { $CleanerArgs += " -k `"$AgentPassphrase`"" }
# The installer is already downloaded at this point by the main logic
if (-not (Test-Path $CleanerDest)) { Write-Log "Cleaner/bootstrapper not available. Aborting" -IsError; return }
Write-Log "Launching Cleaner ($($CleanerDest | Split-Path -Leaf))..."
Remove-Item $ExitCodeFile, $ErrorOutFile -Force -EA 0 # 'HKLM:\SOFTWARE\SentinelOne\Setup\UninstallRebootMark'
$null = Invoke-Process -FilePath $CleanerDest -ArgumentList $CleanerArgs -TimeoutSeconds $CleanerTimeoutSec
Start-Sleep -Seconds 3
$ExitCodeVal = if (Test-Path $ExitCodeFile) { (Get-Content $ExitCodeFile | Out-String).Trim() } else { $null }
if ($Retry -and ($ExitCodeVal -ne '0' -or (Test-Path $SentinelOnePath))) {
Get-LogAndCleanup
Write-Log "Retrying cleaner process..."
if ($CtlPath -and (Test-Path $CtlPath)) { Invoke-UnprotectMode; Start-Sleep -Seconds 10 }
Invoke-CleanerMode -Retry $false -Obliterator (($Failsafe.IsPresent) -or (-not $WithObliterator.IsPresent))
}
if ($CtlPath -and (Test-Path $CtlPath)) { Write-Warning "SentinelCtl.exe still present, not removing directory!"}
elseif (Test-Path ($SentinelOnePath)) {
Write-Log "Removing agent directory '$SentinelOnePath' post-cleaner"
Remove-Item $SentinelOnePath -Recurse -Force -EA 0
Write-Host "Agent directory removal $(if (Test-Path $SentinelOnePath){'incomplete'}else{'successful'})"
} else { Write-Host "Agent directory not present, nothing to remove!" }
Remove-Item "C:\Windows\system32\drivers\SentinelOne" -Recurse -Force -EA 0
Remove-Item "C:\ProgramData\Sentinel" -Recurse -Force -EA 0
Invoke-ServiceCleanup
Get-LogAndCleanup
}
# MSI-only Logic
function Invoke-MsiInstaller {
param([int]$Sec = $InstallTimeoutSec)
$SelectedMsi = Select-Msi
Invoke-TaskKill
if (-not $SelectedMsi) { Write-Log "No suitable MSI found for the current system" -IsError; return }
# The Select-Msi function now handles the download and returns the destination path
$MsiArgs = "/i `"$($SelectedMsi.Dest)`" /QN /NORESTART SITE_TOKEN=$CustomerSiteToken"
if ($ShowInstaller.IsPresent) { $MsiArgs = $MsiArgs.Replace("/QN ", "") }
if ($SkipStateless.IsPresent) { $MsiArgs = $MsiArgs.Replace("/NORESTART ", "") }
$MsiProc = Invoke-Process -FilePath 'msiexec.exe' -ArgumentList $MsiArgs -TimeoutSeconds $Sec
if (-not $MsiProc -and $Sec) { Write-Log "Critical: Failed to start msiexec!" -IsError; return }
}
# Purge Mode Logic
function Invoke-PurgeMode {
$AgentConfiguredUrl = Get-CtlConfig -Prop "server.mgmtServer"
$InitialServices = Get-Service SentinelAgent,LogProcessorService,SentinelStaticEngine,SentinelHelperService -EA 0
if (-not $AnyTarget -and $AgentConfiguredUrl -and ($AgentConfiguredUrl -ne $ConsoleUrl -and $AgentConfiguredUrl -ne "http://localhost")) {
# This is a critical safety gate: prevents the script from purging agents that have already been migrated
# to a new console. Allows for broad-scope execution that only affects the intended legacy cohort.
Write-Log "Portal URL '$AgentConfiguredUrl' does not match target '$ConsoleUrl'. Aborting." -IsError; return
} elseif ($AgentConfiguredUrl) { Write-Host "Portal URL '$AgentConfiguredUrl'" }
if ((Get-CtlConfig -Prop "agent.allowUnprotectByApprovedProcess") -eq "false") {
# Invoke-CleanerMode @(if ($Failsafe.IsPresent) {@{Obliterator=$true}} else {@{}})
# Invoke-CleanerMode -Retry $true $(if ($Failsafe.IsPresent) { ${-Obliterator $true}})
if ($Failsafe.IsPresent) {
Invoke-CleanerMode -Obliterator $true
} else {
Invoke-CleanerMode
}
return
}
if (-not $InitialServices) { Write-Log "No SentinelOne services present, skipping MSI upgrade" }
else { Write-Log "Starting MSI 'upgrade'..."; Invoke-MsiInstaller -Sec 0 }
# Watch for service removal (PSv2 compatible) and mitigate BYOI-style hangs by timing out and tearing down orphaned trees.
$Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
$Timeout = New-TimeSpan -Seconds $CleanerTimeoutSec
$ServicesRemoved = $false
$SentinelAgentGone = $false
while ($Stopwatch.Elapsed -lt $Timeout) {
if ($SentinelAgentGone) {
# Once the main agent is gone, check for the rest more thoroughly
$RemainingServices = Get-Service LogProcessorService,SentinelStaticEngine,SentinelHelperService -EA 0
if (-not $RemainingServices) {
$ServicesRemoved = $true
break
}
} else {
# Primary check focuses on the main service
if (-not (Get-Service SentinelAgent -EA 0)) {
Write-Log "Trigger: SentinelAgent service not detected, checking remaining services..."
$SentinelAgentGone = $true
continue # Immediately re-check for other services
}
}
Start-Sleep -Milliseconds 400
}
if ($ServicesRemoved) {
Write-Log "All SentinelOne services have been removed."
} else {
Write-Log "Warning: SentinelOne service removal watcher timed out" -IsError
}
$Stopwatch.Stop()
Invoke-TaskKill
Invoke-CleanerMode
}
# Install Mode Logic
function Invoke-InstallMode {
if (-not $SentinelAgentVersion) { Write-Log "No SentinelOne agent detected. Proceeding with fresh installation" }
else {
Write-Log "SentinelOne agent detected. Proceeding with rollback"
Invoke-RollbackMode; return
}
Invoke-TaskKill
$InstallerArgs = "-q -f -t $CustomerSiteToken --ignore_pending_reboot_request --dont_fail_on_config_preserving_failures" # --stateless_upgrade 1"
# if ($CustomerSiteToken -like "CHANGE*") { $InstallerArgs = $InstallerArgs -replace " -t CHANGE\w+", "" }
if (($CustomerSiteToken -like "CHANGE*") -and -not $Failsafe.IsPresent) { Write-Log "Unable to proceed, no site token provided!"; return }
if ($ShowInstaller.IsPresent) { $InstallerArgs = $InstallerArgs.Replace("-q ", "") }
if ($SkipStateless.IsPresent) { $InstallerArgs = $InstallerArgs.Replace(" --stateless_upgrade 1", "") }
# The installer is already downloaded at this point by the main logic
if (-not $IsArm64){
$InstallMsi = Select-Msi
if (-not $InstallMsi) { Write-Log "No suitable MSI found for installation" -IsError; return }
if (-not (Test-Path $InstallMsi.Dest)) { Write-Log "Selected MSI path not found after API download." -IsError; return }
$InstallerArgs += " -i `"$($InstallMsi.Dest)`""
}
Write-Log "Starting SentinelOne installation using '$($CleanerDest | Split-Path -Leaf)'..."
Remove-Item $ExitCodeFile, $ErrorOutFile -Force -EA 0 #'Remove-Item HKLM:\SOFTWARE\SentinelOne\Setup\UninstallRebootMark' -Force -EA 0
$null = Invoke-Process -FilePath $CleanerDest -ArgumentList $InstallerArgs -TimeoutSeconds $InstallTimeoutSec
Start-Sleep -Seconds 5
Get-LogAndCleanup -SafeExitCode '0'
Write-Host "Installed SentinelOne agent version:" $(if ($Version = Get-SentinelAgentVersion) { $Version } else { "N/A"})
}
# Rollback Mode Logic
function Invoke-RollbackMode {
if ($SentinelAgentVersion) { Write-Log "SentinelOne agent $SentinelAgentVersion detected. Installing known-good!" }
else {
Write-Log "No SentinelOne agent detected. Proceeding with fresh installation"
Invoke-InstallMode; Exit
}
Invoke-TaskKill
$RollbackArgs = "-q -f -t $CustomerSiteToken --ignore_pending_reboot_request --dont_fail_on_config_preserving_failures --stateless_upgrade 1"
if ($ShowInstaller.IsPresent) { $RollbackArgs = $RollbackArgs.Replace("-q ", "") }
if ($CustomerSiteToken -like "CHANGE*") { $RollbackArgs = $RollbackArgs -replace " -t CHANGE\w+", "" }
if ($SkipStateless.IsPresent) { $RollbackArgs = $RollbackArgs.Replace(" --stateless_upgrade 1", "") }
if ($AgentPassphrase) { $RollbackArgs = "$RollbackArgs -k `"$AgentPassphrase`"" }
$SelectedMsi = Select-Msi
if (-not $SelectedMsi -or -not (Test-Path $SelectedMsi.Dest)) { Write-Log "No suitable MSI found for rollback. Aborting" -IsError; return }
# The cleaner/bootstrapper is already downloaded at this point by the main logic
$FinalBootstrapArgs = "$RollbackArgs -i `"$($SelectedMsi.Dest)`""
Write-Log "Starting SentinelOne installation using '$($SelectedMsi.Dest | Split-Path -Leaf)'..."
Remove-Item $ExitCodeFile, $ErrorOutFile -Force -EA 0 #, 'HKLM:\SOFTWARE\SentinelOne\Setup\UninstallRebootMark'
$null = Invoke-Process -FilePath $CleanerDest -ArgumentList $FinalBootstrapArgs -TimeoutSeconds $RollbackTimeoutSec
Start-Sleep -Seconds 5
Get-LogAndCleanup -SafeExitCode '12'
Write-Host "Installed SentinelOne agent version:" $(if ($Version = Get-SentinelAgentVersion) { $Version } else { "N/A"})
}
#=== Installer URLs and Hashes ===
function Get-DynamicInstaller {
# API calls assume ApiConsoleUrl is reachable by your service user (active tenant), even if endpoints still point at a legacy portal.
if (-not $ApiToken -or $ApiToken -like "CHANGE*") {
Write-Log "API token not set, cannot perform dynamic download." -IsError
return $null
}
if (-not (Get-Command ConvertFrom-Json -ErrorAction SilentlyContinue)) {
Write-Log "ConvertFrom-Json is unavailable (PowerShell < 3.0); dynamic download requires PSv3+." -IsError
return $null
}
$ConsoleForApi = $ApiConsoleUrl
$Arch = if ($IsArm64) { "ARM64" } elseif ($env:PROCESSOR_ARCHITECTURE -eq 'AMD64') { "64%20bit" } else { "32%20bit" }
$ApiUrl = "$ConsoleForApi/web/api/v2.1/update/agent/packages?status=ga&sortBy=version&osArches=$Arch&sortOrder=desc&osTypes=windows&packageType=AgentAndRanger&fileExtension=.exe"
Write-Log "Querying for latest installer package..."
$WebClient = $null
try {
$WebClient = New-Object System.Net.WebClient
$WebClient.Headers.Add("Authorization", "APIToken $ApiToken")
$ApiResponse = $WebClient.DownloadString($ApiUrl) | ConvertFrom-Json
$Package = $ApiResponse.data[0]
if ($Package) {
Write-Log "Found package version $($Package.version) via API."
return $Package
}
} catch {
Write-ExceptionLog "Failed to query or parse installer packages from API" $_
} finally {
if ($WebClient) { $WebClient.Dispose() }
}
return $null
}
function Get-DynamicExeByVersion {
param([string]$Version)
if (-not $ApiToken -or $ApiToken -like "CHANGE*") { return $null }
if (-not (Get-Command ConvertFrom-Json -ErrorAction SilentlyContinue)) {
Write-Log "ConvertFrom-Json is unavailable (PowerShell < 3.0); dynamic download requires PSv3+." -IsError
return $null
}
$ConsoleForApi = $ApiConsoleUrl
$Arch = if ($IsArm64) { "ARM64" } elseif ($env:PROCESSOR_ARCHITECTURE -eq 'AMD64') { "64%20bit" } else { "32%20bit" }
$ApiUrl = "$ConsoleForApi/web/api/v2.1/update/agent/packages?versionStr__contains=$Version&fileExtension=.exe&osArches=$Arch&osTypes=windows&packageType=AgentAndRanger&status=ga&sortBy=version&sortOrder=desc"
Write-VerboseLog "Querying for EXE: $ApiUrl"
try {
$WebClient = New-Object System.Net.WebClient
$WebClient.Headers.Add("Authorization", "APIToken $ApiToken")
$ApiResponse = $WebClient.DownloadString($ApiUrl) | ConvertFrom-Json
return $ApiResponse.data[0]
} catch { Write-ExceptionLog "Failed to query for EXE package" $_ }
finally { if ($WebClient) { $WebClient.Dispose() } }
return $null
}
function Download-FromApi {
param($Package)
if ($SkipDownload) { return $null }
$Ext = if ($Package.fileExtension) { ($Package.fileExtension.ToString()).Trim() } else { ".bin" }
if (-not $Ext.StartsWith(".")) { $Ext = ".$Ext" }
$DestFile = Join-Path $TempDir ("S1-Installer-{0}{1}" -f $Package.version, $Ext)
Write-Log "Downloading via API link to '$($DestFile | Split-Path -Leaf)'..."
$WebClient = $null
try {
$WebClient = New-Object System.Net.WebClient
$WebClient.Headers.Add("Authorization", "APIToken $ApiToken")
$WebClient.DownloadFile($Package.link, $DestFile)
$ActualHash = Get-LocalFileHash -Path $DestFile -Algorithm SHA1 -EA 0
if ($ActualHash -ne $Package.sha1) {
Write-Log "SHA1 mismatch for '$($DestFile | Split-Path -Leaf)'. Expected: $($Package.sha1), Actual: $ActualHash" -IsError
Remove-Item $DestFile -Force -EA 0
return $null
}
$ActualSize = (Get-Item $DestFile).Length
if ($ActualSize -ne $Package.fileSize) {
Write-Log "Filesize mismatch for '$($DestFile | Split-Path -Leaf)'. Expected: $($Package.fileSize), Actual: $ActualSize" -IsError
Remove-Item $DestFile -Force -EA 0
return $null
}
Write-Log "API download successful and verified."
return $DestFile
} catch {
Write-ExceptionLog "Critical: API download failed for version $($Package.version)" $_
} finally {
if ($WebClient) { $WebClient.Dispose() }
}
return $null
}
function Get-DynamicMsi {
param([string]$Version, [string]$Arch)
if (-not $ApiToken -or $ApiToken -like "CHANGE*") { return $null }
if (-not (Get-Command ConvertFrom-Json -ErrorAction SilentlyContinue)) {
Write-Log "ConvertFrom-Json is unavailable (PowerShell < 3.0); dynamic download requires PSv3+." -IsError
return $null
}
$ConsoleForApi = $ApiConsoleUrl
$ApiUrl = "$ConsoleForApi/web/api/v2.1/update/agent/packages?versionStr__contains=$Version&fileExtension=.msi&osArches=$Arch&osTypes=windows&packageType=AgentAndRanger&status=ga&sortBy=version&sortOrder=desc"
Write-VerboseLog "Querying for MSI: $ApiUrl"
try {
$WebClient = New-Object System.Net.WebClient
$WebClient.Headers.Add("Authorization", "APIToken $ApiToken")
$ApiResponse = $WebClient.DownloadString($ApiUrl) | ConvertFrom-Json
return $ApiResponse.data[0]
} catch { Write-ExceptionLog "Failed to query for MSI package" $_ }
finally { if ($WebClient) { $WebClient.Dispose() } }
return $null
}
if (-not (New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) {
Write-Log "This script must be run as an Administrator" -IsError; Exit 1
}
if (-not (Test-Path $TempDir)) { New-Item -Path $TempDir -ItemType Directory -Force -EA 0 | Out-Null }
$MirrorUrl = Get-ValidUrl
$IsArm64 = ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64' -or $env:PROCESSOR_ARCHITEW6432 -eq 'ARM64')
$DynamicPackage = $null
if ($DynamicExe.IsPresent) {
if ($Failsafe.IsPresent) { $DynamicPackage = Get-DynamicExeByVersion -Version "23.4.6" } else { $DynamicPackage = Get-DynamicInstaller }
}
# Cleaner/Bootstrap Installer (used by Purge and Install, and as bootstrapper for Rollback)
if ($DynamicPackage) {
$CleanerDest = Download-FromApi -Package $DynamicPackage
# If API download fails, fall back to static mirrors
if (-not $CleanerDest) { $DynamicPackage = $null }
}
if (-not $DynamicPackage) {
if ($IsArm64) {
$CleanerUrl = "${MirrorUrl}/SentinelOneInstaller_windows_arm64_v25_1_3_334"
$CleanerSha256 = "AE7C25649CEB61C7078A85184CCEC91F65F1166B3F80648151238EF9B250CFF6"
$CleanerDest = "${TempDir}SentinelOneInstaller_25.1.3_windows_arm64.exe"
} elseif (-not ($env:PROCESSOR_ARCHITECTURE -eq 'AMD64')) {
$CleanerUrl = "${MirrorUrl}/SentinelOneInstaller_windows_32bit_v23_4_6_347"
$CleanerSha256 = "4767CC223A04487EA790B45AD4554CB14CD30DCAD58349A2278D95630F277F4C"
$CleanerDest = "${TempDir}SentinelOneInstaller_23.4.6_windows_x86.exe"
} elseif ($Failsafe.IsPresent) {
$CleanerUrl = "${MirrorUrl}/SentinelOneInstaller_windows_64bit_v23_4_6_347"
$CleanerSha256 = "E0E9C6FE7D03A06A82CEC87EA39396A5AE7B588745FDCB54FB8460E0FE036184"
$CleanerDest = "${TempDir}SentinelOneInstaller_23.4.6_windows_x64.exe"
} else {
$CleanerUrl = "${MirrorUrl}/SentinelOneInstaller_windows_64bit_v25_1_3_334"
$CleanerSha256 = "976F304DB5DEC6B1766AA933E902A562BE292053D6BC29A48397BD8283CDDC15"
$CleanerDest = "${TempDir}SentinelOneInstaller_25.1.3_windows_x64.exe"
}
# Ensure the static file is downloaded if it wasn't already by the dynamic process
if (-not (Get-OrDownload -Url $CleanerUrl -Dest $CleanerDest -ExpectHash $CleanerSha256)) {
Write-Log "Failed to download installer from all sources. Aborting." -IsError
Exit 1
}
}
# $LocalCleaner = $false
if ($LocalCleaner) {
foreach ($_ in (Get-ChildItem "${TempDir}Sentinel*.exe" -EA 0 | Where-Object { -not $_.PSIsContainer } |
Sort-Object -Descending -Property CreationTime)) {
if (Test-Path $_.FullName) { $CleanerDest = $_.FullName }
}
Write-VerboseLog "Using: $CleanerDest"
}
# MSI Installers (for Purge and Rollback)
# Primary: dynamic API, Fallback: static mirrors defined below
$MsiVersions = @(
@{
Url = "${MirrorUrl}/SentinelInstaller_windows_32bit_v23_4_6_347"
Sha256 = "B8F70EAEFC084EB57BF42C2A5EC2E650658BA4BF1FAB38EEC284ACDBAD430933"
Dest = "${TempDir}SentinelOneInstaller_23.4.6_windows_x86.msi"
Condition = { -not ($env:PROCESSOR_ARCHITECTURE -eq 'AMD64') } # Alternate MSI if system is 32-bit
},
@{
Url = "${MirrorUrl}/SentinelInstaller_windows_64bit_v23_4_6_347"
Sha256 = "0F9A81561B2543AEBB2706687626B4B4CF204730DAA14FD1D0E7AB333C0AEAC2"
Dest = "${TempDir}SentinelOneInstaller_23.4.6_windows_x64.msi"
Condition = { $Failsafe.IsPresent -or [System.Environment]::OSVersion.Version -lt [Version]"6.3"} # Windows < 8.1 (64-bit)
},
@{
Url = "${MirrorUrl}/SentinelInstaller_windows_64bit_v24_1_6_313"
Sha256 = "96A304A53F9C070EBC9FBFB919B9623E6D3048A6A1C3D8BA9C435FA0CEDC8022"
Dest = "${TempDir}SentinelOneInstaller_24.1.6_windows_x64.msi"
Condition = { (Get-SentinelAgentVersion) -eq "25.1.3.334" } # Alternate MSI if installed version matches default MSI
},
@{
Url = "${MirrorUrl}/SentinelInstaller_windows_64bit_v25_1_3_334"
Sha256 = "39C4E63D11AD5B0BD06F18D84BBA317C291530706D15998550BEEA9E235CFB0B"
Dest = "${TempDir}SentinelOneInstaller_25.1.3_windows_x64.msi"
Condition = { $true } # Default MSI
}
)
function Select-Msi {
# Try API first for the first entry whose Condition is true; on failure, fall back to mirror for that same entry
foreach ($entry in $MsiVersions) {
if (-not (& $entry.Condition)) { continue }
# Derive version and arch for API query from the known mirror metadata
$ver = $null
if ($entry.Dest -match '(\d+\.\d+\.\d+)') { $ver = $Matches[1] }
$arch = if ($entry.Dest -like '*x86*') { '32+bit' } else { '64+bit' }
if ($ver -and $DynamicExe) {
$pkg = Get-DynamicMsi -Version $ver -Arch $arch
if ($pkg) {
$dest = Download-FromApi -Package $pkg
if ($dest) { return @{ Dest = $dest; Url = $null; Sha256 = $null } }
}
}
# Fallback to mirror for this entry
if (Get-OrDownload -Url $entry.Url -Dest $entry.Dest -ExpectHash $entry.Sha256) {
return @{ Dest = $entry.Dest; Url = $entry.Url; Sha256 = $entry.Sha256 }
}
}
Write-Log "Could not obtain a suitable MSI via API or mirrors." -IsError
return $null
}