Reputation:
I am trying to create a simplified SSH connection between client and server with libssh library in C++. My code is as displayed below:
ssh_session session;
session = ssh_new();
if(session == NULL) {
cout << "Session cannot be created. Exiting.." << endl;
exit(EXIT_FAILURE);
}
int verbosity = SSH_LOG_FUNCTIONS;
ssh_options_set(session, SSH_OPTIONS_HOST, "127.0.0.1");
ssh_options_set(session, SSH_OPTIONS_PORT, "22");
ssh_options_set(session, SSH_OPTIONS_USER, "box")
ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
int rc;
// ---- This is where it starts
rc = ssh_connect(session); // <--- CONNECTION IS CREATED, but THEN IT IS REFUSED BY SERVER!
if(rc != SSH_OK) {
cout << "rc != SSH_OK" << endl; // <--- GETS PRINTED AFTER REFUSAL OF CONNECTION
exit(EXIT_FAILURE); // <--- CODE EXITS HERE!
}
enum ssh_known_hosts_e state;
unsigned char *hash = NULL;
ssh_key srvpubkey = NULL;
size_t hashlen;
rc = ssh_get_server_publickey(session, &srvpubkey);
if(rc < 0) {
return -1;
}
rc = ssh_get_publickey_hash(srvpubkey, SSH_PUBLICKEY_HASH_SHA256, &hash, &hashlen);
ssh_key_free(srvpubkey);
if(rc < 0) {
cout << "Public Key Hash @ERROR" << endl;
return -1;
}
switch(state) {
case SSH_KNOWN_HOSTS_OK: {
// ok, no problem!
cout << "All good!" << endl;
break;
}
case SSH_KNOWN_HOSTS_CHANGED: {
ssh_clean_pubkey_hash(&hash);
cout << "Hash: " << hash << endl << "Length: " << hashlen << endl;
return -1;
}
case SSH_KNOWN_HOSTS_OTHER: {
ssh_clean_pubkey_hash(&hash);
return -1;
}
case SSH_KNOWN_HOSTS_NOT_FOUND: {
ssh_clean_pubkey_hash(&hash);
return -1;
}
case SSH_KNOWN_HOSTS_UNKNOWN: {
ssh_clean_pubkey_hash(&hash);
return -1;
}
case SSH_KNOWN_HOSTS_ERROR: {
ssh_clean_pubkey_hash(&hash);
return -1;
}
default: {
ssh_clean_pubkey_hash(&hash);
return -1;
}
}
ssh_clean_pubkey_hash(&hash);
ssh_disconnect(session);
ssh_free(session);
When executing this code, I am greeted with Connection Refused error. Please note that my SSH server is up and running, when I attempt to connect through my command terminal it is working OK. I am able to connect and do all I need, however when executed through this code; as previously stated, the connection is being refused. Any tips, hints or assistance is greatly appreciated.
PS. I've enabled maximum verbosity to learn more about the error but what I said is all that was provided. It gave no further information when debugging.
Upvotes: 1
Views: 1211
Reputation:
This has been solved. Thanks to tcpdump I was able to learn that the connection was being made to a different port. What immediately came to my attention then is to check how the port was being set and the mistake was right here:
ssh_options_set(session, SSH_OPTIONS_PORT, "22");
Fix:
int port = 22;
ssh_options_set(session, SSH_OPTIONS_PORT, &port);
Because SSH_OPTIONS_PORT takes reference.
Upvotes: 1