ssh.c 21.5 KB
Newer Older
Brad Morgan committed
1 2 3 4 5 6 7
/*
 * Copyright (C) the libgit2 contributors. All rights reserved.
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */

8 9
#include "ssh.h"

10 11 12 13
#ifdef GIT_SSH
#include <libssh2.h>
#endif

14
#include "runtime.h"
Brad Morgan committed
15 16
#include "git2.h"
#include "buffer.h"
17
#include "net.h"
Brad Morgan committed
18
#include "netops.h"
Brad Morgan committed
19
#include "smart.h"
20
#include "streams/socket.h"
Brad Morgan committed
21

22 23
#include "git2/credential.h"
#include "git2/sys/credential.h"
24

25 26
#ifdef GIT_SSH

Brad Morgan committed
27 28
#define OWNING_SUBTRANSPORT(s) ((ssh_subtransport *)(s)->parent.subtransport)

29
static const char *ssh_prefixes[] = { "ssh://", "ssh+git://", "git+ssh://" };
30

Brad Morgan committed
31 32 33 34 35
static const char cmd_uploadpack[] = "git-upload-pack";
static const char cmd_receivepack[] = "git-receive-pack";

typedef struct {
	git_smart_subtransport_stream parent;
36
	git_stream *io;
Brad Morgan committed
37 38
	LIBSSH2_SESSION *session;
	LIBSSH2_CHANNEL *channel;
Brad Morgan committed
39 40 41 42 43 44 45
	const char *cmd;
	char *url;
	unsigned sent_command : 1;
} ssh_stream;

typedef struct {
	git_smart_subtransport parent;
Brad Morgan committed
46
	transport_smart *owner;
Brad Morgan committed
47
	ssh_stream *current_stream;
48
	git_credential *cred;
49 50
	char *cmd_uploadpack;
	char *cmd_receivepack;
Brad Morgan committed
51 52
} ssh_subtransport;

53
static int list_auth_methods(int *out, LIBSSH2_SESSION *session, const char *username);
54

55 56 57 58 59
static void ssh_error(LIBSSH2_SESSION *session, const char *errmsg)
{
	char *ssherr;
	libssh2_session_last_error(session, &ssherr, NULL, 0);

60
	git_error_set(GIT_ERROR_SSH, "%s: %s", errmsg, ssherr);
61 62
}

Brad Morgan committed
63 64 65
/*
 * Create a git protocol request.
 *
Brad Morgan committed
66
 * For example: git-upload-pack '/libgit2/libgit2'
Brad Morgan committed
67
 */
68
static int gen_proto(git_buf *request, const char *cmd, const char *url)
Brad Morgan committed
69
{
70
	const char *repo;
71
	int len;
72
	size_t i;
73

74
	for (i = 0; i < ARRAY_SIZE(ssh_prefixes); ++i) {
75 76 77 78 79 80 81 82 83 84
		const char *p = ssh_prefixes[i];

		if (!git__prefixcmp(url, p)) {
			url = url + strlen(p);
			repo = strchr(url, '/');
			if (repo && repo[1] == '~')
				++repo;

			goto done;
		}
85
	}
86 87
	repo = strchr(url, ':');
	if (repo) repo++;
88

89
done:
90
	if (!repo) {
91
		git_error_set(GIT_ERROR_NET, "malformed git protocol URL");
92 93
		return -1;
	}
94

95
	len = strlen(cmd) + 1 /* Space */ + 1 /* Quote */ + strlen(repo) + 1 /* Quote */ + 1;
96

Brad Morgan committed
97
	git_buf_grow(request, len);
98 99 100 101
	git_buf_puts(request, cmd);
	git_buf_puts(request, " '");
	git_buf_decode_percent(request, repo, strlen(repo));
	git_buf_puts(request, "'");
102

Brad Morgan committed
103 104
	if (git_buf_oom(request))
		return -1;
105

Brad Morgan committed
106 107 108
	return 0;
}

Brad Morgan committed
109
static int send_command(ssh_stream *s)
Brad Morgan committed
110 111 112
{
	int error;
	git_buf request = GIT_BUF_INIT;
113

114
	error = gen_proto(&request, s->cmd, s->url);
Brad Morgan committed
115 116
	if (error < 0)
		goto cleanup;
117

118
	error = libssh2_channel_exec(s->channel, request.ptr);
119 120
	if (error < LIBSSH2_ERROR_NONE) {
		ssh_error(s->session, "SSH could not execute request");
Brad Morgan committed
121
		goto cleanup;
122
	}
123

Brad Morgan committed
124
	s->sent_command = 1;
125

Brad Morgan committed
126
cleanup:
127
	git_buf_dispose(&request);
Brad Morgan committed
128 129 130
	return error;
}

