-
Notifications
You must be signed in to change notification settings - Fork 1
/
jj-ddns-client.windows.ps1
393 lines (331 loc) · 11.7 KB
/
jj-ddns-client.windows.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# Dynamic DNS client that works with Google Domains, no-ip.com, GoDaddy and ChangeIP
# Setup wizard will store a configuration file (settings.cfg) with dns to update
#
# Usage: ./jj-ddns-client.windows.ps1 -h
param (
[switch] $u,
[switch] $w,
[switch] $s,
[switch] $h,
[switch] $i,
[switch] $force = $false
)
#region Global variables
$serviceName = "jj-ddns-client.windows"
$userAgent = "jj-ddns-client.windows/v1.3 planetxpres@msn.com"
$ipModes = @("public", "private")
$providers = @("google", "no-ip.com", "godaddy", "changeip")
# Paths
$invocation = (Get-Variable MyInvocation).Value
$configFile = "$(Split-Path $invocation.MyCommand.Path)\settings.cfg"
$scriptPath = $invocation.MyCommand.Source
$logFile = "$(Split-Path $invocation.MyCommand.Path)\dns.log"
#endregion
function updateDns {
$settings = loadSettings
log "[$([DateTime]::Now)] - Starting dns check" -clear
if (isDisabled) {
$fail = "Client status is disabled, Run script with -w flag to run wizard"
log $fail
throw $fail
return
}
if (isSnoozed) {
log "Client is snoozed to be run on $($settings.snoozeUntil)"
return
}
if ($settings.provider -eq "godaddy") {
updateDnsGoDaddy
} elseif ($settings.provider -eq "no-ip.com") {
updateDnsNoIp
} elseif ($settings.provider -eq "google") {
updateDnsGoogle
} elseif ($settings.provider -eq "changeip") {
updateDnsChangeip
} else {
throw "$($settings.provider) is not a valid value for dns provider. Run script with -w flag to run wizard"
}
}
function updateDnsGoDaddy {
log "[$([DateTime]::Now)] Checking godaddy dns..."
$settings = loadSettings
$uri = "https://api.godaddy.com/v1/domains/$($settings.domain)/records/A/$($settings.name)"
$headers = @{}
$headers.Add("Authorization", "sso-key $($settings.key):$($settings.secret)")
$result = Invoke-RestMethod -Method GET -Headers $headers -Uri $uri -UserAgent $userAgent
$dnsIp = $result.data
$currentIp = getIp
if ($dnsIp -ne $currentIp) {
log "Updating $($settings.domain) dns record with $currentIp, old ip $dnsIp"
$request = @(
@{
data = $currentIp;
ttl = 600;
}
);
$json = ConvertTo-Json $request;
try {
$updateResult = Invoke-RestMethod -Method PUT -Headers $headers -Uri $uri -Body $json -ContentType "application/json" -UserAgent $userAgent
$updateResult | Out-File -FilePath $logFile -Append
$updateResult
} catch {
"Error $($_.Exception.Response.StatusCode): $($_.Exception.Response.StatusDescription)" | Out-File -FilePath $logFile -Append
throw $_.Exception
}
}
log "Finished $($settings.provider) check $dnsIp and $currentIp"
}
function updateDnsNoIp {
# https://www.noip.com/integrate
$settings = loadSettings
log "$($settings.provider) Checking dns $($settings.domain)"
$currentIp = getIp
$dnsIp = resolveDns -dns "$($settings.domain)"
if ($dnsIp -ne $currentIp) {
log "Updating $($settings.domain) dns record with $currentIp, old ip $dnsIp"
$auth = base64 "$($settings.key):$($settings.secret)"
$headers = @{}
$headers.Add("Authorization", "Basic $auth")
$uri = "http://dynupdate.no-ip.com/nic/update?hostname=$($settings.domain)&myip=$currentIp"
$result = Invoke-RestMethod -Method GET -Uri $uri -UserAgent $userAgent -Headers $headers
$result | Out-File -FilePath $logFile -Append
if ($result.StartsWith("good")) {
log "no-ip.com succeeded updating ip ($result)"
} elseif ($result.StartsWith("nochg")) {
log "no-ip.com ip update was not needed ($result)"
} elseif ($result.StartsWith("911")) {
log "no-ip.com is down, snoozing client during 30 minutes ($result)"
snoozeUntil [DateTime]::Now.AddMinutes(30)
} elseif (
$result.StartsWith("nohost") -or
$result.StartsWith("badauth") -or
$result.StartsWith("badagent") -or
$result.StartsWith("abuse") -or
$result.StartsWith("!donator")
) {
log "no-ip.com has given an error: $result, wizard has to be run again."
disableClient
}
}
log "Finished $($settings.provider) check $dnsIp and $currentIp"
}
function updateDnsGoogle {
$settings = loadSettings
log "$($settings.provider) Checking dns $($settings.domain)"
$currentIp = getIp
$settings.domain
$dnsIp = resolveDns -dns "$($settings.domain)"
if ($dnsIp -ne $currentIp) {
log "Updating $($settings.domain) dns record with $currentIp, old ip $dnsIp"
$uri = "https://$($settings.key):$($settings.secret)@domains.google.com/nic/update?hostname=$($settings.domain)&myip=$currentIp"
$result = Invoke-RestMethod -Method GET -Uri $uri -UserAgent $userAgent
log $result
}
log "Finished $($settings.provider) check $dnsIp and $currentIp"
}
function updateDnsChangeip {
$settings = loadSettings
log "$($settings.provider) Checking dns $($settings.domain)"
$currentIp = getIp
$dnsIp = resolveDns -dns "$($settings.domain)"
if ($dnsIp -ne $currentIp) {
$uri = "https://nic.changeip.com/nic/update?ip=$currentIp&u=$($settings.key)&p=$($settings.secret)&hostname=$($settings.domain)"
$result = Invoke-RestMethod -Method GET -Uri $uri -UserAgent $userAgent
log $result
}
log "Finished $($settings.provider) check $dnsIp and $currentIp"
}
function getIp {
$settings = loadSettings
if ($settings.ipmode -eq "public") {
$webClient = New-Object System.Net.WebClient
$ip = $webClient.DownloadString('http://ipinfo.io/ip')
} else {
$ip = $(Get-NetIPAddress -InterfaceAlias $settings.interface -AddressFamily IPv4).IpAddress
}
$ip.Trim()
}
function resolveDns($dns) {
[System.Net.Dns]::GetHostAddresses($dns).IPAddressToString
}
#region Setup
function install {
if (!(checkRequiredPrivileges)) {
throw "Please run this script with admin priviliges"
}
uninstall
configWizard
addCron
"Executing client with configuration..."
updateDns
}
function uninstall {
if (Test-Path $configFile) {
Remove-Item -Path $configFile
"Config removed"
}
Unregister-ScheduledTask -TaskName $serviceName -Confirm:$false -ErrorAction SilentlyContinue
}
function confirmUninstall {
if (!(checkRequiredPrivileges)) {
throw "Please run this script with admin priviliges"
}
if (!($force)) {
$confirm = Read-Host -Prompt "Do you want to stop updating configured dns (y/n)?"
if ($confirm -ne "y" ) {
"Uninstallation cancelled"
return
}
}
uninstall
}
function helpDialog {
"script to update a dns address. Options:
[without arguments]: Update dns with current ip. If no config is found, installation wizard is launched.
[-w]: Installation wizard
[-u]: Uninstallation of configured account and execution of script
[-s]: Show current settings
[-h]: Show this help dialog"
}
function currentSettingsDialog {
$settings = loadSettings
"provider: $($settings.provider)"
"ipmode: $($settings.ipmode)"
if ($settings.interface -ne "") {
"interface: $($settings.interface)"
}
"domain: $($settings.domain)"
if (![string]::IsNullOrWhiteSpace($settings.name)) {
"subdomain: $($settings.name)"
}
if (isDisabled) {
"CLIENT DISABLED STATUS, rerun wizard with -w flag"
}
if (![string]::IsNullOrWhiteSpace($settings.snoozeUntil)) {
"snoozeUntil: $($settings.snoozeUntil)"
}
}
function configWizard {
"Installation wizard"
$settings = @{}
$settings.status = "enabled"
$settings.snoozeUntil = $null
$settings.provider = promptOptions -options $providers -prompt "Choose dns provider"
$settings.provider
$settings.ipmode = promptOptions -options $ipModes -prompt "Choose ip address kind"
$settings.interface = Read-Host -Prompt "Network Interface Alias to track IP (ex: Wi-Fi). Check with Get-NetIPAddress."
$settings.domain = Read-Host -Prompt "Domain to update"
if ($settings.provider -eq "godaddy") {
$settings.name = Read-Host -Prompt "Subdomain name"
$settings.key = Read-Host -Prompt "GoDaddy developer key (https://developer.godaddy.com/getstarted)"
$settings.secret = Read-Host -Prompt "GoDaddy developer secret"
}
else {
$settings.key = Read-Host -Prompt "$($settings.provider) user"
$settings.secret = Read-Host -Prompt "$($settings.provider) password"
}
saveSettings $settings
}
function saveSettings($settings) {
"domain=$($settings.domain)" > $configFile
"name=$($settings.name)" >> $configFile
"ipmode=$($settings.ipmode)" >> $configFile
"interface=$($settings.interface)" >> $configFile
"provider=$($settings.provider)" >> $configFile
"key=$($settings.key)" >> $configFile
"secret=$($settings.secret)" >> $configFile
"status=$($settings.status)" >> $configFile
"snoozeUntil=$($settings.snoozeUntil)" >> $configFile
}
function loadSettings {
if (-not (Test-Path $configFile)) {
throw [System.IO.FileNotFoundException] "$configFile not found."
}
Get-Content $configFile | foreach-object -begin {$settings = @{}} -process { $k = [regex]::split($_, '='); if (($k[0].CompareTo("") -ne 0) -and ($k[0].StartsWith("[") -ne $True)) { $settings.Add($k[0], $k[1]) } }
$settings
}
function addCron {
"installing service $serviceName ($scriptPath)"
$repeat = (New-TimeSpan -Minutes 15)
$trigger = New-JobTrigger -Once -At (Get-Date).Date -RepeatIndefinitely -RepetitionInterval $repeat
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "-NoProfile -WindowStyle Hidden -File `"$scriptPath`""
$taskSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfNetworkAvailable -DontStopOnIdleEnd
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Limited
$task = Register-ScheduledTask -Action $action -Trigger $trigger -TaskName $serviceName -Settings $taskSettings -Description "Dynamic DNS Client" -Principal $principal
"Installed ddns client to run in 15 min. intervals."
}
function disableClient {
$settings = loadSettings
$settings.status = "disabled"
saveSettings $settings
}
function isDisabled {
$settings = loadSettings
$settings.status -eq "disabled"
}
function snoozeUntil([DateTime]$dateTime) {
$settings = loadSettings
$settings.snoozeUntil = $dateTime.ToString("s")
saveSettings $settings
}
function isSnoozed() {
$settings = loadSettings
if ([string]::IsNullOrWhiteSpace($settings.snoozeUntil)) {
return $false
}
return (Get-Date -date $settings.snoozeUntil) -gt [DateTime]::Now
}
#endregion
#region Helper functions
function promptOptions($options, $prompt) {
$opts = $options | ForEach-Object { "$($options.IndexOf($_)+1)) $($_)`r`n" }
$promptOpts = "$($prompt):`r`n $opts"
$option = Read-Host -Prompt $promptOpts
while (!(isNumeric $option) -or $option -gt $options.Length -or $option -le 0) {
$option = Read-Host -Prompt "You must choose a valid option. Try again.`r`n$promptOpts"
}
return $options[$option -1]
}
function checkRequiredPrivileges {
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
function isNumeric ($value) {
return $value -match "^[\d\.]+$"
}
function base64 ($value) {
[Convert]::ToBase64String(
[System.Text.Encoding]::Unicode.GetBytes($value)
)
}
function log($message, [switch]$clear) {
if ($clear) {
"" | Out-File -FilePath $logFile -NoNewline
}
$message | Out-File -FilePath $logFile -Append
Write-Host $message -Debug
}
#endregion
#region Main
# Without params, update dns
if (-not (Test-Path $configFile) -and (! $h)) {
install
return
} elseif ($PSBoundParameters.Count -eq 0) {
updateDns
return
}
# Run switches
if ($w) {
install
} elseif ($u) {
confirmUninstall
} elseif ($s) {
currentSettingsDialog
} elseif ($i) {
getIp
} elseif ($h) {
helpDialog
} else {
"Invalid option: $($args[0])"
}
#endregion