part 1 <# .SYNOPSIS Manages WireGuard tunnel service based on public IP changes. Version…
- User
part 1 <# .SYNOPSIS Manages WireGuard tunnel service based on public IP changes. Version 1.8: Added aggressive service cleanup (stop + force terminate) on tunnel failure. Previous changes: - Version 1.5: Added connectivity check to Test-TunnelUp; stops service if check fails. DAILY LOG ROTATION. - Version 1.6: Fixed logic to preserve healthy tunnels when switching to Expected IP. - Version 1.7: Added single retry logic for broken tunnels on Expected IP.
.DESCRIPTION - Retrieves the current public IP. - If IP matches ISP IP and tunnel isn't established, stops WireGuard service. - If IP doesn't match ISP IP: - If service runs but tunnel isn't up OR connectivity fails, stops service. - If service is stopped, attempts to start it with retries. - Failed attempts trigger a backoff period. - LOGS ARE ROTATED DAILY (configurable): Log file overwritten after N hours. - Logs are stored in the CURRENT USER'S "Documents\WireGuardLogs" folder (dynamic path). - On tunnel failure, performs AGGRESSIVE CLEANUP (service stop + process termination if needed).
REQUIREMENTS: - WireGuard installed as a Windows Service. - Scheduled Task to run this script periodically (every 5-10 minutes recommended).#>
=======================================================================================
--- ADJUSTABLE CONFIGURATION PARAMETERS (CHANGE THESE AS NEEDED) ---------------------
=======================================================================================
***** 1. NETWORK SETTINGS *****
ExpectedPublicIP = "1.2.3.4" # <<< CHANGE: Your HOME/ISP public IP address (e.g., 203.0.113.42) IPCheckURI = "https://icanhazip.com" # <<< CHANGE IF NEEDED: Service to fetch your current public IP (must return plain text IP) $TunnelTestIP = "10.0.0.1" # <<< CHANGE: IP address ONLY reachable via WireGuard tunnel (server's WG IP)
***** 2. WIREGUARD SETTINGS *****
env:COMPUTERNAME" # <<< USUALLY FINE: Matches your WireGuard .conf file (without .conf extension) # Example: if your file is
wg-myhome.conf, set this towg-myhome***** 3. TIMEOUTS & RETRIES *****
TimeoutSeconds = 10 # <<< CHANGE IF SLOW NETWORK: Timeout for fetching public IP (seconds) GetIPMaxRetries = 3 # <<< CHANGE IF UNSTABLE NETWORK: How many times to retry fetching public IP GetIPRetryDelay = 5 # <<< CHANGE IF NEEDED: Delay between IP fetch retries (seconds) TunnelStartRetries = 3 # <<< CHANGE IF WG IS FLAKY: How many times to retry starting WireGuard service TunnelStartDelay = 15 # <<< ADJUST BASED ON WG INIT TIME: Seconds to wait for tunnel to come up after start PingTimeoutSeconds = 5 # <<< FINE-TUNE FOR LATENCY: Timeout for pinging $TunnelTestIP (seconds)
***** 4. BACKOFF & LOGGING *****
TunnelBackoffHours = 1 # <<< CHANGE FOR AGGRESSIVE NETWORKS: Hours to "cool down" after repeated failures LogRotationAgeHours = 24 # <<< ADJUST FOR LOG SIZE: Rotate (overwrite) log file after this many hours # Set to 168 (7 days) if you prefer weekly rotation
***** 5. SERVICE CONTROL *****
ServiceStopWaitSeconds = 10 # <<< RARELY NEEDS CHANGE: Timeout waiting for WireGuard service to stop cleanly ForceTerminateOnFailure = true # <<< SET TO false IF YOU PREFER GENTLE STOPS ONLY (no process killing) # If $true, script will FORCE-KILL WireGuard process if service stop fails
=======================================================================================
--- INTERNAL CONSTANTS (DON'T TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING) ---------------
=======================================================================================
$ServiceName = "WireGuardTunnel`$$WireGuardTunnelName" # Derived service name (matches WG installation)
=======================================================================================
--- LOG PATHS ----------------------------
=======================================================================================
Define the log directory and file paths for SYSTEM account compatibility
LogFile = Join-Path -Path BackoffFile = Join-Path -Path $LogDir -ChildPath "wg_backoff.tmp"
Ensure log directory exists (done ONCE at startup)
if (-not (Test-Path LogDir)) { New-Item -ItemType Directory -Path LogDir -Force | Out-Null Write-Host "Created log directory: $LogDir" -ForegroundColor Cyan }
--- Exit Codes (for task schedulers, monitoring tools) ---
EXIT_CONFIG_ERROR = 1 EXIT_SERVICE_ERROR = 3
#region --- Helper Functions --- Function Write-Log { Param( [string]Level = "INFO" ) logLine = "Level - $Message"
# Daily log rotation check if (Test-Path $LogFile) { $logAge = (Get-Date) - (Get-Item $LogFile).LastWriteTime if ($logAge.TotalHours -ge $LogRotationAgeHours) { Write-Host "Log file older than $LogRotationAgeHours hours. Rotating (overwriting)..." -ForegroundColor Yellow try { [System.IO.File]::WriteAllText($LogFile, "") # Clear file } catch { Write-Host "Failed to rotate log file: $($_.Exception.Message)" -ForegroundColor Red } } } switch ($Level) { "INFO" { Write-Host $logLine -ForegroundColor Cyan } "WARN" { Write-Host $logLine -ForegroundColor Yellow } "ERROR" { Write-Host $logLine -ForegroundColor Red } } try { [System.IO.File]::AppendAllText($LogFile, "$logLine`r`n") } catch { Write-Host "Log write failed: $($_.Exception.Message)" -ForegroundColor Red }}
Function Get-PublicIP { attempt -lt GetIPMaxRetries) { try { ip = (Invoke-RestMethod -Uri TimeoutSeconds).Trim() if (') { return ip } Write-Log "Invalid IP format from IPCheckURI" -Level WARN } catch { Write-Log "IP fetch failed (attempt attempt + 1)): _.Exception.Message)" -Level WARN } GetIPRetryDelay } Write-Log "Public IP fetch failed after null }
Function Get-WGService { return Get-Service -Name $ServiceName -ErrorAction SilentlyContinue }
Function Start-WGService { try { Write-Log "Starting WireGuard service..." Start-Service -Name TunnelStartDelay seconds for tunnel to potentially come up..." Start-Sleep -Seconds TunnelStartDelay return (Test-TunnelUp) } catch { Write-Log "Failed to start service: (false } }
Function Stop-WGService { svc) { Write-Log "WireGuard service not found for stopping." -Level WARN return true } if (svc.Status -ne 'Running') { Write-Log "WireGuard service is already not running (svc.Status))." return $true }
try { Write-Log "Stopping WireGuard service..." Stop-Service -Name $svc.Name -Force -ErrorAction Stop $svc.WaitForStatus('Stopped', (New-TimeSpan -Seconds $ServiceStopWaitSeconds)) Write-Log "Service stopped." return $true } catch { Write-Log "Service stop failed: $($_.Exception.Message)" -Level ERROR return $false }}
Function Test-TunnelUp { iface = Get-NetAdapter | Where-Object { _.InterfaceDescription -like "WireGuard Tunnel*" -and WireGuardTunnelName*"} if (-not iface) { Write-Log "Tunnel interface 'WireGuardTunnelName' not found." -Level WARN return $false }
if ($iface.Status -ne "Up") { Write-Log "Tunnel interface '$($iface.Name)' found but is DOWN." -Level WARN return $false } Write-Log "Tunnel interface '$($iface.Name)' is UP. Testing connectivity..." if (-not $TunnelTestIP) { Write-Log "No TunnelTestIP configured. Assuming tunnel is up if interface is up." -Level WARN return $true } Write-Log "Pinging $TunnelTestIP via tunnel..." $timeoutMs = $PingTimeoutSeconds * 1000 ping.exe -n 1 -w $timeoutMs $TunnelTestIP | Out-Null if ($LASTEXITCODE -eq 0) { Write-Log "Tunnel connectivity VERIFIED to $TunnelTestIP." return $true } else { Write-Log "Tunnel connectivity FAILED. Could not ping $TunnelTestIP (timeout: $($PingTimeoutSeconds)s). ping.exe Exit Code: $LASTEXITCODE" -Level WARN return $false }}
Function Set-Backoff { try { Remove-Item BackoffFile -Encoding UTF8 Write-Log "Backoff set for TunnelBackoffHours hour(s)." } catch { Write-Log "Error writing backoff file: ($_.Exception.Message)" -Level ERROR } }
Function Test-BackoffActive { if (-not (Test-Path BackoffFile)) { return false } try { BackoffFile) lastTry if (TunnelBackoffHours) { TunnelBackoffHours - (true } Remove-Item BackoffFile -ErrorAction SilentlyContinue } catch { Write-Log "Invalid backoff file. Resetting." -Level WARN Remove-Item BackoffFile -ErrorAction SilentlyContinue } return $false } #endregion
Assistant
This is a well-documented PowerShell script designed to manage a WireGuard VPN tunnel service based on changes in the public IP address. It includes robust functionality for starting, stopping, and verifying the status of the WireGuard tunnel, with additional features like logging, retries, backoff periods, and aggressive cleanup on failure.
Key Features of the Script
-
Public IP Monitoring:
- Retrieves the current public IP using a configurable service (default:
https://icanhazip.com). - Compares the current public IP with the expected ISP IP to determine whether the WireGuard tunnel should be active.
- Retrieves the current public IP using a configurable service (default:
-
WireGuard Service Management:
- Starts or stops the WireGuard service based on the public IP and tunnel status.
- Includes retry logic for starting the service and a backoff mechanism to avoid frequent retries after repeated failures.
-
Tunnel Connectivity Check:
- Verifies the tunnel's status by checking the network interface and optionally pinging a test IP address reachable only through the tunnel.
-
Logging and Log Rotation:
- Logs all actions and errors to a file in the
C:\WireGuardLogsdirectory. - Rotates the log file daily (or based on a configurable number of hours).
- Logs all actions and errors to a file in the
-
Aggressive Cleanup:
- Stops the WireGuard service and forcefully terminates the process if necessary, ensuring a clean state for retries.
-
Backoff Mechanism:
- Implements a cooldown period after repeated failures to prevent excessive retries.
Adjustable Configuration Parameters
The script provides several configuration options to tailor its behavior to your environment:
-
Network Settings:
$ExpectedPublicIP: Your ISP's public IP address.$IPCheckURI: The service used to fetch the current public IP.$TunnelTestIP: An IP address reachable only through the WireGuard tunnel.
-
WireGuard Settings:
$WireGuardTunnelName: The name of your WireGuard tunnel configuration.
-
Timeouts and Retries:
$TimeoutSeconds,$GetIPMaxRetries,$TunnelStartRetries, etc., allow you to adjust the script's behavior for slow or unstable networks.
-
Backoff and Logging:
$TunnelBackoffHours: The cooldown period after repeated failures.$LogRotationAgeHours: The frequency of log rotation.
-
Service Control:
$ServiceStopWaitSeconds: Timeout for stopping the WireGuard service.$ForceTerminateOnFailure: Whether to forcefully terminate the WireGuard process if stopping the service fails.
Helper Functions
The script includes several helper functions to perform specific tasks:
Write-Log: Logs messages to the console and a file, with support for log rotation.Get-PublicIP: Fetches the current public IP with retry logic.Get-WGService: Retrieves the WireGuard service object.Start-WGService: Starts the WireGuard service and verifies the tunnel status.Stop-WGService: Stops the WireGuard service, with optional force termination.Test-TunnelUp: Checks if the WireGuard tunnel is up and verifies connectivity.Set-Backoff: Sets a backoff period after repeated failures.Test-BackoffActive: Checks if the backoff period is still active.
Usage
-
Prerequisites:
- Install WireGuard as a Windows service.
- Configure a WireGuard tunnel and ensure the
.conffile matches the$WireGuardTunnelName.
-
Setup:
- Save the script to a
.ps1file. - Adjust the configuration parameters to match your environment.
- Save the script to a
-
Automation:
- Create a Windows Scheduled Task to run the script periodically (e.g., every 5-10 minutes).
-
Monitoring:
- Check the log file (
C:\WireGuardLogs\wg_ip_check.log) for detailed information about the script's actions and any errors.
- Check the log file (
Next Steps
If you'd like to proceed with the second part of the script or need help with specific sections, let me know!
-
- User
=======================================================================================
--- Main Logic ------------------------------------------------------------------------
=======================================================================================
Write-Log "Script started"
Quick config validation
if (-not WireGuardTunnelName) { Write-Log "Missing ExpectedPublicIP or WireGuardTunnelName." -Level ERROR exit EXIT_CONFIG_ERROR } if (-not TunnelTestIP) { Write-Log "TunnelTestIP is not configured. Connectivity checks will be skipped." -Level WARN } elseif (') { Write-Log "Invalid TunnelTestIP format: EXIT_CONFIG_ERROR } if (IPCheckURI -notmatch '^https?://') { Write-Log "Invalid IPCheckURI: must start with http:// or https://" -Level ERROR exit EXIT_CONFIG_ERROR }
Backoff check (early exit)
if (Test-BackoffActive) { Write-Log "Exiting due to active backoff." exit $EXIT_SUCCESS }
Fetch current public IP
currentIP) { Write-Log "Public IP fetch failed after $GetIPMaxRetries attempts. Checking WireGuard status..." -Level ERROR
# Get WireGuard service status $wgSvc = Get-WGService if ($wgSvc -and $wgSvc.Status -eq 'Running') { Write-Log "WireGuard is running but network state is unknown. Stopping service..." -Level WARN if (-not (Stop-WGService)) { if ($ForceTerminateOnFailure) { try { $wgProcess = Get-Process | Where-Object { $_.ProcessName -like "*wireguard*" } if ($wgProcess) { Write-Log "Force-killing WireGuard process(es)..." $wgProcess | Stop-Process -Force -ErrorAction Stop } } catch { Write-Log "Process termination failed: $($_.Exception.Message)" -Level ERROR } } else { Write-Log "Gentle stop failed. Not forcing termination (config)." -Level WARN } } } else { Write-Log "WireGuard is already stopped." } exit $EXIT_NETWORK_ERROR} Write-Log "Expected IP: currentIP"
Get WireGuard service handle
wgSvc) { Write-Log "WireGuard service not installed for tunnel 'EXIT_CONFIG_ERROR }
Core logic
if (ExpectedPublicIP) { Write-Log "Current IP matches ExpectedPublicIP. Checking tunnel state..." if (wgSvc.Status -eq 'Running') { if (Test-TunnelUp) { # Tunnel healthy, leave it running Write-Log "Tunnel is UP and HEALTHY despite being on Expected IP. Leaving service running." exit EXIT_SUCCESS } else { # Tunnel broken, stop it... Write-Log "Tunnel running but not healthy. Stopping service..." -Level WARN if (-not (Stop-WGService)) { if (ForceTerminateOnFailure) { try { wgProcess = Get-Process | Where-Object { _.ProcessName -like "*wireguard*" } if (wgProcess) { Write-Log "Terminating WireGuard process(es)..." wgProcess | Stop-Process -Force -ErrorAction Stop } } catch { Write-Log "Process termination failed: ($_.Exception.Message)" -Level ERROR } } else { Write-Log "Gentle stop failed. Not forcing termination (config)." -Level WARN } }
Start-Sleep -Seconds $TunnelStartDelay Write-Log "Attempting to restart WireGuard service after cleanup..." if (Start-WGService) { Write-Log "Service restarted and tunnel HEALTHY." exit $EXIT_SUCCESS } else { Write-Log "Restart failed. Entering backoff." -Level ERROR Set-Backoff exit $EXIT_SERVICE_ERROR } } } else { Write-Log "Service already stopped, expected on ISP IP." } exit $EXIT_SUCCESS} else { # Not on Expected IP: Ensure tunnel is UP and WORKING Write-Log "Current IP does NOT match ExpectedPublicIP. Ensuring tunnel is UP and WORKING..." if (wgSvc.Status -eq 'Running') { if (Test-TunnelUp) { Write-Log "Service running and tunnel healthy. No action needed." exit EXIT_SUCCESS } else { Write-Log "Tunnel check FAILED while service is running. Forcing cleanup..." -Level WARN if (-not (Stop-WGService)) { if (ForceTerminateOnFailure) { try { wgProcess = Get-Process | Where-Object { _.ProcessName -like "*wireguard*" } if (wgProcess) { Write-Log "Terminating WireGuard process(es)..." wgProcess | Stop-Process -Force -ErrorAction Stop } } catch { Write-Log "Process termination failed: ($_.Exception.Message)" -Level ERROR } } }
Start-Sleep -Seconds $TunnelStartDelay Write-Log "Restarting WireGuard service after cleanup..." if (Start-WGService) { Write-Log "Service restarted and tunnel HEALTHY." exit $EXIT_SUCCESS } else { Write-Log "Restart failed. Entering backoff." -Level ERROR Set-Backoff exit $EXIT_SERVICE_ERROR } } } else { # Service stopped, try starting with retries Write-Log "Service is stopped. Attempting to start tunnel..." $startedSuccessfully = $false for ($try = 1; $try -le $TunnelStartRetries; $try++) { Write-Log "Starting service (attempt $try/$TunnelStartRetries)..." if (Start-WGService) { Write-Log "Service started and tunnel is HEALTHY." $startedSuccessfully = $true break } else { Write-Log "Tunnel did not come up successfully on attempt $try." -Level WARN Stop-WGService if ($try -lt $TunnelStartRetries) { Write-Log "Retrying in $GetIPRetryDelay seconds..." Start-Sleep -Seconds $GetIPRetryDelay } } } if (-not $startedSuccessfully) { Write-Log "Failed to establish a working tunnel after $TunnelStartRetries attempts." -Level ERROR Set-Backoff exit $EXIT_SERVICE_ERROR } }}
Write-Log "Script finished successfully." exit $EXIT_SUCCESS
Assistant
This is the main logic section of the PowerShell script for managing a WireGuard VPN tunnel based on public IP changes. It ties together the helper functions and configuration parameters to implement the desired behavior. Below is a breakdown of its functionality and flow:
Main Logic Overview
1. Initialization and Configuration Validation
- Logs the start of the script.
- Validates critical configuration parameters:
- Ensures
$ExpectedPublicIPand$WireGuardTunnelNameare set. - Checks the format of
$TunnelTestIP(if provided). - Verifies that
$IPCheckURIis a valid HTTP/HTTPS URL.
- Ensures
- Exits with an error code if any validation fails.
2. Backoff Check
- If a backoff period is active (set by previous failures), the script exits early to avoid excessive retries.
3. Fetch Current Public IP
- Uses the
Get-PublicIPfunction to retrieve the current public IP address. - If the public IP cannot be fetched:
- Checks the status of the WireGuard service.
- If the service is running, attempts to stop it (with optional force termination).
- Exits with a network error code.
4. WireGuard Service Status
- Retrieves the WireGuard service object using
Get-WGService. - Exits with a configuration error if the service is not installed.
5. Logic Based on Public IP
Case 1: Current IP Matches ExpectedPublicIP
- If the current public IP matches the expected ISP IP:
- Checks if the WireGuard service is running.
- If the service is running:
- Verifies the tunnel's health using
Test-TunnelUp. - If the tunnel is healthy, no action is taken.
- If the tunnel is broken:
- Stops the service (with optional force termination).
- Attempts to restart the service and verify the tunnel's health.
- If restarting fails, enters a backoff period and exits with a service error.
- Verifies the tunnel's health using
- If the service is already stopped, no action is needed.
Case 2: Current IP Does NOT Match ExpectedPublicIP
- If the current public IP does not match the expected ISP IP:
- Ensures the WireGuard tunnel is up and working.
- If the service is running:
- Verifies the tunnel's health using
Test-TunnelUp. - If the tunnel is broken:
- Stops the service (with optional force termination).
- Attempts to restart the service and verify the tunnel's health.
- If restarting fails, enters a backoff period and exits with a service error.
- Verifies the tunnel's health using
- If the service is stopped:
- Attempts to start the service with retries.
- If all retry attempts fail, enters a backoff period and exits with a service error.
6. Exit
- Logs the successful completion of the script and exits with a success code.
Key Features in the Main Logic
Error Handling
- The script gracefully handles errors at every step, logging detailed messages for troubleshooting.
- Implements retries and backoff mechanisms to avoid excessive resource usage during failures.
Service Management
- Ensures the WireGuard service is in the correct state based on the current public IP and tunnel health.
- Includes aggressive cleanup options (e.g., forcefully terminating the WireGuard process) to recover from failures.
Tunnel Health Verification
- Uses the
Test-TunnelUpfunction to check the status of the WireGuard tunnel interface and verify connectivity to a test IP.
Retry Logic
- Retries fetching the public IP and starting the WireGuard service a configurable number of times, with delays between attempts.
Exit Codes
The script uses specific exit codes to indicate the outcome:
$EXIT_SUCCESS(0): The script completed successfully.$EXIT_CONFIG_ERROR(1): Configuration validation failed.$EXIT_NETWORK_ERROR(2): Public IP fetch failed or network issues occurred.$EXIT_SERVICE_ERROR(3): WireGuard service could not be started or the tunnel could not be established.
How to Use
- Save the Script: Save the entire script (including the helper functions and main logic) to a
.ps1file. - Configure Parameters: Update the configuration section with your specific settings (e.g.,
$ExpectedPublicIP,$WireGuardTunnelName). - Schedule the Script: Use Task Scheduler to run the script periodically (e.g., every 5-10 minutes).
- Monitor Logs: Check the log file (
C:\WireGuardLogs\wg_ip_check.log) for detailed information about the script's actions and any errors.
This script is robust and well-suited for managing WireGuard tunnels in dynamic network environments. If you need further assistance or modifications, feel free to ask!
- User
add multiple tunneltestip
Assistant
To add support for multiple
TunnelTestIPaddresses in the provided PowerShell script, you can modify theTest-TunnelUpfunction to iterate through a list of test IPs. This will allow the script to verify connectivity to multiple IPs and consider the tunnel healthy if at least one of them is reachable. Below is an updated version of the relevant parts of the script:
Modifications for Multiple TunnelTestIP Support
1. Update Configuration Section
Replace the single
$TunnelTestIPvariable with an array to hold multiple IP addresses:# ***** 1. NETWORK SETTINGS ***** $ExpectedPublicIP = "1.2.3.4" # <<< CHANGE: Your HOME/ISP public IP address $IPCheckURI = "https://icanhazip.com" # <<< CHANGE IF NEEDED: Service to fetch your current public IP $TunnelTestIPs = @("10.0.0.1", "10.0.0.2", "10.0.0.3") # <<< CHANGE: List of IPs reachable via the WireGuard tunnel
2. Modify
Test-TunnelUpFunctionUpdate the
Test-TunnelUpfunction to test connectivity to all IPs in the$TunnelTestIPsarray. The tunnel will be considered healthy if at least one IP is reachable:Function Test-TunnelUp { $iface = Get-NetAdapter | Where-Object { $_.InterfaceDescription -like "WireGuard Tunnel*" -and $_.Name -like "$WireGuardTunnelName*" } if (-not $iface) { Write-Log "Tunnel interface '$WireGuardTunnelName' not found." -Level WARN return $false } if ($iface.Status -ne "Up") { Write-Log "Tunnel interface '$($iface.Name)' found but is DOWN." -Level WARN return $false } Write-Log "Tunnel interface '$($iface.Name)' is UP. Testing connectivity..." if (-not $TunnelTestIPs -or $TunnelTestIPs.Count -eq 0) { Write-Log "No TunnelTestIPs configured. Assuming tunnel is up if interface is up." -Level WARN return $true } foreach ($testIP in $TunnelTestIPs) { Write-Log "Pinging $testIP via tunnel..." $timeoutMs = $PingTimeoutSeconds * 1000 ping.exe -n 1 -w $timeoutMs $testIP | Out-Null if ($LASTEXITCODE -eq 0) { Write-Log "Tunnel connectivity VERIFIED to $testIP." return $true } else { Write-Log "Tunnel connectivity FAILED to $testIP (timeout: $($PingTimeoutSeconds)s). ping.exe Exit Code: $LASTEXITCODE" -Level WARN } } Write-Log "Tunnel connectivity FAILED to all configured test IPs." -Level ERROR return $false }
Explanation of Changes
-
Configuration Update:
$TunnelTestIPsis now an array, allowing multiple IP addresses to be specified.- Each IP in the array represents a target that should be reachable through the WireGuard tunnel.
-
Function Update:
- The
Test-TunnelUpfunction iterates through all IPs in$TunnelTestIPs. - If any IP is reachable (ping succeeds), the function logs success and returns
$true. - If all pings fail, the function logs an error and returns
$false.
- The
Behavior
- The script will now test connectivity to all specified
TunnelTestIPs. - The tunnel is considered healthy if at least one IP is reachable.
- This approach ensures greater flexibility and reliability in environments where multiple endpoints need to be verified.
Usage
- Update the
$TunnelTestIPsarray in the configuration section with the desired list of IPs. - Run the script as usual. The modified
Test-TunnelUpfunction will handle multiple test IPs automatically.
This enhancement ensures the script can handle scenarios where multiple endpoints need to be validated for tunnel health. Let me know if you need further assistance!
-
- User
explain the logic
Assistant
The logic for adding multiple
TunnelTestIPaddresses to the script ensures that the WireGuard tunnel is considered healthy if at least one of the specified IPs is reachable. Below is a detailed explanation of how this works:
Logic Explanation
1. Configuration
- Instead of a single
$TunnelTestIP, the script now uses an array$TunnelTestIPsto hold multiple IP addresses. - Each IP in this array represents a target that should be reachable only through the WireGuard tunnel.
- Example:
$TunnelTestIPs = @("10.0.0.1", "10.0.0.2", "10.0.0.3")- These IPs could be internal resources, servers, or endpoints that are accessible only when the WireGuard tunnel is active.
2. Testing the Tunnel
The
Test-TunnelUpfunction is responsible for verifying the health of the WireGuard tunnel. Here's how it works:Step 1: Check the Tunnel Interface
- The function first checks if the WireGuard tunnel interface exists and is in the "Up" state:
$iface = Get-NetAdapter | Where-Object { $_.InterfaceDescription -like "WireGuard Tunnel*" -and $_.Name -like "$WireGuardTunnelName*" }- If the interface is not found or is not "Up," the function logs a warning and returns
$false.
- If the interface is not found or is not "Up," the function logs a warning and returns
Step 2: Iterate Through Test IPs
- If the interface is "Up," the function iterates through all IPs in the
$TunnelTestIPsarray:foreach ($testIP in $TunnelTestIPs) { Write-Log "Pinging $testIP via tunnel..." ping.exe -n 1 -w $timeoutMs $testIP | Out-Null }- For each IP, the script attempts to ping it using the
ping.execommand. - The timeout for the ping is set by
$PingTimeoutSeconds.
- For each IP, the script attempts to ping it using the
Step 3: Evaluate Ping Results
- After each ping:
- If the ping succeeds (
$LASTEXITCODE -eq 0), the function logs success and immediately returns$true:if ($LASTEXITCODE -eq 0) { Write-Log "Tunnel connectivity VERIFIED to $testIP." return $true } - If the ping fails, the function logs a warning and moves on to the next IP in the array:
Write-Log "Tunnel connectivity FAILED to $testIP (timeout: $($PingTimeoutSeconds)s)."
- If the ping succeeds (
Step 4: Final Evaluation
- If all pings fail (i.e., none of the IPs in
$TunnelTestIPsare reachable), the function logs an error and returns$false:Write-Log "Tunnel connectivity FAILED to all configured test IPs." -Level ERROR return $false
3. Decision-Making in the Main Logic
The main logic of the script uses the
Test-TunnelUpfunction to decide whether the WireGuard tunnel is healthy. Here's how it integrates with the rest of the script:Case 1: Tunnel is Healthy
- If
Test-TunnelUpreturns$true(at least one IP is reachable):- The script logs that the tunnel is healthy and takes no further action.
Case 2: Tunnel is Unhealthy
- If
Test-TunnelUpreturns$false(none of the IPs are reachable):- The script attempts to stop and restart the WireGuard service.
- If restarting the service fails, the script enters a backoff period to avoid excessive retries.
Why Use Multiple Test IPs?
-
Redundancy:
- If one test IP is temporarily unreachable (e.g., due to server maintenance), the script can still verify the tunnel's health using other IPs.
- This reduces the chances of false negatives (incorrectly marking the tunnel as unhealthy).
-
Multi-Site Connectivity:
- In some setups, the WireGuard tunnel may provide access to multiple networks or endpoints.
- Testing connectivity to multiple IPs ensures that the tunnel is functioning correctly across all intended destinations.
-
Improved Reliability:
- By testing multiple IPs, the script can better handle intermittent network issues or partial tunnel failures.
Example Workflow
Assume the following configuration:
$TunnelTestIPs = @("10.0.0.1", "10.0.0.2", "10.0.0.3")Scenario 1: All IPs Reachable
- The script pings
10.0.0.1,10.0.0.2, and10.0.0.3. - If at least one ping succeeds, the tunnel is marked as healthy, and no further action is taken.
Scenario 2: Partial Reachability
- The script pings
10.0.0.1,10.0.0.2, and10.0.0.3. - If
10.0.0.1and10.0.0.2fail but10.0.0.3succeeds, the tunnel is still marked as healthy.
Scenario 3: All IPs Unreachable
- The script pings
10.0.0.1,10.0.0.2, and10.0.0.3. - If all pings fail, the tunnel is marked as unhealthy, and the script attempts to restart the WireGuard service.
Benefits of This Logic
- Flexibility: Supports multiple test IPs, making the script adaptable to different network setups.
- Resilience: Reduces the impact of temporary network issues or partial failures.
- Accuracy: Ensures the tunnel is truly unhealthy before taking corrective action.
If you have additional questions or need further clarification, feel free to ask!
- Instead of a single
- User
explain the overall script logic
Assistant
The overall logic of the script is designed to manage a WireGuard VPN tunnel service based on changes in the public IP address and the health of the tunnel. It ensures that the WireGuard service is running and the tunnel is operational when required, while also handling failures gracefully with retries, backoff periods, and logging.
Here’s a step-by-step explanation of the overall script logic:
1. Initialization
- Log Start: The script logs the start of its execution.
- Configuration Validation:
- Ensures that critical configuration parameters (e.g.,
$ExpectedPublicIP,$WireGuardTunnelName,$TunnelTestIPs) are set and valid. - Exits with an error if any required configuration is missing or invalid.
- Ensures that critical configuration parameters (e.g.,
- Backoff Check:
- If a backoff period is active (set during previous failures), the script exits early to avoid excessive retries.
2. Fetch Current Public IP
- The script retrieves the current public IP address using the configured
$IPCheckURI(e.g.,https://icanhazip.com). - If the public IP cannot be fetched (e.g., due to network issues):
- The script checks the status of the WireGuard service.
- If the service is running, it attempts to stop it (with optional force termination).
- Exits with a network error code.
3. Determine Action Based on Public IP
The script compares the current public IP (
$currentIP) with the expected ISP IP ($ExpectedPublicIP) to decide whether the WireGuard tunnel should be active.Case 1: Current IP Matches ExpectedPublicIP
- Scenario: The device is on the home/ISP network, where the WireGuard tunnel is not required.
- Actions:
- If the WireGuard service is running:
- Checks the tunnel's health using
Test-TunnelUp. - If the tunnel is healthy, the script logs that no action is needed.
- If the tunnel is broken, the script stops the service (with optional force termination).
- Checks the tunnel's health using
- If the WireGuard service is already stopped, no action is needed.
- If the WireGuard service is running:
Case 2: Current IP Does NOT Match ExpectedPublicIP
- Scenario: The device is outside the home/ISP network, where the WireGuard tunnel is required.
- Actions:
- If the WireGuard service is running:
- Checks the tunnel's health using
Test-TunnelUp. - If the tunnel is healthy, the script logs that no action is needed.
- If the tunnel is broken, the script stops the service (with optional force termination) and attempts to restart it.
- Checks the tunnel's health using
- If the WireGuard service is stopped:
- Attempts to start the service with retries.
- If all retry attempts fail, the script enters a backoff period to avoid excessive retries.
- If the WireGuard service is running:
4. Tunnel Health Check
- The
Test-TunnelUpfunction verifies the health of the WireGuard tunnel:- Checks if the WireGuard tunnel interface exists and is in the "Up" state.
- Pings one or more test IPs (
$TunnelTestIPs) that are only reachable through the tunnel. - If at least one test IP is reachable, the tunnel is considered healthy.
- If all test IPs are unreachable, the tunnel is considered unhealthy.
5. Service Management
- The script manages the WireGuard service based on the current public IP and tunnel health:
- Start Service:
- If the service is stopped and the tunnel is required, the script attempts to start the service with retries.
- After starting the service, it waits for the tunnel to come up and verifies its health.
- Stop Service:
- If the service is running but the tunnel is not required or is unhealthy, the script stops the service.
- If the service cannot be stopped gracefully, the script optionally force-terminates the WireGuard process.
- Start Service:
6. Backoff Mechanism
- If the script encounters repeated failures (e.g., unable to start the service or establish a healthy tunnel), it enters a backoff period:
- The backoff period prevents the script from retrying too frequently, reducing resource usage and avoiding potential issues with the WireGuard service or network.
- The backoff state is stored in a temporary file (
$BackoffFile), and the script checks this file at the start of each execution.
7. Logging
- The script logs all actions, decisions, and errors to a log file (
C:\WireGuardLogs\wg_ip_check.log). - Logs are rotated daily (or based on a configurable number of hours) to prevent the log file from growing too large.
- Log levels (
INFO,WARN,ERROR) help categorize messages for easier troubleshooting.
8. Exit
- The script exits with an appropriate exit code to indicate the outcome:
$EXIT_SUCCESS(0): The script completed successfully.$EXIT_CONFIG_ERROR(1): Configuration validation failed.$EXIT_NETWORK_ERROR(2): Public IP fetch failed or network issues occurred.$EXIT_SERVICE_ERROR(3): WireGuard service could not be started or the tunnel could not be established.
Key Features of the Script
-
Dynamic Tunnel Management:
- Automatically starts or stops the WireGuard service based on the current public IP and tunnel health.
-
Tunnel Health Verification:
- Ensures the tunnel is operational by checking the network interface and pinging test IPs.
-
Error Handling and Recovery:
- Handles errors gracefully with retries and optional force termination of the WireGuard process.
- Implements a backoff mechanism to avoid excessive retries after repeated failures.
-
Logging and Monitoring:
- Logs all actions and errors for troubleshooting.
- Rotates logs to prevent excessive file size.
-
Customizable Configuration:
- Allows users to configure network settings, timeouts, retries, backoff periods, and logging behavior.
Example Workflow
Scenario: Device is Outside the Home Network
- The script starts and fetches the current public IP (e.g.,
203.0.113.45). - The current IP does not match the expected ISP IP (
1.2.3.4), so the WireGuard tunnel is required. - The script checks the status of the WireGuard service:
- If the service is stopped, it attempts to start it.
- If the service is running, it verifies the tunnel's health by pinging the test IPs.
- If the tunnel is unhealthy, the script stops the service, cleans up any lingering processes, and retries starting the service.
- If all retries fail, the script enters a backoff period and exits with an error.
This script is a robust solution for managing WireGuard tunnels in dynamic network environments. It ensures that the tunnel is active and healthy when needed, while minimizing unnecessary resource usage and handling failures gracefully. If you have further questions or need additional features, feel free to ask!
- User
what if the scenario is device already using another network and then switch to home network
Assistant
When a device transitions from using an external network (e.g., LTE or a different Wi-Fi) to the home network, the WireGuard VPN tunnel may encounter challenges due to changes in the network environment. Here's how the script and WireGuard handle this scenario, along with potential issues and solutions:
Scenario: Switching to the Home Network
What Happens?
-
Public IP Changes:
- When the device connects to the home network, its public IP changes to the ISP-assigned IP (e.g.,
$ExpectedPublicIP). - The script detects this change by comparing the current public IP with
$ExpectedPublicIP.
- When the device connects to the home network, its public IP changes to the ISP-assigned IP (e.g.,
-
WireGuard Tunnel Behavior:
- WireGuard is designed to handle roaming, meaning it can adapt to changes in the network endpoint (e.g., public IP changes) without requiring a manual restart.
- However, if the tunnel is still active while transitioning to the home network, it may not behave as expected due to:
- Conflicts between the VPN's routing rules and the local network.
- DNS resolution issues if the endpoint resolves to a private IP on the home network instead of the public IP.
-
Script Logic:
- The script identifies that the current public IP matches
$ExpectedPublicIP(indicating the device is on the home network). - It checks the status of the WireGuard service:
- If the service is running, it verifies the tunnel's health using
Test-TunnelUp. - If the tunnel is healthy, the script stops the service because the VPN is not required on the home network.
- If the tunnel is unhealthy, the script performs cleanup (stopping the service and terminating processes if necessary).
- If the service is running, it verifies the tunnel's health using
- The script identifies that the current public IP matches
Potential Issues
-
DNS Resolution Conflicts:
- If the WireGuard endpoint resolves to a private IP on the home network instead of the public IP, the tunnel may fail to establish or behave unpredictably.
- This is a common issue when transitioning between networks with different DNS configurations.
-
Routing Conflicts:
- If the home network uses the same subnet as the WireGuard tunnel (e.g., both use
192.168.1.0/24), traffic intended for the VPN may be routed locally instead, bypassing the tunnel.
- If the home network uses the same subnet as the WireGuard tunnel (e.g., both use
-
Tunnel Persistence:
- WireGuard may continue to use the old endpoint (from the external network) until it receives traffic from the new endpoint, causing temporary connectivity issues.
How the Script Handles This
-
Public IP Check:
- The script fetches the current public IP and compares it to
$ExpectedPublicIP. - If the IP matches, the script assumes the device is on the home network and stops the WireGuard service.
- The script fetches the current public IP and compares it to
-
Tunnel Health Verification:
- If the service is running, the script uses
Test-TunnelUpto verify the tunnel's health. - If the tunnel is unhealthy, the script stops the service and performs cleanup.
- If the service is running, the script uses
-
Service Management:
- The script ensures that the WireGuard service is stopped when the device is on the home network, preventing unnecessary VPN usage and potential conflicts.
Solutions to Common Issues
-
DNS Resolution:
- Use a dynamic DNS (DDNS) service to ensure the WireGuard endpoint always resolves to the correct public IP, even when on the home network.
- Alternatively, configure the WireGuard client to use the public IP directly instead of relying on DNS.
-
Routing Conflicts:
- Use a unique subnet for the WireGuard tunnel (e.g.,
10.0.0.0/24) that is unlikely to conflict with common home or public Wi-Fi subnets. - Avoid using
192.168.x.xor10.x.x.xranges commonly used by routers.
- Use a unique subnet for the WireGuard tunnel (e.g.,
-
PersistentKeepalive:
- Configure the WireGuard client with
PersistentKeepalive = 25to ensure the server is aware of the client's new endpoint after a network change.
- Configure the WireGuard client with
-
Script Enhancements:
- Add logic to detect and handle DNS resolution issues (e.g., resolving the endpoint to a private IP).
- Implement a mechanism to gracefully restart the WireGuard service after a network transition to ensure proper routing and connectivity.
Example Workflow
-
Before Transition:
- The device is connected to an external network (e.g., LTE) with a public IP different from
$ExpectedPublicIP. - The WireGuard tunnel is active, and traffic is routed through the VPN.
- The device is connected to an external network (e.g., LTE) with a public IP different from
-
During Transition:
- The device connects to the home network, and the public IP changes to
$ExpectedPublicIP. - The script detects the IP change and determines that the VPN is no longer required.
- The device connects to the home network, and the public IP changes to
-
After Transition:
- The script stops the WireGuard service to prevent conflicts with the home network.
- If the service is already stopped, no action is taken.
Conclusion
The script is well-equipped to handle the transition from an external network to the home network by:
- Detecting the public IP change.
- Verifying the tunnel's health.
- Stopping the WireGuard service when the device is on the home network.
However, additional measures (e.g., unique subnets, dynamic DNS, and
PersistentKeepalive) may be needed to address specific issues like DNS conflicts and routing problems. Let me know if you'd like further assistance with implementing these solutions!-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.