Brad Morgan committed
131 132 133 134 135
static int ssh_stream_read(
	git_smart_subtransport_stream *stream,
	char *buffer,
	size_t buf_size,
	size_t *bytes_read)
Brad Morgan committed
136
{
137
	int rc;
138
	ssh_stream *s = GIT_CONTAINER_OF(stream, ssh_stream, parent);
139

Brad Morgan committed
140
	*bytes_read = 0;
141

Brad Morgan committed
142 143
	if (!s->sent_command && send_command(s) < 0)
		return -1;
144

145
	if ((rc = libssh2_channel_read(s->channel, buffer, buf_size)) < LIBSSH2_ERROR_NONE) {
146
		ssh_error(s->session, "SSH could not read data");
Brad Morgan committed
147
		return -1;
148
	}
149

150 151 152 153 154
	/*
	 * If we can't get anything out of stdout, it's typically a
	 * not-found error, so read from stderr and signal EOF on
	 * stderr.
	 */
155 156
	if (rc == 0) {
		if ((rc = libssh2_channel_read_stderr(s->channel, buffer, buf_size)) > 0) {
157
			git_error_set(GIT_ERROR_SSH, "%*s", rc, buffer);
158 159 160 161 162
			return GIT_EEOF;
		} else if (rc < LIBSSH2_ERROR_NONE) {
			ssh_error(s->session, "SSH could not read stderr");
			return -1;
		}
163 164 165
	}


Brad Morgan committed
166
	*bytes_read = rc;
167

Brad Morgan committed
168 169 170
	return 0;
}

Brad Morgan committed
171 172 173 174
static int ssh_stream_write(
	git_smart_subtransport_stream *stream,
	const char *buffer,
	size_t len)
Brad Morgan committed
175
{
176
	ssh_stream *s = GIT_CONTAINER_OF(stream, ssh_stream, parent);
177 178
	size_t off = 0;
	ssize_t ret = 0;
179

Brad Morgan committed
180 181
	if (!s->sent_command && send_command(s) < 0)
		return -1;
182

183 184 185 186 187 188 189 190 191 192
	do {
		ret = libssh2_channel_write(s->channel, buffer + off, len - off);
		if (ret < 0)
			break;

		off += ret;

	} while (off < len);

	if (ret < 0) {
193
		ssh_error(s->session, "SSH could not write data");
Brad Morgan committed
194 195
		return -1;
	}
196

197
	return 0;
Brad Morgan committed
198 199
}

Brad Morgan committed
200
static void ssh_stream_free(git_smart_subtransport_stream *stream)
Brad Morgan committed
201
{
202
	ssh_stream *s = GIT_CONTAINER_OF(stream, ssh_stream, parent);
203
	ssh_subtransport *t;
204

205 206
	if (!stream)
		return;
207

208
	t = OWNING_SUBTRANSPORT(s);
Brad Morgan committed
209
	t->current_stream = NULL;
210

Brad Morgan committed
211 212
	if (s->channel) {
		libssh2_channel_close(s->channel);
213 214
		libssh2_channel_free(s->channel);
		s->channel = NULL;
Brad Morgan committed
215
	}
216

Brad Morgan committed
217
	if (s->session) {
218
		libssh2_session_disconnect(s->session, "closing transport");
219 220
		libssh2_session_free(s->session);
		s->session = NULL;
Brad Morgan committed
221
	}
222

223 224 225 226
	if (s->io) {
		git_stream_close(s->io);
		git_stream_free(s->io);
		s->io = NULL;
Brad Morgan committed
227
	}
228

Brad Morgan committed
229 230 231 232
	git__free(s->url);
	git__free(s);
}

Brad Morgan committed
233 234 235 236 237
static int ssh_stream_alloc(
	ssh_subtransport *t,
	const char *url,
	const char *cmd,
	git_smart_subtransport_stream **stream)
