Skip to content

Instantly share code, notes, and snippets.

@MegaManSec
Last active August 20, 2024 20:48
Show Gist options
  • Save MegaManSec/79d82bf5e303c7a0e4a4fcbffe45553f to your computer and use it in GitHub Desktop.
Save MegaManSec/79d82bf5e303c7a0e4a4fcbffe45553f to your computer and use it in GitHub Desktop.
This small C program can be used to determine whether a public key will be accepted by a remote SSH server. That is to say, by only sending the public key to the server, we can determine whether the server would accept the key if we had the private key.
#include <stdio.h>
#include <stdlib.h>
#include <libssh/libssh.h>
int main(int argc, char *argv[]){
ssh_session session;
int rc;
if (argc != 5) {
fprintf(stderr, "Usage: %s host user port keyfile\n", argv[0]);
exit(1);
}
session = ssh_new();
if (session == NULL) {
fprintf(stderr, "Error creating SSH session\n");
exit(1);
}
int port = atoi(argv[3]);
ssh_options_set(session, SSH_OPTIONS_HOST, argv[1]);
ssh_options_set(session, SSH_OPTIONS_USER, argv[2]);
ssh_options_set(session, SSH_OPTIONS_PORT, &port);
printf("Connecting to %s@%s:%d\n", argv[2], argv[1], port);
rc = ssh_connect(session);
if (rc != SSH_OK) {
fprintf(stderr, "Error connecting to server: %s\n", ssh_get_error(session));
ssh_free(session);
exit(1);
}
ssh_key pubkey;
rc = ssh_pki_import_pubkey_file(argv[4], &pubkey);
if (rc != SSH_OK) {
fprintf(stderr, "Error importing public key: %s\n", ssh_get_error(session));
ssh_disconnect(session);
ssh_free(session);
exit(1);
}
rc = ssh_userauth_try_publickey(session, NULL, pubkey);
if (rc == SSH_AUTH_SUCCESS) {
printf("Public key authentication successful!\n");
} else if (rc == SSH_AUTH_ERROR) {
fprintf(stderr, "Error authenticating with public key: %s\n", ssh_get_error(session));
} else {
fprintf(stderr, "Public key authentication failed\n");
}
ssh_key_free(pubkey);
ssh_disconnect(session);
ssh_free(session);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment