This repository was archived by the owner on Mar 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSecureShell.php
More file actions
341 lines (312 loc) · 9.7 KB
/
Copy pathSecureShell.php
File metadata and controls
341 lines (312 loc) · 9.7 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
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
<?php
namespace Codeception\Extension;
use Codeception\Exception\ModuleException;
use Codeception\Exception\ModuleConfigException;
use Codeception\Module;
use Codeception\Configuration;
use \SplFileObject;
use \RuntimeException;
use \Exception;
class SecureShell extends Module
{
const DEFAULT_PORT = 22;
const AUTH_PASSWORD = 1;
const AUTH_PUBKEY = 2;
const AUTH_HOSTKEY = 3;
const AUTH_AGENT = 4;
const AUTH_NONE = 0;
protected $config = ['StrictHostKeyChecking', 'KnownHostsFile'];
protected $requiredFields = [];
/**
* @var string $knownHostsFile
*/
protected static $knownHostsFile = '';
/**
* @var bool $strictHostKeyChecking
*/
protected static $strictHostKeyChecking = false;
/**
* @var mixed|null $connection
*/
protected $connection;
/**
* @var string[] $output
*/
private $output;
/**
* @codeCoverageIgnore
* @ignore Codeception specific
*/
public function _initialize()
{
if (isset($this->config['StrictHostKeyChecking'])) {
static::$strictHostKeyChecking = (bool) $this->config['StrictHostKeyChecking'];
}
if (isset($this->config['KnownHostsFile'])) {
static::$knownHostsFile = $this->config['KnownHostsFile'];
} elseif (static::$strictHostKeyChecking) {
// default KnownHostsFile if StrictHostKeyChecking enabled
static::$knownHostsFile = Configuration::projectDir().'known_hosts';
}
// check that a KnownHostsFile exists if StrictHostKeyChecking enabled
if (static::$strictHostKeyChecking && !file_exists(static::$knownHostsFile)) {
throw new ModuleConfigException(__CLASS__, 'KnownHostsFile "'.static::$knownHostsFile.'" not found');
}
}
/**
* Open an SSH connection to the host
*
* @param string $host
* @param int $port
* @param int $auth
* @param mixed ...$args
*
* @return resource|null Returns the SSH connection
*/
public function openConnection($host,
$port = SecureShell::DEFAULT_PORT,
$auth = SecureShell::AUTH_PASSWORD,
...$args)
{
$callbacks = array('disconnect' => [$this, '_disconnect']);
try {
$connection = ssh2_connect($host, $port, $callbacks);
if (!$connection) {
throw new ModuleException(__CLASS__, "Unable to connect to {$host} on port {$port}");
} else {
$this->__checkFingerprint($connection);
if ($this->__authenticate($connection, $auth, ...$args) === false) {
throw new ModuleException(__CLASS__, "Authentication failed on server {$host}:{$port}");
} else {
$this->connection = $connection;
}
}
} catch (ModuleException $e) {
throw $e;
} catch (Exception $e) {
throw new ModuleException(__CLASS__, $e->getMessage());
}
return $this->connection;
}
/**
* Close current SSH connection
*
* @return boolean Return true once executed
*/
public function closeConnection() {
$this->connection = null;
return true;
}
/**
* Get current SSH connection
*
* @return resource|null Return current SSH connection
*/
public function getConnection() {
return $this->connection;
}
/**
* Run SSH authentication based on the selected method
*
* @param resource $connection
* @param int $method
* @param mixed ...$args
*
* @return void
*/
protected function __authenticate($connection, $method, ...$args)
{
switch ($method) {
case SecureShell::AUTH_PASSWORD:
return ssh2_auth_password($connection, ...$args);
case SecureShell::AUTH_PUBKEY:
return ssh2_auth_pubkey_file($connection, ...$args);
case SecureShell::AUTH_HOSTKEY:
return ssh2_auth_hostbased_file($connection, ...$args);
case SecureShell::AUTH_AGENT:
return ssh2_auth_agent($connection, ...$args);
case SecureShell::AUTH_NONE:
return ssh2_auth_none($connection, ...$args);
default:
throw new ModuleException(__CLASS__, 'Unsupported authentication method');
}
}
/**
* Check if the SSH server public key fingerprint is valid
*
* @param resource $connection
*
* @return string Server public key fingerprint
*/
protected function __checkFingerprint($connection)
{
$knownHost = false;
try {
$fingerprint = ssh2_fingerprint($connection, SSH2_FINGERPRINT_MD5);
if (file_exists(static::$knownHostsFile)) {
$file = new SplFileObject(static::$knownHostsFile);
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl(' ');
foreach ($file as $entry) {
list(,, $fp) = $entry;
$fp = md5(base64_decode($fp));
$knownHost = (strcasecmp($fp, $fingerprint) === 0);
if ($knownHost) {
break;
}
}
}
$knownHost = $knownHost || !static::$strictHostKeyChecking;
if ($knownHost === false) {
throw new ModuleException(__CLASS__, 'Unable to verify server identity!');
}
} catch (RuntimeException $e) {
if (static::$strictHostKeyChecking) {
throw new ModuleException(__CLASS__, 'Unable to verify server identity!');
}
}
return $fingerprint;
}
/**
* Run a command on the remote host and return the output
*
* @param string $command
*
* @return string[] Return command output 'STDOUT' and 'STDERR'
*/
public function runRemoteCommand($command)
{
try {
$stream = ssh2_exec($this->connection, $command);
stream_set_blocking($stream, true);
$errStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
$this->output['STDOUT'] = stream_get_contents($stream);
$this->output['STDERR'] = stream_get_contents($errStream);
return $this->output;
} catch (Exception $e) {
throw new ModuleException(__CLASS__, $e->getMessage());
}
}
/**
* Verify that the last remote command output contains a specific text
*
* @param string $text
*
* @return void
*/
public function seeInRemoteOutput($text)
{
\PHPUnit_Framework_Assert::assertContains($text, $this->output['STDOUT']);
}
/**
* Verify that the last remote command output does not contain a specific text
*
* @param string $text
*
* @return void
*/
public function dontSeeInRemoteOutput($text)
{
\PHPUnit_Framework_Assert::assertNotContains($text, $this->output['STDOUT']);
}
/**
* Verify that a file exists in the current remote folder
*
* @param string $filename
*
* @return void
*/
public function seeRemoteFile($filename)
{
$sftp = ssh2_sftp($this->connection);
try {
$res = ssh2_sftp_stat($sftp, $filename);
} catch (Exception $e) {
$res = null;
}
\PHPUnit_Framework_Assert::assertNotEmpty($res);
}
/**
* Verify that a file does not exist in the current remote folder
*
* @param string $filename
*
* @return void
*/
public function dontSeeRemoteFile($filename)
{
$sftp = ssh2_sftp($this->connection);
try {
$res = (bool) ssh2_sftp_stat($sftp, $filename);
} catch (Exception $e) {
$res = false;
}
\PHPUnit_Framework_Assert::assertFalse($res);
}
/**
* Get the content of a remote file over SFTP
*
* @param string $filename
*
* @return string File content
*/
public function grabRemoteFile($filename)
{
try {
$sftp = ssh2_sftp($this->connection);
return file_get_contents("ssh2.sftp://{$sftp}/{$filename}");
} catch (Exception $e) {
throw new ModuleException(__CLASS__, $e->getMessage());
}
}
/**
* Verify that a remote folder exists in the current remote path
*
* @param string $dirname
*
* @return void
*/
public function seeRemoteDir($dirname)
{
try {
$res = (bool) $this->grabRemoteDir($dirname);
} catch (Exception $e) {
$res = false;
}
\PHPUnit_Framework_Assert::assertTrue($res);
}
/**
* Verify that a remote folder does not exist in the current remote path
*
* @param string $dirname
*
* @return void
*/
public function dontSeeRemoteDir($dirname)
{
try {
$res = (bool) $this->grabRemoteDir($dirname);
} catch (Exception $e) {
$res = false;
}
\PHPUnit_Framework_Assert::assertFalse($res);
}
/**
* Get the remode folder content
*
* @param string $dirname
*
* @return string[] Array of file names and folder names
*/
public function grabRemoteDir($dirname)
{
$res = null;
try {
$sftp = ssh2_sftp($this->connection);
$res = scandir("ssh2.sftp://{$sftp}/{$dirname}");
} catch (Exception $e) {
throw new ModuleException(__CLASS__, $e->getMessage());
}
return $res;
}
}