Brad Morgan committed
238
{
Brad Morgan committed
239
	ssh_stream *s;
240

241
	GIT_ASSERT_ARG(stream);
242

Brad Morgan committed
243
	s = git__calloc(sizeof(ssh_stream), 1);
244
	GIT_ERROR_CHECK_ALLOC(s);
245

Brad Morgan committed
246
	s->parent.subtransport = &t->parent;
Brad Morgan committed
247 248 249
	s->parent.read = ssh_stream_read;
	s->parent.write = ssh_stream_write;
	s->parent.free = ssh_stream_free;
250

Brad Morgan committed
251
	s->cmd = cmd;
252

253
	s->url = git__strdup(url);
Brad Morgan committed
254 255 256 257
	if (!s->url) {
		git__free(s);
		return -1;
	}
258

Brad Morgan committed
259 260 261 262
	*stream = &s->parent;
	return 0;
}

263
static int git_ssh_extract_url_parts(
264
	git_net_url *urldata,
Brad Morgan committed
265 266 267 268
	const char *url)
{
	char *colon, *at;
	const char *start;
269

270
	colon = strchr(url, ':');
271 272


273
	at = strchr(url, '@');
Brad Morgan committed
274
	if (at) {
Etienne Samson committed
275
		start = at + 1;
276 277
		urldata->username = git__substrdup(url, at - url);
		GIT_ERROR_CHECK_ALLOC(urldata->username);
Brad Morgan committed
278
	} else {
279
		start = url;
280
		urldata->username = NULL;
Brad Morgan committed
281
	}
282

283
	if (colon == NULL || (colon < start)) {
284
		git_error_set(GIT_ERROR_NET, "malformed URL");
285 286 287
		return -1;
	}

288 289
	urldata->host = git__substrdup(start, colon - start);
	GIT_ERROR_CHECK_ALLOC(urldata->host);
290

Brad Morgan committed
291 292 293
	return 0;
}

294
static int ssh_agent_auth(LIBSSH2_SESSION *session, git_credential_ssh_key *c) {
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
	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;

320 321 322 323 324 325
		/* rc is set to 1 whenever the ssh agent ran out of keys to check.
		 * Set the error code to authentication failure rather than erroring
		 * out with an untranslatable error code.
		 */
		if (rc == 1) {
			rc = LIBSSH2_ERROR_AUTHENTICATION_FAILED;
326
			goto shutdown;
327
		}
328 329 330 331 332 333 334 335 336 337

		rc = libssh2_agent_userauth(agent, c->username, curr);

		if (rc == 0)
			break;

		prev = curr;
	}

shutdown:
338 339 340 341

	if (rc != LIBSSH2_ERROR_NONE)
		ssh_error(session, "error authenticating");

342 343 344 345 346 347
	libssh2_agent_disconnect(agent);
	libssh2_agent_free(agent);

	return rc;
}

348
static int _git_ssh_authenticate_session(
349 350
	LIBSSH2_SESSION *session,
	git_credential *cred)
351 352
{
	int rc;
353

354
	do {
355
		git_error_clear();
356
		switch (cred->credtype) {
357 358
		case GIT_CREDENTIAL_USERPASS_PLAINTEXT: {
			git_credential_userpass_plaintext *c = (git_credential_userpass_plaintext *)cred;
359
			rc = libssh2_userauth_password(session, c->username, c->password);
360 361
			break;
		}
362 363
		case GIT_CREDENTIAL_SSH_KEY: {
			git_credential_ssh_key *c = (git_credential_ssh_key *)cred;
364 365 366 367 368 369 370 371

			if (c->privatekey)
				rc = libssh2_userauth_publickey_fromfile(
					session, c->username, c->publickey,
					c->privatekey, c->passphrase);
			else
				rc = ssh_agent_auth(session, c);

372 373
			break;
		}
374 375
		case GIT_CREDENTIAL_SSH_CUSTOM: {
			git_credential_ssh_custom *c = (git_credential_ssh_custom *)cred;
376

377
			rc = libssh2_userauth_publickey(
378
				session, c->username, (const unsigned char *)c->publickey,
379
				c->publickey_len, c->sign_callback, &c->payload);
380 381
			break;
		}
382
		case GIT_CREDENTIAL_SSH_INTERACTIVE: {
383
			void **abstract = libssh2_session_abstract(session);
384
			git_credential_ssh_interactive *c = (git_credential_ssh_interactive *)cred;
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

			/* ideally, we should be able to set this by calling
			 * libssh2_session_init_ex() instead of libssh2_session_init().
			 * libssh2's API is inconsistent here i.e. libssh2_userauth_publickey()
			 * allows you to pass the `abstract` as part of the call, whereas
			 * libssh2_userauth_keyboard_interactive() does not!
			 *
			 * The only way to set the `abstract` pointer is by calling
			 * libssh2_session_abstract(), which will replace the existing
			 * pointer as is done below. This is safe for now (at time of writing),
			 * but may not be valid in future.
			 */
			*abstract = c->payload;

			rc = libssh2_userauth_keyboard_interactive(
				session, c->username, c->prompt_callback);
			break;
		}
403
#ifdef GIT_SSH_MEMORY_CREDENTIALS
404 405
		case GIT_CREDENTIAL_SSH_MEMORY: {
			git_credential_ssh_key *c = (git_credential_ssh_key *)cred;
406

407 408
			GIT_ASSERT(c->username);
			GIT_ASSERT(c->privatekey);
409

410 411 412 413 414
			rc = libssh2_userauth_publickey_frommemory(
				session,
				c->username,
				strlen(c->username),
				c->publickey,
415
				c->publickey ? strlen(c->publickey) : 0,
416 417 418 419 420 421
				c->privatekey,
				strlen(c->privatekey),
				c->passphrase);
			break;
		}
#endif
422 423
		default:
			rc = LIBSSH2_ERROR_AUTHENTICATION_FAILED;
424
		}
Etienne Samson committed
425
	} while (LIBSSH2_ERROR_EAGAIN == rc || LIBSSH2_ERROR_TIMEOUT == rc);
426

427 428 429 430
	if (rc == LIBSSH2_ERROR_PASSWORD_EXPIRED ||
		rc == LIBSSH2_ERROR_AUTHENTICATION_FAILED ||
		rc == LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED)
			return GIT_EAUTH;
431

432
	if (rc != LIBSSH2_ERROR_NONE) {
433
		if (!git_error_last())
434
			ssh_error(session, "Failed to authenticate SSH session");
435 436 437 438
		return -1;
	}

	return 0;
439 440
}

