Connecting to Mikrotik RouterOS via ssh using libssh2

I came across a bug in either libssh2 or Mikrotik RouterOS, when trying to get one to connect to the other. This problem reared its head when trying to use PHP, which uses libssh2 as its default SSH provider (there are a number of other libraries, including a pure-PHP one, but the libssh2 version seems to be the official one).

When you try to connect to RouterOS from libssh2, it fails at the key exchange step with the message

Unable to exchange encryption keys

After some digging around in the code, I came to the conclusion that this was because libssh2 is trying to start a Diffie-Hellman GEX (group exchange) and RouterOS isn’t expecting that. It looks to me like RouterOS is in the wrong here, but I haven’t dug deep enough to know that for certain.

Anyway, it turns out there’s an easy workaround by setting the SSH method preference to ‘diffie-hellman-group1-sha1’. This can be done in PHP with the following:

$methods = array(
 'kex' => 'diffie-hellman-group1-sha1'
);

$connection = ssh2_connect($server, 22, $methods);

One thought on “Connecting to Mikrotik RouterOS via ssh using libssh2

  1. Igor

    hello

    very interesting. I’m developing some project. Web server via libssh2 must execute commands on remote Mikrotik routers.
    It’s fine, when i have one command, for example, “int bri add name=bridge1”
    but when i want to execute script, similar:
    “/int bridge
    add name=bridge1
    add name=bridge2”
    ssh_exec returns false in second way and command has no executed.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *