gcr-ssh-askpass.c 12.6 KB
Newer Older
Stef Walter's avatar
Stef Walter committed
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
/*
 * Copyright (C) 2014 Stefan Walter
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 * Auther: Stef Walter <stefw@gnome.org>
 */

#include "config.h"

#include "gcr-ssh-askpass.h"

#include <glib-unix.h>
#include <glib/gi18n.h>
#include <glib/gstdio.h>

#include <sys/socket.h>
#include <sys/un.h>

#include <errno.h>
#include <unistd.h>

Niels De Graef's avatar
Niels De Graef committed
34
35
#define GCR_SSH_ASKPASS_BIN "gcr4-ssh-askpass"

Stef Walter's avatar
Stef Walter committed
36
/* Used from tests to override location */
Niels De Graef's avatar
Niels De Graef committed
37
const char *gcr_ssh_askpass_executable = LIBEXECDIR "/" GCR_SSH_ASKPASS_BIN;
Stef Walter's avatar
Stef Walter committed
38
39

/**
40
 * GcrSshAskpass:
Stef Walter's avatar
Stef Walter committed
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
 *
 * When used as the setup function while spawning an ssh command like ssh-add
 * or ssh, this allows callbacks for passwords on the provided interaction.
 */

enum {
	PROP_0,
	PROP_INTERACTION
};

struct _GcrSshAskpass {
	GObject parent;
	GTlsInteraction *interaction;
	gchar *directory;
	gchar *socket;
	guint source;
	gint fd;
	GCancellable *cancellable;
	GMainContext *context;
};

G_DEFINE_TYPE (GcrSshAskpass, gcr_ssh_askpass, G_TYPE_OBJECT);

static void
gcr_ssh_askpass_init (GcrSshAskpass *self)
{
	self->cancellable = g_cancellable_new ();
	self->context = g_main_context_ref_thread_default ();
}

static void
gcr_ssh_askpass_set_property (GObject *obj,
                              guint prop_id,
                              const GValue *value,
                              GParamSpec *pspec)
{
	GcrSshAskpass *self = GCR_SSH_ASKPASS (obj);

	switch (prop_id) {
	case PROP_INTERACTION:
		self->interaction = g_value_dup_object (value);
		g_return_if_fail (self->interaction != NULL);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
		break;
	}
}

static void
gcr_ssh_askpass_get_property (GObject *obj,
                              guint prop_id,
                              GValue *value,
                              GParamSpec *pspec)
{
	GcrSshAskpass *self = GCR_SSH_ASKPASS (obj);

	switch (prop_id) {
	case PROP_INTERACTION:
		g_value_set_object (value, gcr_ssh_askpass_get_interaction (self));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
		break;
	}
}

static gboolean
write_all (gint fd,
           const guchar *buf,
           gsize len)
{
	guint all = len;
	int res;

	while (len > 0) {
		res = write (fd, buf, len);
		if (res <= 0) {
			if (errno == EAGAIN || errno == EINTR)
				continue;
			if (errno != EPIPE)
				g_warning ("couldn't write %u bytes to client: %s", all,
				           res < 0 ? g_strerror (errno) : "");
			return FALSE;
		} else  {
			len -= res;
			buf += res;
		}
	}
	return TRUE;
}

static GString *
read_all_into_string (gint fd)
{
	GString *input = g_string_new ("");
	gsize len;
	gssize ret;

	for (;;) {
		len = input->len;
		g_string_set_size (input, len + 256);
		ret = read (fd, input->str + len, 256);
		if (ret < 0) {
			if (errno != EINTR && errno != EAGAIN) {
Niels De Graef's avatar
Niels De Graef committed
146
				g_critical ("couldn't read from " GCR_SSH_ASKPASS_BIN ": %s", g_strerror (errno));
Stef Walter's avatar
Stef Walter committed
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
				g_string_free (input, TRUE);
				return NULL;
			}
		} else if (ret == 0) {
			return input;
		} else {
			input->len = len + ret;
			input->str[input->len] = '\0';
		}
	}
}