441
static int request_creds(git_credential **out, ssh_subtransport *t, const char *user, int auth_methods)
442 443
{
	int error, no_callback = 0;
444
	git_credential *cred = NULL;
445 446 447 448 449 450 451

	if (!t->owner->cred_acquire_cb) {
		no_callback = 1;
	} else {
		error = t->owner->cred_acquire_cb(&cred, t->owner->url, user, auth_methods,
						  t->owner->cred_acquire_payload);

452
		if (error == GIT_PASSTHROUGH) {
453
			no_callback = 1;
454
		} else if (error < 0) {
455
			return error;
456
		} else if (!cred) {
457
			git_error_set(GIT_ERROR_SSH, "callback failed to initialize SSH credentials");
458 459 460 461 462
			return -1;
		}
	}

	if (no_callback) {
463
		git_error_set(GIT_ERROR_SSH, "authentication required but no callback set");
464
		return GIT_EAUTH;
465 466
	}

467 468
	if (!(cred->credtype & auth_methods)) {
		cred->free(cred);
469 470
		git_error_set(GIT_ERROR_SSH, "authentication callback returned unsupported credentials type");
		return GIT_EAUTH;
471 472
	}

473 474 475 476 477
	*out = cred;

	return 0;
}

Etienne Samson committed
478
static int _git_ssh_session_create(
479
	LIBSSH2_SESSION **session,
480
	git_stream *io)
Brad Morgan committed
481
{
482
	int rc = 0;
483
	LIBSSH2_SESSION *s;
484
	git_socket_stream *socket = GIT_CONTAINER_OF(io, git_socket_stream, parent);
485

486
	GIT_ASSERT_ARG(session);
487 488 489

	s = libssh2_session_init();
	if (!s) {
490
		git_error_set(GIT_ERROR_NET, "failed to initialize SSH session");
Etienne Samson committed
491
		return -1;
492
	}
493

Etienne Samson committed
494
	do {
495
		rc = libssh2_session_handshake(s, socket->s);
Etienne Samson committed
496
	} while (LIBSSH2_ERROR_EAGAIN == rc || LIBSSH2_ERROR_TIMEOUT == rc);
497

498
	if (rc != LIBSSH2_ERROR_NONE) {
499
		ssh_error(s, "failed to start SSH session");
500 501
		libssh2_session_free(s);
		return -1;
502
	}
503

Brad Morgan committed
504
	libssh2_session_set_blocking(s, 1);
505

Brad Morgan committed
506
	*session = s;
507

Brad Morgan committed
508 509 510
	return 0;
}

511 512
#define SSH_DEFAULT_PORT "22"

Brad Morgan committed
513
static int _git_ssh_setup_conn(
Brad Morgan committed
514 515
	ssh_subtransport *t,
	const char *url,
Brad Morgan committed
516
	const char *cmd,
517
	git_smart_subtransport_stream **stream)
