Simulating SSH Jump Host Behavior in PHP with phpseclib

54 Views Asked by At

I'm facing an issue with trying to simulate a jump similar to the command "ssh -J [email protected] [email protected]" using the phpseclib2 or phpseclib3 library or natively with Secure Shell2 (libssh2).

I can successfully connect to the bastion, but when I try to execute an SSH command using "exec", it's not allowed, giving me a "Permission denied (publickey)" error. This seems to be because it's not a true jump like the direct bash command "ssh -J".

Implementing in PHP with phpseclib3

<?php

require __DIR__ . '/../vendor/autoload.php';

use phpseclib\Crypt\RSA;
use phpseclib\Net\SSH2;

// Connection parameters
$bastionHost = 'bastion.net';
$bastionPort = 22;
$bastionUser = 'identifier';
$bastionPass = '';

$address = 'xx.xx.xx.xx';
$user = 'identifier';
$port = 22;

$privateKeyPath = 'ssh_key';

$rsa = new RSA();
$rsa->loadKey(file_get_contents($privateKeyPath));

$ssh = new SSH2($bastionHost, $bastionPort);
if (!$ssh->login($bastionUser, $rsa)) {
    throw new \Exception('Login failed');
}

echo $ssh->exec("ssh $user@$address");  // Permission denied (publickey)

I'm looking for a solution to truly simulate the behavior of a jump. Any suggestions would be greatly appreciated. Thanks!

1

There are 1 best solutions below

1
Sammitch On

Tunnelling is not simply "start another ssh command on remote", it's part of the protocol, and it is not currently implemented in phpseclib.

https://github.com/phpseclib/phpseclib/issues/1096

The alternative would be using your existing code with an SSH Agent and Agent Forwarding.

https://phpseclib.com/docs/auth#ssh-agent

Eg:

$agent = new Agent;
$agent->startSSHForwarding($ssh);

$ssh = new SSH2($bastionHost, $bastionPort);
if (!$ssh->login($bastionUser, $agent)) {
    throw new \Exception('Login failed');
}

echo $ssh->exec("ssh $user@$address");

Though it's important to note that this simply connects to an ssh-agent or similar instance already running in the environment.