summaryrefslogtreecommitdiff
path: root/daemon/gkr-daemon-io.c
blob: 0716208235c7bcb1d28133f9652b18825b60eb7c (plain)
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
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
146
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
195
196
197
198
199
200
201
202
203
204
205
206
207
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
244
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
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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
/* gnome-keyring-daemon-io.c - handles i/o from the clients

   Copyright (C) 2003 Red Hat, Inc

   Gnome keyring is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.
  
   Gnome keyring 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
   General Public License for more details.
  
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

   Author: Alexander Larsson <alexl@redhat.com>
*/

#include "config.h"

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include "gkr-daemon.h"

#include "common/gkr-async.h"
#include "common/gkr-buffer.h"
#include "common/gkr-cleanup.h"
#include "common/gkr-daemon-util.h"
#include "common/gkr-secure-memory.h"
#include "common/gkr-unix-credentials.h"

#include "keyrings/gkr-keyrings.h"

#include "library/gnome-keyring.h"
#include "library/gnome-keyring-private.h"
#include "library/gnome-keyring-proto.h"

#include "ui/gkr-ask-daemon.h"

#ifndef HAVE_SOCKLEN_T
#define socklen_t int
#endif

typedef enum {
	GNOME_CLIENT_STATE_CREDENTIALS,
	GNOME_CLIENT_STATE_READ_DISPLAYNAME,
	GNOME_CLIENT_STATE_READ_PACKET,
	GNOME_CLIENT_STATE_COLLECT_INFO,
	GNOME_CLIENT_STATE_REQUEST_ACCESS,
	GNOME_CLIENT_STATE_EXECUTE_OP,
	GNOME_CLIENT_STATE_WRITE_REPLY
} GnomeKeyringClientStates;

typedef struct {
	GkrAsyncWorker *worker;
	int sock;

	GnomeKeyringApplicationRef *app_ref;

	GkrBuffer input_buffer;
	GkrBuffer output_buffer;
} GnomeKeyringClient;

static char socket_path[1024] = { 0, };

#if 0
#define debug_print(x) g_print x
#else
#define debug_print(x)
#endif

static gboolean
set_local_creds (int fd, gboolean on)
{
  gboolean retval = TRUE;

#if defined(LOCAL_CREDS) && !defined(HAVE_CMSGCRED)
  int val = on ? 1 : 0;
  if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
    {
      g_warning ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
      retval = FALSE;
    }
#endif

  return retval;
}

static GnomeKeyringApplicationRef*
application_ref_new_from_pid (pid_t pid)
{
	GnomeKeyringApplicationRef *app_ref;

	app_ref = g_new0 (GnomeKeyringApplicationRef, 1);

#if defined(__linux__) || defined(__FreeBSD__)
	g_assert (pid > 0);
	{
		char *buffer;
		int len;
		char *path = NULL;
		
#if defined(__linux__)
		path = g_strdup_printf ("/proc/%d/exe", (gint)pid);
#elif defined(__FreeBSD__)
		path = g_strdup_printf ("/proc/%d/file", (gint)pid);
#endif
		buffer = g_file_read_link (path, NULL);
		g_free (path);

		len = (buffer != NULL) ? strlen (buffer) : 0;
		if (len > 0) {
			app_ref->pathname = g_malloc (len + 1);
			memcpy (app_ref->pathname, buffer, len);
			app_ref->pathname[len] = 0;
		}
		g_free (buffer);
	}
#endif

	return app_ref;
}

static gboolean
yield_and_read_all (int fd, guchar *buf, int len)
{
	int all = len;
	int res;
	
	while (len > 0) {
		
		/* Is this worker stopping? */
		if (gkr_async_is_stopping ())
			return FALSE;
			
		/* Don't block other threads during the read */
		gkr_async_begin_concurrent ();
		
			res = read (fd, buf, len);
			
		gkr_async_end_concurrent ();
		
		if (res <= 0) {
			if (errno == EAGAIN && errno == EINTR)
				continue;

			g_warning ("couldn't read %u bytes from client: %s", all, 
			           res < 0 ? g_strerror (errno) : "");
			return FALSE;
		} else  {
			len -= res;
			buf += res;
		}
	}
	
	return TRUE;
}