Brad Morgan committed
518
{
519
	git_net_url urldata = GIT_NET_URL_INIT;
520
	int auth_methods, error = 0;
521
	size_t i;
Brad Morgan committed
522
	ssh_stream *s;
523
	git_credential *cred = NULL;
524 525
	LIBSSH2_SESSION *session=NULL;
	LIBSSH2_CHANNEL *channel=NULL;
526

527 528
	t->current_stream = NULL;

Brad Morgan committed
529
	*stream = NULL;
Brad Morgan committed
530
	if (ssh_stream_alloc(t, url, cmd, stream) < 0)
Brad Morgan committed
531
		return -1;
532

Brad Morgan committed
533
	s = (ssh_stream *)*stream;
534 535
	s->session = NULL;
	s->channel = NULL;
536

537
	for (i = 0; i < ARRAY_SIZE(ssh_prefixes); ++i) {
538 539 540
		const char *p = ssh_prefixes[i];

		if (!git__prefixcmp(url, p)) {
541
			if ((error = git_net_url_parse(&urldata, url)) < 0)
542 543 544 545
				goto done;

			goto post_extract;
		}
546
	}
547
	if ((error = git_ssh_extract_url_parts(&urldata, url)) < 0)
548
		goto done;
549 550 551 552 553

	if (urldata.port == NULL)
		urldata.port = git__strdup(SSH_DEFAULT_PORT);

	GIT_ERROR_CHECK_ALLOC(urldata.port);
554

555
post_extract:
556
	if ((error = git_socket_stream_new(&s->io, urldata.host, urldata.port)) < 0 ||
557
	    (error = git_stream_connect(s->io)) < 0)
558
		goto done;
559

560
	if ((error = _git_ssh_session_create(&session, s->io)) < 0)
561
		goto done;
562 563

	if (t->owner->certificate_check_cb != NULL) {
564
		git_cert_hostkey cert = {{ 0 }}, *cert_ptr;
565
		const char *key;
566 567
		size_t cert_len;
		int cert_type;
568

569
		cert.parent.cert_type = GIT_CERT_HOSTKEY_LIBSSH2;
570

571 572 573 574 575 576 577 578 579 580 581 582
		key = libssh2_session_hostkey(session, &cert_len, &cert_type);
		if (key != NULL) {
			cert.type |= GIT_CERT_SSH_RAW;
			cert.hostkey = key;
			cert.hostkey_len = cert_len;
			switch (cert_type) {
				case LIBSSH2_HOSTKEY_TYPE_RSA:
					cert.raw_type = GIT_CERT_SSH_RAW_TYPE_RSA;
					break;
				case LIBSSH2_HOSTKEY_TYPE_DSS:
					cert.raw_type = GIT_CERT_SSH_RAW_TYPE_DSS;
					break;
583 584
					
#ifdef LIBSSH2_HOSTKEY_TYPE_ECDSA_256
585 586 587 588 589 590 591 592 593
				case LIBSSH2_HOSTKEY_TYPE_ECDSA_256:
					cert.raw_type = GIT_CERT_SSH_RAW_TYPE_KEY_ECDSA_256;
					break;
				case LIBSSH2_HOSTKEY_TYPE_ECDSA_384:
					cert.raw_type = GIT_CERT_SSH_RAW_TYPE_KEY_ECDSA_384;
					break;
				case LIBSSH2_KNOWNHOST_KEY_ECDSA_521:
					cert.raw_type = GIT_CERT_SSH_RAW_TYPE_KEY_ECDSA_521;
					break;
594 595 596
#endif
					
#ifdef LIBSSH2_HOSTKEY_TYPE_ED25519
597 598 599
				case LIBSSH2_HOSTKEY_TYPE_ED25519:
					cert.raw_type = GIT_CERT_SSH_RAW_TYPE_KEY_ED25519;
					break;
600
#endif
601 602 603 604 605
				default:
					cert.raw_type = GIT_CERT_SSH_RAW_TYPE_UNKNOWN;
			}
		}

606 607 608 609 610 611 612 613
#ifdef LIBSSH2_HOSTKEY_HASH_SHA256
		key = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA256);
		if (key != NULL) {
			cert.type |= GIT_CERT_SSH_SHA256;
			memcpy(&cert.hash_sha256, key, 32);
		}
#endif

614 615
		key = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
		if (key != NULL) {
616 617
			cert.type |= GIT_CERT_SSH_SHA1;
			memcpy(&cert.hash_sha1, key, 20);
618 619
		}

620 621 622 623 624 625 626
		key = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5);
		if (key != NULL) {
			cert.type |= GIT_CERT_SSH_MD5;
			memcpy(&cert.hash_md5, key, 16);
		}

		if (cert.type == 0) {
627
			git_error_set(GIT_ERROR_SSH, "unable to get the host key");
628 629
			error = -1;
			goto done;
630 631 632
		}

		/* We don't currently trust any hostkeys */
