Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSH Tunnelling to MySQL in c++

I am developing a test app to understand how to do SSH tunnelling to connect to a MySQL Database in C++.

I am using the libssh2 library and I am using an example from https://www.libssh2.org/examples/direct_tcpip.html but I am not 100% sure whether or not this is the correct thing to use.

I've pretty much copied the example but when connecting to MySQL on my socket, MySQL throws:

Errro 2013 (HY000): Lost connection to mysql server at 'reading communication packet', system error: 0

When I connect to mysql using mysql -uroot -p -P2222 my app reads data on the channel using the following:

int len = libssh2_channel_read(channel, buf, sizeof(len));

and the buf contains SSH-2.0- and then this is written to the forwarding socket as follows:

wr = 0;
while (wr < len)
{
    i = send(forward_socket, buf + wr, len - wr, 0);
    if (i <= 0)
    {
        perror("write");
        return EXIT_FAILURE;
    }
    wr += i;
}

As soon as the send is done, I instantly get the mysql error. I assume it is because I am sending SSH-2.0- to MySQL which MySQL isn't expecting so its closing the connection but I can't see what's wrong, and I can't find for certain whether or not libssh2 direct_tcpip is the correct thing to use.

like image 933
Boardy Avatar asked Oct 29 '22 15:10

Boardy


1 Answers

Finally, managed to figure out what to do, with lots of trial and error and hair pulling managed it.

Using the example from https://www.libssh2.org/examples/direct_tcpip.html but I was setting the variables with the wrong value.

Basically, in the example it has

const char *remote_desthost = "localhost"; /* resolved by the server */ 
unsigned int remote_destport = 22;

Because of remote_destport in the example being 22, I thought this was the SSH connection details so I set this to be my SSH settings.

It turns out this is where the connection gets forwarded to from the SSH session so I changed it to be

const char *remote_desthost = "localhost"; /* resolved by the server */ 
unsigned int remote_destport = 3306;

So now I can run my app from my laptop, which connects to my SSH server for my web server and then on my laptop run in the command

mysql -uroot -p -P2222 and I connect to the database on my webserver through the SSH tunnel.

like image 59
Boardy Avatar answered Nov 15 '22 06:11

Boardy