static gboolean
yield_and_write_all (int fd, const guchar *buf, int len)
{
	int all = len;
	int res;
	
	while (len > 0) {
		
		/* Is this worker stopping? */
		if (gkr_async_is_stopping ())
			return FALSE;
			
		/* Don't block other threads during the read */
		gkr_async_begin_concurrent ();

			res = write (fd, buf, len);
			
		gkr_async_end_concurrent ();
		
		if (res <= 0) {
			if (errno == EAGAIN && errno == EINTR)
				continue;

			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 gboolean
read_packet_with_size (GnomeKeyringClient *client)
{
	int fd;
	guint32 packet_size;

	fd = client->sock;
	
	gkr_buffer_resize (&client->input_buffer, 4);
	if (!yield_and_read_all (fd, client->input_buffer.buf, 4))
		return FALSE;

	if (!gkr_proto_decode_packet_size (&client->input_buffer, &packet_size) ||
	    packet_size < 4) {
	    	g_warning ("invalid packet size from client");
		return FALSE;
	}

	gkr_buffer_resize (&client->input_buffer, packet_size + 4);
	if (!yield_and_read_all (fd, client->input_buffer.buf + 4, packet_size - 4))
		return FALSE;

	return TRUE;
}

static gboolean
yield_and_read_credentials (int sock, pid_t *pid, uid_t *uid)
{
	gboolean ret;
	
	gkr_async_begin_concurrent ();
	
		ret = gkr_unix_credentials_read (sock, pid, uid) >= 0;
		
	gkr_async_end_concurrent ();
	
	return ret;
}

static void
close_fd (gpointer data)
{
	int *fd = (int*)data;
	g_assert (fd);

	/* If we're waiting anywhere this makes the thread stop */
	shutdown (*fd, SHUT_RDWR);
}

static gpointer
client_worker_main (gpointer user_data)
{
	GnomeKeyringClient *client = (GnomeKeyringClient*)user_data;
	GnomeKeyringOpCode op;
	GkrKeyringRequest req;
	pid_t pid;
	uid_t uid;
	char *str;

	/* This helps any reads wakeup when this worker is stopping */
	gkr_async_register_cancel (close_fd, &client->sock);
	
	/* 1. First we read and verify the client's user credentials */	
	debug_print (("GNOME_CLIENT_STATE_CREDENTIALS %p\n", client));
	if (!yield_and_read_credentials (client->sock, &pid, &uid))
		return NULL;
	if (getuid() != uid) {
		g_warning ("uid mismatch: %u, should be %u\n", (guint)uid, (guint)getuid());
		return NULL;
	}
	client->app_ref = application_ref_new_from_pid (pid);


	/* 2. Read the connecting application display name */
	debug_print (("GNOME_CLIENT_STATE_READ_DISPLAYNAME %p\n", client));
	if (!read_packet_with_size (client))
		return NULL;
	debug_print (("read packet\n"));
	if (!gkr_proto_get_utf8_string (&client->input_buffer, 4, NULL, &str))
		return NULL;
	if (!str)
		return NULL;
	debug_print (("got name: %s\n", str));
	client->app_ref->display_name = str;


	/* 3. Now read the actual packet of the operation */	
	debug_print (("GNOME_CLIENT_STATE_READ_PACKET %p\n", client));
	if (!read_packet_with_size (client))
		return NULL;
	debug_print (("read packet, size: %d\n", client->input_buffer.len));


	/* 4. Next decode the operation, and execute the operation */	
	debug_print (("GNOME_CLIENT_STATE_EXECUTE_OP %p\n", client));
	if (!gkr_proto_decode_packet_operation (&client->input_buffer, &op))
		return NULL;
	if (op < 0 || op >= GNOME_KEYRING_NUM_OPS)
		return NULL;
	g_assert (keyring_ops[op]);

	/* Make sure keyrings in memory are up to date before doing anything */
	gkr_keyrings_update ();

	gkr_buffer_init_full (&client->output_buffer, 128, (GkrBufferAllocator)g_realloc);
	
	/* Add empty size */
	gkr_buffer_add_uint32 (&client->output_buffer, 0);
		
	memset (&req, 0, sizeof (req));
	req.app_ref = client->app_ref;
		
	if (!(keyring_ops[op])(&client->input_buffer, &client->output_buffer, &req))
		return NULL;
		
	if (!gkr_buffer_set_uint32 (&client->output_buffer, 0,
	                            client->output_buffer.len))
		return NULL;


	/* 5. Write the reply back out */
	debug_print (("GNOME_CLIENT_STATE_WRITE_REPLY %p\n", client));
	debug_print (("writing %d bytes\n", client->output_buffer.len));
	if (!yield_and_write_all (client->sock, client->output_buffer.buf,
                                  client->output_buffer.len))
		return NULL;

	/* All done */
	return NULL;
}

static void
client_worker_done (GkrAsyncWorker *worker, gpointer result, gpointer user_data)
{
	GnomeKeyringClient *client = (GnomeKeyringClient*)user_data;

	gkr_buffer_uninit (&client->input_buffer);
	gkr_buffer_uninit (&client->output_buffer);

	if (client->app_ref != NULL) {
		gnome_keyring_application_ref_free (client->app_ref);
	}

	shutdown (client->sock, SHUT_RDWR);
	close (client->sock);
	g_free (client);
}

static void
client_new (int fd)
{
	GnomeKeyringClient *client;

	debug_print (("client_new(fd:%d) -> %p\n", fd, client));
	
	client = g_new0 (GnomeKeyringClient, 1);
	client->sock = fd;
	
	/* 
	 * We really have no idea what operation the client will send, 
	 * so we err on the side of caution and use secure memory in case
	 * passwords or secrets are involved.
	 */  
	gkr_buffer_init_full (&client->input_buffer, 128, gkr_secure_realloc);

	client->worker = gkr_async_worker_start (client_worker_main, 
	                                         client_worker_done, client);
	g_assert (client->worker);
	
	/* 
	 * The worker thread is tracked in a global list, and is guaranteed to 
	 * be cleaned up, either when it exits, or when the application closes.
	 */
}

static gboolean
accept_client (GIOChannel *channel, GIOCondition cond,
               gpointer callback_data)
{
	int fd;
	int new_fd;
	struct sockaddr_un addr;
	socklen_t addrlen;
  
	fd = g_io_channel_unix_get_fd (channel);
	
	addrlen = sizeof (addr);
	new_fd = accept(fd, (struct sockaddr *) &addr, &addrlen);
	
	if (new_fd >= 0) 
		client_new (new_fd);
	return TRUE;
}

static void
cleanup_socket_dir (gpointer data)
{
	if(*socket_path)
		unlink (socket_path);
}

const gchar*
gkr_daemon_io_get_socket_path (void)
{
	return socket_path[0] ? socket_path : NULL;
}

gboolean
gkr_daemon_io_create_master_socket (void)
{
	const gchar *tmp_dir;
	int sock;
	struct sockaddr_un addr;
	GIOChannel *channel;

	tmp_dir = gkr_daemon_util_get_master_directory ();
	g_return_val_if_fail (tmp_dir, FALSE);
		
	snprintf (socket_path, sizeof (socket_path), "%s/socket", tmp_dir);
	
#ifdef WITH_TESTS
	if (g_getenv ("GNOME_KEYRING_TEST_PATH"))
		unlink (socket_path);
#endif

	gkr_cleanup_register (cleanup_socket_dir, NULL);
	
	sock = socket(AF_UNIX, SOCK_STREAM, 0);
	if (sock < 0) {
		perror("socket");
		return FALSE;
	}
	memset(&addr, 0, sizeof(addr));
	addr.sun_family = AF_UNIX;
	strncpy (addr.sun_path, socket_path, sizeof (addr.sun_path));
	if (bind (sock, (struct sockaddr *) & addr, sizeof (addr)) < 0) {
		perror ("bind");
		return FALSE;
	}
	
	if (listen (sock, 128) < 0) {
		perror ("listen");
		return FALSE;
	}

        if (!set_local_creds (sock, TRUE)) {
		close (sock);
		return FALSE;
	}

	channel = g_io_channel_unix_new (sock);
	g_io_add_watch (channel, G_IO_IN | G_IO_HUP, accept_client, NULL);
	g_io_channel_unref (channel);
	
	gkr_daemon_util_push_environment ("GNOME_KEYRING_SOCKET", socket_path);
	return TRUE;
}