633
		git_error_clear();
634 635 636

		cert_ptr = &cert;

637
		error = t->owner->certificate_check_cb((git_cert *) cert_ptr, 0, urldata.host, t->owner->message_cb_payload);
638 639

		if (error < 0 && error != GIT_PASSTHROUGH) {
640 641
			if (!git_error_last())
				git_error_set(GIT_ERROR_NET, "user cancelled hostkey check");
642

643
			goto done;
644
		}
645
	}
646

647
	/* we need the username to ask for auth methods */
648
	if (!urldata.username) {
649
		if ((error = request_creds(&cred, t, NULL, GIT_CREDENTIAL_USERNAME)) < 0)
650
			goto done;
651

652
		urldata.username = git__strdup(((git_credential_username *) cred)->username);
653 654
		cred->free(cred);
		cred = NULL;
655
		if (!urldata.username)
656
			goto done;
657
	} else if (urldata.username && urldata.password) {
658
		if ((error = git_credential_userpass_plaintext_new(&cred, urldata.username, urldata.password)) < 0)
659
			goto done;
660 661
	}

662
	if ((error = list_auth_methods(&auth_methods, session, urldata.username)) < 0)
663
		goto done;
664

665 666
	error = GIT_EAUTH;
	/* if we already have something to try */
667
	if (cred && auth_methods & cred->credtype)
668
		error = _git_ssh_authenticate_session(session, cred);
669

670 671 672 673 674 675
	while (error == GIT_EAUTH) {
		if (cred) {
			cred->free(cred);
			cred = NULL;
		}

676
		if ((error = request_creds(&cred, t, urldata.username, auth_methods)) < 0)
677
			goto done;
678

679
		if (strcmp(urldata.username, git_credential_get_username(cred))) {
680
			git_error_set(GIT_ERROR_SSH, "username does not match previous request");
681
			error = -1;
682
			goto done;
683 684
		}

685
		error = _git_ssh_authenticate_session(session, cred);
686 687 688

		if (error == GIT_EAUTH) {
			/* refresh auth methods */
kas committed
689
			if ((error = list_auth_methods(&auth_methods, session, urldata.username)) < 0)
690
				goto done;
kas committed
691 692
			else
				error = GIT_EAUTH;
693
		}
694
	}
695

696
	if (error < 0)
697
		goto done;
698

Brad Morgan committed
699
	channel = libssh2_channel_open_session(session);
700
	if (!channel) {
701
		error = -1;
702
		ssh_error(session, "Failed to open SSH channel");
703
		goto done;
704
	}
705

Brad Morgan committed
706
	libssh2_channel_set_blocking(channel, 1);
707

Brad Morgan committed
708 709
	s->session = session;
	s->channel = channel;
710

Brad Morgan committed
711
	t->current_stream = s;
712

713 714
done:
	if (error < 0) {
715
		ssh_stream_free(*stream);
716

717 718 719
		if (session)
			libssh2_session_free(session);
	}
720

721 722 723
	if (cred)
		cred->free(cred);

724
	git_net_url_dispose(&urldata);
Brad Morgan committed
725

726
	return error;
Brad Morgan committed
727 728
}

Brad Morgan committed
729
static int ssh_uploadpack_ls(
Brad Morgan committed
730 731 732 733
	ssh_subtransport *t,
	const char *url,
	git_smart_subtransport_stream **stream)
{
734 735
	const char *cmd = t->cmd_uploadpack ? t->cmd_uploadpack : cmd_uploadpack;

736
	return _git_ssh_setup_conn(t, url, cmd, stream);
Brad Morgan committed
737 738
}

Brad Morgan committed
739
static int ssh_uploadpack(
Brad Morgan committed
740 741 742 743 744
	ssh_subtransport *t,
	const char *url,
	git_smart_subtransport_stream **stream)
{
	GIT_UNUSED(url);
745

Brad Morgan committed
746 747 748 749
	if (t->current_stream) {
		*stream = &t->current_stream->parent;
		return 0;
	}
750

751
	git_error_set(GIT_ERROR_NET, "must call UPLOADPACK_LS before UPLOADPACK");
Brad Morgan committed
752 753 754
	return -1;
}

