-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEnableSSHRemoting.psm1
502 lines (437 loc) · 17.1 KB
/
EnableSSHRemoting.psm1
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
## Enable-SSHRemoting Cmdlet
##
class PlatformInfo
{
[bool] $isCoreCLR
[bool] $isLinux
[bool] $isOSX
[bool] $isWindows
[bool] $isAdmin
[bool] $isUbuntu
[bool] $isUbuntu14
[bool] $isUbuntu16
[bool] $isCentOS
[bool] $isFedora
[bool] $isOpenSUSE
[bool] $isOpenSUSE13
[bool] $isOpenSUSE42_1
[bool] $isRedHatFamily
}
function DetectPlatform
{
param (
[ValidateNotNull()]
[PlatformInfo] $PlatformInfo
)
try
{
$Runtime = [System.Runtime.InteropServices.RuntimeInformation]
$OSPlatform = [System.Runtime.InteropServices.OSPlatform]
$platformInfo.isCoreCLR = $true
$platformInfo.isLinux = $Runtime::IsOSPlatform($OSPlatform::Linux)
$platformInfo.isOSX = $Runtime::IsOSPlatform($OSPlatform::OSX)
$platformInfo.isWindows = $Runtime::IsOSPlatform($OSPlatform::Windows)
}
catch
{
$platformInfo.isCoreCLR = $false
$platformInfo.isLinux = $false
$platformInfo.isOSX = $false
$platformInfo.isWindows = $true
}
if ($platformInfo.isWindows)
{
$platformInfo.isAdmin = ([System.Security.Principal.WindowsPrincipal]::new([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole( `
[System.Security.Principal.WindowsBuiltInRole]::Administrator)
}
if ($platformInfo.isLinux)
{
$LinuxInfo = Get-Content /etc/os-release -Raw | ConvertFrom-StringData
$platformInfo.isUbuntu = $LinuxInfo.ID -match 'ubuntu'
$platformInfo.isUbuntu14 = $platformInfo.isUbuntu -and ($LinuxInfo.VERSION_ID -match '14.04')
$platformInfo.isUbuntu16 = $platformInfo.isUbuntu -and ($LinuxInfo.VERSION_ID -match '16.04')
$platformInfo.isCentOS = ($LinuxInfo.ID -match 'centos') -and ($LinuxInfo.VERSION_ID -match '7')
$platformInfo.isFedora = ($LinuxInfo.ID -match 'fedora') -and ($LinuxInfo.VERSION_ID -ge '24')
$platformInfo.isOpenSUSE = $LinuxInfo.ID -match 'opensuse'
$platformInfo.isOpenSUSE13 = $platformInfo.isOpenSUSE -and ($LinuxInfo.VERSION_ID -match '13')
$platformInfo.isOpenSUSE42_1 = $platformInfo.isOpenSUSE -and ($LinuxInfo.VERSION_ID -match '42.1')
$platformInfo.isRedHatFamily = $platformInfo.isCentOS -or $platformInfo.isFedora -or $platformInfo.isOpenSUSE
}
}
class SSHSubSystemEntry
{
[string] $subSystemLine
[string] $subSystemName
[string] $subSystemCommand
[string[]] $subSystemCommandArgs
}
class SSHRemotingConfig
{
[PlatformInfo] $platformInfo
[SSHSubSystemEntry[]] $psSubSystemEntries = @()
[string] $configFilePath
$configComponents = @()
SSHRemotingConfig(
[PlatformInfo] $platInfo,
[string] $configFilePath)
{
$this.platformInfo = $platInfo
$this.configFilePath = $configFilePath
$this.ParseSSHRemotingConfig()
}
[string[]] SplitConfigLine([string] $line)
{
$line = $line.Trim()
$lineLength = $line.Length
$rtnStrArray = [System.Collections.Generic.List[string]]::new()
for ($i=0; $i -lt $lineLength; )
{
$startIndex = $i
while (($i -lt $lineLength) -and ($line[$i] -ne " ") -and ($line[$i] -ne "`t")) { $i++ }
$rtnStrArray.Add($line.Substring($startIndex, ($i - $startIndex)))
while (($i -lt $lineLength) -and ($line[$i] -eq " ") -or ($line[$i] -eq "`t")) { $i++ }
}
return $rtnStrArray.ToArray()
}
ParseSSHRemotingConfig()
{
[string[]] $contents = Get-Content -Path $this.configFilePath
foreach ($line in $contents)
{
$components = $this.SplitConfigLine($line)
$this.configComponents += @{ Line = $line; Components = $components }
if (($components[0] -eq "Subsystem") -and ($components[1] -eq "powershell"))
{
$entry = [SSHSubSystemEntry]::New()
$entry.subSystemLine = $line
$entry.subSystemName = $components[1]
$entry.subSystemCommand = $components[2]
$entry.subSystemCommandArgs = @()
for ($i=3; $i -lt $components.Count; $i++)
{
$entry.subSystemCommandArgs += $components[$i]
}
$this.psSubSystemEntries += $entry
}
}
}
}
function UpdateConfiguration
{
param (
[SSHRemotingConfig] $config,
[string] $PowerShellPath
)
#
# Update and re-write config file with existing settings plus new PowerShell remoting settings
#
# Subsystem
[System.Collections.Generic.List[string]] $newContents = [System.Collections.Generic.List[string]]::new()
$psSubSystemEntry = "Subsystem powershell {0} {1} {2} {3}" -f $powerShellPath, "-SSHS", "-NoProfile", "-NoLogo"
$subSystemAdded = $false
foreach ($lineItem in $config.configComponents)
{
$line = $lineItem.Line
$components = $lineItem.Components
if ($components[0] -eq "SubSystem")
{
if (! $subSystemAdded)
{
# Add new powershell subsystem entry
$newContents.Add($psSubSystemEntry)
$subSystemAdded = $true
}
if ($components[1] -eq "powershell")
{
# Remove all existing powershell subsystem entries
continue
}
# Include existing subsystem entries.
$newContents.Add($line)
}
else
{
# Include all other configuration lines
$newContents.Add($line)
}
}
if (! $subSystemAdded)
{
$newContents.Add($psSubSystemEntry)
}
# Copy existing file to a backup version
$uniqueName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName())
$backupFilePath = $config.configFilePath + "_backup_" + $uniqueName
Copy-Item -Path $config.configFilePath -Destination $backupFilePath
if ($?)
{
WriteLine "A backup copy of the old sshd_config configuration file has been created at:"
WriteLine $backupFilePath
}
Set-Content -Path $config.configFilePath -Value $newContents.ToArray() -ErrorAction Stop
}
function CheckPowerShellVersion
{
param (
[string] $FilePath
)
if (! (Test-Path $FilePath))
{
throw "CheckPowerShellVersion failed with invalid path: $FilePath"
}
$commandToExec = "& '$FilePath' -noprofile -noninteractive -c '`$PSVersionTable.PSVersion.Major'"
$sb = [scriptblock]::Create($commandToExec)
$psVersionMajor = 0
try
{
$psVersionMajor = [int] (& $sb) 2>$null
Write-Verbose ""
Write-Verbose "CheckPowerShellVersion: $psVersionMajor for FilePath: $FilePath"
}
catch { }
if ($psVersionMajor -ge 6)
{
return $true
}
else
{
return $false
}
}
function WriteLine
{
param (
[string] $Message,
[int] $PrependLines = 0,
[int] $AppendLines = 0
)
for ($i=0; $i -lt $PrependLines; $i++)
{
Write-Output ""
}
Write-Output $Message
for ($i=0; $i -lt $AppendLines; $i++)
{
Write-Output ""
}
}
# Windows only GetShortPathName PInvoke
$typeDef = @'
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace NativeUtils
{
public class Path
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern int GetShortPathName(
[MarshalAs(UnmanagedType.LPTStr)]
string path,
[MarshalAs(UnmanagedType.LPTStr)]
StringBuilder shortPath,
int shortPathLength);
public static string ConvertToShortPath(
string longPath)
{
int shortPathLength = 2048;
StringBuilder shortPath = new StringBuilder(shortPathLength);
GetShortPathName(
path: longPath,
shortPath: shortPath,
shortPathLength: shortPathLength);
return shortPath.ToString();
}
}
}
'@
<#
.Synopsis
Enables PowerShell SSH remoting endpoint on local system
.Description
This cmdlet will set up an SSH based remoting endpoint on the local system, based on
the PowerShell executable file path passed in. Or if no PowerShell file path is provided then
the currently running PowerShell file path is used.
The end point is enabled by adding a 'powershell' subsystem entry to the SSHD configuration, using
the provided or current PowerShell file path.
Both the SSH client and SSHD server components are detected and if not found a terminating
error is emitted, asking the user to install the components.
Then the sshd_config is parsed, and if a new 'powershell' subsystem entry is added.
.Parameter SSHDConfigFilePath
File path to the SSHD service configuration file. This file will be updated to include a
'powershell' subsystem entry to define a PowerShell SSH remoting endpoint, so current credentials
must have write access to the file.
.Parameter PowerShellFilePath
Specifies the file path to the PowerShell command used to host the SSH remoting PowerShell
endpoint. If no value is specified then the currently running PowerShell executable path is used
in the subsytem command.
.Parameter Force
When true, this cmdlet will update the sshd_config configuration file without prompting.
#>
function Enable-SSHRemoting
{
[CmdletBinding()]
param (
[string] $SSHDConfigFilePath,
[string] $PowerShellFilePath,
[switch] $Force
)
# Non-Windows platforms must run this cmdlet as 'root'
if (!$platformInfo.isWindows)
{
$user = whoami
if ($user -ne 'root')
{
if (! $PSCmdlet.ShouldContinue("This cmdlet must be run as 'root'. If you continue, PowerShell will restart under 'root'. Do you wish to continue?", "Enable-SSHRemoting"))
{
return
}
# Spawn new PowerShell with sudo and exit this session.
$modFilePath = (Get-Module -Name EnableSSHRemoting | Select-Object -Property Path).Path
$parameters = ""
foreach ($key in $PSBoundParameters.Keys)
{
$parameters += "-${key} "
$value = $PSBoundParameters[$key]
if ($value -is [string])
{
$parameters += "'$value' "
}
}
& sudo "$PSHOME/pwsh" -NoExit -c "Import-Module -Name $modFilePath; Enable-SSHRemoting $parameters"
exit
}
}
# Detect platform
$platformInfo = [PlatformInfo]::new()
DetectPlatform $platformInfo
Write-Verbose "Platform information"
Write-Verbose "$($platformInfo | Out-String)"
# Detect SSH client installation
if (! (Get-Command -Name ssh -ErrorAction SilentlyContinue))
{
Write-Warning "SSH client is not installed or not discoverable on this machine. SSH client must be installed before PowerShell SSH based remoting can be enabled."
}
# Detect SSHD server installation
$SSHDFound = $false
if ($platformInfo.IsWindows)
{
$SSHDFound = $null -ne (Get-Service -Name sshd -ErrorAction SilentlyContinue)
}
elseif ($platformInfo.IsLinux)
{
$sshdStatus = systemctl status sshd
$SSHDFound = $null -ne $sshdStatus
}
else
{
# macOS
$SSHDFound = ((launchctl list | Select-String 'com.openssh.sshd') -ne $null)
}
if (! $SSHDFound)
{
Write-Warning "SSHD service is not found on this machine. SSHD service must be installed and running before PowerShell SSH based remoting can be enabled."
}
# Validate a SSHD configuration file path
if ([string]::IsNullOrEmpty($SSHDConfigFilePath))
{
Write-Warning "-SSHDConfigFilePath not provided. Using default configuration file location."
if ($platformInfo.IsWindows)
{
$SSHDConfigFilePath = Join-Path -Path $env:ProgramData -ChildPath 'ssh' -AdditionalChildPath 'sshd_config'
}
elseif ($platformInfo.isLinux)
{
$SSHDConfigFilePath = '/etc/ssh/sshd_config'
}
else
{
# macOS
$SSHDConfigFilePath = '/private/etc/ssh/sshd_config'
}
}
# Validate a PowerShell command to use for endpoint
$PowerShellToUse = $PowerShellFilePath
if (! [string]::IsNullOrEmpty($PowerShellToUse))
{
WriteLine "Validating provided -PowerShellFilePath argument." -AppendLines 1 -PrependLines 1
if (! (Test-Path $PowerShellToUse))
{
throw "The provided PowerShell file path is invalid: $PowerShellToUse"
}
if (! (CheckPowerShellVersion $PowerShellToUse))
{
throw "The provided PowerShell file path is an unsupported version of PowerShell. PowerShell version 6.0 or greater is required."
}
}
else
{
WriteLine "Validating current PowerShell to use as endpoint subsystem." -AppendLines 1
# Try currently running PowerShell
$PowerShellToUse = Get-Command -Name "$PSHome/pwsh" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source
if (! $PowerShellToUse -or ! (CheckPowerShellVersion $PowerShellToUse))
{
throw "Current running PowerShell version is not valid for SSH remoting endpoint. SSH remoting is only supported for PowerShell version 6.0 and higher. Specify a valid PowerShell 6.0+ file path with the -PowerShellFilePath parameter."
}
}
# SSHD configuration file uses the space character as a delimiter.
# Consequently, the configuration Subsystem entry will not allow argument paths containing space characters.
# For Windows platforms, we can a short cut path.
# But for non-Windows platforms, we currently throw an error.
# One possible solution is to crete a symbolic link
# New-Item -ItemType SymbolicLink -Path <NewNoSpacesPath> -Value $<PathwithSpaces>
if ($PowerShellToUse.Contains(' '))
{
if ($platformInfo.IsWindows)
{
Add-Type -TypeDefinition $typeDef
$PowerShellToUse = [NativeUtils.Path]::ConvertToShortPath($PowerShellToUse)
if (! (Test-Path -Path $PowerShellToUse))
{
throw "Converting long Windows file path resulted in an invalid path: ${PowerShellToUse}."
}
}
else
{
throw "The PowerShell executable (pwsh) selected for hosting the remoting endpoint has a file path containing space characters, which cannot be used with SSHD configuration."
}
}
WriteLine "Using PowerShell at this path for SSH remoting endpoint:"
WriteLine "$PowerShellToUse" -AppendLines 1
# Validate the SSHD configuration file path
if (! (Test-Path -Path $SSHDConfigFilePath))
{
throw "The provided SSHDConfigFilePath parameter, $SSHDConfigFilePath, is not a valid path."
}
WriteLine "Modifying SSHD configuration file at this location:"
WriteLine "$SSHDConfigFilePath" -AppendLines 1
# Get the SSHD configurtion
$sshdConfig = [SSHRemotingConfig]::new($platformInfo, $SSHDConfigFilePath)
if ($sshdConfig.psSubSystemEntries.Count -gt 0)
{
WriteLine "The following PowerShell subsystems were found in the sshd_config file:"
foreach ($entry in $sshdConfig.psSubSystemEntries)
{
WriteLine $entry.subSystemLine
}
Writeline "Continuing will overwrite any existing PowerShell subsystem entries with the new subsystem." -PrependLines 1
WriteLine "The new SSH remoting endpoint will use this PowerShell executable path:"
WriteLine "$PowerShellToUse" -AppendLines 1
}
$shouldContinue = $Force
if (! $shouldContinue)
{
$shouldContinue = $PSCmdlet.ShouldContinue("The SSHD service configuration file (sshd_config) will now be updated to enable PowerShell remoting over SSH. Do you wish to continue?", "Enable-SSHRemoting")
}
if ($shouldContinue)
{
WriteLine "Updating configuration file ..." -PrependLines 1 -AppendLines 1
UpdateConfiguration $sshdConfig $PowerShellToUse
WriteLine "The configuration file has been updated:" -PrependLines 1
WriteLine $sshdConfig.configFilePath -AppendLines 1
WriteLine "You must restart the SSHD service for the changes to take effect." -AppendLines 1
}
}