296 lines
15 KiB
PowerShell
296 lines
15 KiB
PowerShell
<#
|
|
.SYNOPSIS
|
|
MozOut dynamic DNS for Windows.
|
|
|
|
.DESCRIPTION
|
|
Keeps an A and/or AAAA record of your domain pointing at the public IP of this network,
|
|
through the MozOut API. Runs on Windows PowerShell 5.1 and PowerShell 7.
|
|
Schedule it with Task Scheduler (see README). The API key is never printed.
|
|
|
|
.EXAMPLE
|
|
$env:MOZOUT_API_KEY = 'sandbox_...'
|
|
.\ddns.ps1 -Domain example.com -Name home -Type A
|
|
#>
|
|
[CmdletBinding()]
|
|
param(
|
|
# Your domain, such as example.com.
|
|
[string]$Domain = $env:DDNS_DOMAIN,
|
|
# Names to keep up to date. @ is the domain itself.
|
|
[string[]]$Name = $(if ($env:DDNS_NAME) { $env:DDNS_NAME -split '[\s,]+' } else { @('@') }),
|
|
# A, AAAA or Both.
|
|
[ValidateSet('A', 'AAAA', 'Both')]
|
|
[string]$Type = $(if ($env:DDNS_TYPE) { $env:DDNS_TYPE } else { 'A' }),
|
|
[ValidateRange(60, 604800)]
|
|
[int]$Ttl = $(if ($env:DDNS_TTL) { [int]$env:DDNS_TTL } else { 300 }),
|
|
# A file with the API key, instead of the MOZOUT_API_KEY environment variable.
|
|
[string]$ApiKeyFile = $env:DDNS_API_KEY_FILE,
|
|
# Fixed addresses, instead of asking an address service.
|
|
[string]$IPv4 = $env:DDNS_IP4,
|
|
[string]$IPv6 = $env:DDNS_IP6,
|
|
[string[]]$IPv4Url = $(if ($env:DDNS_IP4_URL) { $env:DDNS_IP4_URL -split '\s+' } else { @('https://api.ipify.org', 'https://ipv4.icanhazip.com') }),
|
|
[string[]]$IPv6Url = $(if ($env:DDNS_IP6_URL) { $env:DDNS_IP6_URL -split '\s+' } else { @('https://api6.ipify.org', 'https://ipv6.icanhazip.com') }),
|
|
# Ask the API again after this many hours even if the IP did not change.
|
|
[int]$ForceHours = $(if ($env:DDNS_FORCE_HOURS) { [int]$env:DDNS_FORCE_HOURS } else { 24 }),
|
|
# Delete other records with the same name and type.
|
|
[switch]$DeleteExtra,
|
|
[switch]$Force,
|
|
[switch]$DryRun,
|
|
[switch]$Quiet
|
|
)
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
Set-StrictMode -Version 2.0
|
|
|
|
$Version = '1.0.1'
|
|
$ApiUrl = 'https://api.mozout.com'
|
|
$KeyVar = 'MOZOUT_API_KEY'
|
|
$UserAgent = "mozout-ddns/$Version (PowerShell)"
|
|
|
|
# Windows PowerShell 5.1 may not offer TLS 1.2 by default.
|
|
try {
|
|
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
|
|
} catch { }
|
|
|
|
# Messages go straight to the console, so they never mix with the values functions return.
|
|
function Write-Info([string]$Text) { if (-not $Quiet) { [Console]::Out.WriteLine(('{0} {1}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Text)) } }
|
|
function Write-Note([string]$Text) { [Console]::Out.WriteLine(('{0} {1}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Text)) }
|
|
function Write-Fail([string]$Text) { [Console]::Error.WriteLine(('{0} ERROR: {1}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Text)) }
|
|
|
|
# ---------- settings ----------
|
|
|
|
$ApiKey = [Environment]::GetEnvironmentVariable($KeyVar)
|
|
if (-not $ApiKey -and $ApiKeyFile) {
|
|
if (-not (Test-Path -LiteralPath $ApiKeyFile)) { Write-Fail "Cannot read $ApiKeyFile"; exit 2 }
|
|
$ApiKey = (Get-Content -LiteralPath $ApiKeyFile -Raw).Trim()
|
|
}
|
|
if (-not $ApiKey) { Write-Fail "No API key. Set the $KeyVar environment variable or use -ApiKeyFile."; exit 2 }
|
|
if ($ApiKey -notmatch '^(sandbox|prod)_') { Write-Fail 'The API key must start with sandbox_ or prod_.'; exit 2 }
|
|
$Domain = ("$Domain").Trim().TrimEnd('.').ToLowerInvariant()
|
|
if ($Domain -notmatch '^[a-z0-9-]+(\.[a-z0-9-]+)+$') { Write-Fail 'Set -Domain to your domain, such as example.com (no accents: use the xn-- form).'; exit 2 }
|
|
|
|
$StateDir = if ($env:DDNS_STATE_DIR) { $env:DDNS_STATE_DIR } elseif ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA 'mozout-ddns' } else { Join-Path ([IO.Path]::GetTempPath()) 'mozout-ddns' }
|
|
if (-not (Test-Path -LiteralPath $StateDir)) { New-Item -ItemType Directory -Path $StateDir -Force | Out-Null }
|
|
|
|
# ---------- API ----------
|
|
|
|
$Hints = @{
|
|
'unauthorized' = 'The API key is missing, invalid, revoked or expired.'
|
|
'insufficient_scope' = 'The API key needs the dns:read and dns:write permissions.'
|
|
'ip_not_allowed' = 'The API key only works from some IP addresses. A dynamic IP changes: remove the IP list of the key.'
|
|
'not_found' = 'The domain is not on this account, is not active or does not have DNS on.'
|
|
'account_email_domain' = 'This name receives the mail of the account email. Change it in My MozOut.'
|
|
'cname_conflict' = 'There is a CNAME with this name. Delete it first, or choose another name.'
|
|
'rate_limited' = 'Too many requests. Run less often.'
|
|
'validation_failed' = 'The API did not accept the record.'
|
|
}
|
|
|
|
function Invoke-Api {
|
|
param([string]$Method, [string]$Path, $Body = $null)
|
|
$headers = @{
|
|
'Authorization' = "Bearer $ApiKey"
|
|
'Accept' = 'application/json'
|
|
'Accept-Language' = 'en'
|
|
}
|
|
if ($Method -eq 'POST') { $headers['Idempotency-Key'] = 'ddns-' + [guid]::NewGuid().ToString() }
|
|
$params = @{ Uri = $ApiUrl + $Path; Method = $Method; Headers = $headers; UserAgent = $UserAgent; TimeoutSec = 30; UseBasicParsing = $true }
|
|
if ($null -ne $Body) {
|
|
$params['Body'] = [Text.Encoding]::UTF8.GetBytes(($Body | ConvertTo-Json -Compress))
|
|
$params['ContentType'] = 'application/json'
|
|
}
|
|
for ($try = 1; ; $try++) {
|
|
$status = 0; $text = ''; $respHeaders = @{}; $netError = $null
|
|
try {
|
|
$r = Invoke-WebRequest @params
|
|
$status = [int]$r.StatusCode
|
|
$text = [string]$r.Content
|
|
foreach ($k in $r.Headers.Keys) { $respHeaders[$k.ToLowerInvariant()] = (@($r.Headers[$k]) -join ',') }
|
|
} catch {
|
|
$resp = $null
|
|
if ($_.Exception.PSObject.Properties['Response']) { $resp = $_.Exception.Response }
|
|
if ($null -eq $resp) {
|
|
$netError = $_.Exception.Message
|
|
} else {
|
|
$status = [int]$resp.StatusCode
|
|
if ($_.ErrorDetails -and $_.ErrorDetails.Message) {
|
|
$text = $_.ErrorDetails.Message
|
|
} else {
|
|
try {
|
|
$reader = New-Object IO.StreamReader($resp.GetResponseStream())
|
|
$text = $reader.ReadToEnd()
|
|
} catch { $text = '' }
|
|
}
|
|
try {
|
|
foreach ($k in $resp.Headers.AllKeys) { $respHeaders[$k.ToLowerInvariant()] = $resp.Headers[$k] }
|
|
} catch {
|
|
try { foreach ($h in $resp.Headers) { $respHeaders[$h.Key.ToLowerInvariant()] = (@($h.Value) -join ',') } } catch { }
|
|
}
|
|
}
|
|
}
|
|
if (($null -ne $netError -or $status -in 429, 500, 502, 503) -and $try -lt 3) {
|
|
$wait = 5 * $try
|
|
if ($respHeaders.ContainsKey('retry-after') -and ("$($respHeaders['retry-after'])" -match '^\d+$')) { $wait = [Math]::Min(60, [int]$respHeaders['retry-after']) }
|
|
Write-Info "The API answered $(if ($netError) { 'nothing' } else { $status }), trying again in $wait s..."
|
|
Start-Sleep -Seconds $wait
|
|
continue
|
|
}
|
|
$json = $null
|
|
if ($text) { try { $json = $text | ConvertFrom-Json } catch { } }
|
|
return [pscustomobject]@{
|
|
Status = $status
|
|
Json = $json
|
|
Simulated = ($respHeaders.ContainsKey('x-api-simulated') -and "$($respHeaders['x-api-simulated'])" -eq 'true')
|
|
NetError = $netError
|
|
}
|
|
}
|
|
}
|
|
|
|
function Write-ApiError([string]$What, $Answer) {
|
|
if ($Answer.NetError) { Write-Fail "Could not reach the API: $($Answer.NetError)"; return }
|
|
$code = ''; $message = ''
|
|
if ($Answer.Json -and $Answer.Json.PSObject.Properties['error']) {
|
|
$e = $Answer.Json.error
|
|
$code = [string]$e.code
|
|
$message = [string]$e.message
|
|
if ($code -eq 'conflict' -and $e.PSObject.Properties['details'] -and $e.details -and $e.details.PSObject.Properties['reason']) { $code = [string]$e.details.reason }
|
|
}
|
|
$hint = if ($Hints.ContainsKey($code)) { ' ' + $Hints[$code] } else { '' }
|
|
Write-Fail ("{0}: HTTP {1} {2}{3}{4}" -f $What, $Answer.Status, $(if ($code) { $code } else { 'error' }), $(if ($message) { ": $message" } else { '' }), $hint)
|
|
}
|
|
|
|
# ---------- public IP ----------
|
|
|
|
function Get-PublicIP([int]$Family) {
|
|
$fixed = if ($Family -eq 4) { $IPv4 } else { $IPv6 }
|
|
$urls = if ($Family -eq 4) { $IPv4Url } else { $IPv6Url }
|
|
$want = if ($Family -eq 4) { [Net.Sockets.AddressFamily]::InterNetwork } else { [Net.Sockets.AddressFamily]::InterNetworkV6 }
|
|
$candidates = if ($fixed) { @($fixed) } else { $urls }
|
|
foreach ($u in $candidates) {
|
|
$value = $u
|
|
if (-not $fixed) {
|
|
try { $value = ([string](Invoke-WebRequest -Uri $u -UseBasicParsing -TimeoutSec 15 -UserAgent $UserAgent).Content).Trim() } catch { continue }
|
|
}
|
|
$ip = $null
|
|
if ([Net.IPAddress]::TryParse($value, [ref]$ip) -and $ip.AddressFamily -eq $want) {
|
|
return $ip.ToString().ToLowerInvariant()
|
|
}
|
|
if ($fixed) { Write-Fail "Not an IPv$Family address: $value"; return $null }
|
|
}
|
|
Write-Fail "Could not find the public IPv$Family address (no answer from: $($urls -join ' '))."
|
|
return $null
|
|
}
|
|
|
|
# ---------- update ----------
|
|
|
|
function Get-RelativeName([string]$N) {
|
|
$n = $N.Trim().TrimEnd('.').ToLowerInvariant()
|
|
if ($n -eq '' -or $n -eq '@' -or $n -eq $Domain) { return '@' }
|
|
if ($n.EndsWith(".$Domain")) { return $n.Substring(0, $n.Length - $Domain.Length - 1) }
|
|
return $n
|
|
}
|
|
|
|
$script:Zone = $null
|
|
|
|
function Get-Zone {
|
|
if ($null -ne $script:Zone) { return , $script:Zone }
|
|
$a = Invoke-Api -Method GET -Path "/v1/domains/$Domain/dns"
|
|
if ($a.Status -ne 200) { Write-ApiError "Reading the zone of $Domain" $a; return $null }
|
|
$script:Zone = @($a.Json.data)
|
|
return , $script:Zone
|
|
}
|
|
|
|
function Update-Record([string]$RecordName, [string]$RecordType, [string]$Address) {
|
|
$fqdn = if ($RecordName -eq '@') { $Domain } else { "$RecordName.$Domain" }
|
|
$stateFile = Join-Path $StateDir ("{0}-{1}-{2}" -f $Domain, ($RecordName -replace '[@*]', '_'), $RecordType)
|
|
if (-not $Force -and -not $DryRun -and (Test-Path -LiteralPath $stateFile)) {
|
|
$saved = (Get-Content -LiteralPath $stateFile -Raw).Trim() -split '\s+'
|
|
if ($saved.Count -ge 2 -and $saved[0] -eq $Address -and ([DateTimeOffset]::UtcNow.ToUnixTimeSeconds() - [long]$saved[1]) -lt ($ForceHours * 3600)) {
|
|
Write-Info "$fqdn $RecordType is $Address (unchanged)."
|
|
return $true
|
|
}
|
|
}
|
|
$zone = Get-Zone
|
|
if ($null -eq $zone) { return $false }
|
|
$same = @($zone | Where-Object { $_.type -eq $RecordType -and ([string]$_.name).ToLowerInvariant() -eq $RecordName })
|
|
$body = [ordered]@{ name = $RecordName; type = $RecordType; value = $Address; ttl = $Ttl }
|
|
$what = ''
|
|
$answer = $null
|
|
|
|
if ($same.Count -eq 0) {
|
|
if (@($zone | Where-Object { $_.type -eq 'CNAME' -and ([string]$_.name).ToLowerInvariant() -eq $RecordName }).Count -gt 0) {
|
|
Write-Fail "$fqdn is a CNAME, so it cannot also have an $RecordType record. Delete the CNAME first, or choose another name."
|
|
return $false
|
|
}
|
|
if ($DryRun) { Write-Note "Would create $fqdn $RecordType $Address."; return $true }
|
|
$answer = Invoke-Api -Method POST -Path "/v1/domains/$Domain/dns" -Body $body
|
|
if ($answer.Status -ne 201 -and $answer.Status -ne 200) { Write-ApiError "Creating $fqdn $RecordType" $answer; return $false }
|
|
$what = 'Created'
|
|
} else {
|
|
$current = $same[0]
|
|
if (([string]$current.value).ToLowerInvariant() -eq $Address -and [int]$current.ttl -eq $Ttl) {
|
|
Write-Info "$fqdn $RecordType is already $Address."
|
|
if (-not $DryRun) { Set-Content -LiteralPath $stateFile -Value ("{0} {1}" -f $Address, [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()) }
|
|
} elseif ($DryRun) {
|
|
Write-Note "Would change $fqdn $RecordType from $($current.value) to $Address."
|
|
} else {
|
|
$answer = Invoke-Api -Method PUT -Path "/v1/domains/$Domain/dns/$($current.id)" -Body $body
|
|
if ($answer.Status -ne 200) { Write-ApiError "Changing $fqdn $RecordType" $answer; return $false }
|
|
$what = 'Changed'
|
|
}
|
|
foreach ($extra in ($same | Select-Object -Skip 1)) {
|
|
if ($DeleteExtra -and -not $DryRun) {
|
|
$d = Invoke-Api -Method DELETE -Path "/v1/domains/$Domain/dns/$($extra.id)"
|
|
if ($d.Status -eq 200) { Write-Note "Deleted the extra $fqdn $RecordType $($extra.value)." } else { Write-ApiError "Deleting $fqdn $RecordType $($extra.value)" $d }
|
|
} else {
|
|
Write-Note "Warning: $fqdn has another $RecordType record ($($extra.value)) that also answers. Delete it, or use -DeleteExtra."
|
|
}
|
|
}
|
|
if (-not $what) { return $true }
|
|
}
|
|
|
|
if ($answer.Simulated) {
|
|
Write-Note "$what $fqdn $RecordType $Address (simulated: Sandbox key, nothing changed in the zone)."
|
|
} else {
|
|
Write-Note "$what $fqdn $RecordType $Address."
|
|
Set-Content -LiteralPath $stateFile -Value ("{0} {1}" -f $Address, [DateTimeOffset]::UtcNow.ToUnixTimeSeconds())
|
|
$script:Zone = $null
|
|
}
|
|
return $true
|
|
}
|
|
|
|
# ---------- key check ----------
|
|
|
|
# One GET /v1/token before touching DNS: a wrong key stops here with exit code 3,
|
|
# a key without the DNS permissions with exit code 4.
|
|
$check = Invoke-Api -Method GET -Path '/v1/token'
|
|
if ($check.Status -eq 401) {
|
|
Write-Fail "The API key is not valid: it was deleted, has expired or was typed wrong. Check $KeyVar or create a new key in My MozOut."
|
|
exit 3
|
|
}
|
|
if ($check.Status -eq 403) { Write-ApiError 'The API refused the key' $check; exit 3 }
|
|
if ($check.Status -eq 200 -and $check.Json -and $check.Json.PSObject.Properties['data']) {
|
|
$keyData = $check.Json.data
|
|
$perms = if ($keyData.PSObject.Properties['permissions']) { @($keyData.permissions) } else { @() }
|
|
$missing = @(@('dns:read', 'dns:write') | Where-Object { $perms -notcontains $_ })
|
|
if ($missing.Count -gt 0) {
|
|
Write-Fail ("The API key does not have the permissions DDNS needs: {0}. Add them to the key in My MozOut." -f ($missing -join ', '))
|
|
exit 4
|
|
}
|
|
if ($keyData.PSObject.Properties['mode'] -and [string]$keyData.mode -eq 'sandbox') { Write-Info 'Sandbox key: changes are simulated, the zone stays the same.' }
|
|
} else {
|
|
Write-ApiError 'Checking the API key' $check
|
|
}
|
|
|
|
$ok = $true
|
|
$families = switch ($Type) { 'A' { @(4) } 'AAAA' { @(6) } default { @(4, 6) } }
|
|
foreach ($family in $families) {
|
|
$recordType = if ($family -eq 4) { 'A' } else { 'AAAA' }
|
|
$address = Get-PublicIP $family
|
|
if (-not $address) { $ok = $false; continue }
|
|
foreach ($n in $Name) {
|
|
if (-not $n) { continue }
|
|
$rel = Get-RelativeName $n
|
|
if ($rel -notmatch '^[a-z0-9._@*-]+$') { Write-Fail "Invalid name: $n"; $ok = $false; continue }
|
|
if (-not (Update-Record $rel $recordType $address)) { $ok = $false }
|
|
}
|
|
}
|
|
if ($ok) { exit 0 } else { exit 1 }
|