Skip to content

Commit 9f63f0d

Browse files
committed
Initial work on SSH server fingerprinting
1 parent 261d2ba commit 9f63f0d

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/SSHConnection.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,27 @@ public function run(string $command): SSHCommand
112112
return new SSHCommand($this->ssh, $command);
113113
}
114114

115+
public function md5Fingerprint(): string
116+
{
117+
return $this->getFingerprint(0 | 0);
118+
}
119+
120+
public function sha1Fingerprint(): string
121+
{
122+
return $this->getFingerprint(0 | 0);
123+
}
124+
125+
private function getFingerprint(int $flags)
126+
{
127+
if (!$this->connected) {
128+
throw new RuntimeException('Unable to get fingerprint when not connected.');
129+
}
130+
131+
$hostkey = substr($this->ssh->getServerPublicHostKey(), 8);
132+
$hostkey = ($flags & 1) ? sha1($hostkey) : md5($hostkey);
133+
return ($flags & 2) ? pack('H*', $hostkey) : strtoupper($hostkey);
134+
}
135+
115136
public function upload(string $localPath, string $remotePath): bool
116137
{
117138
if (!$this->connected) {

tests/Integration/SSHConnectionTest.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,42 @@ public function testSSHConnectionWithPassword()
7272
$this->assertEquals('', $command->getError());
7373
$this->assertEquals('', $command->getRawError());
7474
}
75+
76+
public function testMd5Fingerprint()
77+
{
78+
$connection1 = (new SSHConnection())
79+
->to('localhost')
80+
->onPort(22)
81+
->as('travis')
82+
->withPrivateKey('/home/travis/.ssh/id_rsa')
83+
->connect();
84+
85+
$connection2 = (new SSHConnection())
86+
->to('localhost')
87+
->onPort(22)
88+
->as('travis')
89+
->withPrivateKey('/home/travis/.ssh/id_rsa')
90+
->connect();
91+
92+
$this->assertEquals($connection1->md5Fingerprint(), $connection2->md5Fingerprint());
93+
}
94+
95+
public function testSha1Fingerprint()
96+
{
97+
$connection1 = (new SSHConnection())
98+
->to('localhost')
99+
->onPort(22)
100+
->as('travis')
101+
->withPrivateKey('/home/travis/.ssh/id_rsa')
102+
->connect();
103+
104+
$connection2 = (new SSHConnection())
105+
->to('localhost')
106+
->onPort(22)
107+
->as('travis')
108+
->withPrivateKey('/home/travis/.ssh/id_rsa')
109+
->connect();
110+
111+
$this->assertEquals($connection1->sha1Fingerprint(), $connection2->sha1Fingerprint());
112+
}
75113
}

0 commit comments

Comments
 (0)