Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Libgit2 - Failed to authenticate SSH session: Unable to open public key file

Tags:

c++

ssh

libgit2

I'm trying to do a very simple git clone using ssh over a network with Libgit2 -- getting the error in the title in the process. I am not sure what I'm doing wrong -- it is not a network issue as I can clone the repo via the command line. The keys are also in the specified path.

Also the keys are already set up such that if I wanted to ssh to the machine I'm trying to clone from I just need to supply a password, so not really sure why I need to redefine it here.

#include <git2.h>
#include <iostream> 

// Callback function
int cred_cb(git_cred **out, const char *url, const char *username_from_url,
     unsigned int allowed_types, void *payload) {

  // https://libgit2.github.com/libgit2/#HEAD/group/cred/git_cred_ssh_key_new
  return git_cred_ssh_key_new(out, "username", 
        "~/.ssh/id_rsa.pub", "~/.ssh/id_rsa", "password");
}

int main() {
  // Start up libgit2
  git_libgit2_init();

  // Test clone setup
  git_repository *repo = NULL;
  const char *url = "ssh://[email protected]/home/git_repo_to_clone";
  const char *path = "tmp";

  // Test clone
  git_clone_options clone_opts = GIT_CLONE_OPTIONS_INIT;
  clone_opts.fetch_opts.callbacks.credentials = cred_cb;
  int error = git_clone(&repo, url, path, &clone_opts);

  // Prints the last error message
  std::cout << giterr_last()->message << std::endl;

  // Clean up
  git_libgit2_shutdown();

  return 0;
}

Printing allowed_types in cred_cb says 22, and so if you try to return a different type of git_cred (for example, git_cred_userpass_plaintext) the library complains that callback returned unsupported credentials type, and also if no callback is specified (by calling git_clone with NULL as the third parameter) then it says that authentication required but no callback set. I might be missing something obvious, I would appreciate any help, thanks.

Edit

I instead tried with git_cred_ssh_key_from_agent(out, "username") and it seems to have done something (the git folder gets cloned), albeit with missing files. Although now the problem is it becomes an endless loop between cred_cb and git_clone (seems to be called back and forth).

like image 900
ifma Avatar asked Sep 19 '25 04:09

ifma


1 Answers

The path to the key files should be the full path without ~. Libgit2 doesn't expand ~ like the shell would.

Also, the password should be the passphrase used to encrypt your private key, not the password you use to authenticate with the remote.

like image 57
Jason Haslam Avatar answered Sep 21 '25 21:09

Jason Haslam