ssh: add support for ssh-agent authentication
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
diff --git a/src/transports/cred.c b/src/transports/cred.c
index 05d2c8d..abae70b 100644
--- a/src/transports/cred.c
+++ b/src/transports/cred.c
@@ -165,6 +165,28 @@ int git_cred_ssh_key_new(
return 0;
}
+int git_cred_ssh_key_from_agent(git_cred **cred, const char *username) {
+ git_cred_ssh_key *c;
+
+ assert(cred);
+
+ c = git__calloc(1, sizeof(git_cred_ssh_key));
+ GITERR_CHECK_ALLOC(c);
+
+ c->parent.credtype = GIT_CREDTYPE_SSH_KEY;
+ c->parent.free = ssh_key_free;
+
+ if (username) {
+ c->username = git__strdup(username);
+ GITERR_CHECK_ALLOC(c->username);
+ }
+
+ c->privatekey = NULL;
+
+ *cred = &c->parent;
+ return 0;
+}
+
int git_cred_ssh_custom_new(
git_cred **cred,
const char *username,
diff --git a/src/transports/ssh.c b/src/transports/ssh.c
index 4a905e3..37f1708 100644
--- a/src/transports/ssh.c
+++ b/src/transports/ssh.c
@@ -235,6 +235,50 @@ static int git_ssh_extract_url_parts(
return 0;
}
+static int ssh_agent_auth(LIBSSH2_SESSION *session, git_cred_ssh_key *c) {
+ int rc = LIBSSH2_ERROR_NONE;
+
+ struct libssh2_agent_publickey *curr, *prev = NULL;
+
+ LIBSSH2_AGENT *agent = libssh2_agent_init(session);
+
+ if (agent == NULL)
+ return -1;
+
+ rc = libssh2_agent_connect(agent);
+
+ if (rc != LIBSSH2_ERROR_NONE)
+ goto shutdown;
+
+ rc = libssh2_agent_list_identities(agent);
+
+ if (rc != LIBSSH2_ERROR_NONE)
+ goto shutdown;
+
+ while (1) {
+ rc = libssh2_agent_get_identity(agent, &curr, prev);
+
+ if (rc < 0)
+ goto shutdown;
+
+ if (rc == 1)
+ goto shutdown;
+
+ rc = libssh2_agent_userauth(agent, c->username, curr);
+
+ if (rc == 0)
+ break;
+
+ prev = curr;
+ }
+
+shutdown:
+ libssh2_agent_disconnect(agent);
+ libssh2_agent_free(agent);
+
+ return rc;
+}
+
static int _git_ssh_authenticate_session(
LIBSSH2_SESSION* session,
const char *user,
@@ -253,8 +297,14 @@ static int _git_ssh_authenticate_session(
case GIT_CREDTYPE_SSH_KEY: {
git_cred_ssh_key *c = (git_cred_ssh_key *)cred;
user = c->username ? c->username : user;
- rc = libssh2_userauth_publickey_fromfile(
- session, c->username, c->publickey, c->privatekey, c->passphrase);
+
+ if (c->privatekey)
+ rc = libssh2_userauth_publickey_fromfile(
+ session, c->username, c->publickey,
+ c->privatekey, c->passphrase);
+ else
+ rc = ssh_agent_auth(session, c);
+
break;
}
case GIT_CREDTYPE_SSH_CUSTOM: {