Brad Morgan committed
755
static int ssh_receivepack_ls(
Brad Morgan committed
756 757 758 759
	ssh_subtransport *t,
	const char *url,
	git_smart_subtransport_stream **stream)
{
760 761
	const char *cmd = t->cmd_receivepack ? t->cmd_receivepack : cmd_receivepack;

762

763
	return _git_ssh_setup_conn(t, url, cmd, stream);
Brad Morgan committed
764 765
}

Brad Morgan committed
766
static int ssh_receivepack(
Brad Morgan committed
767 768 769
	ssh_subtransport *t,
	const char *url,
	git_smart_subtransport_stream **stream)
Brad Morgan committed
770 771
{
	GIT_UNUSED(url);
772

Brad Morgan committed
773 774 775 776
	if (t->current_stream) {
		*stream = &t->current_stream->parent;
		return 0;
	}
777

778
	git_error_set(GIT_ERROR_NET, "must call RECEIVEPACK_LS before RECEIVEPACK");
Brad Morgan committed
779 780 781
	return -1;
}

Brad Morgan committed
782
static int _ssh_action(
Brad Morgan committed
783 784 785 786
	git_smart_subtransport_stream **stream,
	git_smart_subtransport *subtransport,
	const char *url,
	git_smart_service_t action)
Brad Morgan committed
787
{
788
	ssh_subtransport *t = GIT_CONTAINER_OF(subtransport, ssh_subtransport, parent);
789

Brad Morgan committed
790 791
	switch (action) {
		case GIT_SERVICE_UPLOADPACK_LS:
Brad Morgan committed
792
			return ssh_uploadpack_ls(t, url, stream);
793

Brad Morgan committed
794
		case GIT_SERVICE_UPLOADPACK:
Brad Morgan committed
795
			return ssh_uploadpack(t, url, stream);
796

Brad Morgan committed
797
		case GIT_SERVICE_RECEIVEPACK_LS:
Brad Morgan committed
798
			return ssh_receivepack_ls(t, url, stream);
799

Brad Morgan committed
800
		case GIT_SERVICE_RECEIVEPACK:
Brad Morgan committed
801
			return ssh_receivepack(t, url, stream);
Brad Morgan committed
802
	}
803

Brad Morgan committed
804 805 806 807
	*stream = NULL;
	return -1;
}

Brad Morgan committed
808
static int _ssh_close(git_smart_subtransport *subtransport)
Brad Morgan committed
809
{
810
	ssh_subtransport *t = GIT_CONTAINER_OF(subtransport, ssh_subtransport, parent);
811

812
	GIT_ASSERT(!t->current_stream);
813

Brad Morgan committed
814
	GIT_UNUSED(t);
815

Brad Morgan committed
816 817 818
	return 0;
}

Brad Morgan committed
819
static void _ssh_free(git_smart_subtransport *subtransport)
Brad Morgan committed
820
{
821
	ssh_subtransport *t = GIT_CONTAINER_OF(subtransport, ssh_subtransport, parent);
822

823 824
	git__free(t->cmd_uploadpack);
	git__free(t->cmd_receivepack);
Brad Morgan committed
825 826
	git__free(t);
}
827 828 829 830 831

#define SSH_AUTH_PUBLICKEY "publickey"
#define SSH_AUTH_PASSWORD "password"
#define SSH_AUTH_KEYBOARD_INTERACTIVE "keyboard-interactive"

