<# ProfiLab Health - agent for Windows - v1.0.0 What it does (English, so that anyone can check it): Once a day and when someone signs in, it reads the HARDWARE and MAINTENANCE state of this computer and sends a short report to ProfiLab (https://profilab.org), so that we can warn you before something breaks. What it sends: make, model and serial number, Windows version and uptime, memory size, processor name, disk model/size/health and wear, SMART error counters, free space on local disks, battery capacity and cycle count, whether File History backup is set up and when it last ran, which antivirus is on (Windows Security Center), firewall and BitLocker on/off, and the date of the last Windows update. What it never reads or sends: your files, file or document names, browser history, passwords, e-mail, messages, photos, screen, keystrokes, location, the computer name or user names. It cannot control the computer: it only sends, and it accepts no commands from the server. See exactly what would be sent, without sending anything: powershell -ExecutionPolicy Bypass -File profilab-health.ps1 -DryRun Install (PowerShell as administrator): powershell -ExecutionPolicy Bypass -File profilab-health.ps1 -Install -Token Remove everything (PowerShell as administrator): powershell -ExecutionPolicy Bypass -File "C:\ProgramData\ProfiLab\Health\profilab-health.ps1" -Uninstall More, in Spanish, English, Russian and Ukrainian: https://profilab.org/mantenimiento-informatico/salud-de-equipos/ This file is plain ASCII on purpose: Windows PowerShell 5.1 reads scripts without a BOM in the local code page. #> [CmdletBinding()] param( [switch]$Install, [switch]$Uninstall, [switch]$DryRun, [string]$Token = '', [string]$Endpoint = '' ) Set-StrictMode -Off $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' $Version = '1.0.0' $DefaultEndpoint = 'https://profilab.org/api/fleet/report' $BaseDir = Join-Path $env:ProgramData 'ProfiLab\Health' $TaskName = 'ProfiLab Health' $TaskPath = '\ProfiLab\' # --- Small helpers ----------------------------------------------------------- function Fail([string]$Message) { Write-Host "ProfiLab Health: $Message" exit 1 } # Run a block and return $null instead of an error: one missing piece of # information must not stop the whole report. function Try-Get([scriptblock]$Block) { try { & $Block } catch { $null } } # Short, non-reversible id for a disk: the disk serial itself is not sent. function Get-ShortId([string]$Text) { $sha = [Security.Cryptography.SHA256]::Create() $bytes = $sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($Text)) 'w' + (($bytes[0..4] | ForEach-Object { $_.ToString('x2') }) -join '') } function Get-IsoUtc($Value, [switch]$IsUtc) { if ($null -eq $Value) { return $null } try { $d = [datetime]$Value if ($d.Year -lt 2005) { return $null } if ($IsUtc) { $d = [datetime]::SpecifyKind($d, [DateTimeKind]::Utc) } else { $d = $d.ToUniversalTime() } return $d.ToString('yyyy-MM-ddTHH:mm:ssZ') } catch { return $null } } function Get-Text($Value) { if ($null -eq $Value) { return $null } $s = ("$Value").Trim() if ($s) { return $s } return $null } # Letters and digits only, upper case: to find the same disk in two lists. function Get-Plain($Value) { (("$Value").ToUpperInvariant() -replace '[^A-Z0-9]', '') } function Test-Admin { $id = [Security.Principal.WindowsIdentity]::GetCurrent() (New-Object Security.Principal.WindowsPrincipal($id)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } # --- Collect ------------------------------------------------------------------- function Get-PlReport { $cs = Try-Get { Get-CimInstance Win32_ComputerSystem } $csp = Try-Get { Get-CimInstance Win32_ComputerSystemProduct } $bios = Try-Get { Get-CimInstance Win32_BIOS } $os = Try-Get { Get-CimInstance Win32_OperatingSystem } $proc = Try-Get { Get-CimInstance Win32_Processor | Select-Object -First 1 } $enc = Try-Get { Get-CimInstance Win32_SystemEnclosure | Select-Object -First 1 } $batt = Try-Get { Get-CimInstance Win32_Battery | Select-Object -First 1 } $cv = Try-Get { Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' } # --- Device $maker = $null; $model = $null if ($cs) { $maker = Get-Text $cs.Manufacturer; $model = Get-Text $cs.Model } # Lenovo keeps the readable model name in Version ("ThinkPad T14 Gen 2"). if ($csp -and $maker -match 'lenovo' -and (Get-Text $csp.Version)) { $model = Get-Text $csp.Version } $serial = $null if ($bios) { $serial = Get-Text $bios.SerialNumber } $type = 'desktop' $laptopChassis = @(8, 9, 10, 11, 12, 14, 18, 21, 30, 31, 32) if ($batt) { $type = 'laptop' } elseif ($enc -and @($enc.ChassisTypes | Where-Object { $laptopChassis -contains $_ }).Count) { $type = 'laptop' } # --- System $osName = $null; $osVer = $null; $uptime = $null if ($os) { $osName = (Get-Text $os.Caption) -replace '^Microsoft\s+', '' $osVer = Get-Text $os.Version if ($os.LastBootUpTime) { $uptime = [math]::Round(((Get-Date) - $os.LastBootUpTime).TotalHours, 1) } } $release = $null if ($cv) { if ($cv.DisplayVersion) { $release = Get-Text $cv.DisplayVersion } elseif ($cv.ReleaseId) { $release = Get-Text $cv.ReleaseId } if ($osVer -and $null -ne $cv.UBR) { $osVer = "$osVer.$($cv.UBR)" } } $ramGb = $null if ($cs -and $cs.TotalPhysicalMemory) { $ramGb = [math]::Round($cs.TotalPhysicalMemory / 1GB) } $modules = @(Try-Get { Get-CimInstance Win32_PhysicalMemory } | Where-Object { $_ }).Count # --- Disks: health and wear from Windows Storage, SMART counters from WMI $disks = @() $plain = @{} foreach ($pd in @(Try-Get { Get-PhysicalDisk })) { if ($null -eq $pd) { continue } $rc = Try-Get { $pd | Get-StorageReliabilityCounter } $media = $null switch -Regex ("$($pd.MediaType)") { '^(SSD|4)$' { $media = 'ssd' } '^(HDD|3)$' { $media = 'hdd' } } $bus = 'other' switch -Regex ("$($pd.BusType)") { '^(NVMe|17)$' { $bus = 'nvme' } '^(SATA|11|ATA|3)$' { $bus = 'sata' } '^(USB|7)$' { $bus = 'usb' } '^(SAS|10|SCSI|1)$' { $bus = 'scsi' } '^(RAID|8)$' { $bus = 'raid' } } $health = $null switch -Regex ("$($pd.HealthStatus)") { '^(Healthy|0)$' { $health = 'ok' } '^(Warning|1)$' { $health = 'warning' } '^(Unhealthy|2)$' { $health = 'failing' } } $key = Get-Text $pd.SerialNumber if (-not $key) { $key = "pd$($pd.DeviceId)" } $sizeGb = $null if ($pd.Size) { $sizeGb = [math]::Round($pd.Size / 1GB) } $wear = $null; $temp = $null; $hours = $null; $readErr = $null; $writeErr = $null if ($rc) { $wear = $rc.Wear if ($rc.Temperature) { $temp = $rc.Temperature } $hours = $rc.PowerOnHours $readErr = $rc.ReadErrorsUncorrected $writeErr = $rc.WriteErrorsUncorrected } $id = Get-ShortId $key $plain[$id] = Get-Plain $pd.FriendlyName $disks += [ordered]@{ id = $id name = Get-Text $pd.FriendlyName media = $media bus = $bus sizeGb = $sizeGb health = $health wearPct = $wear tempC = $temp powerOnHours = $hours errors = [ordered]@{ reallocated = $null pending = $null uncorrectable = $null readUncorrected = $readErr writeUncorrected = $writeErr } } } # SMART attribute table (SATA drives): 30 entries of 12 bytes from offset 2; # id at +0, raw value (little-endian) from +5. 5 = reallocated sectors, # 197 = pending, 198 = offline uncorrectable. $smart = @(Try-Get { Get-CimInstance -Namespace root\wmi -ClassName MSStorageDriver_FailurePredictData }) $predict = @(Try-Get { Get-CimInstance -Namespace root\wmi -ClassName MSStorageDriver_FailurePredictStatus }) foreach ($s in $smart) { if ($null -eq $s) { continue } $inst = Get-Plain $s.InstanceName $target = $null foreach ($d in $disks) { $p = $plain[$d.id] if ($p -and $inst.Contains($p)) { $target = $d; break } } # Not sure which disk this is: skip rather than guess. if (-not $target) { continue } $b = $s.VendorSpecific if ($b -and $b.Length -ge 362) { for ($i = 2; $i -le 350; $i += 12) { $attr = [int]$b[$i] if ($attr -eq 0) { continue } $raw = [uint64]$b[$i + 5] + [uint64]$b[$i + 6] * 256 + [uint64]$b[$i + 7] * 65536 + [uint64]$b[$i + 8] * 16777216 if ($attr -eq 5) { $target.errors.reallocated = $raw } if ($attr -eq 197) { $target.errors.pending = $raw } if ($attr -eq 198) { $target.errors.uncorrectable = $raw } } } $st = $predict | Where-Object { $_ -and $_.InstanceName -eq $s.InstanceName } | Select-Object -First 1 if ($st -and $st.PredictFailure -eq $true) { $target.health = 'failing' } } # --- Free space on local disks (as Explorer counts it: 1 GB = 1024^3 bytes) $volumes = @() foreach ($v in @(Try-Get { Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' })) { if ($null -eq $v -or -not $v.Size) { continue } $volumes += [ordered]@{ mount = Get-Text $v.DeviceID sizeGb = [math]::Round($v.Size / 1GB, 1) freeGb = [math]::Round($v.FreeSpace / 1GB, 1) system = ($v.DeviceID -eq $env:SystemDrive) } } # --- Battery: design and full-charge capacity, cycle count $battery = $null if ($batt) { $design = Try-Get { (Get-CimInstance -Namespace root\wmi -ClassName BatteryStaticData | Select-Object -First 1).DesignedCapacity } $full = Try-Get { (Get-CimInstance -Namespace root\wmi -ClassName BatteryFullChargedCapacity | Select-Object -First 1).FullChargedCapacity } $cycles = Try-Get { (Get-CimInstance -Namespace root\wmi -ClassName BatteryCycleCount | Select-Object -First 1).CycleCount } if (-not $design -or -not $full) { # Fallback: the battery report of powercfg. Only the capacities are # read from it, and the file is deleted right away. $xmlPath = Join-Path $env:TEMP ('pl-battery-' + [guid]::NewGuid().ToString() + '.xml') try { & powercfg.exe /batteryreport /xml /output $xmlPath | Out-Null [xml]$x = Get-Content -LiteralPath $xmlPath -Raw $one = @($x.BatteryReport.Batteries.Battery)[0] if ($one) { $design = [int64]$one.DesignCapacity $full = [int64]$one.FullChargeCapacity if (-not $cycles) { $cycles = [int64]$one.CycleCount } } } catch { } finally { Remove-Item -LiteralPath $xmlPath -Force -ErrorAction SilentlyContinue } } if ($cycles -eq 0) { $cycles = $null } $pct = $null if ($design -and $full) { $pct = [math]::Round(100 * $full / $design) } $battery = [ordered]@{ design = $design; full = $full; healthPct = $pct; cycles = $cycles; condition = $null } } # --- Backup: File History. Only the existence and time of its own catalog # files are checked; the user folders themselves are not opened. $fhConfigured = $false $fhLast = $null foreach ($u in @(Try-Get { Get-ChildItem -LiteralPath (Join-Path $env:SystemDrive 'Users') -Directory -Force })) { if ($null -eq $u) { continue } $cfg = Join-Path $u.FullName 'AppData\Local\Microsoft\Windows\FileHistory\Configuration' if (-not (Test-Path -LiteralPath $cfg)) { continue } if (Test-Path -LiteralPath (Join-Path $cfg 'Config1.xml')) { $fhConfigured = $true } foreach ($c in @(Get-ChildItem -LiteralPath $cfg -Filter 'Catalog*.edb' -ErrorAction SilentlyContinue)) { if ($null -eq $fhLast -or $c.LastWriteTimeUtc -gt $fhLast) { $fhLast = $c.LastWriteTimeUtc } } } # --- Protection: antivirus products from Windows Security Center $av = @() foreach ($p in @(Try-Get { Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct })) { if ($null -eq $p) { continue } $hex = '{0:X6}' -f [int]$p.productState $av += [ordered]@{ name = Get-Text $p.displayName active = (@('10', '11') -contains $hex.Substring(2, 2)) upToDate = ($hex.Substring(4, 2) -eq '00') } } $defender = $null $mp = Try-Get { Get-MpComputerStatus } if ($mp) { $defender = [ordered]@{ enabled = [bool]$mp.AntivirusEnabled; realtime = [bool]$mp.RealTimeProtectionEnabled; sigAgeDays = $mp.AntivirusSignatureAge } } $firewall = $null $profiles = @(Try-Get { Get-NetFirewallProfile } | Where-Object { $_ }) if ($profiles.Count) { $firewall = -not @($profiles | Where-Object { "$($_.Enabled)" -ne 'True' }).Count } $encrypted = $null $blv = Try-Get { Get-BitLockerVolume -MountPoint $env:SystemDrive } if ($blv) { $encrypted = ("$($blv.ProtectionStatus)" -eq 'On') } # --- Last Windows update $updated = $null try { $au = New-Object -ComObject Microsoft.Update.AutoUpdate $updated = Get-IsoUtc $au.Results.LastInstallationSuccessDate -IsUtc } catch { } if (-not $updated) { $hf = Try-Get { Get-HotFix | Where-Object { $_.InstalledOn } | Sort-Object InstalledOn -Descending | Select-Object -First 1 } if ($hf) { $updated = Get-IsoUtc $hf.InstalledOn } } [ordered]@{ v = 1 os = 'windows' agent = $Version device = [ordered]@{ maker = $maker; model = $model; serial = $serial; type = $type } system = [ordered]@{ name = $osName; version = $osVer; release = $release; uptimeHours = $uptime } cpu = $(if ($proc) { Get-Text $proc.Name } else { $null }) ram = [ordered]@{ totalGb = $ramGb; modules = $modules } disks = @($disks) volumes = @($volumes) battery = $battery backup = [ordered]@{ kind = 'file_history'; configured = $fhConfigured; lastAt = (Get-IsoUtc $fhLast -IsUtc) } security = [ordered]@{ av = @($av); defender = $defender; firewall = $firewall; encrypted = $encrypted } updates = [ordered]@{ lastAt = $updated } } } # --- Send -------------------------------------------------------------------------- function Test-Args { # The token travels only over HTTPS; plain http is for local testing only. if ($script:Token -cnotmatch '^pl_[A-Za-z0-9_-]{43}$') { Fail 'the token is missing or malformed.' } if ($script:Endpoint -notmatch '^(https://|http://(127\.0\.0\.1|localhost):)') { Fail 'the server address must start with https://' } } function Write-PlLog([string]$Line) { $log = Join-Path $BaseDir 'agent.log' if (-not (Test-Path -LiteralPath $BaseDir)) { return } try { Add-Content -LiteralPath $log -Value ((Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' ' + $Line) -Encoding ASCII $tail = @(Get-Content -LiteralPath $log -Tail 200) Set-Content -LiteralPath $log -Value $tail -Encoding ASCII } catch { } } function Send-PlReport { Test-Args $json = Get-PlReport | ConvertTo-Json -Depth 6 -Compress [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 $code = 0 try { $r = Invoke-WebRequest -Uri $script:Endpoint -Method Post -UseBasicParsing -TimeoutSec 40 ` -Headers @{ Authorization = "Bearer $($script:Token)" } ` -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($json)) $code = [int]$r.StatusCode } catch { if ($_.Exception.Response) { $code = [int]$_.Exception.Response.StatusCode } } switch ($code) { 200 { Write-PlLog 'sent'; Write-Host 'ProfiLab Health: report sent.' } 403 { Write-PlLog 'disabled by ProfiLab'; Write-Host 'ProfiLab Health: watching is turned off for this computer.' } 401 { Write-PlLog 'token not accepted'; Write-Host 'ProfiLab Health: the token was not accepted (HTTP 401).' } 429 { Write-PlLog 'too many reports, will try later'; Write-Host 'ProfiLab Health: too many reports today, the next one will go later.' } default { Write-PlLog "not sent (HTTP $code)"; Write-Host "ProfiLab Health: report not sent (HTTP $code)." } } return $code } function Read-PlConfig { $f = Join-Path $BaseDir 'config.json' if (-not (Test-Path -LiteralPath $f)) { return } $c = Get-Content -LiteralPath $f -Raw | ConvertFrom-Json if (-not $script:Token) { $script:Token = "$($c.token)" } if (-not $script:Endpoint) { $script:Endpoint = "$($c.endpoint)" } } # --- Install / uninstall ------------------------------------------------------------ function Install-Pl { if (-not (Test-Admin)) { Fail 'open PowerShell as administrator and run the command again.' } Test-Args New-Item -ItemType Directory -Force -Path $BaseDir | Out-Null # Only SYSTEM and Administrators may read the folder: the token is inside. # SIDs instead of names: group names differ between Windows languages. & icacls.exe $BaseDir /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' | Out-Null $target = Join-Path $BaseDir 'profilab-health.ps1' if ($PSCommandPath -ne $target) { Copy-Item -LiteralPath $PSCommandPath -Destination $target -Force } $cfg = [ordered]@{ token = $script:Token; endpoint = $script:Endpoint } | ConvertTo-Json Set-Content -LiteralPath (Join-Path $BaseDir 'config.json') -Value $cfg -Encoding ASCII # Daily at 12:xx (a random minute spreads the load; if the computer is off, # the run happens as soon as it is on again) and at every sign-in. $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument ('-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File "{0}"' -f $target) $daily = New-ScheduledTaskTrigger -Daily -At ([datetime]::Today.AddHours(12).AddMinutes((Get-Random -Minimum 0 -Maximum 60))) $logon = New-ScheduledTaskTrigger -AtLogOn $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 10) -MultipleInstances IgnoreNew Register-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath -Action $action -Trigger @($daily, $logon) -Principal $principal -Settings $settings -Force | Out-Null Write-Host "ProfiLab Health: installed in $BaseDir (daily and at sign-in)." # The first report right now, from this window, so that the result is visible. $null = Send-PlReport } function Uninstall-Pl { if (-not (Test-Admin)) { Fail 'open PowerShell as administrator and run the command again.' } try { Unregister-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath -Confirm:$false } catch { } try { $svc = New-Object -ComObject Schedule.Service $svc.Connect() $svc.GetFolder('\').DeleteFolder('ProfiLab', 0) } catch { } if (Test-Path -LiteralPath $BaseDir) { Remove-Item -LiteralPath $BaseDir -Recurse -Force } $parent = Split-Path $BaseDir -Parent if ((Test-Path -LiteralPath $parent) -and -not @(Get-ChildItem -LiteralPath $parent -Force).Count) { Remove-Item -LiteralPath $parent -Force } Write-Host 'ProfiLab Health: removed. Nothing is sent any more.' } # --- Start ------------------------------------------------------------------------------ if ($Uninstall) { Uninstall-Pl; exit 0 } if ($DryRun) { Get-PlReport | ConvertTo-Json -Depth 6; exit 0 } if ($Install) { if (-not $Endpoint) { $Endpoint = $DefaultEndpoint } Install-Pl exit 0 } Read-PlConfig if (-not $Endpoint) { $Endpoint = $DefaultEndpoint } $result = Send-PlReport if ($result -eq 200) { exit 0 } exit 1