typedef struct {
	gint fd;
	GTlsInteraction *interaction;
	GCancellable *cancellable;
} AskpassContext;

static gpointer
askpass_thread (gpointer data)
{
	AskpassContext *ctx = data;
	gboolean success = FALSE;
	GTlsPassword *password = NULL;
	GTlsInteractionResult res;
	GError *error = NULL;
	const guchar *value;
	GString *input;
	gsize length;

	input = read_all_into_string (ctx->fd);
	if (!input)
		goto out;

	if (input->len == 0)
		g_string_append (input, _("Enter your OpenSSH passphrase"));

	g_debug ("asking for ssh-askpass password: %s", input->str);

	password = g_tls_password_new (G_TLS_PASSWORD_NONE, input->str);
	res = g_tls_interaction_invoke_ask_password (ctx->interaction, password, ctx->cancellable, &error);

	g_debug ("ask password returned %d", res);

	success = FALSE;
	if (res == G_TLS_INTERACTION_HANDLED) {
		value = g_tls_password_get_value (password, &length);
		if (write_all (ctx->fd, (const guchar *)value, length))
Niels De Graef's avatar
Niels De Graef committed
195
			g_debug ("password written to " GCR_SSH_ASKPASS_BIN);
Stef Walter's avatar
Stef Walter committed
196
		else
Niels De Graef's avatar
Niels De Graef committed
197
			g_message ("failed to write password to " GCR_SSH_ASKPASS_BIN);
Stef Walter's avatar
Stef Walter committed
198
199
200
201
202
203
204
205
206
		success = TRUE;
	} else if (error && !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
		g_warning ("couldn't prompt for password: %s", error->message);
	} else {
		g_debug ("unhandled or cancelled ask password");
	}

out:
	if (!success) {
Niels De Graef's avatar
Niels De Graef committed
207
		g_debug ("writing failure to " GCR_SSH_ASKPASS_BIN);
Stef Walter's avatar
Stef Walter committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
		write_all (ctx->fd, (const guchar *)"\xff", 1);
	}
	if (password)
		g_object_unref (password);
	if (input)
		g_string_free (input, TRUE);
	g_clear_error (&error);

	g_close (ctx->fd, NULL);
	g_object_unref (ctx->interaction);
	g_object_unref (ctx->cancellable);
	g_free (ctx);

	return NULL;
}

static gboolean
askpass_accept (gint fd,
                GIOCondition cond,
                gpointer user_data)
{
	GcrSshAskpass *self = user_data;
	AskpassContext *ctx;
	struct sockaddr_un addr;
	socklen_t addrlen;
	GThread *thread;
	gint new_fd;

	addrlen = sizeof (addr);
	new_fd = accept (fd, (struct sockaddr *) &addr, &addrlen);
	if (new_fd < 0) {
		if (errno != EAGAIN && errno != EINTR)
			g_warning ("couldn't accept new control request: %s", g_strerror (errno));
		return TRUE;
	}

Niels De Graef's avatar
Niels De Graef committed
244
	g_debug ("accepted new connection from " GCR_SSH_ASKPASS_BIN);
Stef Walter's avatar
Stef Walter committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294

	ctx = g_new0 (AskpassContext, 1);
	ctx->fd = new_fd;
	ctx->interaction = g_object_ref (self->interaction);
	ctx->cancellable = g_object_ref (self->cancellable);

	thread = g_thread_new ("ssh-askpass", askpass_thread, ctx);
	g_thread_unref (thread);

	return TRUE;
}

