This repository was archived by the owner on Apr 27, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathSsh.php
More file actions
280 lines (256 loc) · 10.2 KB
/
Copy pathSsh.php
File metadata and controls
280 lines (256 loc) · 10.2 KB
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
<?php
namespace Platformsh\Cli\Service;
use Platformsh\Cli\Console\HiddenInputOption;
use Platformsh\Cli\SshCert\Certifier;
use Platformsh\Cli\Util\OsUtil;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Ssh implements InputConfiguringInterface
{
const SSH_NO_REFRESH_ENV_VAR = 'CLI_SSH_NO_REFRESH';
protected $input;
protected $output;
protected $stdErr;
protected $config;
protected $certifier;
protected $sshConfig;
protected $sshKey;
private $configuredSession = false;
public function __construct(InputInterface $input, OutputInterface $output, Config $config, Certifier $certifier, SshConfig $sshConfig, SshKey $sshKey)
{
$this->input = $input;
$this->output = $output;
$this->config = $config;
$this->sshKey = $sshKey;
$this->certifier = $certifier;
$this->sshConfig = $sshConfig;
$this->stdErr = $this->output instanceof ConsoleOutputInterface ? $this->output->getErrorOutput() : $this->output;
}
/**
* @param \Symfony\Component\Console\Input\InputDefinition $definition
*/
public static function configureInput(InputDefinition $definition)
{
$definition->addOption(
new HiddenInputOption('identity-file', 'i', InputOption::VALUE_REQUIRED, 'Deprecated: an SSH identity (private key) to use. The auto-generated certificate is recommended instead.')
);
}
/**
* Returns arguments for an SSH command.
*
* @param string $uri
* The SSH URI. This is required for detecting whether authentication
* should be added. It will not be returned as one of the arguments.
* @param string[] $extraOptions
* Extra SSH options in the OpenSSH config format, e.g. 'RequestTTY yes'.
* @param string[]|string|null $remoteCommand
* A command to run on the remote host.
*
* @return array
*/
public function getSshArgs($uri, array $extraOptions = [], $remoteCommand = null)
{
$options = array_merge($this->getSshOptions($this->hostIsInternal($uri)), $extraOptions);
$args = [];
foreach ($options as $option) {
$args[] = '-o';
$args[] = $option;
}
if (!empty($remoteCommand)) {
// The remote command may be provided as 1 argument (escaped
// according to the user), or as multiple arguments, in which case
// it will be collapsed into a string escaped for the remote POSIX
// shell.
if (is_array($remoteCommand)) {
if (count($remoteCommand) === 1) {
$args[] = reset($remoteCommand);
} else {
$args[] = implode(' ', array_map([OsUtil::class, 'escapePosixShellArg'], $remoteCommand));
}
} else {
$args[] = $remoteCommand;
}
}
return $args;
}
/**
* Returns an array of SSH options, based on the input options.
*
* @param bool|null $hostIsInternal
*
* @return string[] An array of SSH options.
*/
private function getSshOptions($hostIsInternal)
{
$options = [];
if ($this->output->isDebug()) {
if ($this->config->get('api.debug')) {
$options[] = 'LogLevel DEBUG3';
} else {
$options[] = 'LogLevel DEBUG';
}
} elseif ($this->output->isVeryVerbose()) {
$options[] = 'LogLevel VERBOSE';
} elseif ($this->output->isQuiet()) {
$options[] = 'LogLevel QUIET';
}
if ($this->input->hasOption('identity-file') && ($file = $this->input->getOption('identity-file'))) {
foreach ($this->sshConfig->formattedPaths($file) as $path) {
$options[] = 'IdentityFile ' . $path;
}
$options[] = 'IdentitiesOnly yes';
} elseif ($hostIsInternal !== false) {
// Inject the SSH certificate.
$sshCert = $this->certifier->getExistingCertificate();
if ($sshCert || $this->certifier->isAutoLoadEnabled()) {
if ((!$sshCert || !$this->certifier->isValid($sshCert)) && $this->sshConfig->checkRequiredVersion()) {
$this->stdErr->writeln('Generating SSH certificate...', OutputInterface::VERBOSITY_VERBOSE);
try {
$sshCert = $this->certifier->generateCertificate($sshCert);
$this->stdErr->writeln("A new SSH certificate has been generated.\n", OutputInterface::VERBOSITY_VERBOSE);
} catch (\Exception $e) {
$this->stdErr->writeln(sprintf("Failed to generate SSH certificate: <error>%s</error>\n", $e->getMessage()));
}
}
if ($sshCert) {
if ($this->sshConfig->supportsCertificateFile()) {
foreach ($this->sshConfig->formattedPaths($sshCert->certificateFilename()) as $path) {
$options[] = 'CertificateFile ' . $path;
}
}
foreach ($this->sshConfig->formattedPaths($sshCert->privateKeyFilename()) as $path) {
$options[] = 'IdentityFile ' . $path;
}
if ($hostIsInternal) {
$options[] = 'IdentitiesOnly yes';
}
}
}
if (!$sshCert && ($sessionIdentityFile = $this->sshKey->selectIdentity())) {
foreach ($this->sshConfig->formattedPaths($sessionIdentityFile) as $path) {
$options[] = 'IdentityFile ' . $path;
}
if ($hostIsInternal) {
$options[] = 'IdentitiesOnly yes';
}
}
}
// Configure host keys and link them.
if ($hostIsInternal !== false) {
try {
$keysFile = $this->sshConfig->configureHostKeys();
if ($keysFile !== null) {
$options[] = 'UserKnownHostsFile ~/.ssh/known_hosts ~/.ssh/known_hosts2 ' . implode(' ', $this->sshConfig->formattedPaths($keysFile));
}
} catch (\Exception $e) {
$this->stdErr->writeln('Error configuring host keys: ' . $e->getMessage(), OutputInterface::VERBOSITY_VERBOSE);
}
}
if ($configuredOptions = $this->config->get('ssh.options')) {
$options = array_merge($options, is_array($configuredOptions) ? $configuredOptions : explode("\n", $configuredOptions));
}
// Avoid repeating options.
return array_unique($options);
}
/**
* Returns an SSH command line.
*
* @param string $url
* The SSH URL. Use $omitUrl to control whether this should be added to
* the command line.
* @param string[] $extraOptions
* SSH options, e.g. 'RequestTTY yes'.
* @param string|null $remoteCommand
* A remote command to run on the host.
* @param bool $omitUrl
* Omit the URL from the command. Use this if the URL is specified in
* another way (e.g. when providing the command to rsync or Git).
* @param bool $autoConfigure
* Write or validate SSH configuration automatically after building the
* command.
*
* @return string
*/
public function getSshCommand($url, array $extraOptions = [], $remoteCommand = null, $omitUrl = false, $autoConfigure = true)
{
$command = 'ssh';
if (!$omitUrl) {
$command .= ' ' . OsUtil::escapeShellArg($url);
}
if ($args = $this->getSshArgs($url, $extraOptions, $remoteCommand)) {
$command .= ' ' . implode(' ', array_map([OsUtil::class, 'escapeShellArg'], $args));
}
// Configure or validate the session SSH config.
if ($autoConfigure && !$this->configuredSession && $this->hostIsInternal($url) !== false) {
try {
$this->sshConfig->configureSessionSsh();
$this->configuredSession = true;
} catch (\Exception $e) {
$this->stdErr->writeln('Error configuring SSH: ' . $e->getMessage(), OutputInterface::VERBOSITY_VERBOSE);
}
}
return $command;
}
/**
* Returns environment variables to set on SSH commands.
*
* @return array<string, string>
*/
public function getEnv()
{
// Suppress refreshing the certificate while SSH is running through the CLI.
return [self::SSH_NO_REFRESH_ENV_VAR => '1'];
}
/**
* Finds a host from an SSH URI.
*
* @param string $uri
*
* @return string|false|null
*/
private function getHost($uri)
{
if (\strpos($uri, '@') !== false) {
list(, $uri) = \explode('@', $uri, 2);
}
if (\strpos($uri, '://') !== false) {
list(, $uri) = \explode('://', $uri, 2);
}
if (\strpos($uri, ':') !== false) {
list($uri, ) = \explode(':', $uri, 2);
}
if (!preg_match('@^[\p{Ll}0-9-]+\.[\p{Ll}0-9-]+@', $uri)) {
return false;
}
return \parse_url('ssh://' . $uri, PHP_URL_HOST);
}
/**
* Checks if an SSH URI is for an internal (first-party) SSH server.
*
* @param string $uri
*
* @return bool|null
* True if the URI is for an internal server, false if it's external, or null if it cannot be determined.
*/
public function hostIsInternal($uri)
{
$host = $this->getHost($uri);
if (!$host) {
return null;
}
// Check against the wildcard list.
$wildcards = $this->config->getWithDefault('ssh.domain_wildcards', []);
if (!$wildcards) {
return null;
}
foreach ($wildcards as $wildcard) {
if (\strpos($host, \str_replace('*.', '', $wildcard)) !== false) {
return true;
}
}
return false;
}
}