Vlad
Vlad

Reputation: 1601

Server with ssh public key authentication with libssh

Can someone give an example with server with ssh public key authentication with libssh? I found this https://github.com/substack/libssh/blob/master/examples/samplesshd-tty.c, but it's authentication with password. May be someone seen example like this, but with public key authentication on libssh. Or may be someone can change the code below to get it.

I added this to switch(ssh_message_subtype(message))

                  case SSH_AUTH_METHOD_PUBLICKEY:
                        printf("User %s wants to auth with key %s\n",
                               ssh_message_auth_user(message),
                               ssh_message_auth_pubkey(message));
                        if(authenticate_pubkey(session, message)){
                            ssh_message_auth_reply_success(message,0);
                            ssh_message_free(message);
                            return 1;
                        }
                        ssh_message_auth_set_methods(message,
                                                     SSH_AUTH_METHOD_PUBLICKEY);
                        // not authenticated, send default message
                        ssh_message_reply_default(message);
                        break;

and this

static int authenticate_pubkey(ssh_session session, ssh_message message)
{
    int rc;
    std::string us =  ssh_message_auth_user(message);
    rc = ssh_userauth_publickey_auto(session, ssh_message_auth_user(message), NULL);
    if (rc == SSH_AUTH_ERROR)
    {
        fprintf(stderr, "Authentication failed: %s\n",
                ssh_get_error(session));
        return SSH_AUTH_ERROR;
    }
    return rc;
}

Upvotes: 1

Views: 2261

Answers (1)

asn
asn

Reputation: 838

This is not really hard. However I suggest to write a callback based ssh server. See the samplesshd-cb.c example in the libssh source code.

Public key auth:

First read RFC 4252 section 7. It describes how public key auth works. The callback provides you the public key and tells you if it is a probe of the public key or a login.

So first you have to read the authorized keys. Normally you have a file with all the keys in it. You use ssh_pki_import_pubkey_base64() to read the key and then call ssh_key_cmp() to compare it with the public key sent by the client. Depending if it is a probe you return partial success or auth success if it is a login.

Upvotes: 1

Related Questions