[CmdletBinding(SupportsShouldProcess = $true)] param( [string]$MbtoolsPath = '', [switch]$Quiet ) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' $script:MbuxRuleName = 'MBTools-HU6-HTTPS-8443-v1' $script:MbuxRuleGroup = 'MBTools' function Test-MbuxPortMatch { param([object[]]$Values) foreach ($entry in $Values) { foreach ($value in ([string]$entry -split ',')) { $value = $value.Trim() if ($value -in @('Any', '*', '8443', '8444', '8445', '48223')) { return $true } if ($value -match '^(\d+)-(\d+)$' -and (([int]$Matches[1] -le 8445 -and [int]$Matches[2] -ge 8443) -or ([int]$Matches[1] -le 48223 -and [int]$Matches[2] -ge 48223))) { return $true } } } return $false } function Test-MbuxAddressMatch { param([object[]]$Values, [string]$Address) $target = [Net.IPAddress]::Parse($Address).GetAddressBytes() foreach ($entry in $Values) { foreach ($raw in ([string]$entry -split ',')) { $value = $raw.Trim() if ($value -in @('Any', '*', 'LocalSubnet', 'LocalSubnet4', $Address)) { return $true } if ($value -match '^([\d.]+)/([0-9]|[12][0-9]|3[0-2])$') { $network = [Net.IPAddress]::Parse($Matches[1]).GetAddressBytes() $remaining = [int]$Matches[2] $same = $true for ($index = 0; $index -lt 4; ++$index) { $bits = [Math]::Min(8, [Math]::Max(0, $remaining)) $mask = if ($bits -eq 0) { 0 } else { (255 -shl (8 - $bits)) -band 255 } if (($target[$index] -band $mask) -ne ($network[$index] -band $mask)) { $same = $false } $remaining -= 8 } if ($same) { return $true } } elseif ($value -match '^([\d.]+)-([\d.]+)$') { $first = [Net.IPAddress]::Parse($Matches[1]).GetAddressBytes() $last = [Net.IPAddress]::Parse($Matches[2]).GetAddressBytes() $number = [uint64]0; $low = [uint64]0; $high = [uint64]0 for ($index = 0; $index -lt 4; ++$index) { $number = ($number -shl 8) + $target[$index] $low = ($low -shl 8) + $first[$index] $high = ($high -shl 8) + $last[$index] } if ($number -ge $low -and $number -le $high) { return $true } } } } return $false } function Get-MbuxFirewallNetwork { $addresses = @(Get-NetIPAddress -AddressFamily IPv4 -IPAddress '169.254.0.45' -ErrorAction SilentlyContinue) $profiles = @() $aliases = @() foreach ($address in $addresses) { $aliases += $address.InterfaceAlias foreach ($connection in @(Get-NetConnectionProfile -InterfaceIndex $address.InterfaceIndex -ErrorAction SilentlyContinue)) { $profiles += switch ([string]$connection.NetworkCategory) { 'DomainAuthenticated' { 'Domain' } 'Private' { 'Private' } default { 'Public' } } } } [pscustomobject]@{ Addresses = $addresses; Profiles = $profiles; Aliases = $aliases } } function Test-MbuxBlockRuleMatch { param($Rule, [string]$Program, $Network, [switch]$ExactProgram) if ([string]$Rule.Enabled -ne 'True' -or $Rule.Direction -ne 'Inbound' -or $Rule.Action -ne 'Block') { return $false } if ($Network.Profiles.Count -gt 0 -and [string]$Rule.Profile -ne 'Any') { $ruleProfiles = @(([string]$Rule.Profile -split ',') | ForEach-Object { $_.Trim() }) if (@($Network.Profiles | Where-Object { $_ -in $ruleProfiles }).Count -eq 0) { return $false } } $app = $Rule | Get-NetFirewallApplicationFilter $ruleProgram = [Environment]::ExpandEnvironmentVariables([string]$app.Program) if (-not [string]::Equals($ruleProgram, $Program, [StringComparison]::OrdinalIgnoreCase)) { if ($ExactProgram -or $ruleProgram -notin @('Any', '*', '')) { return $false } } $service = $Rule | Get-NetFirewallServiceFilter if ([string]$service.Service -notin @('Any', '*', '')) { return $false } $ports = $Rule | Get-NetFirewallPortFilter if ([string]$ports.Protocol -notin @('TCP', '6', 'Any', '256') -or -not (Test-MbuxPortMatch $ports.LocalPort)) { return $false } $type = $Rule | Get-NetFirewallInterfaceTypeFilter if ([string]$type.InterfaceType -notmatch 'Any|Wired') { return $false } $interface = $Rule | Get-NetFirewallInterfaceFilter if ($Network.Aliases.Count -gt 0 -and [string]$interface.InterfaceAlias -notin @('Any', '*', '')) { if (@($Network.Aliases | Where-Object { $_ -in @($interface.InterfaceAlias) }).Count -eq 0) { return $false } } $scope = $Rule | Get-NetFirewallAddressFilter return (Test-MbuxAddressMatch $scope.LocalAddress '169.254.0.45') -and (Test-MbuxAddressMatch $scope.RemoteAddress '169.254.133.27') } function Get-MbuxFirewallWarnings { param([string]$Program) $messages = [Collections.Generic.List[string]]::new() $network = Get-MbuxFirewallNetwork foreach ($address in $network.Addresses) { if ($address.PrefixLength -gt 16) { $messages.Add("The Ethernet subnet /$($address.PrefixLength) does not include the HU6 address 169.254.133.27. Check the manual Ethernet subnet mask before retrying.") } } if ($network.Addresses.Count -eq 0) { $messages.Add('Ethernet address 169.254.0.45 is not currently configured. Keep the manual Ethernet setup and check this address before retrying HU6 setup.') } foreach ($profile in @(Get-NetFirewallProfile -PolicyStore ActiveStore)) { if ($network.Profiles.Count -gt 0 -and [string]$profile.Name -notin $network.Profiles) { continue } if ([string]$profile.Enabled -eq 'False') { continue } if ([string]$profile.AllowInboundRules -eq 'False' -or [string]$profile.AllowLocalFirewallRules -eq 'False') { $messages.Add("The $($profile.Name) firewall profile restricts inbound or local allow rules. An administrator may need to allow HU6 TCP ports 8443-8445 and 48223 through company policy.") } } foreach ($rule in @(Get-NetFirewallRule -PolicyStore ActiveStore -All)) { if (-not (Test-MbuxBlockRuleMatch -Rule $rule -Program $Program -Network $network)) { continue } $messages.Add("An explicit block rule may prevent this connection: $($rule.DisplayName). It was left unchanged; a block rule takes precedence over an allow rule.") } return $messages.ToArray() } function Repair-MbuxHu6Firewall { [CmdletBinding(SupportsShouldProcess = $true)] param([Parameter(Mandatory = $true)][string]$Program) $Program = [Environment]::ExpandEnvironmentVariables($Program) if (-not [IO.Path]::IsPathRooted($Program) -or [IO.Path]::GetFileName($Program) -ine 'MBTools.exe') { throw 'The firewall target must be the full path to MBTools.exe.' } $Program = [IO.Path]::GetFullPath($Program) # The portable wrapper extracts this executable only while MBTools runs. # The file need not exist yet when this script is selected in Launcher. $owned = @(Get-NetFirewallRule -PolicyStore PersistentStore | Where-Object { $_.Name -eq $script:MbuxRuleName }) if ($owned.Count -gt 1 -or ($owned.Count -eq 1 -and $owned[0].Group -ne $script:MbuxRuleGroup)) { throw 'The MBTools firewall rule name is already used by an unrecognized rule. No rule was changed.' } $settings = @{ Name = $script:MbuxRuleName PolicyStore = 'PersistentStore' Direction = 'Inbound' Action = 'Allow' Enabled = 'True' Profile = 'Any' Protocol = 'TCP' LocalPort = @('8443-8445', '48223') RemotePort = 'Any' LocalAddress = '169.254.0.45' RemoteAddress = '169.254.133.27' Program = $Program InterfaceType = 'Wired' EdgeTraversalPolicy = 'Block' } $changed = $false $displayName = 'MBTools HU6 connection (TCP 8443-8445, 48223)' $description = 'Allows the HU6 installer download and temporary SSH back-connection to MBTools. Managed by MBTools Launcher.' if ($PSCmdlet.ShouldProcess($displayName, 'Create or repair the scoped inbound firewall rule')) { if ($owned.Count -eq 0) { New-NetFirewallRule @settings -DisplayName $displayName -Group $script:MbuxRuleGroup -Description $description | Out-Null } else { Set-NetFirewallRule @settings -DisplayName $displayName -Description $description | Out-Null } $changed = $true } $disabled = [Collections.Generic.List[string]]::new() $network = Get-MbuxFirewallNetwork # PersistentStore contains local policy only. Pass the exact local CIM object # to avoid touching a policy rule or a similarly named rule in another store. if ($changed -or $WhatIfPreference) { foreach ($rule in @(Get-NetFirewallRule -PolicyStore PersistentStore -All)) { if (-not (Test-MbuxBlockRuleMatch -Rule $rule -Program $Program -Network $network -ExactProgram)) { continue } $description = "$($rule.DisplayName) [$($rule.Name)]" if ($PSCmdlet.ShouldProcess($description, 'Disable the local MBTools inbound block rule overlapping HU6 TCP 8443-8445 or 48223')) { try { Disable-NetFirewallRule -InputObject $rule -Confirm:$false -ErrorAction Stop | Out-Null } catch { throw "Could not disable local MBTools block rule ${description}: $($_.Exception.Message)" } $disabled.Add($description) } } } [pscustomobject]@{ Program = $Program; Applied = $changed; DisabledBlockRules = $disabled.ToArray(); Warnings = @(Get-MbuxFirewallWarnings $Program) } } function Invoke-MbuxElevatedRepair { param( [Parameter(Mandatory = $true)][string]$ScriptPath, [Parameter(Mandatory = $true)][string]$Program, [switch]$Quiet, [string]$PowerShellHome = $PSHOME, [string]$WindowsDirectory = $env:SystemRoot ) # RunAs uses ShellExecute: use a real path visible to either architecture, # rather than the Sysnative alias (which only exists for 32-bit callers). $hostPath = Join-Path $PowerShellHome 'powershell.exe' foreach ($path in @($hostPath, $ScriptPath)) { if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Required repair file was not found: $path" } } if (-not (Test-Path -LiteralPath $WindowsDirectory -PathType Container)) { throw 'The Windows directory could not be found.' } if ($Program.Contains('"')) { throw 'The MBTools executable path contains an invalid quote.' } $arguments = '-NoProfile -ExecutionPolicy Bypass -File "' + $ScriptPath + '" -MbtoolsPath "' + $Program + '"' if ($Quiet) { $arguments += ' -Quiet' } $child = Start-Process -FilePath $hostPath -ArgumentList $arguments -WorkingDirectory $WindowsDirectory ` -Verb RunAs -WindowStyle Hidden -PassThru -ErrorAction Stop $null = $child.Handle $child.WaitForExit() $child.Refresh() return $child.ExitCode } function Show-MbuxFirewallResult { param([string]$Message, [bool]$Failed, [bool]$Warning = $false) Write-Output $Message if (-not $Quiet) { Add-Type -AssemblyName System.Windows.Forms $icon = if ($Failed) { 'Error' } elseif ($Warning) { 'Warning' } else { 'Information' } [Windows.Forms.MessageBox]::Show($Message, 'MBTools - HU6 firewall repair', 'OK', $icon) | Out-Null } } # Dot-sourcing exposes the functions for tests without changing the machine. if ($MyInvocation.InvocationName -eq '.') { return } $stage = 'starting the repair' try { # Preserve the Launcher's user's target even if elevation uses another account. if (-not $MbtoolsPath) { $MbtoolsPath = Join-Path ([IO.Path]::GetTempPath()) 'MBTools\App\MBTools.exe' } $principal = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { if ($WhatIfPreference) { throw 'Run an elevated PowerShell window for firewall inspection with -WhatIf.' } $stage = 'requesting administrator access' exit (Invoke-MbuxElevatedRepair -ScriptPath $PSCommandPath -Program $MbtoolsPath -Quiet:$Quiet) } $stage = 'loading Windows firewall support' Import-Module NetSecurity -ErrorAction Stop $stage = 'applying and inspecting the firewall rule' $result = Repair-MbuxHu6Firewall -Program $MbtoolsPath -WhatIf:$WhatIfPreference $message = if ($result.Applied) { "The MBTools firewall rule is ready for the HU6 connection on TCP ports 8443-8445 and 48223." } else { 'Inspection completed. No firewall rule was changed.' } if ($result.DisabledBlockRules.Count -gt 0) { $message += "`r`n`r`nDisabled matching local MBTools block rules:`r`n" + ($result.DisabledBlockRules -join "`r`n") } $message += "`r`n`r`nKeep Windows Firewall enabled, then open MBTools and retry Set up HU6." if ($result.Warnings.Count -gt 0) { $message += "`r`n`r`nAction required:`r`n" + ($result.Warnings -join "`r`n`r`n") } $message += "`r`n`r`nHU6-to-PC connectivity must be confirmed by retrying setup. Third-party security software or vehicle routing can still block it." Show-MbuxFirewallResult $message $false ($result.Warnings.Count -gt 0) if ($result.Warnings.Count -gt 0) { exit 2 } exit 0 } catch { Show-MbuxFirewallResult ("The HU6 firewall repair could not complete while $stage.`r`n`r`n" + $_.Exception.Message) $true exit 1 }