Search code examples
sshproxy

Dynamic Hostname when using SSH Proxy with ProxyCommand


I am trying to configure an SSH connection through a proxy server such that

Host bridge-test
  HostName TARGETHOST
  ProxyCommand ssh -W BRIDGEHOST %h:%p

however, my problem is that I do not know a priori what TARGETHOST is. This information can only be accessed by executing a command on the BRIDGEHOST (which is static). Is there any way to configure SSH to pick up the TARGETHOST as a variable from the proxy server?


Solution

  • It is possible with a bit inline magic

    Match originalhost bridge-test exec "ssh BRIDGEHOST 'cat host.txt' > /tmp/host.txt; true"
      hostname dummy
      ProxyCommand ssh BRIDGEHOST -W $(cat /tmp/host.txt):%p
    

    How it works?

    1. The match exec expression is used only to connect to BRIDGEHOST and get there the hostname dynamically (I used a simple cat host.txt as example)
    2. Save the hostname to a local file /tmp/host.txt
    3. Finish the match command with true, then the match exec will always match
    4. Use the hostname from /tmp/host.txt in the ProxyCommand

    But the obvious variant fails (ssh version dependent)

    I would expect that it could be simplified to

    HOST bridge-test
      hostname dummy
      ProxyCommand ssh BRIDGEHOST -W $(ssh BRIDGEHOST 'cat host.txt'):%p
    

    But this variant fails with:

    Bad packet length 1231976033.
    ssh_dispatch_run_fatal: Connection to UNKNOWN port 65535: message authentication code incorrect

    I've tested many simplified variants, but as soon as I call ssh somewhere this leads to an error.
    Tested with:

    $ ssh -V
    OpenSSH_8.9p1 Ubuntu-3ubuntu0.6, OpenSSL 3.0.2 15 Mar 2022
    

    Edit 2024-09-05:
    Retested today with OpenSSH_9.0p1 and it works with nested ssh, too