static void
gcr_ssh_askpass_constructed (GObject *obj)
{
	GcrSshAskpass *self = GCR_SSH_ASKPASS (obj);
	struct sockaddr_un addr;

	G_OBJECT_CLASS (gcr_ssh_askpass_parent_class)->constructed (obj);

	self->directory = g_build_filename (g_get_user_runtime_dir (), "ssh-askpass.XXXXXX", NULL);
	if (!g_mkdtemp_full (self->directory, 0700)) {
		g_warning ("couldn't create temporary directory: %s: %s", self->directory, g_strerror (errno));
		return;
	}

	self->socket = g_build_filename (self->directory, "socket", NULL);

	self->fd = socket (AF_UNIX, SOCK_STREAM, 0);
	if (self->fd < 0) {
		g_warning ("couldn't open socket: %s", g_strerror (errno));
		return;
	}

	if (!g_unix_set_fd_nonblocking (self->fd, TRUE, NULL))
		g_return_if_reached ();

	memset (&addr, 0, sizeof (addr));
	addr.sun_family = AF_UNIX;
	g_strlcpy (addr.sun_path, self->socket, sizeof (addr.sun_path));
	if (bind (self->fd, (struct sockaddr*) &addr, sizeof (addr)) < 0) {
		g_warning ("couldn't bind to askpass socket: %s: %s", self->socket, g_strerror (errno));
		return;
	}

	if (listen (self->fd, 128) < 0) {
		g_warning ("couldn't listen on askpass socket: %s: %s", self->socket, g_strerror (errno));
		return;
	}

Niels De Graef's avatar
Niels De Graef committed
295
	g_debug ("listening for " GCR_SSH_ASKPASS_BIN " at: %s", self->socket);
Stef Walter's avatar
Stef Walter committed
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428

	self->source = g_unix_fd_add (self->fd, G_IO_IN, askpass_accept, self);
}

static void
gcr_ssh_askpass_dispose (GObject *obj)
{
	GcrSshAskpass *self = GCR_SSH_ASKPASS (obj);

	g_cancellable_cancel (self->cancellable);

	if (self->source) {
		g_source_remove (self->source);
		self->source = 0;
	}

	if (self->fd >= 0) {
		g_close (self->fd, NULL);
		self->fd = -1;
	}

	if (self->socket) {
		g_unlink (self->socket);
		g_free (self->socket);
		self->socket = NULL;
	}

	if (self->directory) {
		g_rmdir (self->directory);
		g_free (self->directory);
		self->directory = NULL;
	}

	if (self->interaction) {
		g_object_unref (self->interaction);
		self->interaction = NULL;
	}

	G_OBJECT_CLASS (gcr_ssh_askpass_parent_class)->dispose (obj);
}

static void
gcr_ssh_askpass_finalize (GObject *obj)
{
	GcrSshAskpass *self = GCR_SSH_ASKPASS (obj);

	g_object_unref (self->cancellable);
	g_main_context_unref (self->context);

	G_OBJECT_CLASS (gcr_ssh_askpass_parent_class)->finalize (obj);
}

/**
 * gcr_ssh_askpass_new:
 * @interaction: the interaction to use for prompting paswords
 *
 * Create a new GcrSshAskpass object which can be used to spawn an
 * ssh command and prompt for any necessary passwords.
 *
 * Use the gcr_ssh_askpass_child_setup() function as a callback with
 * g_spawn_sync(), g_spawn_async() or g_spawn_async_with_pipes().
 *
 * Returns: (transfer full): A new #GcrSshAskpass object
 */
GcrSshAskpass *
gcr_ssh_askpass_new (GTlsInteraction *interaction)
{
	g_return_val_if_fail (G_IS_TLS_INTERACTION (interaction), NULL);
	return g_object_new (GCR_TYPE_SSH_ASKPASS,
	                     "interaction", interaction,
	                     NULL);
}

/**
 * gcr_ssh_askpass_get_interaction:
 * @self: a #GcrSshAskpass object
 *
 * Get the interaction associated with this object.
 *
 * Returns: (transfer none): the interaction
 */
GTlsInteraction *
gcr_ssh_askpass_get_interaction (GcrSshAskpass *self)
{
	g_return_val_if_fail (GCR_IS_SSH_ASKPASS (self), NULL);
	return self->interaction;
}

/**
 * gcr_ssh_askpass_child_setup:
 * @askpass: a #GcrSshAskpass object
 *
 * Use this function as a callback setup function passed to g_spawn_sync(),
 * g_spawn_async(), g_spawn_async_with_pipes().
 */
