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);