Repository navigation
Expand file tree
/
Copy pathSftpConnectionProvider.php
More file actions
254 lines (207 loc) · 7.69 KB
/
Copy pathSftpConnectionProvider.php
File metadata and controls
254 lines (207 loc) · 7.69 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
<?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV3;
use League\Flysystem\FilesystemException;
use phpseclib3\Crypt\Common\AsymmetricKey;
use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Exception\NoKeyLoadedException;
use phpseclib3\Net\SFTP;
use phpseclib3\System\SSH\Agent;
use Throwable;
use function base64_decode;
use function bin2hex;
use function hash;
use function hash_equals;
use function preg_match;
use function rtrim;
use function str_replace;
use function strtolower;
class SftpConnectionProvider implements ConnectionProvider
{
/**
* @var SFTP|null
*/
private $connection;
/**
* @var ConnectivityChecker
*/
private $connectivityChecker;
public function __construct(
private string $host,
private string $username,
private ?string $password = null,
private ?string $privateKey = null,
private ?string $passphrase = null,
private int $port = 22,
private bool $useAgent = false,
private int $timeout = 10,
private int $maxTries = 4,
private string|array|null $hostFingerprint = null,
?ConnectivityChecker $connectivityChecker = null,
private array $preferredAlgorithms = [],
private bool $disableStatCache = true,
) {
$this->connectivityChecker = $connectivityChecker ?? new SimpleConnectivityChecker();
}
public function provideConnection(): SFTP
{
$tries = 0;
start:
$tries++;
try {
$connection = $this->connection instanceof SFTP
? $this->connection
: $this->setupConnection();
} catch (Throwable $exception) {
if ($tries <= $this->maxTries) {
goto start;
}
if ($exception instanceof FilesystemException) {
throw $exception;
}
throw UnableToConnectToSftpHost::atHostname($this->host, $exception);
}
if ( ! $this->connectivityChecker->isConnected($connection)) {
$connection->disconnect();
$this->connection = null;
if ($tries <= $this->maxTries) {
goto start;
}
throw UnableToConnectToSftpHost::atHostname($this->host);
}
return $this->connection = $connection;
}
public function disconnect(): void
{
if ($this->connection) {
$this->connection->disconnect();
$this->connection = null;
}
}
private function setupConnection(): SFTP
{
$connection = new SFTP($this->host, $this->port, $this->timeout);
$connection->setPreferredAlgorithms($this->preferredAlgorithms);
$this->disableStatCache && $connection->disableStatCache();
try {
$this->checkFingerprint($connection);
$this->authenticate($connection);
} catch (Throwable $exception) {
$connection->disconnect();
throw $exception;
}
return $connection;
}
private function checkFingerprint(SFTP $connection): void
{
if ( ! $this->hostFingerprint) {
return;
}
$publicKey = $connection->getServerPublicHostKey();
if ($publicKey === false) {
throw UnableToEstablishAuthenticityOfHost::becauseTheAuthenticityCantBeEstablished($this->host);
}
$expectedFingerprints = is_array($this->hostFingerprint)
? $this->hostFingerprint
: [$this->hostFingerprint];
foreach ($expectedFingerprints as $expectedFingerprint) {
if ($this->fingerprintMatchesPublicKey($expectedFingerprint, $publicKey)) {
return;
}
}
throw UnableToEstablishAuthenticityOfHost::becauseTheAuthenticityCantBeEstablished($this->host);
}
private function fingerprintMatchesPublicKey(string $expectedFingerprint, string $publicKey): bool
{
$content = explode(' ', $publicKey, 3);
$binaryKey = base64_decode($content[1]);
$algorithms = ['md5', 'sha1', 'sha256', 'sha512'];
if (preg_match('/^(md5|sha1|sha256|sha512):(.+)$/i', $expectedFingerprint, $matches)) {
$algorithms = [strtolower($matches[1])];
$expectedFingerprint = $matches[2];
}
foreach ($algorithms as $algorithm) {
$binaryHash = hash($algorithm, $binaryKey, true);
// Hex form: normalise by dropping the colon separators and lowercasing
// so both "AB:CD" and "abcd" match a lowercase hex digest.
$hexHash = bin2hex($binaryHash);
$expectedHex = strtolower(str_replace(':', '', $expectedFingerprint));
if (hash_equals($hexHash, $expectedHex)) {
return true;
}
// Base64 form (OpenSSH SHA256 style), tolerating stripped padding.
$base64Hash = rtrim(base64_encode($binaryHash), '=');
$expectedBase64 = rtrim($expectedFingerprint, '=');
if (hash_equals($base64Hash, $expectedBase64)) {
return true;
}
}
return false;
}
private function authenticate(SFTP $connection): void
{
if ($this->privateKey !== null) {
$this->authenticateWithPrivateKey($connection);
} elseif ($this->useAgent) {
$this->authenticateWithAgent($connection);
} else {
$this->authenticateWithUsernameAndPassword($connection);
}
}
private function authenticateWithUsernameAndPassword(SFTP $connection): void
{
if ( ! $connection->login($this->username, $this->password)) {
throw UnableToAuthenticate::withPassword($connection->getLastError());
}
}
public static function fromArray(array $options): SftpConnectionProvider
{
return new SftpConnectionProvider(
$options['host'],
$options['username'],
$options['password'] ?? null,
$options['privateKey'] ?? null,
$options['passphrase'] ?? null,
$options['port'] ?? 22,
$options['useAgent'] ?? false,
$options['timeout'] ?? 10,
$options['maxTries'] ?? 4,
$options['hostFingerprint'] ?? null,
$options['connectivityChecker'] ?? null,
$options['preferredAlgorithms'] ?? [],
$options['disableStatCache'] ?? true,
);
}
private function authenticateWithPrivateKey(SFTP $connection): void
{
$privateKey = $this->loadPrivateKey();
if ($connection->login($this->username, $privateKey)) {
return;
}
if ($this->password !== null && $connection->login($this->username, $this->password)) {
return;
}
throw UnableToAuthenticate::withPrivateKey($connection->getLastError());
}
private function loadPrivateKey(): AsymmetricKey
{
if (("---" !== substr($this->privateKey, 0, 3) || "PuTTY" !== substr($this->privateKey, 0, 5)) && is_file($this->privateKey)) {
$this->privateKey = file_get_contents($this->privateKey);
}
try {
if ($this->passphrase !== null) {
return PublicKeyLoader::load($this->privateKey, $this->passphrase);
}
return PublicKeyLoader::load($this->privateKey);
} catch (NoKeyLoadedException $exception) {
throw new UnableToLoadPrivateKey(null, $exception);
}
}
private function authenticateWithAgent(SFTP $connection): void
{
$agent = new Agent();
if ( ! $connection->login($this->username, $agent)) {
throw UnableToAuthenticate::withSshAgent($connection->getLastError());
}
}
}