void
gcr_ssh_askpass_child_setup (gpointer askpass)
{
	GcrSshAskpass *self = askpass;

	g_setenv ("SSH_ASKPASS", gcr_ssh_askpass_executable, TRUE);

	/* ssh wants DISPLAY set in order to use SSH_ASKPASS */
	if (!g_getenv ("DISPLAY"))
		g_setenv ("DISPLAY", "x", TRUE);

	/* For communicating back with ourselves */
	if (self->socket)
		g_setenv ("GCR_SSH_ASKPASS_SOCKET", self->socket, TRUE);

	/* Close the control terminal */
	setsid ();
}

static void
gcr_ssh_askpass_class_init (GcrSshAskpassClass *klass)
{
	GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

	gobject_class->get_property = gcr_ssh_askpass_get_property;
	gobject_class->set_property = gcr_ssh_askpass_set_property;
	gobject_class->constructed = gcr_ssh_askpass_constructed;
	gobject_class->dispose = gcr_ssh_askpass_dispose;
	gobject_class->finalize = gcr_ssh_askpass_finalize;

	/**
	 * GcrSshAskpass:interaction:
	 *
	 * The interaction used to prompt for passwords.
	 */
	g_object_class_install_property (gobject_class, PROP_INTERACTION,
	           g_param_spec_object ("interaction", "Interaction", "Interaction",
	                                G_TYPE_TLS_INTERACTION,
429
	                                G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
Stef Walter's avatar
Stef Walter committed
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
}

#ifdef GCR_SSH_ASKPASS_TOOL

#include "egg/egg-secure-memory.h"

EGG_SECURE_DEFINE_GLIB_GLOBALS ();
EGG_SECURE_DECLARE ("ssh-askpass");

int
main (int argc,
      char *argv[])
{
	GString *message;
	struct sockaddr_un addr;
	const gchar *path;
	guchar *buf;
	gint count;
	gint i;
	int ret;
	int fd;

	path = g_getenv ("GCR_SSH_ASKPASS_SOCKET");
	if (path == NULL) {
Niels De Graef's avatar
Niels De Graef committed
454
		g_printerr (GCR_SSH_ASKPASS_BIN ": this program is not meant to be run directly");
Stef Walter's avatar
Stef Walter committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
		return 2;
	}

	fd = socket (AF_UNIX, SOCK_STREAM, 0);
	if (fd < 0) {
		g_warning ("couldn't open socket: %s", g_strerror (errno));
		return -1;
	}

	memset (&addr, 0, sizeof (addr));
	addr.sun_family = AF_UNIX;
	g_strlcpy (addr.sun_path, path, sizeof (addr.sun_path));
	if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0) {
		g_warning ("couldn't connect to askpass socket: %s: %s", path, g_strerror (errno));
		return -1;
	}

	message = g_string_new ("");
	if (argc > 1) {
		for (i = 1; i < argc; i++) {
			if (i == 1)
				g_string_append_c (message, ' ');
			g_string_append (message, argv[i]);
		}
	}

	if (!write_all (fd, (const guchar *)message->str, message->len)) {
		g_string_free (message, TRUE);
		return -1;
	}
	g_string_free (message, TRUE);

	if (shutdown (fd, SHUT_WR) < 0) {
		g_warning ("couldn't shutdown socket: %s", g_strerror (errno));
		return -1;
	}

	count = 0;
	buf = egg_secure_alloc (128);

	for (;;) {
		ret = read (fd, buf, 128);
		if (ret < 0) {
			if (errno != EINTR && errno != EAGAIN) {
				if (errno != ECONNRESET) {
					g_critical ("couldn't read from ssh-askpass socket: %s",
					            g_strerror (errno));
				}
				egg_secure_free (buf);
				return -1;
			}
			ret = 0;
		} else if (ret == 0) {
			break;
		} else if (!write_all (1, buf, ret)) {
			egg_secure_free (buf);
			return -1;
		}
		count += ret;
	}

	if (count == 1 && buf[0] == 0xff) {
		egg_secure_free (buf);
		return -1;
	}

	egg_secure_free (buf);
	return 0;
}

#endif /* GCR_SSH_ASKPASS_TOOL */