-
Notifications
You must be signed in to change notification settings - Fork 0
/
Setup.ps1
238 lines (193 loc) · 7.36 KB
/
Setup.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
function Get-FreePortPair {
param (
[Parameter(Mandatory)] [int[]] $UsedPorts
)
$socket = [System.Net.Sockets.Socket]::new(
[System.Net.Sockets.AddressFamily]::InterNetworkV6,
[System.Net.Sockets.SocketType]::Stream,
[System.Net.Sockets.ProtocolType]::Tcp
)
$socket.DualMode = $true
$firstPort = 1024
try {
$socket.Bind([System.Net.IPEndPoint]::new([System.Net.IPAddress]::Any, 0))
$firstPort = $socket.LocalEndPoint.Port
} catch {
$firstPort = [int]::MaxValue
} finally {
$socket.Close()
}
$ports = $null
for (; $firstPort -le 60999; $firstPort++) {
$ports = @()
for ($offset = 0; $offset -lt 2; $offset++) {
$isFree = $UsedPorts -notcontains $port
if ($isFree) {
$socket = [System.Net.Sockets.Socket]::new(
[System.Net.Sockets.AddressFamily]::InterNetworkV6,
[System.Net.Sockets.SocketType]::Stream,
[System.Net.Sockets.ProtocolType]::Tcp
)
$socket.DualMode = $true
try {
$socket.Bind([System.Net.IPEndPoint]::new([System.Net.IPAddress]::Any, $firstPort + $offset))
$ports += $firstPort + $offset
} catch {
$isFree = $false
}
$socket.Close()
}
if (-not $isFree) {
break
}
}
if ($ports.Count -eq 2) {
break
}
}
if ($null -ne $ports -and $ports.Count -eq 2) {
return $ports
} else {
throw "No free port pair found."
}
}
<##############################################################################>
# Ensure elevated privileges. (Alternative: `#Requires -RunAsAdministrator`.)
$currentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]::new($currentIdentity)
$isElevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isElevated) {
throw "This script requires elevated privileges. Please restart the script in a command prompt with administrator rights."
}
#
Write-Host 'Welcome to the setup script.'
Write-Host 'You can rerun this script any time to update or reapply the settings to the system.'
Write-Host
# Ask whether to install/uninstall.
Write-Host 'Options:'
Write-Host '1. Install'
Write-Host '2. Uninstall'
$userInput = Read-Host 'Enter number'
Write-Host
$isInstalling = $false
switch ($userInput.Trim()) {
'1' {
$isInstalling = $true
}
'2' {
$isInstalling = $false
}
default {
throw "Invalid input."
}
}
# Ask for ports.
$externalPort = $null
$internalPort = $null
if ($isInstalling) {
Write-Host 'Port forwarding will be set up to avoid needing elevated privileges for the server on every run.'
Write-Host 'Choose your external and internal server ports by entering two comma-separated numbers in that order (may be taken from old config file), or press Enter for auto-selection:'
$userInput = Read-Host 'Ports'
Write-Host
if ($userInput -ne '') {
$parts = $userInput.Split(',') | ForEach-Object { $_.Trim() -as [int] }
if ($parts.Count -ne 2 -or $parts -contains $null) {
throw "Invalid input."
}
$externalPort, $internalPort = $parts
} else {
# Find free port pair.
$usedPorts = @(1433, 1434, 1521, 3306, 3389, 5432, 5900, 5985, 5986, 8080, 8443)
$usedPorts += (
netsh interface portproxy show all |
Select-String -Pattern '(?:^| )(\d+)(?: |$)' -AllMatches |
ForEach-Object { $_.Matches | ForEach-Object { $_.Groups[1].Value } }
# (`Select-String` has idiotic behavior when first using `Out-String`, making `(?m)` and `\r?$` necessary.)
)
$externalPort, $internalPort = Get-FreePortPair $usedPorts
}
Write-Host "Server configured with external port $externalPort and internal port $internalPort."
Write-Host 'Build your webhook URLs using the external port. This port is also recorded in the config file.'
Write-Host
}
# Ask for firewall rule details.
$needsFirewallRule = $false
$firewallRuleName = 'AllowPowerShellWebhook_h8w4e7'
$firewallRuleRemoteAddress = $null
if ($isInstalling) {
Write-Host 'To unblock network requests, specify a remote IP address (e.g., from your home automation system) to create a rule for the Windows firewall. Rerunning this setup will reset manual changes to this rule (manually add separate rule[s]).'
Write-Host 'Press Enter to skip creating a firewall rule (still removing a previous one).'
$userInput = Read-Host 'Remote IP'
Write-Host
$firewallRuleRemoteAddress = $userInput.Trim()
$needsFirewallRule = $firewallRuleRemoteAddress -ne ''
if ($needsFirewallRule -and -not [System.Net.IPAddress]::TryParse($firewallRuleRemoteAddress, [ref]$null)) {
throw "Invalid input."
}
}
<##############################################################################>
# Read config file.
$configFilePath = "$PSScriptRoot\config.json"
$hasConfigFile = Test-Path $configFilePath
$config = $null
if ($hasConfigFile) {
$config = Get-Content $configFilePath | ConvertFrom-Json
if ($null -eq $config.ExternalPort -or $null -eq $config.InternalPort) {
throw "Invalid config file. Ports missing."
}
}
<##############################################################################>
# Always uninstall first.
if (-not $isInstalling -and -not $hasConfigFile) {
throw "No config file."
}
if ($hasConfigFile) {
# Remove port forwarding.
foreach ($command in @('v4tov4', 'v6tov4')) {
$null = netsh interface portproxy delete $command listenport=$($config.ExternalPort)
}
Write-Host 'Removed port forwarding.'
# # Delete config file.
# if (-not $isInstalling) {
# Remove-Item $configFilePath
# }
}
Remove-NetFirewallRule -Name $firewallRuleName -ErrorAction SilentlyContinue
if (-not $isInstalling) {
Write-Host 'Removed firewall rule.'
}
if (-not $isInstalling) {
Write-Host 'Uninstallation finished. You may delete the config file or keep it for future reference.'
Write-Host
}
<##############################################################################>
# Install.
if ($isInstalling) {
# Set up port forwarding.
foreach ($command in @('v4tov4', 'v6tov4')) {
$null = netsh interface portproxy add $command listenport=$externalPort connectaddress=127.0.0.1 connectport=$internalPort
}
# Create config file.
$config = @{
ExternalPort = $externalPort
InternalPort = $internalPort
}
$config | ConvertTo-Json | Set-Content -Path $configFilePath
# Create firewall rule.
if ($needsFirewallRule) {
$displayName = "PowerShell Webhook (From $firewallRuleRemoteAddress)"
$null = New-NetFirewallRule `
-Name $firewallRuleName `
-DisplayName $displayName `
-Direction Inbound `
-Protocol TCP `
-LocalPort $externalPort `
-RemoteAddress $firewallRuleRemoteAddress `
-Action Allow
Write-Host "Created firewall rule ""$displayName""."
Write-Host
}
#
Write-Host 'Installation finished. Do not edit the config file manually.'
Write-Host
}