From 9f63f0d07f2108e08f89a2f861483fc79d903ab8 Mon Sep 17 00:00:00 2001 From: Jordan Hall Date: Thu, 17 Oct 2019 19:38:16 +0100 Subject: [PATCH] Initial work on SSH server fingerprinting --- src/SSHConnection.php | 21 ++++++++++++++ tests/Integration/SSHConnectionTest.php | 38 +++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/src/SSHConnection.php b/src/SSHConnection.php index 4f75fd9..991f269 100644 --- a/src/SSHConnection.php +++ b/src/SSHConnection.php @@ -112,6 +112,27 @@ public function run(string $command): SSHCommand return new SSHCommand($this->ssh, $command); } + public function md5Fingerprint(): string + { + return $this->getFingerprint(0 | 0); + } + + public function sha1Fingerprint(): string + { + return $this->getFingerprint(0 | 0); + } + + private function getFingerprint(int $flags) + { + if (!$this->connected) { + throw new RuntimeException('Unable to get fingerprint when not connected.'); + } + + $hostkey = substr($this->ssh->getServerPublicHostKey(), 8); + $hostkey = ($flags & 1) ? sha1($hostkey) : md5($hostkey); + return ($flags & 2) ? pack('H*', $hostkey) : strtoupper($hostkey); + } + public function upload(string $localPath, string $remotePath): bool { if (!$this->connected) { diff --git a/tests/Integration/SSHConnectionTest.php b/tests/Integration/SSHConnectionTest.php index 6980fd4..74a3809 100644 --- a/tests/Integration/SSHConnectionTest.php +++ b/tests/Integration/SSHConnectionTest.php @@ -72,4 +72,42 @@ public function testSSHConnectionWithPassword() $this->assertEquals('', $command->getError()); $this->assertEquals('', $command->getRawError()); } + + public function testMd5Fingerprint() + { + $connection1 = (new SSHConnection()) + ->to('localhost') + ->onPort(22) + ->as('travis') + ->withPrivateKey('/home/travis/.ssh/id_rsa') + ->connect(); + + $connection2 = (new SSHConnection()) + ->to('localhost') + ->onPort(22) + ->as('travis') + ->withPrivateKey('/home/travis/.ssh/id_rsa') + ->connect(); + + $this->assertEquals($connection1->md5Fingerprint(), $connection2->md5Fingerprint()); + } + + public function testSha1Fingerprint() + { + $connection1 = (new SSHConnection()) + ->to('localhost') + ->onPort(22) + ->as('travis') + ->withPrivateKey('/home/travis/.ssh/id_rsa') + ->connect(); + + $connection2 = (new SSHConnection()) + ->to('localhost') + ->onPort(22) + ->as('travis') + ->withPrivateKey('/home/travis/.ssh/id_rsa') + ->connect(); + + $this->assertEquals($connection1->sha1Fingerprint(), $connection2->sha1Fingerprint()); + } }