This repository has been archived by the owner on Dec 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTailscale-Updater-Windows.ps1
478 lines (431 loc) · 17.2 KB
/
Tailscale-Updater-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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
[CmdletBinding()]
param (
[Parameter()] [ValidateSet('stable','unstable')] [string]$Track = 'stable',
[Parameter()] [switch]$DownloadOnly = $false,
[Parameter()] [string]$SiloPath = (Join-Path -Path (Get-Location) -ChildPath 'tailscale_silo'),
[Parameter()] [switch]$Force = $false,
[Parameter()] [switch]$TaskMode = $false
)
############################
# tailscale-updater script #
$script:version = '0.5.0' ##
############################
function Invoke-SiloMaintenance {
# make sure all silos contain no more than 2 releases
[CmdletBinding()]
param ([string]$Path = $SiloPath)
if(-Not (Test-Path -LiteralPath $Path)){
Write-Host "Silo Maintenance: SiloPath not found [$Path]"
} else {
[array]$silos = Get-ChildItem -LiteralPath $Path -Directory
foreach($silo in $silos){
Write-Verbose "Silo Maintenace: $($silo.FullName)"
[array]$files = Get-ChildItem -LiteralPath $silo.FullName -File -Filter '*.exe' | Sort-Object -Property BaseName -Descending
$files | Select-Object -Skip 2 | Remove-Item -Force -Verbose
}
}
}
function Get-TailscaleLatestReleaseInfo {
# query Tailscale release page for latest Windows version
[CmdletBinding()]
param (
[Parameter(HelpMessage='Specify which release track is of interest, stable (default) or unstable')]
[ValidateSet('stable','unstable')]
[string]$Track = 'stable'
)
Write-Verbose -Message "Release track: $Track"
[string]$uri_base = "https://pkgs.tailscale.com/$Track/"
[string]$release_os = 'windows'
[string]$rest_uri = $uri_base+'?mode=json&os='+$release_os
[string]$release_arch = 'amd64.exe'
[string]$release_uri = $null
[string]$release_file_name = $null
Try {
if(([System.Net.ServicePointManager]::SecurityProtocol -eq "SystemDefault") -and ([enum]::GetNames([System.Net.SecurityProtocolType]) -contains "Tls12")) {
Write-Verbose -Message "Setting connection security: TLS 1.2"
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
}
[PSCustomObject]$response = Invoke-RestMethod -uri $rest_uri
$release_file_name = $response.Installer.$release_arch
Write-Verbose -Message "Release file: $release_file_name"
$release_uri = $uri_base + $release_file_name
Write-Verbose -Message "Release uri: $release_uri"
[version]$release_version = $response.Version
Write-Verbose -Message "Release version: $release_version"
} Catch {
$_ | Write-Error
}
[PSCustomObject]$release_object = @{
name = $release_file_name
version = $release_version
track = $Track
uri = $release_uri
}
return $release_object
}
function Get-TailscaleInstallLocation {
[CmdletBinding()] param()
[string]$tailscale_reg_parent = 'HKLM:\software\Tailscale IPN\'
Try {
[string]$path = (Get-ItemProperty -Path $tailscale_reg_parent).'(default)'
if(Test-Path $path){
Write-Verbose "Tailscale is installed here: $path"
} else {
Throw "Tailscale registry entry found, but path does not exist"
}
} Catch {
$_ | Write-Error
Write-Error "Tailscale not installed properly"
}
return $path
}
function Get-TailscaleServiceVersion {
# find Tailscale on local device using service information and parse the version in use
# this has the nice result that if the service isn't running, or isn't found then the version
# returned is 0.0.0.0 which will in turn cause tailscale to install or re-install
[CmdletBinding()] param()
[string]$tailscale_app = 'tailscale-ipn.exe'
[string]$tailscale_daemon = 'tailscaled'
[version]$tailscale_version = $null
[System.ComponentModel.Component]$tailscale_service = Get-Service -Name Tailscale -WarningAction:SilentlyContinue -ErrorAction:SilentlyContinue
if($tailscale_service){
Write-Verbose "Tailscale status: $($tailscale_service.Status)"
[string]$tailscale_parent = (Get-Item -LiteralPath (Get-Process -Name $tailscale_daemon | Select-Object -ExpandProperty Path -First 1)).Directory
Write-Verbose "Tailscale directory: $tailscale_parent"
$tailscale_app_path = Join-Path -Path $tailscale_parent -ChildPath $tailscale_app
if(Test-Path -LiteralPath $tailscale_app_path){
$tailscale_version = (Get-Item -LiteralPath $tailscale_app_path).VersionInfo.ProductVersionRaw
Write-Verbose "Tailscale version: $tailscale_version"
} else {
Throw "Can't reach Tailscale app [$tailscale_app_path]"
}
} else {
Write-Verbose "Tailscale not installed/running"
}
return $tailscale_version
}
function Get-TailscaleRelease {
# download a release
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)] [PSCustomObject]$Release,
[Parameter(Mandatory=$true)] [string]$Destination
)
[string]$outpath = Join-Path -Path $Destination -ChildPath $Release.track
[string]$outfile = Join-Path -Path $outpath -ChildPath $Release.name
Write-Verbose "Download version: $($Release.version)"
Write-Verbose "Download from: $($Release.uri)"
Try {
If(-not (Test-Path -LiteralPath $outpath)){
Write-Host "Creating directory: $outpath"
New-Item -Path $outpath -ItemType Directory | Out-Null
}
Write-Verbose "Download to: $outfile"
Invoke-WebRequest -Uri $Release.uri -OutFile $outfile
} Catch {
$_ | Write-Error
}
$downloadedFile = Get-Item -LiteralPath $outfile
return $downloadedFile
}
function Invoke-TailscaleIPNLauncher {
# function to re-launch Tailscale-IPN.exe as a logged-on user if needed
[CmdletBinding()] param()
[string[]]$loggedonuser = (Get-WMIObject -ClassName Win32_ComputerSystem).Username
if($loggedonuser.count -gt 0){
Write-Verbose "Interactive session detected"
$userpresent = $true
}
[string]$tailscaleipn = 'tailscale-ipn'
[string]$tailscaleparent = Get-TailscaleInstallLocation
if($tailscaleparent){
[string]$tailscaleipn_path = Join-Path -Path $tailscaleparent -ChildPath "$tailscaleipn.exe"
[ComponentModel.Component[]]$existingprocesses = Get-Process -Name $tailscaleipn -ErrorAction:SilentlyContinue -WarningAction:SilentlyContinue
if($existingprocesses){
Write-Verbose "Stopping existing Tailscale-IPN processes"
$existingprocesses | ForEach-Object{$_ | Stop-Process -Force}
}
Write-Verbose "Stopping Tailscale service"
Get-Service -Name Tailscale | Where-Object {$_.CanStop -and $_.Status -eq "Running"} | Stop-Service -Force -Confirm:$False | Out-Null
Start-Sleep -Seconds 2
Write-Verbose "Starting Tailscale service"
Start-Service -Name Tailscale -Confirm:$False | Out-Null
if($userpresent){
[boolean]$launchresult = Invoke-ProcessAsInteractiveUser -ApplicationPath $tailscaleipn_path
Switch ($launchresult){
$true {Write-Verbose "Tailscale-IPN launched as logged-on user"}
default {Write-Verbose "Tailscale-IPN NOT launched"}
}
} else {
Write-Verbose "No interactive session, not re-launching Tailscale-IPN"
}
} else {
Write-Verbose "Tailscale install not found. Launch attempt aborted"
}
}
function Invoke-TailscaleInstall {
# install a given release
[CmdletBinding()]
param (
[Parameter()] [System.IO.FileSystemInfo] $Release
)
Write-Verbose "Testing for admin rights"
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Error "Not running as Admin"
break
} else {
Write-Verbose "Admin rights available"
}
if(Test-Path -Path $Release){
Write-Host "Starting installation: '$Release' /S"
Try {
Start-Process -FilePath $Release -ArgumentList '/S' -NoNewWindow -Wait
Start-Sleep -Seconds 5
Invoke-TailscaleIPNLauncher
} Catch {
$_ | Write-Error
}
} else {
Write-Error "Can't find installer"
}
}
function Invoke-ProcessAsInteractiveUser {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]
$ApplicationPath
)
# PowerShell source: https://rzander.azurewebsites.net/create-a-process-as-loggedon-user/
$source = @'
// C# source: https://github.com/murrayju/CreateProcessAsUser
using System;
using System.Runtime.InteropServices;
namespace murrayju.ProcessExtensions {
public static class ProcessExtensions {
private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
private const int CREATE_NO_WINDOW = 0x08000000;
private const int CREATE_NEW_CONSOLE = 0x00000010;
private const uint INVALID_SESSION_ID = 0xFFFFFFFF;
private static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
[DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
private static extern bool CreateProcessAsUser(
IntPtr hToken, String lpApplicationName, String lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandle, uint dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
private static extern bool DuplicateTokenEx(
IntPtr ExistingTokenHandle, uint dwDesiredAccess, IntPtr lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
[DllImport("userenv.dll", SetLastError = true)]
private static extern bool CreateEnvironmentBlock(ref IntPtr lpEnvironment, IntPtr hToken, bool bInherit);
[DllImport("userenv.dll", SetLastError = true)][
return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hSnapshot);
[DllImport("kernel32.dll")]
private static extern uint WTSGetActiveConsoleSessionId();
[DllImport("Wtsapi32.dll")]
private static extern uint WTSQueryUserToken(uint SessionId, ref IntPtr phToken);
[DllImport("wtsapi32.dll", SetLastError = true)]
private static extern int WTSEnumerateSessions(
IntPtr hServer, int Reserved, int Version, ref IntPtr ppSessionInfo, ref int pCount);
private enum SW {
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_MAX = 10
}
private enum WTS_CONNECTSTATE_CLASS {
WTSActive,
WTSConnected,
WTSConnectQuery,
WTSShadow,
WTSDisconnected,
WTSIdle,
WTSListen,
WTSReset,
WTSDown,
WTSInit
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION {
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
private enum SECURITY_IMPERSONATION_LEVEL {
SecurityAnonymous = 0,
SecurityIdentification = 1,
SecurityImpersonation = 2,
SecurityDelegation = 3,
}
[StructLayout(LayoutKind.Sequential)]
private struct STARTUPINFO {
public int cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
private enum TOKEN_TYPE {
TokenPrimary = 1,
TokenImpersonation = 2
}
[StructLayout(LayoutKind.Sequential)]
private struct WTS_SESSION_INFO {
public readonly UInt32 SessionID;
[MarshalAs(UnmanagedType.LPStr)]
public readonly String pWinStationName;
public readonly WTS_CONNECTSTATE_CLASS State;
}
private static bool GetSessionUserToken(ref IntPtr phUserToken) {
var bResult = false;
var hImpersonationToken = IntPtr.Zero;
var activeSessionId = INVALID_SESSION_ID;
var pSessionInfo = IntPtr.Zero;
var sessionCount = 0;
if (WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref pSessionInfo, ref sessionCount) != 0) {
var arrayElementSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));
var current = pSessionInfo;
for (var i = 0; i < sessionCount; i++) {
var si = (WTS_SESSION_INFO) Marshal.PtrToStructure((IntPtr) current, typeof(WTS_SESSION_INFO));
current += arrayElementSize;
if (si.State == WTS_CONNECTSTATE_CLASS.WTSActive) {
activeSessionId = si.SessionID;
}
}
}
if (activeSessionId == INVALID_SESSION_ID) {
activeSessionId = WTSGetActiveConsoleSessionId();
}
if (WTSQueryUserToken(activeSessionId, ref hImpersonationToken) != 0) {
bResult = DuplicateTokenEx(hImpersonationToken, 0, IntPtr.Zero, (int) SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int) TOKEN_TYPE.TokenPrimary, ref phUserToken);
CloseHandle(hImpersonationToken);
}
return bResult;
}
public static bool StartProcessAsCurrentUser(string appPath, string cmdLine = null, string workDir = null, bool visible = true) {
var hUserToken = IntPtr.Zero;
var startInfo = new STARTUPINFO();
var procInfo = new PROCESS_INFORMATION();
var pEnv = IntPtr.Zero;
int iResultOfCreateProcessAsUser;
startInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO));
try {
if (!GetSessionUserToken(ref hUserToken)) {
throw new Exception("StartProcessAsCurrentUser: GetSessionUserToken failed.");
}
uint dwCreationFlags = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE: CREATE_NO_WINDOW);
startInfo.wShowWindow = (short)(visible ? SW.SW_SHOW: SW.SW_HIDE);
startInfo.lpDesktop = "winsta0\\default";
if (!CreateEnvironmentBlock(ref pEnv, hUserToken, false)) {
throw new Exception("StartProcessAsCurrentUser: CreateEnvironmentBlock failed.");
}
if (!CreateProcessAsUser(hUserToken, appPath, // Application Name
cmdLine, // Command Line
IntPtr.Zero, IntPtr.Zero, false, dwCreationFlags, pEnv, workDir, // Working directory
ref startInfo, out procInfo)) {
throw new Exception("StartProcessAsCurrentUser: CreateProcessAsUser failed.\n");
}
iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
}
finally {
CloseHandle(hUserToken);
if (pEnv != IntPtr.Zero) {
DestroyEnvironmentBlock(pEnv);
}
CloseHandle(procInfo.hThread);
CloseHandle(procInfo.hProcess);
}
return true;
}
}
}
'@
Add-Type -ReferencedAssemblies 'System', 'System.Runtime.InteropServices' -TypeDefinition $source -Language CSharp
[boolean]$result = $false
if(Test-Path $ApplicationPath){
Try {
[boolean]$result = [murrayju.ProcessExtensions.ProcessExtensions]::StartProcessAsCurrentUser($ApplicationPath)
} Catch {
$_ | Write-Host
Write-Error "Unable to launch [$ApplicationPath] as interactive user"
}
} else {
Write-Error "[$ApplicationPath] not found"
}
return $result
}
function Invoke-TailscaleUpdate {
# test for installed release vs latest downloaded and install if newer available
[CmdletBinding()]
param (
[Parameter()] [PSCustomObject]$available,
[Parameter()] [version]$installed
)
if($force -or $available.version -gt $installed){
Write-Host "Tailscale release: $($available.version)"
$file = Get-TailscaleRelease -Release $available -Destination $script:SiloPath
if(Test-Path $file){
Write-Host "Release downloaded: $($file.FullName)"
if(-not $script:DownloadOnly){
Invoke-TailscaleInstall -Release $file
}
} else {
Write-Error "Release not downloaded."
}
} else {
Write-Host "No new release found."
}
}
function Invoke-TailscaleUpdaterUpdate {
[CmdletBinding()]
param ()
$repouri = "https://api.github.com/repos/needscoffee/tailscale-updater-windows"
[version]$runningversion = $script:version
Write-Verbose "Testing for new release of Tailscale updater"
Try {
$latest = Invoke-RestMethod "$repouri/releases/latest" -Headers @{Accept='application/vnd.github.v3+json'}
$latestversion = [version]($latest.tag_name -replace("v"))
Write-Verbose "This updater version = $runningversion"
Write-Verbose "Latest updater version = $latestversion"
if($latestversion -gt $runningversion){
Write-Host "New version detected. Updating to $latestversion"
$latest.assets | Where-Object -Property name -NotLike "Install-Updater.ps1" | ForEach-Object{Write-Verbose "Downloading $($_.url) to $($_.name)"; Invoke-RestMethod -Uri $_.url -Headers @{Accept='application/octet-stream'} -OutFile $_.name}
}
} Catch {
$_ | Write-Error
Write-Verbose "Unable to test for latest release of updater script"
}
}
#Start
Invoke-TailscaleUpdaterUpdate
[PSCustomObject]$available_release = Get-TailscaleLatestReleaseInfo -Track $Track
[version]$running_release = Get-TailscaleServiceVersion
Invoke-TailscaleUpdate -available $available_release -installed $running_release
Invoke-SiloMaintenance -Path $SiloPath
#End