diff --git a/.github/workflows/powershell.yml b/.github/workflows/powershell.yml index d475abb..2bfee60 100644 --- a/.github/workflows/powershell.yml +++ b/.github/workflows/powershell.yml @@ -26,15 +26,26 @@ jobs: runs-on: windows-latest steps: - uses: actions/checkout@v5 - - name: Run isolated regression tests + - name: Install pinned test dependencies shell: powershell run: | - .\Debug\test_privacy.ps1 - .\Debug\test_update.ps1 - .\Debug\test_network_math.ps1 - .\Debug\test_export.ps1 - .\Debug\test_profiles.ps1 - .\Debug\test_log_query.ps1 + $ErrorActionPreference = 'Stop' + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope CurrentUser -Force + # Hosted images include Pester 5 signed with a different certificate chain. + Install-Module Pester -RequiredVersion 4.10.1 -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck + Install-Module PSScriptAnalyzer -RequiredVersion 1.25.0 -Scope CurrentUser -Force + - name: Run isolated regression tests and quality checks + shell: powershell + run: | + .\Debug\test_regression.ps1 + exit $LASTEXITCODE + - name: Upload test reports and logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: windows-powershell-test-results + path: Debug/test-results/ build: permissions: diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7b29231 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +Debug/test-results/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a835aa..76e635b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,34 @@ All notable changes to this project are documented in this file. This project follows a practical changelog format for a single-file Windows PowerShell admin utility. +## [3.0] - Unreleased + +### Fixed + +- Prevent duplicate-gateway failures by configuring IPv4 addresses and default routes separately, reconciling both route stores on the selected adapter, and using the supported dual-store creation default. Gateway-free profiles remove both default-route stores; provider errors appear in the console. +- Handle empty CIM address stores when disabling DHCP removes a lease. Re-read state before retrying partial address creation, preserve a different working address until its replacement is ready, and reject Duplicate or timed-out Tentative addresses. +- Require a readable snapshot before mutation and attempt recovery of previous static or DHCP settings. Restore address stores/prefixes, route stores/metrics, and DNS mode, including manual DHCP DNS overrides; wait for lease readiness and report incomplete recovery. +- Fail configuration when gateway, DNS, or final-state verification fails. Scope DNS changes to IPv4 and verify the requested server order. +- Clear static default routes during DHCP conversion and renew through an adapter-specific CIM method with identity checks, operation timeout, structured result checks, and Preferred DHCP-origin lease verification. Keep formatted failure output out of the returned success value. +- Prevent log rotation or write failures from interrupting configuration and recovery. Reject non-Boolean stored logging consent, including the JSON string `"false"`. +- Include virtual NICs in adapter selection and return when the inventory is empty. + +### Changed + +- Replace the previous NetBIOS/ARP/TCP conflict-probing sequence with bounded local ownership and selected-interface neighbor checks, followed by Windows address-readiness verification. Negative probes do not prove that an address is unused. +- Refresh documentation for the current menu keys, MAC lookup caching, recovery limits, and user-confirmed Proxmox behavior. + +### Added + +- A process-isolated test runner with timeouts, failure-reporting self-tests, required static checks, command coverage, JSON/JUnit reports, and CI artifact collection. +- Core and network transaction regressions covering configuration, recovery, CIM failures, asymmetric stores, privacy, and user input, plus a testing guide with dependency setup and live validation tracking. + +### Validation + +- Local Windows PowerShell 5.1: all 11 suites passed, including 130 named Pester tests and required static analysis. +- User-reported Proxmox Windows VM tests confirm profile and manual static reapplication, static-to-DHCP conversion, and DHCP-to-static profile application with the requested address, prefix, gateway, DNS order, and DHCP disabled. +- A failed gateway apply displayed successful recovery in the guest. Exact restored state and the remaining live checklist, including reboot persistence, still need verification. + ## [2.9] - 2026-09-13 ### Fixed diff --git a/Debug/NetworkTestHarness.ps1 b/Debug/NetworkTestHarness.ps1 new file mode 100644 index 0000000..90c8316 --- /dev/null +++ b/Debug/NetworkTestHarness.ps1 @@ -0,0 +1,205 @@ +#Requires -Version 5.1 +param([string]$TestLibraryPath) +# Isolated stateful regression tests. Never dot-source the application startup or call live networking cmdlets. +$ErrorActionPreference = 'Stop' +$sourcePath = Join-Path $PSScriptRoot '..\Network_Configuration.ps1' +$errors = $null +$ast = [System.Management.Automation.Language.Parser]::ParseFile($sourcePath, [ref]$null, [ref]$errors) +if ($errors) { throw ($errors | Out-String) } +$names = @('Set-StaticIP', 'Set-DHCP', 'Get-IPv4StoreState', 'Restore-NetworkConfiguration', 'Wait-IPv4AddressReady', 'Invoke-InterfaceDHCPRenewal', + 'Set-IPv4DefaultGatewaySafe', 'Remove-IPv4AddressSafe', 'Set-IPv4DnsServersSafe', 'Reset-IPv4DnsServersSafe', + 'Test-ValidIPAddress', 'Test-ValidDNSServer', 'Test-ValidSubnetMask', 'Get-PrefixLength', + 'ConvertTo-IPv4UInt32', 'ConvertFrom-IPv4UInt32', 'Get-IPv4NetworkDetails', 'Test-IPConflict', 'Select-NetworkInterface') +if ($TestLibraryPath) { . $TestLibraryPath } +else { foreach ($name in $names) { + $definition = $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true) | + Where-Object Name -eq $name | Select-Object -First 1 + if (-not $definition) { throw "Missing function $name" } + Set-Item -Path ("Function:script:" + $name) -Value $definition.Body.GetScriptBlock() +} } +function Assert-True($Condition, $Message) { if (-not $Condition) { throw $Message } } +function Register-TestOperation { + param($Name, $Target, $Store) + $script:operations += [pscustomobject]@{ Name = $Name; Target = $Target; Store = $Store } + if ($script:failOperation -eq $Name -and $script:failCount -gt 0 -and + (-not $script:failTarget -or $script:failTarget -eq $Target)) { + $script:failCount-- + throw "Injected $Name failure for $Target" + } +} +function Write-LogMessage { param($Message, $Level) } +function Start-Sleep { param($Milliseconds, $Seconds) } +function Show-IPv4ConfigurationSummary { param($InterfaceName, $IPConfig, $IPv4Address, $DHCPStatus) } +function Test-DNSConnectivity { param($DNSServer) return $true } +function Test-SystemDNSResolution { return $true } +function Clear-DnsClientCache { [CmdletBinding()]param() } +function Read-YesNo { param($Prompt, $Default) return $true } +function Get-NetAdapter { [CmdletBinding()]param($Name) [pscustomobject]@{ Name = 'Ethernet'; Status = 'Up'; ifIndex = 7; InterfaceGuid = '11111111-1111-1111-1111-111111111111' } } +function Get-NetworkAdapterSafe { param($InterfaceName) Get-NetAdapter -Name $InterfaceName } +function Get-NetIPInterface { [CmdletBinding()]param($InterfaceAlias, $AddressFamily) [pscustomobject]@{ Dhcp = $script:dhcp } } +function Set-NetIPInterface { + [CmdletBinding()]param($InterfaceAlias, $AddressFamily, $Dhcp) + Register-TestOperation -Name SetDhcp -Target $Dhcp + if ($Dhcp -eq 'Disabled' -and $script:dhcp -eq 'Enabled' -and $script:releaseDhcpOnDisable) { + $script:addresses = @($script:addresses | Where-Object { $_.InterfaceAlias -ne $InterfaceAlias -or $_.PrefixOrigin -ne 'Dhcp' }) + $script:routes = @($script:routes | Where-Object { $_.InterfaceAlias -ne $InterfaceAlias -or $_.Protocol -ne 'Dhcp' }) + } + $script:dhcp = $Dhcp; $script:mutations++ +} +function Get-NetIPAddress { + [CmdletBinding()]param($InterfaceAlias, $AddressFamily, $PolicyStore = 'ActiveStore') + Register-TestOperation -Name ReadAddress -Target $InterfaceAlias -Store $PolicyStore + if ($script:readFailure) { throw 'Injected read failure' } + if ($script:leaseDelayQueries -gt 0) { + $script:leaseDelayQueries-- + if ($script:leaseDelayQueries -eq 0) { + foreach ($address in @($script:addresses | Where-Object PrefixOrigin -eq 'Dhcp')) { $address.AddressState = 'Preferred' } + } + } + $result = @($script:addresses | Where-Object { $_.Store -eq $PolicyStore -and (-not $InterfaceAlias -or $_.InterfaceAlias -eq $InterfaceAlias) }) + if ($script:noMatchesError -and $result.Count -eq 0) { + $PSCmdlet.WriteError([System.Management.Automation.ErrorRecord]::new( + [Exception]::new('No matching MSFT_NetIPAddress objects found by CIM query'), + 'CmdletizationQuery_NotFound', [System.Management.Automation.ErrorCategory]::ObjectNotFound, $InterfaceAlias)) + } + $result +} +function New-NetIPAddress { + [CmdletBinding()]param($InterfaceAlias, $AddressFamily, $IPAddress, $PrefixLength, $DefaultGateway, $PolicyStore, $SkipAsSource = $false, $ValidLifetime, $PreferredLifetime) + Assert-True (-not $DefaultGateway) 'Address creation attempted to create a gateway' + Assert-True ($PolicyStore -ne 'PersistentStore') 'Used unsupported explicit PersistentStore address creation' + Register-TestOperation -Name NewAddress -Target $IPAddress -Store $PolicyStore + $stores = if ($PolicyStore) { @($PolicyStore) } else { @('ActiveStore', 'PersistentStore') } + foreach ($store in $stores) { + Assert-True (-not ($script:addresses | Where-Object { $_.InterfaceAlias -eq $InterfaceAlias -and $_.IPAddress -eq $IPAddress -and $_.Store -eq $store })) 'Duplicate address creation' + $state = if ($script:duplicate -and $IPAddress -eq '192.168.1.25') { 'Duplicate' } else { 'Preferred' } + $script:addresses += [pscustomobject]@{ InterfaceAlias = $InterfaceAlias; InterfaceIndex = 7; IPAddress = $IPAddress; PrefixLength = $PrefixLength; PrefixOrigin = 'Manual'; AddressState = $state; SkipAsSource = $SkipAsSource; Store = $store } + } + $script:mutations++ + if ($script:partialAdd) { $script:partialAdd = $false; throw 'Injected error after successful address creation' } +} +function Remove-NetIPAddress { + [CmdletBinding(SupportsShouldProcess)]param($InterfaceAlias, $IPAddress, $AddressFamily, $PolicyStore) + Register-TestOperation -Name RemoveAddress -Target $IPAddress -Store $PolicyStore + if ($script:removeFailure) { throw 'Injected address removal failure' } + $script:addresses = @($script:addresses | Where-Object { $_.InterfaceAlias -ne $InterfaceAlias -or $_.IPAddress -ne $IPAddress -or ($PolicyStore -and $_.Store -ne $PolicyStore) }) + $script:mutations++ +} +function Set-NetIPAddress { + [CmdletBinding()]param($InterfaceAlias, $AddressFamily, $IPAddress, $SkipAsSource, $PrefixLength, $PolicyStore) + Assert-True ($PolicyStore -ne 'PersistentStore') 'Used unsupported explicit PersistentStore address mutation' + Register-TestOperation -Name SetAddress -Target $IPAddress -Store $PolicyStore + foreach ($address in @($script:addresses | Where-Object { $_.InterfaceAlias -eq $InterfaceAlias -and $_.IPAddress -eq $IPAddress -and (-not $PolicyStore -or $_.Store -eq $PolicyStore) })) { + if ($PSBoundParameters.ContainsKey('PrefixLength')) { $address.PrefixLength = $PrefixLength } + if ($PSBoundParameters.ContainsKey('SkipAsSource')) { $address.SkipAsSource = $SkipAsSource } + } + $script:mutations++ +} +function Get-NetRoute { + [CmdletBinding()]param($InterfaceAlias, $AddressFamily, $PolicyStore = 'ActiveStore') + Register-TestOperation -Name ReadRoute -Target $InterfaceAlias -Store $PolicyStore + if ($script:readFailure) { throw 'Injected route read failure' } + $script:routes | Where-Object { $_.InterfaceAlias -eq $InterfaceAlias -and $_.Store -eq $PolicyStore } +} +function Remove-NetRoute { + [CmdletBinding(SupportsShouldProcess)]param($InterfaceAlias, $AddressFamily, $DestinationPrefix, $NextHop, $PolicyStore) + Assert-True ($InterfaceAlias -eq 'Ethernet') 'Touched another adapter route' + Register-TestOperation -Name RemoveRoute -Target $NextHop -Store $PolicyStore + $script:routes = @($script:routes | Where-Object { $_.InterfaceAlias -ne $InterfaceAlias -or $_.DestinationPrefix -ne $DestinationPrefix -or $_.NextHop -ne $NextHop -or $_.Store -ne $PolicyStore }) + $script:mutations++ +} +function New-NetRoute { + [CmdletBinding()]param($InterfaceAlias, $AddressFamily, $DestinationPrefix, $NextHop, $PolicyStore, $RouteMetric = 256) + Register-TestOperation -Name NewRoute -Target $NextHop -Store $PolicyStore + if ($PolicyStore -eq 'PersistentStore') { throw 'New-NetRoute cannot explicitly create in PersistentStore' } + if ($script:routeFailure -and $NextHop -eq '192.168.1.1') { throw 'Injected gateway failure' } + Assert-True (-not ($script:routes | Where-Object { $_.InterfaceAlias -eq $InterfaceAlias -and $_.DestinationPrefix -eq $DestinationPrefix -and $_.NextHop -eq $NextHop -and $_.Store -eq $PolicyStore })) 'Duplicate route creation' + $stores = if ($PolicyStore) { @($PolicyStore) } else { @('ActiveStore', 'PersistentStore') } + foreach ($targetStore in $stores) { + Assert-True (-not ($script:routes | Where-Object { $_.InterfaceAlias -eq $InterfaceAlias -and $_.DestinationPrefix -eq $DestinationPrefix -and $_.NextHop -eq $NextHop -and $_.Store -eq $targetStore })) 'Duplicate route creation' + $script:routes += [pscustomobject]@{ InterfaceAlias = $InterfaceAlias; DestinationPrefix = $DestinationPrefix; NextHop = $NextHop; Store = $targetStore; Protocol = 'NetMgmt'; RouteMetric = $RouteMetric } + } + $script:mutations++ +} +function Set-NetRoute { + [CmdletBinding()]param($InterfaceAlias, $AddressFamily, $DestinationPrefix, $NextHop, $PolicyStore, $RouteMetric) + Assert-True ($InterfaceAlias -eq 'Ethernet') 'Changed another adapter route metric' + foreach ($route in @($script:routes | Where-Object { $_.InterfaceAlias -eq $InterfaceAlias -and $_.DestinationPrefix -eq $DestinationPrefix -and $_.NextHop -eq $NextHop -and $_.Store -eq $PolicyStore })) { + $route.RouteMetric = $RouteMetric + } + $script:mutations++ +} +function Get-DnsClientServerAddress { [CmdletBinding()]param($InterfaceAlias, $AddressFamily) Register-TestOperation -Name ReadDNS -Target $InterfaceAlias; [pscustomobject]@{ ServerAddresses = @($script:dns); AddressFamily = 2 } } +function Set-DnsClientServerAddress { + [CmdletBinding()]param([Parameter(ValueFromPipeline)]$InputObject, $ServerAddresses, [switch]$ResetServerAddresses) + process { + $operation = if ($ResetServerAddresses) { 'ResetDNS' } else { 'SetDNS' } + Register-TestOperation -Name $operation -Target ($ServerAddresses -join ',') + Assert-True ($InputObject.AddressFamily -eq 2) 'DNS update was not scoped to IPv4' + if ($script:dnsFailure -and $ServerAddresses -contains '1.1.1.1') { throw 'Injected DNS failure' } + $script:dns = if ($ResetServerAddresses) { @('192.168.1.1') } else { @($ServerAddresses) } + $script:mutations++ + } +} +function Get-NetIPConfiguration { + [CmdletBinding()]param($InterfaceAlias) + $addresses = @(Get-NetIPAddress -InterfaceAlias $InterfaceAlias) + if ($script:finalMismatch) { $addresses = @() } + [pscustomobject]@{ IPv4Address = $addresses; IPv4DefaultGateway = @(Get-NetRoute -InterfaceAlias $InterfaceAlias | Where-Object DestinationPrefix -eq '0.0.0.0/0') } +} +function Get-NetNeighbor { [CmdletBinding()]param($InterfaceIndex, $AddressFamily) $script:neighbors | Where-Object InterfaceIndex -eq $InterfaceIndex } +function ipconfig { throw 'Unexpected native DHCP command' } +function Get-CimInstance { + [CmdletBinding()]param($Namespace, $ClassName, $Filter, $OperationTimeoutSec) + Assert-True ($ClassName -eq 'Win32_NetworkAdapterConfiguration' -and $Namespace -eq 'root/cimv2') 'Unexpected CIM query' + Assert-True ($Filter -eq 'InterfaceIndex = 7' -and $OperationTimeoutSec -gt 0) 'Unscoped or untimed DHCP lookup' + if ($script:cimLookupFailure) { throw 'Injected CIM lookup failure' } + if ($script:cimEmpty) { return } + $id = if ($script:cimIdentityMismatch) { '22222222-2222-2222-2222-222222222222' } else { '11111111-1111-1111-1111-111111111111' } + [pscustomobject]@{ InterfaceIndex = 7; SettingID = $id } +} +function Invoke-CimMethod { + [CmdletBinding()]param($InputObject, $MethodName, $OperationTimeoutSec) + Assert-True ($InputObject.InterfaceIndex -eq 7 -and $MethodName -eq 'RenewDHCPLease' -and $OperationTimeoutSec -gt 0) 'Renewal not scoped to one adapter with timeout' + $script:cimCalls++ + if ($script:cimTimeout) { throw 'Injected CIM operation timeout' } + if ($script:cimMissingResult) { return [pscustomobject]@{} } + $code = if ($null -ne $script:cimReturnCode) { $script:cimReturnCode } elseif ($script:renewSuccess) { 0 } else { 82 } + if ($code -eq 0 -and -not $script:acknowledgedNoLease) { + $script:leaseDelayQueries = $script:renewDelayQueries + $leaseState = if ($script:leaseDelayQueries -gt 0) { 'Tentative' } else { 'Preferred' } + $script:addresses += [pscustomobject]@{ InterfaceAlias = 'Ethernet'; InterfaceIndex = 7; IPAddress = '192.168.1.100'; PrefixLength = 24; PrefixOrigin = 'Dhcp'; AddressState = $leaseState; SkipAsSource = $false; Store = 'ActiveStore' } + } + [pscustomobject]@{ ReturnValue = $code } +} +function Backup-NetworkConfiguration { + param($InterfaceName) + if ($script:backupFailure) { return $null } + @{ Interface = $InterfaceName; IPv4Address = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address); PersistentAddresses = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address -PolicyStore PersistentStore); + IPv4Routes = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Route); PersistentRoutes = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Route -PolicyStore PersistentStore); + DNSServers = @($script:dns); DHCPEnabled = $script:dhcp; DNSAutomatic = $false } +} +function Reset-TestState { + $script:operations = @(); $script:failOperation = ''; $script:failTarget = ''; $script:failCount = 0 + $script:addresses = @() + $script:routes = @() + $script:neighbors = @() + $script:dhcp = 'Disabled'; $script:dns = @('9.9.9.9'); $script:mutations = 0 + $script:duplicate = $false; $script:partialAdd = $false; $script:dnsFailure = $false + $script:routeFailure = $false; $script:readFailure = $false; $script:backupFailure = $false; $script:removeFailure = $false + $script:finalMismatch = $false; $script:renewSuccess = $false + $script:cimLookupFailure = $false; $script:cimIdentityMismatch = $false; $script:cimEmpty = $false + $script:cimTimeout = $false; $script:cimReturnCode = $null; $script:cimMissingResult = $false + $script:acknowledgedNoLease = $false; $script:cimCalls = 0 + $script:leaseDelayQueries = 0; $script:renewDelayQueries = 0 + $script:releaseDhcpOnDisable = $false; $script:noMatchesError = $false + New-NetIPAddress -InterfaceAlias Ethernet -IPAddress '192.168.1.50' -PrefixLength 24 + New-NetRoute -InterfaceAlias Ethernet -DestinationPrefix '0.0.0.0/0' -NextHop '192.168.1.254' -RouteMetric 42 + New-NetRoute -InterfaceAlias Ethernet -DestinationPrefix '10.0.0.0/8' -NextHop '192.168.1.254' + foreach ($store in @('ActiveStore', 'PersistentStore')) { + $script:routes += [pscustomobject]@{ InterfaceAlias = 'Wi-Fi'; DestinationPrefix = '0.0.0.0/0'; NextHop = '192.168.1.1'; Store = $store; Protocol = 'NetMgmt'; RouteMetric = 99 } + } + $script:mutations = 0 + $script:operations = @() +} +$settings = @{ InterfaceName = 'Ethernet'; IPAddress = '192.168.1.25'; SubnetMask = '24'; Gateway = '192.168.1.1'; PrimaryDNS = '1.1.1.1'; SecondaryDNS = '1.0.0.1'; Confirm = $false } diff --git a/Debug/Network_Core.Tests.ps1 b/Debug/Network_Core.Tests.ps1 new file mode 100644 index 0000000..f0ce15a --- /dev/null +++ b/Debug/Network_Core.Tests.ps1 @@ -0,0 +1,382 @@ +#Requires -Version 5.1 +param([string]$TestLibraryPath) +# Load only function bodies, preserving their source locations for Pester coverage. +$sourcePath = Join-Path $PSScriptRoot '..\Network_Configuration.ps1' +$parseErrors = $null +$sourceAst = [System.Management.Automation.Language.Parser]::ParseFile($sourcePath, [ref]$null, [ref]$parseErrors) +if ($parseErrors) { throw 'Application source does not parse.' } +$functionNames = @('Read-YesNo', 'Get-ValidatedInput', 'Read-IPConfigurationSettings', 'Test-ValidIPAddress', + 'Test-ValidSubnetMask', 'Test-ValidDNSServer', 'Get-PrefixLength', 'ConvertTo-IPv4UInt32', 'ConvertFrom-IPv4UInt32', + 'Get-IPv4NetworkDetails', 'Get-SuggestedGateway', 'Remove-OldFiles', 'Remove-LocalItemSafe', 'New-ManagedBackupPath', + 'Write-IPProfileFile', 'Get-IPProfiles', 'Get-SavedIPConfig', 'Save-SelectedInterface', 'Get-SavedInterface', + 'Get-NetworkLogEntries', 'Hide-IPAddress', 'Get-GDPRConsent', 'Get-MACVendor', 'Invoke-DNSLookup', + 'Invoke-Traceroute', 'Invoke-PortCheck', 'Test-TcpPort', 'Install-ValidatedScriptUpdate', 'Get-SafeProfileFileName', + 'Write-MenuOption', 'Write-MenuSection', 'Show-MainMenu', 'Get-InterfaceStatus', 'Start-LiveInterfaceMonitor', 'Remove-AllLogs', 'Update-NetworkScript') +if ($TestLibraryPath) { . $TestLibraryPath } +else { foreach ($name in $functionNames) { + $definition = $sourceAst.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true) | + Where-Object Name -eq $name | Select-Object -First 1 + if (-not $definition) { throw "Missing function $name" } + Set-Item -Path ('Function:script:' + $name) -Value $definition.Body.GetScriptBlock() +} } +function Write-LogMessage { param($Message, $Level) } +function Resolve-DnsName { [CmdletBinding()]param($Name, $Type, $Server) throw 'Unmocked DNS boundary' } +function tracert.exe { param([Parameter(ValueFromRemainingArguments)]$Arguments) } +function Get-TestReply { + if ($script:replyIndex -ge $script:replies.Count) { throw 'Unexpected prompt: fixture exhausted' } + $reply = $script:replies[$script:replyIndex]; $script:replyIndex++; return $reply +} +$script:fixtureParent = Join-Path $PSScriptRoot 'test-results' +New-Item -ItemType Directory -Path $script:fixtureParent -Force | Out-Null + +Describe 'Core helpers and user flows' { + BeforeEach { + $script:caseRoot = Join-Path $script:fixtureParent ('core_' + [guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $script:caseRoot | Out-Null + Mock Write-Host { } + Mock Clear-Host { } + Mock Start-Sleep { } + Mock Read-Host { Get-TestReply } + $script:replies = @(); $script:replyIndex = 0 + $script:LoggingConsent = $false; $script:MACVendorCache = @{} + } + AfterEach { + $resolved = [IO.Path]::GetFullPath($script:caseRoot) + $allowed = [IO.Path]::GetFullPath($script:fixtureParent).TrimEnd('\') + '\' + if (-not $resolved.StartsWith($allowed, [StringComparison]::OrdinalIgnoreCase)) { throw 'Fixture cleanup outside test results' } + Remove-Item -LiteralPath $resolved -Recurse -Force + } + Context 'Confirmation and input cancellation' { + $confirmationCases = @( + @{ Text = 'y'; Expected = $true }, @{ Text = ' YES '; Expected = $true }, + @{ Text = 'n'; Expected = $false }, @{ Text = ' No '; Expected = $false } + ) + It 'interprets confirmation ' -TestCases $confirmationCases { + param($Text, $Expected) + $script:replies = @($Text) + (Read-YesNo -Prompt 'Apply?') | Should Be $Expected + $script:replyIndex | Should Be 1 + } + It 'uses both defaults only after blank input' { + $script:replies = @('', '') + (Read-YesNo -Prompt 'Apply?' -Default $true) | Should Be $true + (Read-YesNo -Prompt 'Delete?' -Default $false) | Should Be $false + } + It 'reprompts invalid confirmation without treating it as approval' { + $script:replies = @('perhaps', 'n') + (Read-YesNo -Prompt 'Apply?') | Should Be $false + $script:replyIndex | Should Be 2 + } + It 'bounds invalid input retries' { + $script:replies = @('bad', 'bad', 'bad') + { Get-ValidatedInput -Prompt 'IP' -ValidationFunction { param($Value) Test-ValidIPAddress $Value } -MaxAttempts 3 } | Should Throw + $script:replyIndex | Should Be 3 + } + It 'returns a validated default and trims user input' { + $script:replies = @('', ' 192.168.1.25 ') + (Get-ValidatedInput -Prompt 'IP' -DefaultValue '192.168.1.25' -ValidationFunction { param($Value) Test-ValidIPAddress $Value }) | Should Be '192.168.1.25' + (Get-ValidatedInput -Prompt 'IP' -ValidationFunction { param($Value) Test-ValidIPAddress $Value }) | Should Be '192.168.1.25' + } + It 'does not prompt without an adapter' { + (Read-IPConfigurationSettings -InterfaceName '') | Should BeNullOrEmpty + $script:replyIndex | Should Be 0 + } + It 'captures default gateway and DNS settings' { + $script:replies = @('192.168.1.25', '24', '', '', '', 'y') + $settings = Read-IPConfigurationSettings -InterfaceName Ethernet + $settings.Gateway | Should Be '192.168.1.1' + $settings.PrimaryDNS | Should Be '1.1.1.1' + $settings.SecondaryDNS | Should Be '1.0.0.1' + } + It 'captures gateway-free and secondary-DNS-free settings' { + $script:replies = @('192.168.1.25', '24', 'none', '9.9.9.9', 'none', 'y') + $settings = Read-IPConfigurationSettings -InterfaceName Ethernet + $settings.Gateway | Should BeNullOrEmpty + $settings.SecondaryDNS | Should BeNullOrEmpty + $settings.PrimaryDNS | Should Be '9.9.9.9' + } + It 'uses the alternate gateway inside a narrow subnet' { + $script:replies = @('192.168.1.200', '25', 'last', '', '', 'y') + (Read-IPConfigurationSettings -InterfaceName Ethernet).Gateway | Should Be '192.168.1.254' + } + It 'returns no settings when review is declined' { + $script:replies = @('192.168.1.25', '24', '', '', '', 'n') + (Read-IPConfigurationSettings -InterfaceName Ethernet) | Should BeNullOrEmpty + } + It 'stops after invalid address retries without prompting for later fields' { + $script:replies = @('bad', 'bad', 'bad') + (Read-IPConfigurationSettings -InterfaceName Ethernet) | Should BeNullOrEmpty + $script:replyIndex | Should Be 3 + } + } + Context 'Independent address arithmetic and boundaries' { + $badAddresses = @('192.168.1', '192.168.001.1', '256.1.1.1', '0.1.2.3', '127.0.0.1', '224.0.0.1', '255.255.255.255', '2001:db8::1', '1e2.1.1.1', '192.168.1.1;exit') + It 'rejects malformed or reserved address
' -TestCases @($badAddresses | ForEach-Object { @{ Address = $_ } }) { + param($Address) (Test-ValidIPAddress $Address) | Should Be $false + } + It 'round-trips 64 seeded IPv4 values and bounds each subnet independently' { + $random = New-Object System.Random(300) + for ($i = 0; $i -lt 64; $i++) { + $octets = @(10, $random.Next(256), $random.Next(256), $random.Next(256)) + $ip = $octets -join '.' + $number = [uint64]$octets[0] * 16777216 + [uint64]$octets[1] * 65536 + [uint64]$octets[2] * 256 + [uint64]$octets[3] + (ConvertTo-IPv4UInt32 $ip) | Should Be $number + (ConvertFrom-IPv4UInt32 $number) | Should Be $ip + $prefix = $random.Next(8, 33) + $block = [uint64][math]::Pow(2, (32 - $prefix)) + $network = [uint64]([math]::Floor($number / $block) * $block) + $details = Get-IPv4NetworkDetails -IPAddress $ip -PrefixLength $prefix + $details.NetworkValue | Should Be $network + $details.BroadcastValue | Should Be ($network + $block - 1) + foreach ($gateway in @(Get-SuggestedGateway -IPAddress $ip -PrefixLength $prefix)) { + $gw = ConvertTo-IPv4UInt32 $gateway + ($gw -ge $network -and $gw -le ($network + $block - 1) -and $gateway -ne $ip) | Should Be $true + } + } + } + It 'accepts every supported dotted mask and rejects holes in its bits' { + for ($prefix = 8; $prefix -le 32; $prefix++) { + $bits = ('1' * $prefix).PadRight(32, '0') + $mask = @(0..3 | ForEach-Object { [Convert]::ToInt32($bits.Substring($_ * 8, 8), 2) }) -join '.' + (Get-PrefixLength $mask) | Should Be $prefix + (Get-PrefixLength ("/$prefix")) | Should Be $prefix + } + foreach ($mask in @('255.0.255.0', '255.255.255.1', '7', '33', '-1')) { { Get-PrefixLength $mask } | Should Throw } + } + It 'handles zero and maximum unsigned IPv4 boundaries' { + (ConvertFrom-IPv4UInt32 0) | Should Be '0.0.0.0' + (ConvertFrom-IPv4UInt32 4294967295) | Should Be '255.255.255.255' + } + } + Context 'Profiles and saved adapter state' { + BeforeEach { + $profilesPath = Join-Path $script:caseRoot 'profiles'; New-Item -ItemType Directory -Path $profilesPath -Force | Out-Null + $configPath = Join-Path $script:caseRoot 'legacy.xml' + $interfacePath = Join-Path $script:caseRoot 'adapter.txt' + } + It 'ignores corrupt profiles and sorts valid profiles by group and name' { + @{ Name = 'Z'; Environment = 'work'; IPAddress = '10.0.0.2' } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $profilesPath 'z.json') + @{ Name = 'A'; Environment = 'home'; IPAddress = '10.0.0.3' } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $profilesPath 'a.json') + '{broken' | Set-Content -LiteralPath (Join-Path $profilesPath 'bad.json') + $profiles = @(Get-IPProfiles) + $profiles.Count | Should Be 2 + $profiles[0].Name | Should Be 'A' + } + It 'keeps the existing profile on malformed replacement and removes temporary files' { + $path = Join-Path $profilesPath 'profile.json' + Write-IPProfileFile -Path $path -Json '{"Name":"original"}' + { Write-IPProfileFile -Path $path -Json '{invalid' } | Should Throw + (Get-Content -LiteralPath $path -Raw | ConvertFrom-Json).Name | Should Be 'original' + @(Get-ChildItem -LiteralPath $profilesPath -Force | Where-Object Name -like '.*').Count | Should Be 0 + } + It 'loads legacy XML only when no modern profiles exist' { + @{ IPAddress = '192.168.1.25'; SubnetMask = '24'; PrimaryDNS = '1.1.1.1' } | Export-Clixml -LiteralPath $configPath + (Get-SavedIPConfig).IPAddress | Should Be '192.168.1.25' + @{ Name = 'modern'; IPAddress = '10.0.0.2'; Environment = 'lab' } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $profilesPath 'modern.json') + $script:replies = @('1') + (Get-SavedIPConfig).Name | Should Be 'modern' + } + It 'preserves a profile when deletion is declined' { + $path = Join-Path $profilesPath 'site.json'; '{"Name":"site"}' | Set-Content -LiteralPath $path + $script:replies = @('d', '1', 'n') + $null = Get-SavedIPConfig + (Test-Path -LiteralPath $path) | Should Be $true + } + It 'deletes only the selected profile after confirmation' { + $path = Join-Path $profilesPath 'site.json'; '{"Name":"site"}' | Set-Content -LiteralPath $path + $script:replies = @('d', '1', 'y') + $null = Get-SavedIPConfig + (Test-Path -LiteralPath $path) | Should Be $false + } + It 'rejects overflow and out-of-range profile selections without deleting anything' { + '{"Name":"site"}' | Set-Content -LiteralPath (Join-Path $profilesPath 'site.json') + foreach ($choice in @('0', '-1', '2147483648', '999999999999999999999')) { + $script:replies = @($choice); $script:replyIndex = 0 + (Get-SavedIPConfig) | Should BeNullOrEmpty + } + @(Get-ChildItem -LiteralPath $profilesPath).Count | Should Be 1 + } + It 'persists and reloads an adapter name containing spaces' { + Save-SelectedInterface -InterfaceName 'Lab Ethernet' + (Get-SavedInterface) | Should Be 'Lab Ethernet' + } + } + Context 'Retention, backup naming, and log queries' { + It 'retains newest files, removes expired files, and leaves unrelated files intact' { + $root = Join-Path $script:caseRoot 'retention'; New-Item -ItemType Directory -Path $root | Out-Null + foreach ($i in 1..5) { + $path = Join-Path $root ("backup_$i.json"); '{}' | Set-Content -LiteralPath $path + (Get-Item -LiteralPath $path).LastWriteTime = (Get-Date).AddDays(-$i) + } + $expired = Join-Path $root 'backup_old.json'; '{}' | Set-Content -LiteralPath $expired + (Get-Item -LiteralPath $expired).LastWriteTime = (Get-Date).AddDays(-60) + 'keep' | Set-Content -LiteralPath (Join-Path $root 'unrelated.txt') + (Remove-OldFiles -Path $root -Filter 'backup_*.json' -KeepNewest 2 -MaxAgeDays 30) | Should Be 4 + @(Get-ChildItem -LiteralPath $root -Filter 'backup_*.json').Count | Should Be 2 + (Test-Path -LiteralPath (Join-Path $root 'unrelated.txt')) | Should Be $true + } + It 'uses unique managed backup names even for rapid consecutive requests' { + $script:BackupsPath = Join-Path $script:caseRoot 'backups' + $names = @(1..100 | ForEach-Object { New-ManagedBackupPath -BaseName network -Extension json }) + @($names | Select-Object -Unique).Count | Should Be 100 + } + It 'rejects reversed or identical log date ranges' { + { Get-NetworkLogEntries -LogPath 'missing' -From ([datetime]'2026-01-02') -Until ([datetime]'2026-01-01') } | Should Throw + { Get-NetworkLogEntries -LogPath 'missing' -From ([datetime]'2026-01-01') -Until ([datetime]'2026-01-01') } | Should Throw + } + } + Context 'Privacy consent and vendor lookup' { + It 'does not interpret a string false as logging consent' { + $script:ConsentPath = Join-Path $script:caseRoot 'consent.json' + '{"LoggingConsent":"false","PseudonymizeData":false}' | Set-Content -LiteralPath $script:ConsentPath + $script:replies = @('n') + Get-GDPRConsent + ($script:LoggingConsent -is [bool] -and -not $script:LoggingConsent) | Should Be $true + } + It 'asks for consent again after corrupt consent data' { + $script:ConsentPath = Join-Path $script:caseRoot 'consent.json' + '{broken' | Set-Content -LiteralPath $script:ConsentPath + $script:replies = @('n') + Get-GDPRConsent + $script:LoggingConsent | Should Be $false + $script:replyIndex | Should Be 1 + } + It 'rejects malformed MAC addresses without calling an external service' { + foreach ($mac in @(' ', 'not-a-mac', '00112233445566', 'GG1122334455')) { (Get-MACVendor $mac) | Should Be 'Invalid MAC' } + } + It 'normalizes MAC formats and uses a vendor-prefix cache' { + $script:MACVendorCache = @{ '001122' = 'Synthetic Vendor' } + foreach ($mac in @('00:11:22:33:44:55', '00-11-22-33-44-66', '0011.2233.4477', '001122334488')) { (Get-MACVendor $mac) | Should Be 'Synthetic Vendor' } + } + It 'deletes only logs and consent after approval, preserving profiles and backups' { + $script:AppDataDir = Join-Path $script:caseRoot 'privacy'; New-Item -ItemType Directory -Path $script:AppDataDir | Out-Null + $script:LogFileName = 'network_config.log'; $script:LogFile = Join-Path $script:AppDataDir $script:LogFileName + $script:ConsentPath = Join-Path $script:AppDataDir 'consent.json' + $profile = Join-Path $script:AppDataDir 'profile.json'; $backup = Join-Path $script:AppDataDir 'backup.json' + foreach ($path in @($script:LogFile, ($script:LogFile + '.1.log'), $script:ConsentPath, $profile, $backup)) { '{}' | Set-Content -LiteralPath $path } + $script:replies = @('y'); $script:LoggingConsent = $true + Remove-AllLogs + (Test-Path -LiteralPath $script:LogFile) | Should Be $false + (Test-Path -LiteralPath $script:ConsentPath) | Should Be $false + (Test-Path -LiteralPath $profile) | Should Be $true + (Test-Path -LiteralPath $backup) | Should Be $true + $script:LoggingConsent | Should Be $false + } + } + Context 'Diagnostic boundaries without real traffic' { + It 'cancels blank DNS lookup without performing a query' { + Mock Resolve-DnsName { throw 'Unexpected DNS query' } + $script:replies = @('') + $null = Invoke-DNSLookup + Assert-MockCalled Resolve-DnsName -Times 0 -Exactly -Scope It + } + It 'validates DNS server input before querying' { + Mock Resolve-DnsName { throw 'Unexpected DNS query' } + $script:replies = @('example.test', 'A', 'not-an-ip') + $null = Invoke-DNSLookup + Assert-MockCalled Resolve-DnsName -Times 0 -Exactly -Scope It + } + It 'uses the requested DNS server and record type' { + Mock Resolve-DnsName { return $null } + $script:replies = @('example.test', 'AAAA', '9.9.9.9') + $null = Invoke-DNSLookup + Assert-MockCalled Resolve-DnsName -Times 1 -Exactly -Scope It -ParameterFilter { $Name -eq 'example.test' -and $Type -eq 'AAAA' -and $Server -eq '9.9.9.9' } + } + It 'falls back to A for unsupported DNS record types and reports query failure' { + Mock Resolve-DnsName { throw 'Synthetic DNS failure' } + $script:replies = @('example.test', 'INVALID', '') + $null = Invoke-DNSLookup + Assert-MockCalled Resolve-DnsName -Times 1 -Exactly -Scope It -ParameterFilter { $Type -eq 'A' } + Assert-MockCalled Write-Host -Times 1 -Exactly -Scope It -ParameterFilter { $Object -like 'DNS lookup failed:*' } + } + It 'deduplicates valid TCP ports and skips invalid tokens' { + Mock Test-TcpPort { return $false } + $script:replies = @('example.test', '443,443,0,65536,bad,22') + $null = Invoke-PortCheck + Assert-MockCalled Test-TcpPort -Times 2 -Exactly -Scope It + Assert-MockCalled Test-TcpPort -Times 0 -Exactly -Scope It -ParameterFilter { $Port -notin @(22, 443) } + } + It 'does not execute traceroute after blank target input' { + Mock tracert.exe { throw 'Unexpected native traceroute' } + $script:replies = @('') + $null = Invoke-Traceroute + Assert-MockCalled tracert.exe -Times 0 -Exactly -Scope It + } + It 'passes a target as a separate native argument with bounded hop input' { + Mock tracert.exe { } + $script:replies = @('example.test', '999', 'n') + $null = Invoke-Traceroute + Assert-MockCalled tracert.exe -Times 1 -Exactly -Scope It + } + } + Context 'TCP client resource cleanup' { + $socketCases = @( + @{ Mode = 'Connected'; Expected = $true }, @{ Mode = 'Refused'; Expected = $false }, + @{ Mode = 'Timeout'; Expected = $false }, @{ Mode = 'Fault'; Expected = $false } + ) + It 'disposes its TCP client after ' -TestCases $socketCases { + param($Mode, $Expected) + $socket = [pscustomobject]@{ Connected = ($Mode -eq 'Connected'); Mode = $Mode; Closed = $false; Disposed = $false } + $socket | Add-Member ScriptMethod ConnectAsync { + param($Computer, $Port) + if ($this.Mode -eq 'Fault') { throw 'Synthetic connect failure' } + $task = [pscustomobject]@{ Mode = $this.Mode } + $task | Add-Member ScriptMethod Wait { param($Timeout) return ($this.Mode -ne 'Timeout') } + return $task + } + $socket | Add-Member ScriptMethod Close { $this.Closed = $true } + $socket | Add-Member ScriptMethod Dispose { $this.Disposed = $true } + $global:NetworkTestSocket = $socket + Mock New-Object { return $global:NetworkTestSocket } -ParameterFilter { $TypeName -eq 'System.Net.Sockets.TcpClient' } + (Test-TcpPort -ComputerName example.test -Port 443) | Should Be $Expected + $socket.Closed | Should Be $true + $socket.Disposed | Should Be $true + Remove-Variable NetworkTestSocket -Scope Global + } + } + Context 'Updates and console rendering' { + It 'does not update after a rejected upgrade' { + $path = Join-Path $script:caseRoot 'Network.ps1'; $old = "# Version: 1.0`nWrite-Output 'old'" + [IO.File]::WriteAllText($path, $old) + $script:VersionPath = Join-Path $script:caseRoot 'version.txt'; '1.0' | Set-Content -LiteralPath $script:VersionPath + $script:ScriptVersion = '1.0' + Mock Invoke-WebRequest { [pscustomobject]@{ Content = "# Version: 2.0`nWrite-Output 'new'" } } + Mock Install-ValidatedScriptUpdate { throw 'Unexpected replacement' } + $script:replies = @('n') + Update-NetworkScript -CurrentScriptPath $path + ([IO.File]::ReadAllText($path)) | Should Be $old + Assert-MockCalled Install-ValidatedScriptUpdate -Times 0 -Exactly -Scope It + } + $badDownloads = @( + @{ Content = ''; Scenario = 'empty' }, @{ Content = 'Write-Output 1'; Scenario = 'missing header' }, + @{ Content = "# Version: nope`nWrite-Output 1"; Scenario = 'invalid version' }, + @{ Content = "# Version: 2.0`nfunction Broken {"; Scenario = 'invalid syntax' }, + @{ Content = "# Version: 1.0`nWrite-Output 1"; Scenario = 'same version' }, + @{ Content = "# Version: 0.5`nWrite-Output 1"; Scenario = 'older version' } + ) + It 'keeps the script for an download' -TestCases $badDownloads { + param($Content, $Scenario) + $path = Join-Path $script:caseRoot 'Network.ps1'; $old = "# Version: 1.0`nWrite-Output 'old'" + [IO.File]::WriteAllText($path, $old) + $script:VersionPath = Join-Path $script:caseRoot 'version.txt'; '1.0' | Set-Content -LiteralPath $script:VersionPath + $script:ScriptVersion = '1.0'; $script:download = $Content + Mock Invoke-WebRequest { [pscustomobject]@{ Content = $script:download } } + Mock Install-ValidatedScriptUpdate { throw 'Unexpected replacement' } + Update-NetworkScript -CurrentScriptPath $path + ([IO.File]::ReadAllText($path)) | Should Be $old + Assert-MockCalled Install-ValidatedScriptUpdate -Times 0 -Exactly -Scope It + } + It 'renders all menu sections and a no-adapter hint without network reads' { + Mock Get-InterfaceStatus { return 'No adapter' } + $script:ScriptVersion = '3.0' + Show-MainMenu -InterfaceName '' + Assert-MockCalled Write-Host -Times 1 -Exactly -Scope It -ParameterFilter { ([string]$Object).Contains('Select an adapter with [6]') } + Assert-MockCalled Write-Host -Times 1 -Exactly -Scope It -ParameterFilter { $Object -eq 'Logging off' } + } + It 'returns from monitoring when no adapter is selected' { + $script:replies = @('') + Start-LiveInterfaceMonitor -InterfaceName '' + $script:replyIndex | Should Be 1 + } + } +} diff --git a/Debug/Network_Transactions.Tests.ps1 b/Debug/Network_Transactions.Tests.ps1 new file mode 100644 index 0000000..0871ea7 --- /dev/null +++ b/Debug/Network_Transactions.Tests.ps1 @@ -0,0 +1,195 @@ +#Requires -Version 5.1 +param([string]$TestLibraryPath) +. (Join-Path $PSScriptRoot 'NetworkTestHarness.ps1') -TestLibraryPath $TestLibraryPath + +function Set-TestStartingMode { + param($Mode) + Reset-TestState + $script:renewSuccess = $true + $script:releaseDhcpOnDisable = $true + $script:noMatchesError = $true + switch ($Mode) { + DHCP { + $script:dhcp = 'Enabled' + $script:addresses = @($script:addresses | Where-Object Store -eq 'ActiveStore') + $script:addresses[0].PrefixOrigin = 'Dhcp' + } + APIPA { + $script:dhcp = 'Enabled' + $script:addresses = @($script:addresses | Where-Object Store -eq 'ActiveStore') + $script:addresses[0].IPAddress = '169.254.5.10'; $script:addresses[0].PrefixOrigin = 'WellKnown' + } + Empty { $script:addresses = @() } + ActiveOnly { $script:addresses = @($script:addresses | Where-Object Store -eq 'ActiveStore') } + SavedOnly { $script:addresses = @($script:addresses | Where-Object Store -eq 'PersistentStore') } + Multiple { + New-NetIPAddress -InterfaceAlias Ethernet -IPAddress '192.168.1.60' -PrefixLength 24 -SkipAsSource $true + } + StalePersistentRoute { + foreach ($route in @($script:routes | Where-Object { $_.InterfaceAlias -eq 'Ethernet' -and $_.DestinationPrefix -eq '0.0.0.0/0' -and $_.Store -eq 'PersistentStore' })) { $route.NextHop = '192.168.1.253' } + } + } + $script:mutations = 0; $script:operations = @() +} +function Get-ManualAddressFingerprint { + @($script:addresses | Where-Object PrefixOrigin -eq 'Manual' | ForEach-Object { "$($_.InterfaceAlias)|$($_.Store)|$($_.IPAddress)|$($_.PrefixLength)|$($_.SkipAsSource)" } | Sort-Object) -join ';' +} +function Get-RouteFingerprint { + @($script:routes | Where-Object Protocol -eq 'NetMgmt' | ForEach-Object { "$($_.InterfaceAlias)|$($_.Store)|$($_.DestinationPrefix)|$($_.NextHop)|$($_.RouteMetric)" } | Sort-Object) -join ';' +} +$modes = @('Static', 'DHCP', 'APIPA', 'Empty', 'ActiveOnly', 'SavedOnly', 'Multiple', 'StalePersistentRoute') +$successCases = @($modes | ForEach-Object { @{ Mode = $_ } }) +$failureCases = @(foreach ($mode in $modes) { foreach ($failure in @('Address', 'Gateway', 'DNS', 'FinalState')) { @{ Mode = $mode; Failure = $failure } } }) + +Describe 'IPv4 transaction state matrix' { + BeforeEach { + Mock Write-Host { } + Mock Out-Host { } + Mock Test-IPConflict { return $false } + } + It 'applies and persists static configuration from ' -TestCases $successCases { + param($Mode) + Set-TestStartingMode $Mode + $otherRoutes = @($script:routes | Where-Object InterfaceAlias -eq 'Wi-Fi' | ConvertTo-Json -Compress) + (Set-StaticIP @settings) | Should Be $true + @($script:addresses | Where-Object IPAddress -eq '192.168.1.25').Count | Should Be 2 + @($script:addresses | Where-Object InterfaceAlias -eq 'Ethernet').Count | Should Be 2 + @($script:routes | Where-Object { $_.InterfaceAlias -eq 'Ethernet' -and $_.DestinationPrefix -eq '0.0.0.0/0' -and $_.NextHop -eq '192.168.1.1' }).Count | Should Be 2 + (@($script:routes | Where-Object InterfaceAlias -eq 'Wi-Fi' | ConvertTo-Json -Compress) -join '') | Should Be ($otherRoutes -join '') + ($script:dns -join ',') | Should Be '1.1.1.1,1.0.0.1' + $script:dhcp | Should Be 'Disabled' + } + It 'restores state after failure' -TestCases $failureCases { + param($Mode, $Failure) + Set-TestStartingMode $Mode + $addressesBefore = Get-ManualAddressFingerprint + $routesBefore = Get-RouteFingerprint + $dhcpBefore = $script:dhcp + switch ($Failure) { + Address { $script:failOperation = 'NewAddress'; $script:failTarget = '192.168.1.25'; $script:failCount = 2 } + Gateway { $script:routeFailure = $true } + DNS { $script:dnsFailure = $true } + FinalState { $script:finalMismatch = $true } + } + (Set-StaticIP @settings) | Should Be $false + (Get-ManualAddressFingerprint) | Should Be $addressesBefore + (Get-RouteFingerprint) | Should Be $routesBefore + $script:dhcp | Should Be $dhcpBefore + ($script:dns -join ',') | Should Be '9.9.9.9' + } + It 'creates the replacement address before deleting a different working address' { + Set-TestStartingMode Static + (Set-StaticIP @settings) | Should Be $true + $newIndex = -1; $removeIndex = -1 + for ($i = 0; $i -lt $script:operations.Count; $i++) { + if ($newIndex -lt 0 -and $script:operations[$i].Name -eq 'NewAddress') { $newIndex = $i } + if ($removeIndex -lt 0 -and $script:operations[$i].Name -eq 'RemoveAddress' -and $script:operations[$i].Target -eq '192.168.1.50') { $removeIndex = $i } + } + ($newIndex -ge 0 -and $removeIndex -gt $newIndex) | Should Be $true + } + $routeStoreCases = @(@{ Store = 'ActiveStore' }, @{ Store = 'PersistentStore' }, @{ Store = 'Neither' }) + It 'creates a durable gateway when the requested route initially exists in ' -TestCases $routeStoreCases { + param($Store) + Set-TestStartingMode DHCP + $script:routes = @($script:routes | Where-Object { $_.InterfaceAlias -ne 'Ethernet' -or $_.DestinationPrefix -ne '0.0.0.0/0' }) + if ($Store -ne 'Neither') { + $script:routes += [pscustomobject]@{ InterfaceAlias = 'Ethernet'; DestinationPrefix = '0.0.0.0/0'; NextHop = '192.168.1.1'; Store = $Store; Protocol = 'NetMgmt'; RouteMetric = 42 } + } + (Set-StaticIP @settings) | Should Be $true + @($script:routes | Where-Object { $_.InterfaceAlias -eq 'Ethernet' -and $_.DestinationPrefix -eq '0.0.0.0/0' }).Count | Should Be 2 + @($script:operations | Where-Object { $_.Name -eq 'NewRoute' -and $_.Store -eq 'PersistentStore' }).Count | Should Be 0 + } + $recoveryRouteCases = @(@{ Store = 'ActiveStore' }, @{ Store = 'PersistentStore' }, @{ Store = 'DifferentMetrics' }) + It 'restores original route stores and metrics after DNS failure from ' -TestCases $recoveryRouteCases { + param($Store) + Set-TestStartingMode Static + if ($Store -eq 'DifferentMetrics') { + foreach ($route in @($script:routes | Where-Object { $_.InterfaceAlias -eq 'Ethernet' -and $_.Store -eq 'ActiveStore' })) { $route.RouteMetric = 73 } + } else { + $script:routes = @($script:routes | Where-Object { $_.InterfaceAlias -ne 'Ethernet' -or $_.Store -eq $Store }) + } + $original = Get-RouteFingerprint + $script:dnsFailure = $true + (Set-StaticIP @settings) | Should Be $false + (Get-RouteFingerprint) | Should Be $original + } + It 'shows the underlying gateway provider failure on the console' { + Set-TestStartingMode DHCP + $script:routeFailure = $true + (Set-StaticIP @settings) | Should Be $false + Assert-MockCalled Write-Host -Scope It -Times 1 -Exactly -ParameterFilter { $Object -like '*[[]ERROR[]] Gateway*Injected gateway failure*' } + } + It 'does not create addresses or routes when reapplying identical durable settings' { + Set-TestStartingMode Static + (Set-StaticIP @settings) | Should Be $true + $script:operations = @() + (Set-StaticIP @settings) | Should Be $true + @($script:operations | Where-Object { $_.Name -in @('NewAddress', 'NewRoute', 'RemoveAddress', 'RemoveRoute') }).Count | Should Be 0 + } + It 'recovers from a transient address creation failure with exactly two attempts' { + Set-TestStartingMode Static + $script:failOperation = 'NewAddress'; $script:failTarget = '192.168.1.25'; $script:failCount = 1 + (Set-StaticIP @settings) | Should Be $true + @($script:operations | Where-Object { $_.Name -eq 'NewAddress' -and $_.Target -eq '192.168.1.25' }).Count | Should Be 2 + } + It 'removes both default-route stores when a profile requests no gateway' { + Set-TestStartingMode StalePersistentRoute + $request = $settings.Clone(); $request.Gateway = $null + (Set-StaticIP @request) | Should Be $true + @($script:routes | Where-Object { $_.InterfaceAlias -eq 'Ethernet' -and $_.DestinationPrefix -eq '0.0.0.0/0' }).Count | Should Be 0 + @($script:routes | Where-Object DestinationPrefix -eq '10.0.0.0/8').Count | Should Be 2 + } + It 'returns false and reports failed recovery instead of success when recovery also fails' { + Set-TestStartingMode Static + $script:routeFailure = $true; $script:removeFailure = $true + (Set-StaticIP @settings) | Should Be $false + Assert-MockCalled Write-Host -Times 1 -Exactly -Scope It -ParameterFilter { $Object -like '*Recovery incomplete*' } + } + It 'does not mutate an adapter under WhatIf' { + Set-TestStartingMode Static + (Set-StaticIP @settings -WhatIf) | Should Be $false + $script:mutations | Should Be 0 + (Set-DHCP -InterfaceName Ethernet -WhatIf) | Should Be $false + $script:mutations | Should Be 0 + } + It 'does not mutate without a usable snapshot' { + Set-TestStartingMode Static + $script:backupFailure = $true + (Set-StaticIP @settings) | Should Be $false + (Set-DHCP -InterfaceName Ethernet -Confirm:$false) | Should Be $false + $script:mutations | Should Be 0 + } + It 'cancels a reported conflict without touching configuration' { + Set-TestStartingMode Static + Mock Test-IPConflict { return $true } + Mock Read-YesNo { return $false } + $null = Set-StaticIP @settings + $script:mutations | Should Be 0 + } +} + +$invalidCases = @( + @{ Field = 'IPAddress'; Value = '192.168.1.256' }, @{ Field = 'IPAddress'; Value = '192.168.1.0' }, + @{ Field = 'IPAddress'; Value = '192.168.1.255' }, @{ Field = 'IPAddress'; Value = '192.168.1.1' }, + @{ Field = 'SubnetMask'; Value = '255.0.255.0' }, @{ Field = 'SubnetMask'; Value = '33' }, + @{ Field = 'Gateway'; Value = '10.0.0.1' }, @{ Field = 'Gateway'; Value = '192.168.1.0' }, + @{ Field = 'Gateway'; Value = '192.168.1.255' }, @{ Field = 'PrimaryDNS'; Value = 'bad' }, + @{ Field = 'SecondaryDNS'; Value = '2001:db8::1' } +) +Describe 'Transaction validation boundaries' { + BeforeEach { Mock Write-Host { }; Mock Test-IPConflict { return $false }; Set-TestStartingMode Static } + It 'rejects value before mutation' -TestCases $invalidCases { + param($Field, $Value) + $request = $settings.Clone(); $request[$Field] = $Value + $null = Set-StaticIP @request + $script:mutations | Should Be 0 + } + It 'accepts a /31 peer gateway' { + $request = $settings.Clone(); $request.IPAddress = '192.168.1.10'; $request.SubnetMask = '31'; $request.Gateway = '192.168.1.11' + (Set-StaticIP @request) | Should Be $true + } + It 'accepts a /32 address without a gateway' { + $request = $settings.Clone(); $request.IPAddress = '192.168.1.10'; $request.SubnetMask = '32'; $request.Gateway = $null + (Set-StaticIP @request) | Should Be $true + } +} diff --git a/Debug/TESTING.md b/Debug/TESTING.md new file mode 100644 index 0000000..5a70d51 --- /dev/null +++ b/Debug/TESTING.md @@ -0,0 +1,79 @@ +# Regression testing + +## Setup + +The application itself needs no third-party PowerShell modules. To run the complete test suite, open Windows PowerShell 5.1 and install the same dependencies pinned in CI from the PowerShell Gallery: + +```powershell +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope CurrentUser -Force +Install-Module Pester -RequiredVersion 4.10.1 -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck +Install-Module PSScriptAnalyzer -RequiredVersion 1.25.0 -Scope CurrentUser -Force +``` + +These commands install modules for the current user. The tests do not require administrator elevation. The runner supports Pester 3.4 and 4.x and selects the highest compatible installed version; Pester 5 alone will not satisfy the dependency. + +The pinned Pester install uses `-SkipPublisherCheck` to allow its older signing certificate chain alongside preinstalled Pester 5. This bypasses PowerShellGet's comparison with the installed module's publisher certificate. + +## Run + +Run from the repository root: + +```powershell +powershell -NoProfile -ExecutionPolicy Bypass -File .\Debug\test_regression.ps1 +``` + +The runner uses Windows PowerShell 5.1, Pester 3.4 or 4.x, and PSScriptAnalyzer. CI installs pinned Pester 4.10.1 and PSScriptAnalyzer 1.25.0. Each suite runs in a separate process, with a five-minute timeout and a nonzero exit status on failure. Missing dependencies, missing suites, empty Pester suites, skipped or pending tests, crashes, and timeouts fail the run. The runner continues collecting results after individual failures. + +## Coverage + +The suite includes existing privacy, updater, network math, export, profiles, and log-query regressions, plus named Pester cases for: + +- Static, DHCP, APIPA, empty, asymmetric address stores, multiple addresses, and stale persistent routes. +- Address, gateway, DNS, and final verification failures in each starting state, with rollback comparisons. +- Repeated applies, operation ordering, transient retries, gateway-free profiles, incomplete recovery, snapshot failure, conflict cancellation, and WhatIf. +- Durable route creation with the documented dual-store default, active-route collisions, asymmetric route stores, differing recovery metrics, and visible gateway provider errors. The route mock rejects explicit PersistentStore creation. +- Input validation, subnet arithmetic, narrow subnets, prompt cancellation, corrupt profiles, file retention, unique backups, consent types, MAC cache, DNS and traceroute boundaries, TCP resource cleanup, update rejection, and console guards. +- Runner crash, missing-suite, empty-suite, timeout, and successful-suite reporting. + +Networking and external-service boundaries are mocked. Tests do not change real adapter settings. Filesystem cases use isolated fixtures beneath the ignored `Debug/test-results` directory. + +Results include `summary.json`, per-suite logs, Pester JSON and JUnit XML. Pester command coverage uses a generated function-only copy of the application, preserving original line numbers. Startup and the interactive menu loop are excluded from execution. Coverage counts describe commands exercised by those Pester suites; they are not a claim of complete behavioral coverage. Standalone regressions exercise additional code without contributing to those counts. + +## Release validation + +### Observed results + +As of 2026-10-06, the latest local Windows PowerShell 5.1 run passed all 11 suites: 62 core Pester cases, 68 transaction Pester cases, seven standalone regression suites, static checks, and runner self-tests. Local Pester was 3.4.0; the CI configuration targets 4.10.1. A CI run is not established by these local results. + +User-provided Proxmox Windows VM transcripts confirm: + +- Profile static reapplication and manual static reapplication with changed DNS. +- Static-to-DHCP conversion, obtaining `192.168.1.59`. +- DHCP-to-static profile application, obtaining `192.168.1.25/24`, gateway `192.168.1.1`, DNS `1.1.1.1, 9.9.9.9`, and DHCP disabled, with final verification passing. +- Successful recovery reported after a failed gateway apply. The transcript does not independently verify the restored state. + +Windows build, NIC model, and driver version were not supplied. These observations confirm the reported workflows on that guest; they do not complete the entire checklist below. + +### Live validation checklist + +Automation cannot cover every Windows driver, timing race, DHCP server, or hypervisor. Use a disposable Windows guest with a VM snapshot and console access. Record Windows build, PowerShell version, NIC model, and driver version; test VirtIO and an emulated NIC where available. + +Status reflects user-provided guest transcripts as of 2026-10-06. **Confirmed** means the listed workflow succeeded on that guest; **Partial** means some observations or variants remain unverified; **Pending** means no live evidence has been recorded. + +| Check | Status | Evidence or remaining work | +| --- | --- | --- | +| Profile and manual static reapplication | Confirmed | Both succeeded; manual reapplication changed DNS. | +| Changed address and same-address prefix changes | Pending | Exercise both changes and inspect resulting stores. | +| Static-to-DHCP and DHCP-to-static | Confirmed | DHCP acquired `.59`; the static profile restored `.25/24`, gateway, DNS order, and disabled DHCP. | +| Lease origin and address readiness | Partial | Application verification passed; capture raw provider state independently. | +| Multiple adapters with default routes | Pending | Verify the other adapter's addresses, routes, metrics, and DNS remain unchanged. | +| Stale persistent routes and gateway-free profiles | Pending | Verify obsolete defaults disappear and custom routes remain. | +| Reboot persistence | Pending | Inspect address, route, and DNS state after reboot. | +| Recovery after gateway failure | Partial | Successful recovery banner observed; verify exact restored state. | +| Failed DHCP renewal and manual DNS recovery | Pending | Exercise failed renewal and static-apply recovery with a manual DNS override. | +| Duplicate addresses, reconnects, and slow DAD | Pending | Verify failure/recovery and absence of false success banners. | +| IPv6 DNS preservation | Pending | Compare before/after static apply, DHCP conversion, and recovery. | + +Record before/after address, route, DHCP, and DNS state, including ActiveStore and PersistentStore. Complete the remaining checks and verify reboot persistence before publishing the release. diff --git a/Debug/invoke_pester_suite.ps1 b/Debug/invoke_pester_suite.ps1 new file mode 100644 index 0000000..a8d000c --- /dev/null +++ b/Debug/invoke_pester_suite.ps1 @@ -0,0 +1,69 @@ +#Requires -Version 5.1 +param( + [Parameter(Mandatory=$true)][string]$TestsPath, + [Parameter(Mandatory=$true)][string]$ResultPath +) +$ErrorActionPreference = 'Stop' +try { + $module = Get-Module -ListAvailable Pester | Where-Object { $_.Version -ge [version]'3.4' -and $_.Version.Major -lt 5 } | + Sort-Object Version -Descending | Select-Object -First 1 + if (-not $module) { throw 'Pester 3.4 or 4.x is required; no tests were run.' } + Import-Module $module.Path -Force + $sourcePath = Join-Path $PSScriptRoot '..\Network_Configuration.ps1' + $sourceErrors = $null + $sourceAst = [System.Management.Automation.Language.Parser]::ParseFile($sourcePath, [ref]$null, [ref]$sourceErrors) + if ($sourceErrors) { throw 'Application source does not parse.' } + # Compile a physical function-only library. Dynamic AST body imports retain a + # filename but do not reliably trigger Pester's file breakpoints (false 0% coverage). + # Preserve original line numbers and omit every startup/menu-loop statement. + $sourceLines = [regex]::Split([IO.File]::ReadAllText($sourcePath), '\r?\n') + $libraryLines = New-Object 'string[]' $sourceLines.Count + foreach ($definition in @($sourceAst.EndBlock.Statements | Where-Object { $_ -is [System.Management.Automation.Language.FunctionDefinitionAst] })) { + for ($line = $definition.Extent.StartLineNumber; $line -le $definition.Extent.EndLineNumber; $line++) { + $libraryLines[$line - 1] = $sourceLines[$line - 1] + } + } + $libraryPath = [IO.Path]::ChangeExtension($ResultPath, '.library.ps1') + [IO.File]::WriteAllLines($libraryPath, $libraryLines, [Text.UTF8Encoding]::new($false)) + $libraryPath = (Resolve-Path -LiteralPath $libraryPath).Path + $pesterScript = @{ Path = (Resolve-Path -LiteralPath $TestsPath).Path; Parameters = @{ TestLibraryPath = $libraryPath } } + $result = Invoke-Pester -Script $pesterScript -PassThru -Quiet -Strict -CodeCoverage $libraryPath + $summary = [ordered]@{ + PesterVersion = [string]$module.Version + Total = $result.TotalCount; Passed = $result.PassedCount; Failed = $result.FailedCount + Skipped = $result.SkippedCount; Pending = $result.PendingCount + Tests = @($result.TestResult | Select-Object Describe, Context, Name, Result, FailureMessage) + Coverage = $result.CodeCoverage + CoverageSource = (Resolve-Path -LiteralPath $sourcePath).Path + } + $summary | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $ResultPath -Encoding UTF8 + # Pester 3's NUnit writer queries Win32_OperatingSystem via CIM. Generate JUnit + # directly so reporting requires no machine/WMI access and escapes test text safely. + $xmlSettings = New-Object System.Xml.XmlWriterSettings + $xmlSettings.Indent = $true + $writer = [System.Xml.XmlWriter]::Create([IO.Path]::ChangeExtension($ResultPath, '.xml'), $xmlSettings) + try { + $writer.WriteStartDocument(); $writer.WriteStartElement('testsuite') + $writer.WriteAttributeString('name', (Split-Path $TestsPath -Leaf)) + $writer.WriteAttributeString('tests', [string]$summary.Total) + $writer.WriteAttributeString('failures', [string]$summary.Failed) + foreach ($test in $summary.Tests) { + $writer.WriteStartElement('testcase'); $writer.WriteAttributeString('name', $test.Name) + $writer.WriteAttributeString('classname', ($test.Describe + '.' + $test.Context)) + if ($test.Result -ne 'Passed') { + $writer.WriteStartElement('failure'); $writer.WriteAttributeString('message', [string]$test.FailureMessage) + $writer.WriteEndElement() + } + $writer.WriteEndElement() + } + $writer.WriteEndElement(); $writer.WriteEndDocument() + } finally { $writer.Dispose() } + Write-Host ("{0}: {1} tests, {2} passed, {3} failed" -f (Split-Path $TestsPath -Leaf), $summary.Total, $summary.Passed, $summary.Failed) + foreach ($failure in @($summary.Tests | Where-Object Result -ne 'Passed')) { Write-Host (" {0}: {1}" -f $failure.Name, $failure.FailureMessage) -ForegroundColor Red } + if ($summary.Total -eq 0 -or $summary.Failed -gt 0 -or $summary.Skipped -gt 0 -or $summary.Pending -gt 0) { exit 1 } + exit 0 +} catch { + @{ Total = 0; Passed = 0; Failed = 1; Error = $_.Exception.Message } | ConvertTo-Json | Set-Content -LiteralPath $ResultPath -Encoding UTF8 + Write-Host $_.Exception.Message -ForegroundColor Red + exit 1 +} diff --git a/Debug/test_network_configuration.ps1 b/Debug/test_network_configuration.ps1 new file mode 100644 index 0000000..8e83e7f --- /dev/null +++ b/Debug/test_network_configuration.ps1 @@ -0,0 +1,155 @@ +#Requires -Version 5.1 +. (Join-Path $PSScriptRoot 'NetworkTestHarness.ps1') +# Exercise the actual conflict checker before replacing it for deterministic transaction tests. +Reset-TestState +Assert-True (-not (Test-IPConflict -InterfaceName Ethernet -IPAddress '192.168.1.50')) 'Self-address reported as conflict' +$script:addresses += [pscustomobject]@{ InterfaceAlias = 'Wi-Fi'; InterfaceIndex = 8; IPAddress = '192.168.1.25'; AddressState = 'Preferred'; Store = 'ActiveStore' } +Assert-True (Test-IPConflict -InterfaceName Ethernet -IPAddress '192.168.1.25') 'Other local adapter ownership missed' +function New-Object { + param($TypeName) + Assert-True ($TypeName -eq 'System.Net.NetworkInformation.Ping') 'Unexpected object construction in conflict test' + $probe = [pscustomobject]@{} + $probe | Add-Member -MemberType ScriptMethod -Name Send -Value { param($Address, $Timeout) } + $probe | Add-Member -MemberType ScriptMethod -Name Dispose -Value { } + return $probe +} +Reset-TestState +$script:neighbors = @( + [pscustomobject]@{ InterfaceIndex = 7; IPAddress = '192.168.1.250'; State = 'Reachable'; LinkLayerAddress = '00-11-22-33-44-55' }, + [pscustomobject]@{ InterfaceIndex = 8; IPAddress = '192.168.1.25'; State = 'Reachable'; LinkLayerAddress = '00-11-22-33-44-55' } +) +Assert-True (-not (Test-IPConflict -InterfaceName Ethernet -IPAddress '192.168.1.25')) 'Unrelated IP or other-interface neighbor reported as conflict' +$script:neighbors += [pscustomobject]@{ InterfaceIndex = 7; IPAddress = '192.168.1.25'; State = 'Incomplete'; LinkLayerAddress = '00-00-00-00-00-00' } +Assert-True (-not (Test-IPConflict -InterfaceName Ethernet -IPAddress '192.168.1.25')) 'Incomplete neighbor reported as conflict' +$script:neighbors += [pscustomobject]@{ InterfaceIndex = 7; IPAddress = '192.168.1.25'; State = 'Reachable'; LinkLayerAddress = '00-11-22-33-44-55' } +Assert-True (Test-IPConflict -InterfaceName Ethernet -IPAddress '192.168.1.25') 'Exact neighbor conflict missed' +Remove-Item Function:\New-Object +function Test-IPConflict { param($InterfaceName, $IPAddress) return $false } + +Reset-TestState +Assert-True (Set-StaticIP @settings) 'Static apply failed with other adapter and existing persistent gateway' +Assert-True (@($script:routes | Where-Object { $_.InterfaceAlias -eq 'Wi-Fi' }).Count -eq 2) 'Other adapter routes changed' +Assert-True (@($script:routes | Where-Object DestinationPrefix -eq '10.0.0.0/8').Count -eq 2) 'Custom route removed' +Assert-True (@($script:addresses | Where-Object IPAddress -eq '192.168.1.25').Count -eq 2) 'New address not persisted' +Assert-True (Set-StaticIP @settings) 'Reapplying same configuration failed' +$noGateway = $settings.Clone(); $noGateway.Gateway = $null +Assert-True (Set-StaticIP @noGateway) 'Gateway-free apply failed' +Assert-True (-not ($script:routes | Where-Object { $_.InterfaceAlias -eq 'Ethernet' -and $_.DestinationPrefix -eq '0.0.0.0/0' })) 'Gateway-free profile retained gateway' + +foreach ($failure in @('partialAdd', 'duplicate', 'dnsFailure', 'routeFailure', 'backupFailure', 'finalMismatch')) { + Reset-TestState + Set-Variable -Name $failure -Value $true -Scope Script + $result = Set-StaticIP @settings + if ($failure -eq 'partialAdd') { + Assert-True $result 'Partial successful address creation was not reconciled on retry' + } else { + Assert-True (-not $result) "Failure $failure reported success" + Assert-True (@($script:addresses | Where-Object IPAddress -eq '192.168.1.50').Count -eq 2) "Failure $failure did not restore old static address" + Assert-True (($script:dns -join ',') -eq '9.9.9.9') "Failure $failure did not restore DNS" + Assert-True (@($script:routes | Where-Object { $_.InterfaceAlias -eq 'Ethernet' -and $_.NextHop -eq '192.168.1.254' -and $_.RouteMetric -eq 42 }).Count -eq 2) "Failure $failure did not restore gateway metrics" + if ($failure -eq 'backupFailure') { Assert-True ($script:mutations -eq 0) 'Modified adapter without backup' } + } +} +Reset-TestState +$script:addresses[1].PrefixLength = 25; $script:addresses[1].SkipAsSource = $true +$script:addresses += [pscustomobject]@{ InterfaceAlias = 'Ethernet'; InterfaceIndex = 7; IPAddress = '192.168.1.99'; PrefixLength = 32; PrefixOrigin = 'Manual'; AddressState = 'Invalid'; SkipAsSource = $true; Store = 'PersistentStore' } +$script:routeFailure = $true +Assert-True (-not (Set-StaticIP @settings)) 'Route failure with asymmetric address stores reported success' +Assert-True (@($script:addresses | Where-Object { $_.IPAddress -eq '192.168.1.50' -and $_.Store -eq 'ActiveStore' -and $_.PrefixLength -eq 24 -and -not $_.SkipAsSource }).Count -eq 1) 'Original active address was not restored' +Assert-True (@($script:addresses | Where-Object { $_.IPAddress -eq '192.168.1.50' -and $_.Store -eq 'PersistentStore' -and $_.PrefixLength -eq 25 -and $_.SkipAsSource }).Count -eq 1) 'Original persistent address was not restored' +Assert-True (@($script:addresses | Where-Object IPAddress -eq '192.168.1.99').Count -eq 1 -and ($script:addresses | Where-Object IPAddress -eq '192.168.1.99').Store -eq 'PersistentStore') 'Saved-only address was not restored' +Reset-TestState +$sameAddress = $settings.Clone(); $sameAddress.IPAddress = '192.168.1.50'; $sameAddress.SubnetMask = '25' +Assert-True (Set-StaticIP @sameAddress) 'Changing prefix on same address failed' +Assert-True (@($script:addresses | Where-Object { $_.IPAddress -eq '192.168.1.50' -and $_.PrefixLength -eq 25 }).Count -eq 2) 'New prefix not persisted' +Reset-TestState +$script:addresses = @($script:addresses | Where-Object Store -eq 'ActiveStore') +$existing = $settings.Clone(); $existing.IPAddress = '192.168.1.50' +Assert-True (Set-StaticIP @existing) 'Active-only existing address was not made persistent' +Reset-TestState +$script:addresses[0].AddressState = 'Tentative' +try { Wait-IPv4AddressReady -InterfaceName Ethernet -IPAddress '192.168.1.50' -PrefixLength 24 -TimeoutSeconds 0; throw 'Tentative address accepted' } catch { if ($_.Exception.Message -eq 'Tentative address accepted') { throw } } +Reset-TestState +Assert-True (-not (Set-StaticIP @settings -WhatIf)) 'WhatIf reported applied' +Assert-True ($script:mutations -eq 0) 'WhatIf modified adapter' +$invalid = $settings.Clone(); $invalid.Gateway = '10.0.0.1' +Assert-True (-not (Set-StaticIP @invalid)) 'Invalid gateway was accepted' +Assert-True ($script:mutations -eq 0) 'Validation failure modified adapter' +Reset-TestState +Assert-True (-not (Set-DHCP -InterfaceName Ethernet -MaxRetries 1 -Confirm:$false)) 'Failed DHCP renewal reported success' +Assert-True (@($script:addresses | Where-Object IPAddress -eq '192.168.1.50').Count -eq 2) 'DHCP failure lost old static address' +Reset-TestState +$script:renewSuccess = $true +Assert-True (Set-DHCP -InterfaceName Ethernet -MaxRetries 1 -Confirm:$false) 'Successful DHCP lease was rejected' +Assert-True ($script:dhcp -eq 'Enabled') 'DHCP not enabled' +Assert-True (-not ($script:routes | Where-Object { $_.InterfaceAlias -eq 'Ethernet' -and $_.DestinationPrefix -eq '0.0.0.0/0' })) 'Static gateway retained after DHCP' +$script:releaseDhcpOnDisable = $true; $script:noMatchesError = $true +Assert-True (Set-StaticIP @settings) 'DHCP-to-static failed when disabling DHCP removed its lease and CIM reported no matches' +Assert-True ($script:dhcp -eq 'Disabled' -and @($script:addresses | Where-Object IPAddress -eq '192.168.1.25').Count -eq 2) 'DHCP-to-static did not apply and persist the target address' +Reset-TestState +$script:renewSuccess = $true; $script:acknowledgedNoLease = $true +Assert-True (-not (Set-DHCP -InterfaceName Ethernet -MaxRetries 1 -Confirm:$false)) 'CIM success without a Preferred lease reported success' +Assert-True (@($script:addresses | Where-Object IPAddress -eq '192.168.1.50').Count -eq 2) 'Missing DHCP lease lost the previous static settings' +Reset-TestState +$script:renewSuccess = $true; $script:routeFailure = $true; $script:dhcp = 'Enabled' +$script:releaseDhcpOnDisable = $true; $script:noMatchesError = $true +$script:addresses = @($script:addresses | Where-Object Store -eq 'ActiveStore') +$script:addresses[0].PrefixOrigin = 'Dhcp' +$script:renewDelayQueries = 3 +Assert-True (-not (Set-StaticIP @settings)) 'Failed DHCP-to-static gateway apply reported success' +Assert-True ($script:dhcp -eq 'Enabled') 'DHCP-to-static failure did not restore DHCP' +Assert-True (-not ($script:addresses | Where-Object IPAddress -eq '192.168.1.25')) 'Partial static address remained after DHCP rollback' +Assert-True (($script:dns -join ',') -eq '9.9.9.9') 'DHCP rollback lost static DNS override' +Reset-TestState +$script:addresses = @(); $script:noMatchesError = $true +Assert-True (@(Get-IPv4StoreState -InterfaceName Ethernet -Kind Address).Count -eq 0) 'CIM no-match was not treated as an empty address store' +try { + Wait-IPv4AddressReady -InterfaceName Ethernet -IPAddress '192.168.1.25' -PrefixLength 24 -TimeoutSeconds 0 + throw 'Missing address passed readiness check' +} catch { + Assert-True ($_.Exception.Message -like '*did not become Preferred*') 'Readiness failed on CIM no-match instead of its bounded timeout' +} +Reset-TestState +$script:readFailure = $true +try { $null = Get-IPv4StoreState -InterfaceName Ethernet -Kind Route; throw 'Read failure swallowed' } catch { if ($_.Exception.Message -eq 'Read failure swallowed') { throw } } +foreach ($failure in @('cimLookupFailure', 'cimIdentityMismatch', 'cimEmpty', 'cimTimeout', 'cimMissingResult')) { + Reset-TestState + Set-Variable -Name $failure -Value $true -Scope Script + try { Invoke-InterfaceDHCPRenewal -InterfaceName Ethernet; throw 'CIM failure was accepted' } catch { if ($_.Exception.Message -eq 'CIM failure was accepted') { throw } } + if ($failure -in @('cimLookupFailure', 'cimIdentityMismatch', 'cimEmpty')) { Assert-True ($script:cimCalls -eq 0) 'Renewed DHCP after identity lookup failed' } +} +foreach ($code in @(1, 64, 82, 91, 100, [uint32]::MaxValue)) { + Reset-TestState + $script:cimReturnCode = $code + try { Invoke-InterfaceDHCPRenewal -InterfaceName Ethernet; throw 'Non-ready CIM result was accepted' } catch { if ($_.Exception.Message -eq 'Non-ready CIM result was accepted') { throw } } +} + +# Test the real snapshot function and its versioned disk representation with mocked reads. +Reset-TestState +$definition = $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true) | Where-Object Name -eq 'Backup-NetworkConfiguration' | Select-Object -First 1 +. ([scriptblock]::Create($definition.Extent.Text)) +$script:snapshotPath = Join-Path $PSScriptRoot ('network_snapshot_test_' + [guid]::NewGuid().ToString('N') + '.json') +function New-ManagedBackupPath { param($BaseName, $Extension) return $script:snapshotPath } +function Invoke-BackupRetention { param($Filter) } +function Get-ItemProperty { [CmdletBinding()]param($LiteralPath) [pscustomobject]@{ NameServer = $script:dnsOverride } } +try { + $script:dnsOverride = '9.9.9.9' + $backup = Backup-NetworkConfiguration -InterfaceName Ethernet + Assert-True ($backup -and -not $backup.DNSAutomatic) 'Snapshot lost explicit DNS mode' + $record = Get-Content -LiteralPath $script:snapshotPath -Raw | ConvertFrom-Json + Assert-True ($record.FormatVersion -eq 2 -and $record.PersistentAddresses.Count -eq 1 -and $record.PersistentRoutes.Count -eq 2) 'Disk backup missing policy-store information' + $script:dnsOverride = '' + Assert-True ((Backup-NetworkConfiguration -InterfaceName Ethernet).DNSAutomatic) 'Automatic DNS mode not captured' + $script:readFailure = $true + Assert-True (-not (Backup-NetworkConfiguration -InterfaceName Ethernet)) 'Snapshot accepted failed network reads' +} finally { if (Test-Path -LiteralPath $script:snapshotPath) { Remove-Item -LiteralPath $script:snapshotPath -Force } } + +# Adapter selection must include a virtual NIC and return when no adapters exist. +function Get-NetAdapter { [CmdletBinding()]param($Name) $script:selectableAdapters } +function Read-Host { return '7' } +function Save-SelectedInterface { param($InterfaceName) } +$script:selectableAdapters = @([pscustomobject]@{ Name = 'Ethernet'; InterfaceIndex = 7; Status = 'Up'; Virtual = $true; InterfaceDescription = 'VMware Virtual Ethernet Adapter'; MacAddress = '00-11-22-33-44-55' }) +Assert-True ((Select-NetworkInterface) -eq 'Ethernet') 'Virtual NIC was excluded from selection' +$script:selectableAdapters = @() +Assert-True (-not (Select-NetworkInterface)) 'Empty adapter inventory did not return' +Write-Host 'Network configuration regression tests passed.' -ForegroundColor Green diff --git a/Debug/test_privacy.ps1 b/Debug/test_privacy.ps1 index ce7c072..0717a75 100644 --- a/Debug/test_privacy.ps1 +++ b/Debug/test_privacy.ps1 @@ -52,6 +52,13 @@ try { $script:LoggingConsent = $false Write-LogMessage -Message 'Address 10.0.0.1' -Level INFO if (@(Get-Content $script:LogFile).Count -ne $entries.Count) { throw 'Logging continued without consent.' } + $script:LoggingConsent = $true + $originalLogPath = $script:LogFile + try { + $script:LogFile = Join-Path ([System.IO.Path]::GetTempPath()) ('missing_' + [guid]::NewGuid().ToString('N') + '\network.log') + Write-LogMessage -Message 'A log write failure must not block adapter recovery' -Level ERROR + if (-not $script:LogWriteFailureReported) { throw 'Log failure was not handled.' } + } finally { $script:LogFile = $originalLogPath } Write-Host 'Privacy masking tests passed.' -ForegroundColor Green } finally { Remove-Item -LiteralPath $script:LogFile -Force -ErrorAction SilentlyContinue diff --git a/Debug/test_regression.ps1 b/Debug/test_regression.ps1 new file mode 100644 index 0000000..222c8a7 --- /dev/null +++ b/Debug/test_regression.ps1 @@ -0,0 +1,79 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Runs all automated checks in separate Windows PowerShell 5.1 processes. +.DESCRIPTION + Aggregates failures, rejects empty/Pending/Skipped Pester runs, and saves JSON, + JUnit XML, command coverage, and per-suite logs. No application startup is executed. +#> +param( + [string]$OutputDirectory = (Join-Path $PSScriptRoot 'test-results'), + [ValidateRange(10,1800)][int]$SuiteTimeoutSeconds = 300, + [string[]]$Suites = @('test_privacy.ps1', 'test_update.ps1', 'test_network_math.ps1', 'test_network_configuration.ps1', + 'test_export.ps1', 'test_profiles.ps1', 'test_log_query.ps1', 'Network_Core.Tests.ps1', 'Network_Transactions.Tests.ps1', 'test_syntax.ps1', 'test_runner_contracts.ps1') +) +$ErrorActionPreference = 'Stop' +$windowsPowerShell = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' +if (-not (Test-Path -LiteralPath $windowsPowerShell)) { throw 'Windows PowerShell 5.1 is required.' } +New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null +$OutputDirectory = (Resolve-Path -LiteralPath $OutputDirectory).Path +if ($Suites.Count -eq 0) { throw 'At least one suite is required.' } +$results = @() +foreach ($suite in $suites) { + $suitePath = Join-Path $PSScriptRoot $suite + $base = [IO.Path]::GetFileNameWithoutExtension($suite) + $logPath = Join-Path $OutputDirectory ($base + '.log') + $errorPath = Join-Path $OutputDirectory ($base + '.stderr.log') + $resultPath = Join-Path $OutputDirectory ($base + '.json') + if (Test-Path -LiteralPath $resultPath) { Remove-Item -LiteralPath $resultPath -Force } + $arguments = @('-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File') + if ($suite -like '*.Tests.ps1') { + $arguments += @((Join-Path $PSScriptRoot 'invoke_pester_suite.ps1'), '-TestsPath', $suitePath, '-ResultPath', $resultPath) + } else { + $arguments += $suitePath + if ($suite -eq 'test_syntax.ps1') { $arguments += '-RequireAnalyzer' } + } + # Start-Process joins arguments on Windows; all paths are quoted as literal values. + $quotedArguments = @($arguments | ForEach-Object { '"' + $_.Replace('"', '\"') + '"' }) + $started = Get-Date + Write-Host "Running $suite..." -ForegroundColor Cyan + try { + if (-not (Test-Path -LiteralPath $suitePath)) { throw "Missing suite $suite" } + $process = Start-Process -FilePath $windowsPowerShell -ArgumentList $quotedArguments -WindowStyle Hidden ` + -RedirectStandardOutput $logPath -RedirectStandardError $errorPath -PassThru + $null = $process.Handle # Retain the handle so Windows PowerShell can read ExitCode after a fast child exits. + $completed = $process.WaitForExit($SuiteTimeoutSeconds * 1000) + if (-not $completed) { $process.Kill(); $process.WaitForExit(); throw "Suite timed out after $SuiteTimeoutSeconds seconds" } + $process.Refresh() + $exitCode = $process.ExitCode + if ($null -eq $exitCode) { throw 'Child process did not report an exit code' } + $record = [ordered]@{ Suite = $suite; ExitCode = $exitCode; Status = $(if ($exitCode -eq 0) { 'Passed' } else { 'Failed' }); DurationSeconds = [math]::Round(((Get-Date) - $started).TotalSeconds, 2) } + if ($suite -like '*.Tests.ps1' -and (Test-Path -LiteralPath $resultPath)) { + $named = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json + $record.Total = $named.Total; $record.Passed = $named.Passed; $record.Failed = $named.Failed + if ($named.Total -eq 0 -or $named.Failed -gt 0 -or $named.Skipped -gt 0 -or $named.Pending -gt 0) { + $record.Status = 'Failed'; $record.ExitCode = 1 + } + } + elseif ($suite -like '*.Tests.ps1') { throw 'Pester child did not produce a result report' } + if ($exitCode -ne 0) { + Get-Content -LiteralPath $logPath -Tail 30 | Out-Host + Get-Content -LiteralPath $errorPath -Tail 20 | Out-Host + } + $results += [pscustomobject]$record + Write-Host " $($record.Status) ($($record.DurationSeconds)s)" + } catch { + $results += [pscustomobject]@{ Suite = $suite; ExitCode = 1; Status = 'Failed'; Error = $_.Exception.Message } + Write-Host " Failed: $_" -ForegroundColor Red + } +} +$summary = [ordered]@{ + Timestamp = (Get-Date).ToString('o'); HostVersion = [string]$PSVersionTable.PSVersion + Suites = $results; FailedSuites = @($results | Where-Object Status -ne 'Passed').Count + NamedTests = ($results | Where-Object { $_.PSObject.Properties['Total'] } | Measure-Object Total -Sum).Sum +} +$summary | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $OutputDirectory 'summary.json') -Encoding UTF8 +$results | Format-Table Suite, Status, Total, DurationSeconds -AutoSize | Out-Host +Write-Host "Reports: $OutputDirectory" +if ($summary.FailedSuites -gt 0) { exit 1 } +exit 0 diff --git a/Debug/test_runner_contracts.ps1 b/Debug/test_runner_contracts.ps1 new file mode 100644 index 0000000..1ce56fe --- /dev/null +++ b/Debug/test_runner_contracts.ps1 @@ -0,0 +1,47 @@ +#Requires -Version 5.1 +# Exercise reporting failure paths with owned disposable child processes and files. +$ErrorActionPreference = 'Stop' +$root = Join-Path $PSScriptRoot ('test-results/runner_contract_' + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root -Force | Out-Null +$windowsPowerShell = Join-Path $env:SystemRoot 'System32/WindowsPowerShell/v1.0/powershell.exe' +$runner = Join-Path $PSScriptRoot 'test_regression.ps1' +$contractsPassed = $false +try { + 'throw "Intentional fixture failure"' | Set-Content -LiteralPath (Join-Path $root 'failure.ps1') + '# Deliberately empty Pester suite' | Set-Content -LiteralPath (Join-Path $root 'empty.Tests.ps1') + 'Start-Sleep -Seconds 90' | Set-Content -LiteralPath (Join-Path $root 'timeout.ps1') + 'exit 0' | Set-Content -LiteralPath (Join-Path $root 'success.ps1') + $cases = @( + @{ File = 'failure.ps1'; Failed = 1 }, @{ File = 'missing.ps1'; Failed = 1 }, + @{ File = 'empty.Tests.ps1'; Failed = 1 }, @{ File = 'timeout.ps1'; Failed = 1 }, + @{ File = 'success.ps1'; Failed = 0 } + ) + foreach ($case in $cases) { + $suite = 'test-results/' + (Split-Path $root -Leaf) + '/' + $case.File + $output = Join-Path $root ($case.File + '_report') + $previousPreference = $ErrorActionPreference + $timeout = 10 + if ($case.File -eq 'empty.Tests.ps1') { $timeout = 60 } + try { + $ErrorActionPreference = 'Continue' + $null = & $windowsPowerShell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $runner ` + -Suites $suite -OutputDirectory $output -SuiteTimeoutSeconds $timeout 2>&1 + } finally { $ErrorActionPreference = $previousPreference } + $code = $LASTEXITCODE + if (($case.Failed -gt 0 -and $code -eq 0) -or ($case.Failed -eq 0 -and $code -ne 0)) { throw "Incorrect runner exit status for $($case.File): $code" } + $summary = Get-Content -LiteralPath (Join-Path $output 'summary.json') -Raw | ConvertFrom-Json + if ($summary.FailedSuites -ne $case.Failed -or @($summary.Suites).Count -ne 1) { throw "Incorrect runner summary for $($case.File)" } + if ($case.File -eq 'empty.Tests.ps1') { + $report = Get-Content -LiteralPath (Join-Path $output 'empty.Tests.json') -Raw | ConvertFrom-Json + if ($report.Total -ne 0) { throw 'Empty suite was not recognized as empty' } + } + } + Write-Host 'Runner contracts passed: crash, missing suite, empty Pester suite, timeout, and success.' -ForegroundColor Green + $contractsPassed = $true +} finally { + $resolved = [IO.Path]::GetFullPath($root) + $allowed = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot 'test-results')).TrimEnd('\') + '\' + if (-not $resolved.StartsWith($allowed, [StringComparison]::OrdinalIgnoreCase)) { throw 'Cleanup path outside test results' } + if ($contractsPassed) { Remove-Item -LiteralPath $resolved -Recurse -Force } + else { Write-Host "Failed runner fixtures retained: $resolved" } +} diff --git a/Debug/test_syntax.ps1 b/Debug/test_syntax.ps1 index ae1a1be..d5b321f 100644 --- a/Debug/test_syntax.ps1 +++ b/Debug/test_syntax.ps1 @@ -25,7 +25,8 @@ param( [string]$ScriptPath = "$PSScriptRoot\..\Network_Configuration.ps1", - [string]$SettingsPath = "$PSScriptRoot\PSScriptAnalyzerSettings.psd1" + [string]$SettingsPath = "$PSScriptRoot\PSScriptAnalyzerSettings.psd1", + [switch]$RequireAnalyzer ) # Resolve paths @@ -428,6 +429,11 @@ try { } # Summary +if (@($results | Where-Object { $_.Status -in @('FAILED', 'ERROR') -or + ($_.Critical -and $_.Status -eq 'WARNING') -or + ($_.Test -eq 'PSScriptAnalyzer' -and ($_.Status -eq 'WARNING' -or ($RequireAnalyzer -and $_.Status -eq 'SKIPPED'))) }).Count -gt 0) { + $allPassed = $false +} Write-Host "`n================================================================" -ForegroundColor Cyan Write-Host " TEST SUMMARY" -ForegroundColor Cyan Write-Host "================================================================" -ForegroundColor Cyan @@ -511,7 +517,7 @@ if ($criticalFailed) { Write-Host " [!] SOME NON-CRITICAL TESTS FAILED" -ForegroundColor Yellow Write-Host " Script is functional but review quality issues above" -ForegroundColor Yellow Write-Host "================================================================" -ForegroundColor Yellow - exit 0 + exit 1 } else { Write-Host "================================================================" -ForegroundColor Green Write-Host " [OK] ALL TESTS PASSED" -ForegroundColor Green diff --git a/Network_Configuration.ps1 b/Network_Configuration.ps1 index 00c0398..6ff602b 100644 --- a/Network_Configuration.ps1 +++ b/Network_Configuration.ps1 @@ -1,4 +1,4 @@ -# Version: 2.9 +# Version: 3.0 #Requires -Version 5.1 # Network Configuration Script # @@ -6,7 +6,7 @@ # - Static IP and DHCP configuration # - Live Interface Monitoring with real-time event tracking # - Network connectivity testing (Gateway, DNS, Internet) -# - Configuration save/load (XML) +# - JSON IP profiles with legacy XML fallback # - Subnet Calculator with CIDR calculations # - Interface management and renaming # - Opt-in logging with IP address masking @@ -245,6 +245,9 @@ function Get-GDPRConsent { if (Test-Path $script:ConsentPath) { try { $consentData = Get-Content $script:ConsentPath -Raw | ConvertFrom-Json + if ($consentData.LoggingConsent -isnot [bool]) { + throw 'Stored logging consent must be a JSON boolean; request explicit consent again.' + } $script:LoggingConsent = $consentData.LoggingConsent # Existing consent files may contain false; current consent always promises masked logs. $script:PseudonymizeData = $true @@ -790,6 +793,9 @@ function Write-LogMessage { if (-not $script:LoggingConsent) { return } if ($script:LogLevels[$Level] -lt $script:LogLevels[$script:MinLogLevel]) { return } + try { + # File logging must never prevent configuration recovery. + $ErrorActionPreference = 'Stop' # Pseudonymize IP addresses in the message if ($script:PseudonymizeData) { @@ -817,6 +823,12 @@ function Write-LogMessage { } | ConvertTo-Json -Compress $logEntry = $logEntry -replace '\\u0027', "'" -replace '\\u003c', '<' -replace '\\u003e', '>' -replace '\\u0026', '&' $logEntry | Out-File -FilePath $script:LogFile -Append -Encoding UTF8 + } catch { + if (-not $script:LogWriteFailureReported) { + $script:LogWriteFailureReported = $true + Write-Host '[WARN] File logging unavailable; network operations will continue.' -ForegroundColor Yellow + } + } } #endregion @@ -1591,153 +1603,55 @@ function Test-MTUSize { function Test-IPConflict { <# .SYNOPSIS - Detects if an IP address is already in use using gratuitous ARP and multiple detection methods. - - .PARAMETER IPAddress - The IP address to check for conflicts. - - .PARAMETER InterfaceName - The network interface name to exclude from conflict check. + Checks local ownership and exact IPv4 neighbors on the selected interface. + A negative probe is advisory; Windows DAD is checked during address application. #> [CmdletBinding()] [OutputType([bool])] param ( - [Parameter(Mandatory=$true)] - [string]$IPAddress, - - [Parameter(Mandatory=$true)] - [string]$InterfaceName + [Parameter(Mandatory=$true)][string]$IPAddress, + [Parameter(Mandatory=$true)][string]$InterfaceName ) - try { - # Get all current IPs on this interface - $currentIPs = (Get-NetIPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue).IPAddress - - # If we're checking an IP that's already configured on THIS interface, skip conflict check - if ($currentIPs -contains $IPAddress) { - Write-LogMessage -Message "IP $IPAddress already configured on this interface - skipping conflict check" -Level "DEBUG" - return $false - } - - Write-Host " Scanning: " -NoNewline -ForegroundColor Gray - Write-LogMessage -Message "Starting comprehensive IP conflict detection for $IPAddress..." -Level "DEBUG" - - # Method 1: NetBIOS Name Query (nbtstat) - Works for Windows clients - # Run with short timeout to avoid hanging - Write-Host "[NBT]" -NoNewline -ForegroundColor DarkGray - try { - $nbtJob = Start-Job -ScriptBlock { & nbtstat -A $using:IPAddress 2>&1 | Out-String } - $nbtstatOutput = Wait-Job $nbtJob -Timeout 1 | Receive-Job - Remove-Job $nbtJob -Force -ErrorAction SilentlyContinue - - if ($nbtstatOutput -and $nbtstatOutput -notmatch "Host not found" -and ($nbtstatOutput -match "MAC Address" -or $nbtstatOutput -match "<00>")) { - $computerName = "Unknown" - if ($nbtstatOutput -match "([A-Z0-9-]+)\s+<00>\s+UNIQUE") { - $computerName = $matches[1] - } - - $macAddress = "Unknown" - if ($nbtstatOutput -match "MAC Address = ([0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2})") { - $macAddress = $matches[1] - } - - Write-Host "`r [!] CONFLICT: $computerName ($macAddress)" -ForegroundColor Red - Write-LogMessage -Message "IP conflict detected via NetBIOS: $IPAddress in use by $computerName ($macAddress)" -Level "WARN" - return $true - } - } catch { - Write-LogMessage -Message "NetBIOS conflict probe failed for ${IPAddress}: $_" -Level "DEBUG" - } - - # Method 2: Gratuitous ARP using arp command - Write-Host " [ARP]" -NoNewline -ForegroundColor DarkGray - try { - # Clear old entry first - $null = & arp -d $IPAddress 2>&1 - - # Send ARP request (gratuitous ARP probe) - $pingResult = Test-Connection -ComputerName $IPAddress -Count 1 -Quiet -ErrorAction SilentlyContinue - Start-Sleep -Milliseconds 100 - - # Check if ARP table was populated - $arpCheck = & arp -a $IPAddress 2>&1 - if ($arpCheck -match $IPAddress -and $arpCheck -notmatch "No ARP Entries") { - $macMatch = [regex]::Match($arpCheck, '([0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2})') - if ($macMatch.Success) { - Write-Host "`r [!] CONFLICT: MAC $($macMatch.Value)" -ForegroundColor Red - Write-LogMessage -Message "IP conflict detected via ARP: $IPAddress has MAC $($macMatch.Value)" -Level "WARN" - return $true - } - } - } catch { - Write-LogMessage -Message "ARP conflict probe failed for ${IPAddress}: $_" -Level "DEBUG" - } - - # Method 3: ICMP Ping - Write-Host " [PING]" -NoNewline -ForegroundColor DarkGray - $pingResult = Test-Connection -ComputerName $IPAddress -Count 1 -Quiet -ErrorAction SilentlyContinue - if ($pingResult) { - Write-Host "`r [!] CONFLICT: Host responds to ping" -ForegroundColor Red - Write-LogMessage -Message "IP conflict detected: $IPAddress responds to ICMP" -Level "WARN" + $adapter = Get-NetAdapter -Name ([System.Management.Automation.WildcardPattern]::Escape($InterfaceName)) -ErrorAction Stop + $local = @(Get-NetIPAddress -AddressFamily IPv4 -ErrorAction Stop | Where-Object IPAddress -eq $IPAddress) + if ($local | Where-Object { $_.InterfaceIndex -ne $adapter.ifIndex -or $_.AddressState -eq 'Duplicate' }) { + Write-Host ' [!] Address belongs to another local interface or is marked Duplicate' -ForegroundColor Yellow return $true } - - # Method 4: PowerShell ARP cache - Write-Host " [CACHE]" -NoNewline -ForegroundColor DarkGray - Start-Sleep -Milliseconds 100 - $arpEntry = Get-NetNeighbor -IPAddress $IPAddress -ErrorAction SilentlyContinue | - Where-Object { $_.State -in @('Reachable', 'Stale', 'Delay', 'Probe', 'Permanent') } - - if ($arpEntry) { - Write-Host "`r [!] CONFLICT: MAC $($arpEntry.LinkLayerAddress)" -ForegroundColor Red - Write-LogMessage -Message "IP conflict detected in ARP cache: $IPAddress ($($arpEntry.LinkLayerAddress))" -Level "WARN" + if ($local) { return $false } + # A regular ping may populate the neighbor cache. It is not a gratuitous ARP probe, + # and a response through another interface is not evidence on this interface. + $ping = New-Object System.Net.NetworkInformation.Ping + try { $null = $ping.Send($IPAddress, 500) } finally { $ping.Dispose() } + $neighbors = @(Get-NetNeighbor -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4 -ErrorAction Stop | + Where-Object { $_.IPAddress -eq $IPAddress -and $_.State -in @('Reachable', 'Stale', 'Delay', 'Probe', 'Permanent') -and + $_.LinkLayerAddress -and $_.LinkLayerAddress -notmatch '^(00[-:]?){5}00$|^(FF[-:]?){5}FF$' }) + if ($neighbors) { + Write-Host " [!] Possible conflict: neighbor $($neighbors[0].LinkLayerAddress) on $InterfaceName" -ForegroundColor Yellow + Write-LogMessage -Message "Possible IP conflict for $IPAddress on ${InterfaceName}: $($neighbors[0].LinkLayerAddress)" -Level 'WARN' return $true } - - # Method 5: TCP port scan (Windows services) - Write-Host " [TCP]" -NoNewline -ForegroundColor DarkGray - $commonPorts = @(445, 139) - foreach ($port in $commonPorts) { - try { - $tcpClient = New-Object System.Net.Sockets.TcpClient - $connectTask = $tcpClient.ConnectAsync($IPAddress, $port) - if ($connectTask.Wait(100)) { - if ($tcpClient.Connected) { - $tcpClient.Close() - Write-Host "`r [!] CONFLICT: Port $port open" -ForegroundColor Red - Write-LogMessage -Message "IP conflict detected: $IPAddress responds on TCP port $port" -Level "WARN" - $tcpClient.Dispose() - return $true - } - } - $tcpClient.Dispose() - } catch { - Write-LogMessage -Message "TCP conflict probe failed for ${IPAddress} on port ${port}: $_" -Level "DEBUG" - } - } - - # Method 6: Final comprehensive check - Write-Host " [FINAL]" -NoNewline -ForegroundColor DarkGray - Start-Sleep -Milliseconds 100 - $finalArpCheck = & arp -a | Select-String $IPAddress - if ($finalArpCheck -and $finalArpCheck -notmatch "incomplete") { - Write-Host "`r [!] CONFLICT: Found in final ARP check" -ForegroundColor Red - Write-LogMessage -Message "IP conflict detected in final check for $IPAddress" -Level "WARN" - return $true - } - - Write-Host "`r No conflict detected. " -NoNewline -ForegroundColor Green - Write-Host "[$IPAddress is available]" -NoNewline -ForegroundColor Green - Write-Host (" " * 30) # Clear remaining characters from progress line - Write-LogMessage -Message "No IP conflict detected for $IPAddress after comprehensive scan" -Level "DEBUG" + Write-Host ' No conflict observed; Windows will also perform duplicate-address detection.' -ForegroundColor Gray return $false - } catch { - Write-Host "`r Error during conflict detection: $_" -ForegroundColor Red - Write-LogMessage -Message "Error checking IP conflict for $IPAddress - $($_.Exception.Message)" -Level "DEBUG" + Write-Host ' Conflict probe inconclusive; Windows duplicate-address detection will be checked.' -ForegroundColor Yellow + Write-LogMessage -Message "Conflict probe inconclusive for ${IPAddress}: $_" -Level 'WARN' return $false } } +function Get-IPv4StoreState { + [CmdletBinding()] + param ([string]$InterfaceName, [ValidateSet('Address', 'Route')][string]$Kind, [string]$PolicyStore = 'ActiveStore') + # CIM reports an empty filtered store as ObjectNotFound. Other read failures must abort. + $queryErrors = @() + $parameters = @{ InterfaceAlias = $InterfaceName; AddressFamily = 'IPv4'; PolicyStore = $PolicyStore; ErrorAction = 'SilentlyContinue'; ErrorVariable = 'queryErrors' } + $result = if ($Kind -eq 'Address') { @(Get-NetIPAddress @parameters) } else { @(Get-NetRoute @parameters) } + foreach ($queryError in $queryErrors) { + if ($queryError.CategoryInfo.Category -ne 'ObjectNotFound') { throw $queryError } + } + return $result +} function Backup-NetworkConfiguration { <# @@ -1755,25 +1669,35 @@ function Backup-NetworkConfiguration { ) try { + $adapter = Get-NetAdapter -Name ([System.Management.Automation.WildcardPattern]::Escape($InterfaceName)) -ErrorAction Stop + $dnsRegistryPath = 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\' + ([guid]$adapter.InterfaceGuid).ToString('B') + $dnsOverride = (Get-ItemProperty -LiteralPath $dnsRegistryPath -ErrorAction Stop).NameServer $backup = @{ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" Interface = $InterfaceName - IPv4Address = Get-NetIPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue - IPv4Routes = Get-NetRoute -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue - DNSServers = (Get-DnsClientServerAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue).ServerAddresses - DHCPEnabled = (Get-NetIPInterface -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue).Dhcp + IPv4Address = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address) + PersistentAddresses = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address -PolicyStore PersistentStore) + IPv4Routes = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Route) + PersistentRoutes = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Route -PolicyStore PersistentStore) + DNSServers = @((Get-DnsClientServerAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction Stop).ServerAddresses) + DHCPEnabled = (Get-NetIPInterface -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction Stop).Dhcp + DNSAutomatic = [string]::IsNullOrWhiteSpace($dnsOverride) } + if ($backup.DHCPEnabled -notin @('Enabled', 'Disabled')) { throw 'Could not determine the original DHCP state' } try { $safeInterfaceName = $InterfaceName -replace '[\\/:*?"<>|]', '_' $backupPath = New-ManagedBackupPath -BaseName "network_$safeInterfaceName" -Extension "json" $backupFile = [ordered]@{ - FormatVersion = 1 + FormatVersion = 2 ScriptVersion = $script:ScriptVersion Timestamp = $backup.Timestamp Interface = $backup.Interface DHCPEnabled = [string]$backup.DHCPEnabled DNSServers = @($backup.DNSServers) + DNSAutomatic = $backup.DNSAutomatic + PersistentAddresses = @($backup.PersistentAddresses | Select-Object IPAddress, PrefixLength, SkipAsSource) + PersistentRoutes = @($backup.PersistentRoutes | Select-Object DestinationPrefix, NextHop, RouteMetric, Protocol) IPv4Addresses = @( $backup.IPv4Address | ForEach-Object { [ordered]@{ @@ -1782,6 +1706,7 @@ function Backup-NetworkConfiguration { PrefixOrigin = [string]$_.PrefixOrigin SuffixOrigin = [string]$_.SuffixOrigin AddressState = [string]$_.AddressState + SkipAsSource = $_.SkipAsSource } } ) @@ -1796,7 +1721,8 @@ function Backup-NetworkConfiguration { } ) } - $backupFile | ConvertTo-Json -Depth 5 | Set-Content -Path $backupPath -Encoding UTF8 + $backupFile | ConvertTo-Json -Depth 5 | Set-Content -Path $backupPath -Encoding UTF8 -ErrorAction Stop + $backup.BackupPath = $backupPath Invoke-BackupRetention -Filter "network_$safeInterfaceName`_*.json" } catch { Write-LogMessage -Message "Could not write managed network backup for ${InterfaceName}: $_" -Level "WARN" @@ -1885,7 +1811,15 @@ function Remove-IPv4AddressSafe { ) try { - Remove-NetIPAddress -IPAddress $IPAddress -InterfaceAlias $InterfaceName -Confirm:$false -ErrorAction Stop + foreach ($store in @('PersistentStore', 'ActiveStore')) { + $existing = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address -PolicyStore $store | Where-Object IPAddress -eq $IPAddress) + if ($existing) { + Remove-NetIPAddress -IPAddress $IPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -PolicyStore $store -Confirm:$false -ErrorAction Stop + } + if (Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address -PolicyStore $store | Where-Object IPAddress -eq $IPAddress) { + throw "Address removal did not verify in $store" + } + } if (-not $Quiet) { $suffix = if ($PrefixLength) { "/$PrefixLength" } else { "" } Write-LogMessage -Message "Removed IPv4 address from ${InterfaceName}: $IPAddress$suffix" -Level "DEBUG" @@ -1904,25 +1838,43 @@ function Set-IPv4DefaultGatewaySafe { [Parameter(Mandatory=$true)] [string]$InterfaceName, - [Parameter(Mandatory=$true)] [string]$Gateway ) try { - $existingGateway = Get-NetRoute -InterfaceAlias $InterfaceName -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue - if ($existingGateway -and ($existingGateway | Where-Object { $_.NextHop -eq $Gateway })) { - return $true - } - - if ($existingGateway) { - $existingGateway | Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue + # Routes belong to an interface and store. Never inspect/remove another adapter's routes. + foreach ($store in @('PersistentStore', 'ActiveStore')) { + $routes = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Route -PolicyStore $store | + Where-Object DestinationPrefix -eq '0.0.0.0/0') + foreach ($route in $routes) { + if (-not $Gateway -or $route.NextHop -ne $Gateway -or $route.Protocol -eq 'Dhcp') { + Remove-NetRoute -InterfaceAlias $InterfaceName -AddressFamily IPv4 -DestinationPrefix '0.0.0.0/0' -NextHop $route.NextHop -PolicyStore $store -Confirm:$false -ErrorAction Stop + } + } + if ($Gateway -and -not ($routes | Where-Object { $_.NextHop -eq $Gateway -and $_.Protocol -ne 'Dhcp' })) { + $routeParameters = @{ InterfaceAlias = $InterfaceName; AddressFamily = 'IPv4'; DestinationPrefix = '0.0.0.0/0'; NextHop = $Gateway; ErrorAction = 'Stop' } + if ($store -eq 'PersistentStore') { + # New-NetRoute cannot create directly in PersistentStore. Omit + # PolicyStore to create both stores, clearing any active collision. + $activeMatch = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Route | + Where-Object { $_.DestinationPrefix -eq '0.0.0.0/0' -and $_.NextHop -eq $Gateway }) + if ($activeMatch) { + Remove-NetRoute -InterfaceAlias $InterfaceName -AddressFamily IPv4 -DestinationPrefix '0.0.0.0/0' -NextHop $Gateway -PolicyStore ActiveStore -Confirm:$false -ErrorAction Stop + } + } else { $routeParameters.PolicyStore = 'ActiveStore' } + New-NetRoute @routeParameters | Out-Null + } + $verifiedRoutes = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Route -PolicyStore $store | Where-Object DestinationPrefix -eq '0.0.0.0/0') + if (($Gateway -and -not ($verifiedRoutes | Where-Object NextHop -eq $Gateway)) -or + ($verifiedRoutes | Where-Object { -not $Gateway -or $_.NextHop -ne $Gateway })) { + throw "Default route verification failed in $store" + } } - - New-NetRoute -InterfaceAlias $InterfaceName -DestinationPrefix "0.0.0.0/0" -NextHop $Gateway -ErrorAction Stop | Out-Null Write-LogMessage -Message "Updated gateway to $Gateway" -Level "INFO" return $true } catch { - Write-LogMessage -Message "Warning: Could not update gateway: $_" -Level "WARN" + Write-Host " [ERROR] Gateway $Gateway on $InterfaceName ($store): $($_.Exception.Message)" -ForegroundColor Red + Write-LogMessage -Message "Warning: Could not update gateway $Gateway on $InterfaceName in ${store}: $_" -Level "WARN" return $false } } @@ -1937,14 +1889,11 @@ function Set-IPv4DnsServersSafe { ) try { - Set-DnsClientServerAddress -InterfaceAlias $InterfaceName -ServerAddresses $DNSServers -ErrorAction Stop + Get-DnsClientServerAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction Stop | + Set-DnsClientServerAddress -ServerAddresses $DNSServers -ErrorAction Stop Start-Sleep -Milliseconds 500 $verifyDNS = (Get-DnsClientServerAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue).ServerAddresses - foreach ($dnsServer in $DNSServers) { - if (-not ($verifyDNS -contains $dnsServer)) { - return $false - } - } + if (($verifyDNS -join ',') -ne ($DNSServers -join ',')) { return $false } return $true } catch { @@ -1962,7 +1911,8 @@ function Reset-IPv4DnsServersSafe { ) try { - Set-DnsClientServerAddress -InterfaceAlias $InterfaceName -ResetServerAddresses -ErrorAction Stop + Get-DnsClientServerAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction Stop | + Set-DnsClientServerAddress -ResetServerAddresses -ErrorAction Stop if (-not $Quiet) { Write-LogMessage -Message "Reset IPv4 DNS server addresses for $InterfaceName" -Level "DEBUG" } @@ -1975,26 +1925,143 @@ function Reset-IPv4DnsServersSafe { } } -function Restore-DHCPConfiguration { +function Wait-IPv4AddressReady { + param ([string]$InterfaceName, [string]$IPAddress, [int]$PrefixLength, [int]$TimeoutSeconds = 15) + $deadline = (Get-Date).AddSeconds($TimeoutSeconds) + do { + $address = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address | + Where-Object { $_.IPAddress -eq $IPAddress -and $_.PrefixLength -eq $PrefixLength }) + if ($address | Where-Object AddressState -eq 'Duplicate') { throw "Windows detected a duplicate address: $IPAddress" } + if ($address | Where-Object AddressState -eq 'Preferred') { return } + Start-Sleep -Milliseconds 250 + } while ((Get-Date) -lt $deadline) + throw "Address $IPAddress/$PrefixLength did not become Preferred within $TimeoutSeconds seconds" +} + +function Invoke-InterfaceDHCPRenewal { + <# + .SYNOPSIS + Renews DHCP on one adapter using the Windows CIM provider and a structured result. + #> + [CmdletBinding()] param ( - [Parameter(Mandatory=$true)] - [string]$InterfaceName + [Parameter(Mandatory=$true)][string]$InterfaceName, + [ValidateRange(1,120)][int]$OperationTimeoutSeconds = 20 ) + $adapter = Get-NetAdapter -Name ([System.Management.Automation.WildcardPattern]::Escape($InterfaceName)) -ErrorAction Stop + $interfaceIndex = [uint32]$adapter.ifIndex + $configuration = @(Get-CimInstance -Namespace 'root/cimv2' -ClassName Win32_NetworkAdapterConfiguration -Filter "InterfaceIndex = $interfaceIndex" -OperationTimeoutSec $OperationTimeoutSeconds -ErrorAction Stop) + if ($configuration.Count -ne 1 -or [guid]$configuration[0].SettingID -ne [guid]$adapter.InterfaceGuid) { + throw "Could not uniquely identify the DHCP configuration for $InterfaceName" + } + $result = Invoke-CimMethod -InputObject $configuration[0] -MethodName RenewDHCPLease -OperationTimeoutSec $OperationTimeoutSeconds -ErrorAction Stop + if ($null -eq $result -or $null -eq $result.ReturnValue) { throw 'DHCP renewal provider did not return a result code' } + switch ([uint32]$result.ReturnValue) { + 0 { return } + 1 { throw "DHCP renewal for $InterfaceName requires a reboot; a usable lease is not confirmed" } + default { throw "DHCP renewal failed for $InterfaceName (Windows result $($result.ReturnValue))" } + } +} +function Restore-NetworkConfiguration { + param ([Parameter(Mandatory=$true)][hashtable]$Backup) + $name = $Backup.Interface try { - $partialIP = Get-NetIPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.PrefixOrigin -ne 'Dhcp' } - foreach ($ip in @($partialIP)) { - $null = Remove-IPv4AddressSafe -InterfaceName $InterfaceName -IPAddress $ip.IPAddress -Quiet + Set-NetIPInterface -InterfaceAlias $name -AddressFamily IPv4 -Dhcp Disabled -ErrorAction Stop + if (-not (Set-IPv4DefaultGatewaySafe -InterfaceName $name)) { throw 'Could not clear partial gateway configuration' } + $partialAddresses = @(@(Get-IPv4StoreState -InterfaceName $name -Kind Address) + @(Get-IPv4StoreState -InterfaceName $name -Kind Address -PolicyStore PersistentStore) | Sort-Object IPAddress -Unique) + foreach ($address in $partialAddresses) { + if (-not (Remove-IPv4AddressSafe -InterfaceName $name -IPAddress $address.IPAddress)) { throw 'Could not remove partial address' } + } + foreach ($address in @($Backup.IPv4Address | Where-Object PrefixOrigin -eq 'Manual')) { + $addressParams = @{ + InterfaceAlias = $name; AddressFamily = 'IPv4'; IPAddress = $address.IPAddress + PrefixLength = $address.PrefixLength; SkipAsSource = [bool]$address.SkipAsSource + } + if ($null -ne $address.ValidLifetime) { $addressParams.ValidLifetime = $address.ValidLifetime } + if ($null -ne $address.PreferredLifetime) { $addressParams.PreferredLifetime = $address.PreferredLifetime } + $persistentOriginal = @($Backup.PersistentAddresses | Where-Object IPAddress -eq $address.IPAddress) + if (-not $persistentOriginal) { + $addressParams.PolicyStore = 'ActiveStore' + } else { + # Build the persistent version using the documented dual-store create, + # then adjust only ActiveStore if its original settings differ. + $addressParams.PrefixLength = $persistentOriginal[0].PrefixLength + $addressParams.SkipAsSource = [bool]$persistentOriginal[0].SkipAsSource + } + New-NetIPAddress @addressParams -ErrorAction Stop | Out-Null + if ($persistentOriginal -and ($address.PrefixLength -ne $persistentOriginal[0].PrefixLength -or $address.SkipAsSource -ne $persistentOriginal[0].SkipAsSource)) { + Set-NetIPAddress -InterfaceAlias $name -AddressFamily IPv4 -IPAddress $address.IPAddress -PrefixLength $address.PrefixLength -SkipAsSource ([bool]$address.SkipAsSource) -PolicyStore ActiveStore -ErrorAction Stop + } + Wait-IPv4AddressReady -InterfaceName $name -IPAddress $address.IPAddress -PrefixLength $address.PrefixLength + } + foreach ($address in @($Backup.PersistentAddresses | Where-Object PrefixOrigin -eq 'Manual')) { + $activeOriginal = @($Backup.IPv4Address | Where-Object { $_.IPAddress -eq $address.IPAddress -and $_.PrefixOrigin -eq 'Manual' }) + if (-not $activeOriginal) { + # Create using the documented dual-store default, then remove only the + # temporary ActiveStore entry to recover a saved-only address. + New-NetIPAddress -InterfaceAlias $name -AddressFamily IPv4 -IPAddress $address.IPAddress -PrefixLength $address.PrefixLength -SkipAsSource ([bool]$address.SkipAsSource) -ErrorAction Stop | Out-Null + Remove-NetIPAddress -InterfaceAlias $name -AddressFamily IPv4 -IPAddress $address.IPAddress -PolicyStore ActiveStore -Confirm:$false -ErrorAction Stop + } + } + foreach ($store in @('PersistentStore', 'ActiveStore')) { + $savedRoutes = if ($store -eq 'PersistentStore') { $Backup.PersistentRoutes } else { $Backup.IPv4Routes } + foreach ($route in @($savedRoutes | Where-Object { $_.Protocol -eq 'NetMgmt' })) { + $existing = @(Get-IPv4StoreState -InterfaceName $name -Kind Route -PolicyStore $store | + Where-Object { $_.DestinationPrefix -eq $route.DestinationPrefix -and $_.NextHop -eq $route.NextHop }) + if (-not $existing) { + $routeParameters = @{ InterfaceAlias = $name; AddressFamily = 'IPv4'; DestinationPrefix = $route.DestinationPrefix; NextHop = $route.NextHop; RouteMetric = $route.RouteMetric; ErrorAction = 'Stop' } + if ($store -eq 'PersistentStore') { + $activeMatch = @(Get-IPv4StoreState -InterfaceName $name -Kind Route | + Where-Object { $_.DestinationPrefix -eq $route.DestinationPrefix -and $_.NextHop -eq $route.NextHop }) + if ($activeMatch) { + Remove-NetRoute -InterfaceAlias $name -AddressFamily IPv4 -DestinationPrefix $route.DestinationPrefix -NextHop $route.NextHop -PolicyStore ActiveStore -Confirm:$false -ErrorAction Stop + } + } else { $routeParameters.PolicyStore = 'ActiveStore' } + New-NetRoute @routeParameters | Out-Null + if ($store -eq 'PersistentStore' -and -not ($Backup.IPv4Routes | Where-Object { $_.Protocol -eq 'NetMgmt' -and $_.DestinationPrefix -eq $route.DestinationPrefix -and $_.NextHop -eq $route.NextHop })) { + Remove-NetRoute -InterfaceAlias $name -AddressFamily IPv4 -DestinationPrefix $route.DestinationPrefix -NextHop $route.NextHop -PolicyStore ActiveStore -Confirm:$false -ErrorAction Stop + } + } elseif ($existing | Where-Object RouteMetric -ne $route.RouteMetric) { + Set-NetRoute -InterfaceAlias $name -AddressFamily IPv4 -DestinationPrefix $route.DestinationPrefix -NextHop $route.NextHop -RouteMetric $route.RouteMetric -PolicyStore $store -ErrorAction Stop + } + $restored = @(Get-IPv4StoreState -InterfaceName $name -Kind Route -PolicyStore $store | + Where-Object { $_.DestinationPrefix -eq $route.DestinationPrefix -and $_.NextHop -eq $route.NextHop -and $_.RouteMetric -eq $route.RouteMetric }) + if (-not $restored) { throw "Restored route did not verify in $store" } + } + } + Set-NetIPInterface -InterfaceAlias $name -AddressFamily IPv4 -Dhcp $Backup.DHCPEnabled -ErrorAction Stop + if ($Backup.DNSAutomatic) { + if (-not (Reset-IPv4DnsServersSafe -InterfaceName $name)) { throw 'Could not restore automatic DNS' } + } elseif ($Backup.DNSServers.Count -gt 0) { + if (-not (Set-IPv4DnsServersSafe -InterfaceName $name -DNSServers $Backup.DNSServers)) { throw 'Could not restore DNS' } + } else { + if (-not (Reset-IPv4DnsServersSafe -InterfaceName $name)) { throw 'Could not restore DNS' } + } + if ($Backup.DHCPEnabled -eq 'Enabled') { + Invoke-InterfaceDHCPRenewal -InterfaceName $name + $lease = @() + for ($leaseAttempt = 0; $leaseAttempt -lt 20; $leaseAttempt++) { + $lease = @(Get-IPv4StoreState -InterfaceName $name -Kind Address | Where-Object { + $_.PrefixOrigin -eq 'Dhcp' -and $_.AddressState -eq 'Preferred' -and + $_.IPAddress -notlike '169.254.*' -and $_.IPAddress -ne '0.0.0.0' + }) + if ($lease.Count -gt 0) { break } + Start-Sleep -Milliseconds 500 + } + if (-not $lease) { throw 'DHCP settings restored, but no usable lease was observed' } + } + if ((Get-NetIPInterface -InterfaceAlias $name -AddressFamily IPv4 -ErrorAction Stop).Dhcp -ne $Backup.DHCPEnabled) { throw 'Restored DHCP state did not verify' } + foreach ($store in @('ActiveStore', 'PersistentStore')) { + $original = if ($store -eq 'ActiveStore') { $Backup.IPv4Address } else { $Backup.PersistentAddresses } + $expected = @($original | Where-Object PrefixOrigin -eq 'Manual' | ForEach-Object { "$($_.IPAddress)/$($_.PrefixLength)/$($_.SkipAsSource)" } | Sort-Object) + $actual = @(Get-IPv4StoreState -InterfaceName $name -Kind Address -PolicyStore $store | Where-Object PrefixOrigin -eq 'Manual' | + ForEach-Object { "$($_.IPAddress)/$($_.PrefixLength)/$($_.SkipAsSource)" } | Sort-Object) + if (($actual -join ',') -ne ($expected -join ',')) { throw "Restored addresses did not verify in $store" } } - - Set-NetIPInterface -InterfaceAlias $InterfaceName -AddressFamily IPv4 -Dhcp Enabled -ErrorAction Stop - $null = Reset-IPv4DnsServersSafe -InterfaceName $InterfaceName -Quiet - - $null = & ipconfig /renew $InterfaceName 2>&1 - Write-LogMessage -Message "Successfully rolled back to DHCP after static IP failure" -Level "INFO" return $true } catch { - Write-LogMessage -Message "Rollback to DHCP failed: $_" -Level "ERROR" + Write-LogMessage -Message "Network rollback failed for ${name}: $_" -Level 'ERROR' return $false } } @@ -2040,7 +2107,7 @@ function Get-NetworkPerformance { ) try { - $adapter = Get-NetAdapter -Name $InterfaceName -ErrorAction Stop + $adapter = Get-NetAdapter -Name ([System.Management.Automation.WildcardPattern]::Escape($InterfaceName)) -ErrorAction Stop $stats = Get-NetAdapterStatistics -Name $InterfaceName -ErrorAction Stop return @{ @@ -3161,6 +3228,7 @@ function Set-StaticIP { # Backup current configuration for rollback capability $backupConfig = $null + $configurationChanged = $false try { # === PRE-FLIGHT VALIDATION === @@ -3237,7 +3305,7 @@ function Set-StaticIP { if ($backupConfig) { Write-LogMessage -Message "Current configuration backed up successfully" -Level "DEBUG" } else { - Write-LogMessage -Message "Warning: Could not backup current configuration for $InterfaceName" -Level "WARN" + throw "Cannot safely proceed without a configuration backup" } # Convert subnet mask to prefix length @@ -3261,6 +3329,9 @@ function Set-StaticIP { } Write-LogMessage -Message "Gateway $Gateway validated successfully (network: $($ipDetails.NetworkAddress)/$prefixLength)" -Level "DEBUG" + if ($prefixLength -lt 31 -and $gwDetails.IPValue -in @($ipDetails.NetworkValue, $ipDetails.BroadcastValue)) { + throw 'Gateway cannot be the subnet network or broadcast address' + } } # Validate IP is not gateway, broadcast, or network address @@ -3301,152 +3372,60 @@ function Set-StaticIP { } } - # Check if the IP address is already configured on this interface - Write-Host " Checking existing configuration..." -ForegroundColor Gray - $existingIPv4 = Get-NetIPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue - $ipAlreadyConfigured = $false - - if ($existingIPv4) { - # Check if the exact IP, prefix length AND it's already static (not DHCP) - $dhcpEnabled = (Get-NetIPInterface -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue).Dhcp - $matchingIP = $existingIPv4 | Where-Object { $_.IPAddress -eq $IPAddress -and $_.PrefixLength -eq $prefixLength } - - if ($matchingIP -and $dhcpEnabled -eq 'Disabled' -and $existingIPv4.Count -eq 1) { - # Same IP and prefix, already static, and ONLY one IP - can skip - $ipAlreadyConfigured = $true - Write-LogMessage -Message "IP address $IPAddress/$prefixLength is already configured as static on interface $InterfaceName. Skipping IP removal/addition." -Level "INFO" - } else { - # Remove ALL existing IPv4 addresses (handles multiple IPs, APIPA, etc.) - if ($dhcpEnabled -eq 'Enabled') { - Write-LogMessage -Message "Removing DHCP-assigned IP addresses to configure static IP" -Level "INFO" - } - - # Remove each IP individually to ensure complete cleanup - $removedIpCount = 0 - foreach ($ip in $existingIPv4) { - if (Remove-IPv4AddressSafe -InterfaceName $InterfaceName -IPAddress $ip.IPAddress -PrefixLength $ip.PrefixLength) { - $removedIpCount++ - } - } - Write-LogMessage -Message "Removed $removedIpCount existing IPv4 address(es) from interface $InterfaceName" -Level "INFO" - } + # Disable DHCP before address changes so a lease cannot race the static apply. + $configurationChanged = $true + Set-NetIPInterface -InterfaceAlias $InterfaceName -AddressFamily IPv4 -Dhcp Disabled -ErrorAction Stop + if ((Get-NetIPInterface -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction Stop).Dhcp -ne 'Disabled') { + throw 'DHCP did not become disabled' } - # Remove existing default route ONLY if no other adapters are using it - Write-Host " Managing gateway route..." -ForegroundColor Gray - $existingRoute = Get-NetRoute -InterfaceAlias $InterfaceName -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue - if ($existingRoute) { - # Check if other adapters have the same default route - $allDefaultRoutes = Get-NetRoute -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue - $otherAdapterRoutes = $allDefaultRoutes | Where-Object { $_.InterfaceAlias -ne $InterfaceName } - - if ($otherAdapterRoutes) { - Write-LogMessage -Message "Default route exists on other adapters. Not removing route from $InterfaceName" -Level "INFO" - } else { - # Safe to remove - no other adapters use this route - $existingRoute | Remove-NetRoute -Confirm:$false -ErrorAction Stop - Write-LogMessage -Message "Removed default route from interface $InterfaceName" -Level "INFO" - } - } - - # Prepare new static IP parameters with robust application process Write-Host " Applying IP configuration..." -ForegroundColor Gray - - # CRITICAL STEP 1: Disable DHCP and DNS autoconfiguration to avoid PolicyStore conflicts - $dhcpDisabled = $false - $maxDhcpRetries = 3 - - for ($dhcpAttempt = 1; $dhcpAttempt -le $maxDhcpRetries; $dhcpAttempt++) { + # Manage the route independently. Never pass DefaultGateway to New-NetIPAddress. + # Re-read on retry: a CIM error can occur after an address was created. + $ipConfigured = $false + for ($ipAttempt = 1; $ipAttempt -le $MaxRetries; $ipAttempt++) { try { - Write-LogMessage -Message "Disabling DHCP for interface $InterfaceName (attempt $dhcpAttempt/$maxDhcpRetries)" -Level "INFO" - - # Disable both DHCP for IP and DNS - Set-NetIPInterface -InterfaceAlias $InterfaceName -AddressFamily IPv4 -Dhcp Disabled -ErrorAction Stop - - # Wait briefly and verify DHCP is actually disabled - Start-Sleep -Milliseconds 500 - - $dhcpStatus = (Get-NetIPInterface -InterfaceAlias $InterfaceName -AddressFamily IPv4).Dhcp - if ($dhcpStatus -eq 'Disabled') { - $dhcpDisabled = $true - Write-LogMessage -Message "DHCP disabled and verified for $InterfaceName" -Level "INFO" - break - } else { - Write-LogMessage -Message "DHCP status check returned: $dhcpStatus (expected: Disabled)" -Level "WARN" - if ($dhcpAttempt -lt $maxDhcpRetries) { - Start-Sleep -Seconds 1 + $addresses = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address) + $matching = @($addresses | Where-Object { $_.IPAddress -eq $IPAddress -and $_.PrefixLength -eq $prefixLength -and $_.PrefixOrigin -eq 'Manual' }) + $persistentAddresses = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address -PolicyStore PersistentStore) + $persistentMatch = @($persistentAddresses | Where-Object { $_.IPAddress -eq $IPAddress -and $_.PrefixLength -eq $prefixLength }) + if (-not $matching -or -not $persistentMatch) { + $oldTarget = @(@($addresses) + @($persistentAddresses) | Where-Object IPAddress -eq $IPAddress | Sort-Object IPAddress -Unique) + foreach ($address in $oldTarget) { + if (-not (Remove-IPv4AddressSafe -InterfaceName $InterfaceName -IPAddress $address.IPAddress)) { + throw "Could not remove old prefix or DHCP address for $IPAddress" + } } + New-NetIPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -IPAddress $IPAddress -PrefixLength $prefixLength -ErrorAction Stop | Out-Null + } else { + Set-NetIPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -IPAddress $IPAddress -SkipAsSource $false -ErrorAction Stop } - } catch { - Write-LogMessage -Message "Attempt $dhcpAttempt to disable DHCP failed: $_" -Level "WARN" - if ($dhcpAttempt -lt $maxDhcpRetries) { - Start-Sleep -Seconds 1 + Wait-IPv4AddressReady -InterfaceName $InterfaceName -IPAddress $IPAddress -PrefixLength $prefixLength + if (-not (Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address -PolicyStore PersistentStore | + Where-Object { $_.IPAddress -eq $IPAddress -and $_.PrefixLength -eq $prefixLength })) { + throw 'Static address was not saved in PersistentStore' } + $ipConfigured = $true + break + } catch { + if ($ipAttempt -eq $MaxRetries -or $_.Exception.Message -like 'Windows detected a duplicate*') { throw } + Write-LogMessage -Message "Address attempt $ipAttempt failed: $_" -Level 'WARN' + Start-Sleep -Seconds $RetryDelaySeconds } } - - if (-not $dhcpDisabled) { - throw "Failed to disable DHCP after $maxDhcpRetries attempts. Cannot proceed with static IP configuration." - } - - # CRITICAL STEP 2: Apply static IP configuration with retry mechanism - $params = @{ - InterfaceAlias = $InterfaceName - IPAddress = $IPAddress - PrefixLength = $prefixLength - } - if ($Gateway) { - $params["DefaultGateway"] = $Gateway - } else { - Write-LogMessage -Message "No gateway specified for this profile; skipping default route configuration." -Level "INFO" - } + if (-not $ipConfigured) { throw 'Static address did not become usable' } - # Apply new static IP only if not already configured - if (-not $ipAlreadyConfigured) { - $ipConfigured = $false - - for ($ipAttempt = 1; $ipAttempt -le $MaxRetries; $ipAttempt++) { - try { - Write-LogMessage -Message "Applying static IP configuration (attempt $ipAttempt/$MaxRetries)" -Level "INFO" - - New-NetIPAddress @params -ErrorAction Stop | Out-Null - - # Verify IP was actually set - Start-Sleep -Milliseconds 500 - $verifyIP = Get-NetIPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.IPAddress -eq $IPAddress } - - if ($verifyIP) { - $ipConfigured = $true - Write-LogMessage -Message "Applied and verified static IP configuration: $IPAddress/$prefixLength" -Level "INFO" - break - } else { - Write-LogMessage -Message "IP verification failed on attempt $ipAttempt" -Level "WARN" - if ($ipAttempt -lt $MaxRetries) { - Start-Sleep -Seconds $RetryDelaySeconds - } - } - } catch { - Write-LogMessage -Message "Attempt $ipAttempt to set IP failed: $_" -Level "ERROR" - Write-Host " [ERROR] $_" -ForegroundColor Red - if ($ipAttempt -lt $MaxRetries) { - Start-Sleep -Seconds $RetryDelaySeconds - } else { - throw "Failed to set static IP after $MaxRetries attempts: $_" - } - } - } - - if (-not $ipConfigured) { - throw "Failed to verify static IP configuration after $MaxRetries attempts" + Write-Host " Managing gateway route..." -ForegroundColor Gray + if (-not (Set-IPv4DefaultGatewaySafe -InterfaceName $InterfaceName -Gateway $Gateway)) { + throw 'Failed to configure the default gateway' + } + # Keep old addresses until the replacement address and route are ready. + $superseded = @(@(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address) + @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address -PolicyStore PersistentStore) | + Where-Object IPAddress -ne $IPAddress | Sort-Object IPAddress -Unique) + foreach ($address in $superseded) { + if (-not (Remove-IPv4AddressSafe -InterfaceName $InterfaceName -IPAddress $address.IPAddress)) { + throw "Could not remove superseded address $($address.IPAddress)" } - } else { - # IP was already configured correctly, mark as success - $ipConfigured = $true - } - - # Handle gateway configuration regardless of whether IP was just set or already existed - if ($Gateway) { - $null = Set-IPv4DefaultGatewaySafe -InterfaceName $InterfaceName -Gateway $Gateway } # CRITICAL STEP 3: Configure DNS with retry mechanism @@ -3481,8 +3460,7 @@ function Set-StaticIP { } if (-not $dnsConfigured) { - Write-LogMessage -Message "Warning: DNS configuration may not have been applied correctly" -Level "WARN" - Write-Host " [WARN] DNS configuration may need manual verification" -ForegroundColor Yellow + throw "DNS configuration did not verify" } } else { Write-LogMessage -Message "No DNS servers specified. Skipping DNS configuration." -Level "WARN" @@ -3500,6 +3478,7 @@ function Set-StaticIP { # === FINAL STATE VERIFICATION === Write-Host " Performing final state verification..." -ForegroundColor Gray Start-Sleep -Milliseconds 1500 # Give Windows time to settle (increased from 1000ms) + Wait-IPv4AddressReady -InterfaceName $InterfaceName -IPAddress $IPAddress -PrefixLength $prefixLength $ipConfig = Get-NetIPConfiguration -InterfaceAlias $InterfaceName -ErrorAction Stop $verificationPassed = $true @@ -3545,9 +3524,9 @@ function Set-StaticIP { } # Verify DNS - $currentDNS = (Get-DnsClientServerAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue).ServerAddresses - if (-not ($currentDNS -contains $PrimaryDNS)) { - $verificationIssues += "Primary DNS not found in configuration" + $currentDNS = (Get-DnsClientServerAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction Stop).ServerAddresses + if (($currentDNS -join ',') -ne ($dnsServers -join ',')) { + $verificationIssues += "DNS server order or values differ from the requested configuration" $verificationPassed = $false } @@ -3558,13 +3537,7 @@ function Set-StaticIP { $verificationPassed = $false } - if (-not $verificationPassed) { - Write-Host "`n[WARN] Configuration completed but verification found issues:" -ForegroundColor Yellow - foreach ($issue in $verificationIssues) { - Write-Host " - $issue" -ForegroundColor Yellow - Write-LogMessage -Message "Verification issue: $issue" -Level "WARN" - } - } + if (-not $verificationPassed) { throw ($verificationIssues -join "; ") } # Keep DNS reachability as a quiet diagnostic; the apply step verifies configuration state. if ($verificationPassed -and $Gateway -and $currentDNS) { @@ -3586,25 +3559,6 @@ function Set-StaticIP { Write-LogMessage -Message "Skipped DNS reachability test because no gateway is configured" -Level "DEBUG" } - # Clean up any stray APIPA or duplicate IP addresses after static IP is applied - Start-Sleep -Milliseconds 500 - $allIPs = Get-NetIPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue - if ($allIPs -and $allIPs.Count -gt 1) { - foreach ($ip in $allIPs) { - # Remove APIPA addresses or any IP that isn't our configured static IP - if ($ip.IPAddress -like "169.254.*" -or ($ip.IPAddress -ne $IPAddress)) { - if (Remove-IPv4AddressSafe -InterfaceName $InterfaceName -IPAddress $ip.IPAddress -Quiet) { - Write-LogMessage -Message "Removed stray IP address after static config: $($ip.IPAddress)" -Level "DEBUG" - } - } - } - - # Re-fetch clean config - Start-Sleep -Milliseconds 300 - $ipConfig = Get-NetIPConfiguration -InterfaceAlias $InterfaceName -ErrorAction SilentlyContinue - $ipv4Info = Get-NetIPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.IPAddress -eq $IPAddress } - } - # Show summary Write-Host "`n[OK] Static IP configuration successful" -ForegroundColor Green if ($verificationPassed) { @@ -3614,26 +3568,22 @@ function Set-StaticIP { Show-IPv4ConfigurationSummary -InterfaceName $InterfaceName -IPConfig $ipConfig -IPv4Address $ipv4Info -DHCPStatus $dhcpStatus Write-LogMessage -Message "Static IP configuration verified for ${InterfaceName}: $IPAddress/$prefixLength, gateway=$(if($Gateway){$Gateway}else{'none'}), dns=$($dnsServers -join ', ')" -Level "INFO" + return $true } catch { $errorMessage = "Error: Unable to set static IP configuration. $_" Write-Host "" Write-Host "[FAIL] Configuration failed: $errorMessage" -ForegroundColor Red Write-LogMessage -Message $errorMessage -Level "CRITICAL" - # Attempt rollback to previous configuration if available - if ($backupConfig -and $backupConfig.DHCPEnabled -eq 'Enabled') { - Write-Host "`nAttempting to restore previous DHCP configuration..." -ForegroundColor Yellow - Write-LogMessage -Message "Attempting rollback to DHCP after failed static IP configuration" -Level "WARN" - - if (Restore-DHCPConfiguration -InterfaceName $InterfaceName) { - Write-Host "[OK] Rolled back to DHCP configuration" -ForegroundColor Green + if ($configurationChanged -and $backupConfig) { + Write-Host "`nRestoring previous network configuration..." -ForegroundColor Yellow + if (Restore-NetworkConfiguration -Backup $backupConfig) { + Write-Host "[OK] Previous network settings restored" -ForegroundColor Green } else { - Write-Host "[WARN] Rollback failed" -ForegroundColor Red - Write-Host "You may need to manually reconfigure the network adapter." -ForegroundColor Yellow + Write-Host "[FAIL] Recovery incomplete. Use the saved backup and VM console to restore settings." -ForegroundColor Red } - } else { - Write-Host "`nNo automatic rollback available. Manual intervention may be required." -ForegroundColor Yellow } + return $false } } @@ -3706,6 +3656,11 @@ function Set-DHCP { return $false } + $backupConfig = Backup-NetworkConfiguration -InterfaceName $InterfaceName + if (-not $backupConfig) { + Write-Host '[FAIL] Cannot safely proceed without a configuration backup.' -ForegroundColor Red + return $false + } # Retry mechanism for DHCP configuration for ($attempt = 1; $attempt -le $MaxRetries; $attempt++) { try { @@ -3717,13 +3672,17 @@ function Set-DHCP { # Step 1: Clear existing IP configuration (parallel operations where possible) Write-Host " Releasing existing configuration..." -ForegroundColor Gray + Set-NetIPInterface -InterfaceAlias $InterfaceName -AddressFamily IPv4 -Dhcp Disabled -ErrorAction Stop + if (-not (Set-IPv4DefaultGatewaySafe -InterfaceName $InterfaceName)) { throw 'Could not clear static default routes' } # Remove ALL existing IP addresses (IPv4 only for speed) # This ensures we clear both static IPs and APIPA addresses (169.254.x.x) left from previous configs - $existingIPs = Get-NetIPAddress -InterfaceAlias $InterfaceName -AddressFamily IPv4 -ErrorAction SilentlyContinue + $existingIPs = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address) if ($existingIPs) { foreach ($ip in $existingIPs) { - $null = Remove-IPv4AddressSafe -InterfaceName $InterfaceName -IPAddress $ip.IPAddress -PrefixLength $ip.PrefixLength + if (-not (Remove-IPv4AddressSafe -InterfaceName $InterfaceName -IPAddress $ip.IPAddress -PrefixLength $ip.PrefixLength)) { + throw "Could not remove old address $($ip.IPAddress)" + } } } @@ -3744,14 +3703,7 @@ function Set-DHCP { # Step 3: Trigger DHCP renewal without disconnecting (important for Wi-Fi) Write-Host " Renewing DHCP lease..." -ForegroundColor Gray - # Use ipconfig /renew which doesn't disconnect Wi-Fi adapters - # Try interface-specific renewal first, then fall back to full renew - try { - $null = & ipconfig /renew $InterfaceName 2>&1 - } catch { - # If that fails, try full renewal - $null = & ipconfig /renew 2>&1 - } + Invoke-InterfaceDHCPRenewal -InterfaceName $InterfaceName # Step 4: Wait for DHCP lease with adaptive timeout $maxWait = 10 # Maximum wait time in seconds @@ -3768,10 +3720,12 @@ function Set-DHCP { try { $ipConfig = Get-NetIPConfiguration -InterfaceAlias $InterfaceName -ErrorAction SilentlyContinue if ($ipConfig -and $ipConfig.IPv4Address -and $ipConfig.IPv4Address.IPAddress) { - $currentIP = $ipConfig.IPv4Address.IPAddress # Check if we got a valid DHCP address (not APIPA) - if ($currentIP -notlike "169.254.*" -and $currentIP -ne "0.0.0.0") { + $lease = @(Get-IPv4StoreState -InterfaceName $InterfaceName -Kind Address | + Where-Object { $_.PrefixOrigin -eq 'Dhcp' -and $_.AddressState -eq 'Preferred' -and + $_.IPAddress -notlike '169.254.*' -and $_.IPAddress -ne '0.0.0.0' }) + if ($lease.Count -gt 0) { $dhcpSuccess = $true break } @@ -3844,8 +3798,13 @@ function Set-DHCP { # If we get here, all attempts failed Write-Host "Failed to configure DHCP after $MaxRetries attempts." -ForegroundColor Red Write-Host "Available interfaces:" -ForegroundColor Yellow - Get-NetAdapter | Select-Object Name, Status, LinkSpeed | Format-Table -AutoSize + Get-NetAdapter | Select-Object Name, Status, LinkSpeed | Format-Table -AutoSize | Out-Host Write-LogMessage -Message "Failed to configure DHCP for $InterfaceName after $MaxRetries attempts." -Level "CRITICAL" + if (Restore-NetworkConfiguration -Backup $backupConfig) { + Write-Host '[OK] Previous network settings restored.' -ForegroundColor Green + } else { + Write-Host '[FAIL] Recovery incomplete. Restore settings using the saved backup and local console.' -ForegroundColor Red + } return $false } @@ -4635,22 +4594,16 @@ function Select-NetworkInterface { $showDownInterfaces = $false # Toggle for showing/hiding down interfaces while ($true) { - # Filter interfaces based on the toggle - exclude virtual/loopback adapters + # Guest and host virtual NICs are valid configuration targets. if ($showDownInterfaces) { - $interfaces = Get-NetAdapter | Where-Object { - $_.InterfaceDescription -notmatch '(Hyper-V|WSL|Loopback|Teredo|6to4|VirtualBox|VMware)' -and - $_.Virtual -eq $false - } + $interfaces = @(Get-NetAdapter) } else { - $interfaces = Get-NetAdapter | Where-Object { - $_.Status -eq "Up" -and - $_.InterfaceDescription -notmatch '(Hyper-V|WSL|Loopback|Teredo|6to4|VirtualBox|VMware)' -and - $_.Virtual -eq $false - } + $interfaces = @(Get-NetAdapter | Where-Object Status -eq 'Up') } if ($interfaces.Count -eq 0) { Write-Host "No network interfaces found with the current filter." -ForegroundColor Red + if ($showDownInterfaces) { return $null } $showDownInterfaces = $true # Automatically show down interfaces in case of no results continue } @@ -5622,7 +5575,7 @@ while ($true) { try { $settings = Read-IPConfigurationSettings -InterfaceName $interfaceName if ($settings) { - Set-StaticIP -InterfaceName $interfaceName ` + $null = Set-StaticIP -InterfaceName $interfaceName ` -IPAddress $settings.IPAddress ` -SubnetMask $settings.SubnetMask ` -Gateway $settings.Gateway ` @@ -5720,7 +5673,7 @@ while ($true) { Write-Host "" if (Read-YesNo -Prompt "Apply this configuration?" -Default $false) { - Set-StaticIP -InterfaceName $interfaceName ` + $null = Set-StaticIP -InterfaceName $interfaceName ` -IPAddress $config.IPAddress ` -SubnetMask $config.SubnetMask ` -Gateway $config.Gateway ` diff --git a/Network_Configuration_Menu.png b/Network_Configuration_Menu.png index 86d37dc..3a48e36 100644 Binary files a/Network_Configuration_Menu.png and b/Network_Configuration_Menu.png differ diff --git a/README.md b/README.md index a2d1276..56ad5ba 100644 --- a/README.md +++ b/README.md @@ -4,50 +4,43 @@ ## Description -A powerful PowerShell 5.1-compatible script for managing IPv4 network settings with GDPR-aware privacy controls. Features static IP/DHCP configuration, **modern IP profiles**, real-time network monitoring, diagnostics, subnet tools, **MAC vendor lookup**, managed backups, and log retention. +A Windows PowerShell 5.1 script for managing IPv4 network settings with opt-in logging and IP masking. Features static IP/DHCP configuration, IP profiles, live network monitoring, diagnostics, subnet tools, MAC vendor lookup, managed backups, and log retention. -**Version**: 2.9 +**Version**: 3.0 (unreleased) + +Profile and manual static reapplication, static-to-DHCP, and DHCP-to-static have been confirmed by user testing on a Proxmox Windows VM. Reboot persistence and the remaining live release checks are tracked in [Debug/TESTING.md](Debug/TESTING.md). ## Key Features ### Network Management -- **Live Interface Monitoring** : Real-time event tracking with interactive controls - - Cable plug/unplug detection with link status - - IP acquisition, loss, and configuration changes - - Gateway and DNS server monitoring - - DHCP/Static configuration transitions - - WiFi connection and signal strength tracking - - On-demand diagnostics (D), status (S), clear log (C) - - Dynamic window title with live stats -- **MAC Vendor Lookup**: Identify device manufacturers from MAC addresses - - Online API integration with local caching - - Supports multiple MAC formats (colons, dashes, or no separators) - - Automatic retry for offline scenarios - - Displays vendor info in IP configuration view - - Interactive lookup tool (Option V) -- **Advanced IP Conflict Detection**: Multi-layered scanning (6 methods) - - NetBIOS name query (catches Windows devices) - - Gratuitous ARP with cache clear - - ICMP ping verification - - PowerShell ARP cache analysis - - TCP port scan (SMB ports 445, 139) - - Final comprehensive ARP check +- **Live Interface Monitoring**: Track link, IP, gateway, DNS, DHCP, and Wi-Fi changes; run diagnostics from the monitor. +- **MAC Vendor Lookup**: Query manufacturers using common MAC formats, cache successful results for the session, and retry failed lookups on a later request. +- **IP Conflict Detection**: Exact local ownership and neighbor checks on the selected interface + - Bounded ping probe to populate the neighbor cache + - Ignore unrelated adapters, similar IP strings, and incomplete neighbors + - Wait for Windows duplicate-address detection; reject Duplicate and timed-out Tentative addresses + - Treat negative pre-flight probes as advisory - **Static IP & DHCP**: Switch between static and DHCP configurations - Automatic cleanup of residual IP addresses (prevents APIPA accumulation) - Post-configuration verification - Subnet-aware gateway suggestions and strict IPv4/subnet input validation + - Configure addresses and gateway routes independently to avoid duplicate gateway creation + - Reconcile active and persistent IPv4 default routes on the selected adapter + - Attempt to restore prior static or DHCP settings on apply failure, including DNS mode and manual DNS overrides; report incomplete recovery + - Create durable gateway routes without unsupported explicit PersistentStore creation and show gateway provider errors in the console + - Verify IPv4 DNS values and order without changing IPv6 DNS - **IP Profiles**: Save and apply reusable JSON profiles with names, groups, adapter metadata, gateway/DNS settings, and legacy XML fallback. Profile replacement requires confirmation. - **Diagnostics**: Connectivity test, DNS lookup, traceroute, TCP port check, ARP table, and subnet calculator - **Subnet Calculator**: CIDR calculations, binary representations, subnetting guides, and safer blank/invalid input handling -- **Interface Management**: Rename and manage multiple network adapters +- **Interface Management**: Rename and manage multiple network adapters, including virtual NICs ### Privacy Controls -- **User Consent Management**: Explicit opt-in for logging -- **IP Pseudonymization**: Automatic masking (192.168.1.xxx) -- **User Rights**: Access, logs-only deletion, full local-data deletion, consent changes, and data portability -- **Local Storage**: Logs, profiles, and backups stay on your computer. MAC vendor lookup sends the first six MAC digits (the vendor prefix) to `api.macvendors.com`; update checks download the script from GitHub. +- **Logging Choice**: Explicit opt-in for logging; profiles and backups are created by user actions +- **Stored Data**: Interface names, timestamps, masked log IP addresses, and full settings in saved profiles/backups +- **Data Controls**: Access, logs-only deletion, full local-data deletion, consent changes, and export +- **Local Storage**: Logs, profiles, and backups stay in `%APPDATA%\Network_Configuration_Script`. MAC vendor lookup sends the first six MAC digits (the vendor prefix) to `api.macvendors.com`; update checks download the script from GitHub. - **Privacy Dashboard**: Dedicated menu for privacy controls - **Retention Controls**: Log rotation plus age/count cleanup for logs and managed backups - **Log Viewer**: Search current and rotated JSON logs by message text, severity, and date; page through results in the console @@ -55,12 +48,10 @@ A powerful PowerShell 5.1-compatible script for managing IPv4 network settings w ### User Experience - **Intuitive Menu**: Grouped configuration, diagnostics, and tools sections with single-key actions -- **Smart Validation**: IP, subnet, DNS, and hostname validation +- **Input Validation**: IPv4 addresses, subnet masks, and DNS server addresses - **Consistent Prompts**: `y/yes/n/no` confirmation handling across common workflows - **Auto Version Sync**: Version tracking from script header - **Safer Updates**: Downloads are parsed and staged before replacement, with a managed backup of the previous script -- **AppData Storage**: Organized file management in `%APPDATA%` -- **Pure ASCII**: Maximum compatibility across systems - **PSScriptAnalyzer Clean**: Clean with the included project settings for this interactive console utility ## Quick Actions @@ -76,6 +67,10 @@ A powerful PowerShell 5.1-compatible script for managing IPv4 network settings w - `d` - DNS cache flush - `i` - Adapter details (MAC, speed, status) - `l` - Query logs (recent entries, filters, and raw log access) +- `m` - Live network monitor +- `s` - Subnet calculator +- `p` - Privacy controls +- `u` - Check for updates ## Log Viewer @@ -83,54 +78,20 @@ Press `l` in the main menu or choose **Query Logs** in the Privacy menu. The vie Logging consent controls new entries. Previously saved logs remain viewable until deleted. -## Live Network Monitoring (Option 12) - -Monitor your network interface in real-time with comprehensive event tracking: - -### Features - -- **Event Detection**: Cable connections, IP changes, DHCP/Static transitions, Gateway/DNS updates, WiFi network switching -- **Smart DHCP Tracking**: Time-based DHCP renewal detection (prevents false positives) -- **Activity Heartbeat**: Shows monitoring status during idle periods (every 60 seconds) -- **Interactive Controls**: - - `D` - Run network diagnostics (Gateway, DNS, Internet) - - `S` - Show current interface status - - `C` - Clear event log - - `Q/Esc` - Exit monitoring -- **Live Window Title**: Real-time status updates showing interface state, IP, config type, and event count -- **Color-Coded Events**: Green (acquired), Red (lost), Yellow (changed), Cyan (updated) -- **WiFi Support**: SSID display, signal strength, network switching detection -- **Detailed Diagnostics**: Ping tests with min/max/avg latency and packet loss percentages -- **Consent-Based Logging**: Monitoring events are logged only after opt-in, with IP address masking - -### Example Events - -```text -[14:23:15] NETWORK DISCONNECTED - No link detected -[14:23:15] IP ADDRESS LOST - Was 192.168.1.xxx -[14:23:15] GATEWAY LOST - Was 192.168.1.1 -[14:23:15] DNS SERVERS CLEARED - Was 1.1.1.1, 1.0.0.1 -[14:23:15] LINK SPEED CHANGED: 1.0 Gbps -> 100 Mbps -[14:23:22] NETWORK CONNECTED - Link established -[14:23:22] DHCP REQUEST - Requesting IP address... -[14:23:22] IP ADDRESS ACQUIRED: 10.0.0.xxx -[14:23:22] DHCP: Acquired from 10.0.0.1 -[14:23:22] DHCP LEASE: Expires Friday, 2 December 2025 14:23:20 -[14:23:22] GATEWAY ACQUIRED: 10.0.0.1 -[14:23:22] DNS SERVERS CONFIGURED: 8.8.8.8, 8.8.4.4 - [Monitoring active - No events for 1 minute] -``` +## Live Network Monitoring (M) -## Privacy Controls +Press `m` to monitor the selected adapter. The console shows timestamped link, address, gateway, DNS, DHCP, and Wi-Fi changes, updates the window title, and displays an idle heartbeat every 60 seconds. Monitoring events follow your logging consent and IP masking settings. -- **Data Collected**: Interface names, log IP addresses (pseudonymized), saved profiles/backups, configuration settings, timestamps -- **Logging Choice**: Logging requires opt-in consent; saved profiles and backups are created by user actions -- **Storage**: Local only (`%APPDATA%\Network_Configuration_Script`) -- **Data Controls**: View logs, delete stored data, change logging consent, and export local data +While monitoring: + +- `D` - Run gateway, DNS, and internet diagnostics +- `S` - Show current interface status +- `C` - Clear the displayed event log +- `Q/Esc` - Exit monitoring ## Prerequisites -- Windows OS with PowerShell 5.1+ +- Windows with Windows PowerShell 5.1 - Administrator privileges - Script execution policy @@ -140,7 +101,9 @@ Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned ## Hardware Compatibility -Most standard Windows Ethernet and Wi-Fi adapters should work through the built-in networking cmdlets used by this script. Some Realtek and MediaTek Wi-Fi adapters, especially in virtualized, passthrough, or vendor-driver-specific setups, may behave inconsistently when switching between DHCP and static IPv4 configuration. If an adapter reports that an IP address or gateway already exists during a static change, try DHCP rollback, reconnect the adapter, update the vendor driver, or use the Windows network settings UI for that adapter. +The script uses built-in Windows networking cmdlets and includes virtual adapters in selection. User testing confirms the main static/DHCP workflows on a Proxmox Windows VM; this does not establish compatibility with every NIC model, driver, or Windows build. + +On configuration failure, check the displayed error and recovery result. Recovery is best effort: use the saved backup and local or VM console if it reports incomplete recovery. A configuration change can interrupt a remote session. Managed backups are stored under `%APPDATA%\Network_Configuration_Script\backups`. ## Usage @@ -149,6 +112,12 @@ Most standard Windows Ethernet and Wi-Fi adapters should work through the built- 3. **First Run**: Choose whether to enable optional logging 4. **Configure**: Follow interactive prompts -## Changelog +## Testing + +Run `powershell -NoProfile -ExecutionPolicy Bypass -File .\Debug\test_regression.ps1` for the complete isolated regression suite and static checks. See [Debug/TESTING.md](Debug/TESTING.md) for dependencies, coverage, reports, and live release validation. + +The latest local Windows PowerShell 5.1 run passed all 11 suites, including 130 named Pester tests. Automated network tests use mocks and do not modify real adapters. + +## Release history See [CHANGELOG.md](CHANGELOG.md) for release history.