832
static int list_auth_methods(int *out, LIBSSH2_SESSION *session, const char *username)
833 834 835 836 837
{
	const char *list, *ptr;

	*out = 0;

838
	list = libssh2_userauth_list(session, username, strlen(username));
839 840

	/* either error, or the remote accepts NONE auth, which is bizarre, let's punt */
841 842
	if (list == NULL && !libssh2_userauth_authenticated(session)) {
		ssh_error(session, "Failed to retrieve list of SSH authentication methods");
843
		return GIT_EAUTH;
844
	}
845 846 847 848 849 850 851

	ptr = list;
	while (ptr) {
		if (*ptr == ',')
			ptr++;

		if (!git__prefixcmp(ptr, SSH_AUTH_PUBLICKEY)) {
852 853
			*out |= GIT_CREDENTIAL_SSH_KEY;
			*out |= GIT_CREDENTIAL_SSH_CUSTOM;
854
#ifdef GIT_SSH_MEMORY_CREDENTIALS
855
			*out |= GIT_CREDENTIAL_SSH_MEMORY;
856
#endif
857 858 859 860 861
			ptr += strlen(SSH_AUTH_PUBLICKEY);
			continue;
		}

		if (!git__prefixcmp(ptr, SSH_AUTH_PASSWORD)) {
862
			*out |= GIT_CREDENTIAL_USERPASS_PLAINTEXT;
863 864 865 866 867
			ptr += strlen(SSH_AUTH_PASSWORD);
			continue;
		}

		if (!git__prefixcmp(ptr, SSH_AUTH_KEYBOARD_INTERACTIVE)) {
868
			*out |= GIT_CREDENTIAL_SSH_INTERACTIVE;
869 870 871 872 873 874 875 876 877 878
			ptr += strlen(SSH_AUTH_KEYBOARD_INTERACTIVE);
			continue;
		}

		/* Skipt it if we don't know it */
		ptr = strchr(ptr, ',');
	}

	return 0;
}
879
#endif
Brad Morgan committed
880

881
int git_smart_subtransport_ssh(
882
	git_smart_subtransport **out, git_transport *owner, void *param)
Brad Morgan committed
883
{
884
#ifdef GIT_SSH
Brad Morgan committed
885
	ssh_subtransport *t;
886

887
	GIT_ASSERT_ARG(out);
888

889 890
	GIT_UNUSED(param);

Brad Morgan committed
891
	t = git__calloc(sizeof(ssh_subtransport), 1);
892
	GIT_ERROR_CHECK_ALLOC(t);
893

Brad Morgan committed
894
	t->owner = (transport_smart *)owner;
Brad Morgan committed
895 896 897
	t->parent.action = _ssh_action;
	t->parent.close = _ssh_close;
	t->parent.free = _ssh_free;
898

Brad Morgan committed
899 900
	*out = (git_smart_subtransport *) t;
	return 0;
901 902
#else
	GIT_UNUSED(owner);
903
	GIT_UNUSED(param);
904

905
	GIT_ASSERT_ARG(out);
906
	*out = NULL;
907

908
	git_error_set(GIT_ERROR_INVALID, "cannot create SSH transport. Library was built without SSH support");
909
	return -1;
910
#endif
911
}
912 913 914 915 916 917 918 919 920 921 922 923

int git_transport_ssh_with_paths(git_transport **out, git_remote *owner, void *payload)
{
#ifdef GIT_SSH
	git_strarray *paths = (git_strarray *) payload;
	git_transport *transport;
	transport_smart *smart;
	ssh_subtransport *t;
	int error;
	git_smart_subtransport_definition ssh_definition = {
		git_smart_subtransport_ssh,
		0, /* no RPC */
924
		NULL,
925 926 927
	};

	if (paths->count != 2) {
928
		git_error_set(GIT_ERROR_SSH, "invalid ssh paths, must be two strings");
929 930 931 932 933 934 935 936 937 938
		return GIT_EINVALIDSPEC;
	}

	if ((error = git_transport_smart(&transport, owner, &ssh_definition)) < 0)
		return error;

	smart = (transport_smart *) transport;
	t = (ssh_subtransport *) smart->wrapped;

	t->cmd_uploadpack = git__strdup(paths->strings[0]);
939
	GIT_ERROR_CHECK_ALLOC(t->cmd_uploadpack);
940
	t->cmd_receivepack = git__strdup(paths->strings[1]);
941
	GIT_ERROR_CHECK_ALLOC(t->cmd_receivepack);
942 943 944 945 946

	*out = transport;
	return 0;
#else
	GIT_UNUSED(owner);
Vicent Marti committed
947
	GIT_UNUSED(payload);
948

949
	GIT_ASSERT_ARG(out);
950 951
	*out = NULL;

952
	git_error_set(GIT_ERROR_INVALID, "cannot create SSH transport. Library was built without SSH support");
953 954 955
	return -1;
#endif
}
956

957 958 959 960 961 962 963
#ifdef GIT_SSH
static void shutdown_ssh(void)
{
    libssh2_exit();
}
#endif

964 965 966
int git_transport_ssh_global_init(void)
{
#ifdef GIT_SSH
967
	if (libssh2_init(0) < 0) {
968
		git_error_set(GIT_ERROR_SSH, "unable to initialize libssh2");
969 970
		return -1;
	}
971

972
	return git_runtime_shutdown_register(shutdown_ssh);
973 974 975 976 977 978 979 980

#else

	/* Nothing to initialize */
	return 0;

#endif
}