summaryrefslogtreecommitdiff
path: root/polkit/polkit-context.c
blob: 14953f7f13b313912ecb212092cbff465f84a7ca (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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- */
/***************************************************************************
 *
 * polkit-context.c : context for PolicyKit
 *
 * Copyright (C) 2007 David Zeuthen, <david@fubar.dk>
 *
 * Licensed under the Academic Free License version 2.1
 *
 * This program 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.
 *
 * 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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307	 USA
 *
 **************************************************************************/

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <unistd.h>
#include <errno.h>
#include <sys/inotify.h>

#include <glib.h>
#include "polkit-config.h"
#include "polkit-debug.h"
#include "polkit-context.h"
#include "polkit-policy-cache.h"
#include "polkit-grant-database.h"

/**
 * SECTION:polkit
 * @short_description: Centralized policy management.
 *
 * libpolkit is a C library for centralized policy management.
 **/

/**
 * SECTION:polkit-context
 * @short_description: Context.
 *
 * This class is used to represent the interface to PolicyKit - it is
 * used by Mechanisms that use PolicyKit for making
 * decisions. Typically, it's used as a singleton:
 *
 * <itemizedlist>
 * <listitem>First, the Mechanism need to declare one or more PolicyKit Actions by dropping a <literal>.policy</literal> file into <literal>/usr/share/PolicyKit/policy</literal>. This is described in the PolicyKit specification.</listitem>
 * <listitem>The mechanism starts up and uses polkit_context_new() to create a new context</listitem>
 * <listitem>If the mechanism is a long running daemon, it should use polkit_context_set_config_changed() to register a callback when configuration changes. This is useful if, for example, the mechanism needs to revise decisions based on earlier answers from libpolkit. For example, a daemon that manages permissions on <literal>/dev</literal> may want to add/remove ACL's when configuration changes; for example, the system administrator could have changed the PolicyKit configuration file <literal>/etc/PolicyKit/PolicyKit.conf</literal> such that some user is now privileged to access a specific device.</listitem>
 * <listitem>If polkit_context_set_config_changed() is used, the mechanism must also use polkit_context_set_io_watch_functions() to integrate libpolkit into the mainloop.</listitem>
 * <listitem>The mechanism needs to call polkit_context_init() such that libpolkit can load configuration files and properly initialize.</listitem>
 * <listitem>Whenever the mechanism needs to make a decision whether a caller is allowed to make a perform some action, the mechanism prepares a #PolKitAction and #PolKitCaller object (or #PolKitSession if applicable) and calls polkit_context_can_caller_do_action() (or polkit_context_can_session_do_action() if applicable). The mechanism may use the libpolkit-dbus library (specifically the polkit_caller_new_from_dbus_name() or polkit_caller_new_from_pid() functions) but may opt, for performance reasons, to construct #PolKitCaller (or #PolKitSession if applicable) from it's own cache of information.</listitem>
 * <listitem>The mechanism will get a #PolKitResult object back that describes whether it should carry out the action. This result stems from a number of sources, see the PolicyKit specification document for details.</listitem>
 * <listitem>If the result is #POLKIT_RESULT_YES, the mechanism should carry out the action. If the result is not #POLKIT_RESULT_YES nor #POLKIT_RESULT_UNKNOWN (this would never be returned but is mentioned here for completeness), the mechanism should throw an expcetion to the caller detailing the #PolKitResult as a textual string using polkit_result_to_string_representation(). For example, if the mechanism is using D-Bus it could throw an com.some-mechanism.DeniedByPolicy exception with the #PolKitResult textual representation in the detail field. Then the caller can interpret this exception and then act on it (for example it can attempt to gain that privilege).</listitem>
 * </itemizedlist>
 *
 * For more information about using PolicyKit in mechanisms and
 * callers, refer to the PolicyKit-gnome project which includes a
 * sample application on how to use this in the GNOME desktop.
 **/

/**
 * PolKitContext:
 *
 * Context object for users of PolicyKit.
 **/
struct PolKitContext
{
        int refcount;

        PolKitContextConfigChangedCB config_changed_cb;
        void *config_changed_user_data;

        PolKitContextAddIOWatch      io_add_watch_func;
        PolKitContextRemoveIOWatch   io_remove_watch_func;

        char *policy_dir;

        PolKitPolicyCache *priv_cache;

        PolKitConfig *config;

        polkit_bool_t load_descriptions;

        int inotify_fd;
        int inotify_fd_watch_id;
        int inotify_reload_wd;
};

/**
 * polkit_context_new:
 * 
 * Create a new context
 * 
 * Returns: the object
 **/
PolKitContext *
polkit_context_new (void)
{
        PolKitContext *pk_context;
        pk_context = g_new0 (PolKitContext, 1);
        pk_context->refcount = 1;
        return pk_context;
}
/**
 * polkit_context_init:
 * @pk_context: the context object
 * @error: return location for error
 * 
 * Initializes a new context; loads PolicyKit files from
 * /usr/share/PolicyKit/policy unless the environment variable
 * $POLKIT_POLICY_DIR points to another location.
 *
 * Returns: #FALSE if @error was set, otherwise #TRUE
 **/
polkit_bool_t
polkit_context_init (PolKitContext *pk_context, PolKitError **error)
{
        const char *dirname;

        dirname = getenv ("POLKIT_POLICY_DIR");
        if (dirname != NULL) {
                pk_context->policy_dir = g_strdup (dirname);
        } else {
                pk_context->policy_dir = g_strdup (PACKAGE_DATA_DIR "/PolicyKit/policy");
        }
        _pk_debug ("Using policy files from directory %s", pk_context->policy_dir);

        /* NOTE: we don't populate the cache until it's needed.. */

        /* Load configuration file */
        pk_context->config = polkit_config_new (error);
        if (pk_context->config == NULL) {
                _pk_debug ("failed to load configuration file: %s", strerror (errno));
                /* TODO: set error. TODO: should we error out if the config file is bad?!? Or recover and go without a config file? */
                goto error;
        }

        /* if the client provided watch functions, use inotify to create a watch on /var/lib/PolicyKit/reload */
        if (pk_context->io_add_watch_func != NULL) {
                pk_context->inotify_fd = inotify_init ();
                if (pk_context->inotify_fd < 0) {
                        _pk_debug ("failed to initialize inotify: %s", strerror (errno));
                        /* TODO: set error */
                        goto error;
                }

                pk_context->inotify_reload_wd = inotify_add_watch (pk_context->inotify_fd, 
                                                                   PACKAGE_LOCALSTATE_DIR "/lib/PolicyKit/reload", 
                                                                   IN_MODIFY | IN_CREATE | IN_ATTRIB);
                if (pk_context->inotify_reload_wd < 0) {
                        _pk_debug ("failed to add watch on file '" PACKAGE_LOCALSTATE_DIR "/lib/PolicyKit/reload': %s",
                                   strerror (errno));
                        /* TODO: set error */
                        goto error;
                }

                pk_context->inotify_fd_watch_id = pk_context->io_add_watch_func (pk_context, pk_context->inotify_fd);
                if (pk_context->inotify_fd_watch_id == 0) {
                        _pk_debug ("failed to add io watch");
                        /* TODO: set error */
                        goto error;
                }
        }

        return TRUE;

error:
        if (pk_context != NULL)
                polkit_context_unref (pk_context);

        return FALSE;
}

/**
 * polkit_context_ref:
 * @pk_context: the context object
 * 
 * Increase reference count.
 * 
 * Returns: the object
 **/
PolKitContext *
polkit_context_ref (PolKitContext *pk_context)
{
        g_return_val_if_fail (pk_context != NULL, pk_context);
        pk_context->refcount++;
        return pk_context;
}

/**
 * polkit_context_unref:
 * @pk_context: the context object
 * 
 * Decreases the reference count of the object. If it becomes zero,
 * the object is freed. Before freeing, reference counts on embedded
 * objects are decresed by one.
 **/
void
polkit_context_unref (PolKitContext *pk_context)
{

        g_return_if_fail (pk_context != NULL);
        pk_context->refcount--;
        if (pk_context->refcount > 0) 
                return;

        g_free (pk_context);
}

/**
 * polkit_context_set_config_changed:
 * @pk_context: the context object
 * @cb: the callback to invoke
 * @user_data: user data to pass to the callback
 * 
 * Register the callback function for when configuration changes.
 * Mechanisms should use this callback to e.g. reconfigure all
 * permissions / acl's they have set in response to policy decisions
 * made from information provided by PolicyKit. 
 *
 * Note that this function may be called many times within a short
 * interval due to how file monitoring works if e.g. the user is
 * editing a configuration file (editors typically create back-up
 * files). Mechanisms should use a "cool-off" timer (of, say, one
 * second) to avoid doing many expensive operations (such as
 * reconfiguring all ACL's for all devices) within a very short
 * timeframe.
 *
 * This method must be called before polkit_context_init().
 **/
void
polkit_context_set_config_changed (PolKitContext                *pk_context, 
                                   PolKitContextConfigChangedCB  cb, 
                                   void                         *user_data)
{
        g_return_if_fail (pk_context != NULL);
        pk_context->config_changed_cb = cb;
        pk_context->config_changed_user_data = user_data;
}

/**
 * polkit_context_io_func:
 * @pk_context: the object
 * @fd: the file descriptor passed to the supplied function of type #PolKitContextAddIOWatch.
 * 
 * Method that the application must call when there is data to read
 * from a file descriptor registered with the supplied function of
 * type #PolKitContextAddIOWatch.
 **/
void 
polkit_context_io_func (PolKitContext *pk_context, int fd)
{
        g_return_if_fail (pk_context != NULL);

        _pk_debug ("polkit_context_io_func: data on fd %d", fd);

        if (fd == pk_context->inotify_fd) {
/* size of the event structure, not counting name */
#define EVENT_SIZE  (sizeof (struct inotify_event))
/* reasonable guess as to size of 1024 events */
#define BUF_LEN        (1024 * (EVENT_SIZE + 16))
                char buf[BUF_LEN];
                int len;
                int i = 0;
again:
                len = read (fd, buf, BUF_LEN);
                if (len < 0) {
                        if (errno == EINTR) {
                                goto again;
                        } else {
                                _pk_debug ("read: %s", strerror (errno));
                        }
                } else if (len > 0) {
                        /* BUF_LEN too small? */
                }
                while (i < len) {
                        struct inotify_event *event;
                        event = (struct inotify_event *) &buf[i];
                        _pk_debug ("wd=%d mask=%u cookie=%u len=%u",
                                   event->wd, event->mask, event->cookie, event->len);

                        if (event->wd == pk_context->inotify_reload_wd) {
                                _pk_debug ("config changed!");
                                if (pk_context->config_changed_cb != NULL) {
                                        pk_context->config_changed_cb (pk_context, 
                                                                       pk_context->config_changed_user_data);
                                }
                        }

                        i += EVENT_SIZE + event->len;
                }
        }
}

/**
 * polkit_context_set_io_watch_functions:
 * @pk_context: the context object
 * @io_add_watch_func: the function that the PolicyKit library can invoke to start watching a file descriptor
 * @io_remove_watch_func: the function that the PolicyKit library can invoke to stop watching a file descriptor
 * 
 * Register a functions that PolicyKit can use for watching IO descriptors.
 *
 * This method must be called before polkit_context_init().
 **/
void
polkit_context_set_io_watch_functions (PolKitContext                        *pk_context, 
                                       PolKitContextAddIOWatch               io_add_watch_func,
                                       PolKitContextRemoveIOWatch            io_remove_watch_func)
{
        g_return_if_fail (pk_context != NULL);
        pk_context->io_add_watch_func = io_add_watch_func;
        pk_context->io_remove_watch_func = io_remove_watch_func;
}

/**
 * polkit_context_set_load_descriptions:
 * @pk_context: the context
 * 
 * Set whether policy descriptions should be loaded. By default these
 * are not loaded to keep memory use down. TODO: specify whether they
 * are localized and how.
 *
 * This method must be called before polkit_context_init().
 **/
void
polkit_context_set_load_descriptions  (PolKitContext *pk_context)
{
        g_return_if_fail (pk_context != NULL);
        pk_context->load_descriptions = TRUE;
}

extern PolKitPolicyCache     *_polkit_policy_cache_new       (const char *dirname, polkit_bool_t load_descriptions, PolKitError **error);

/**
 * polkit_context_get_policy_cache:
 * @pk_context: the context
 * 
 * Get the #PolKitPolicyCache object that holds all the defined policies as well as their defaults.
 * 
 * Returns: the #PolKitPolicyCache object. Caller shall not unref it.
 **/
PolKitPolicyCache *
polkit_context_get_policy_cache (PolKitContext *pk_context)
{
        g_return_val_if_fail (pk_context != NULL, NULL);

        if (pk_context->priv_cache == NULL) {
                PolKitError *error;

                _pk_debug ("Populating cache from directory %s", pk_context->policy_dir);

                error = NULL;
                pk_context->priv_cache = _polkit_policy_cache_new (pk_context->policy_dir, 
                                                                   pk_context->load_descriptions, 
                                                                   &error);
                if (pk_context->priv_cache == NULL) {
                        g_warning ("Error loading policy files from %s: %s", 
                                   pk_context->policy_dir, polkit_error_get_error_message (error));
                        polkit_error_free (error);
                } else {
                        polkit_policy_cache_debug (pk_context->priv_cache);
                }
        }

        return pk_context->priv_cache;
}

/**
 * polkit_context_can_session_do_action:
 * @pk_context: the PolicyKit context
 * @action: the type of access to check for
 * @session: the session in question
 *
 * Determine if a given session can do a given action.
 *
 * Returns: A #PolKitResult - can only be one of
 * #POLKIT_RESULT_YES, #POLKIT_RESULT_NO.
 */
PolKitResult
polkit_context_can_session_do_action (PolKitContext   *pk_context,
                                      PolKitAction    *action,
                                      PolKitSession   *session)
{
        PolKitPolicyCache *cache;
        PolKitPolicyFileEntry *pfe;
        PolKitPolicyDefault *policy_default;
        PolKitResult result;

        result = POLKIT_RESULT_NO;
        g_return_val_if_fail (pk_context != NULL, result);

        if (action == NULL || session == NULL)
                goto out;

        /* now validate the incoming objects */
        if (!polkit_action_validate (action))
                goto out;
        if (!polkit_session_validate (session))
                goto out;

        cache = polkit_context_get_policy_cache (pk_context);
        if (cache == NULL)
                goto out;

        _pk_debug ("entering polkit_can_session_do_action()");
        polkit_action_debug (action);
        polkit_session_debug (session);

        pfe = polkit_policy_cache_get_entry (cache, action);
        if (pfe == NULL) {
                char *action_name;
                if (!polkit_action_get_action_id (action, &action_name)) {
                        g_warning ("given action has no name");
                } else {
                        g_warning ("no action with name '%s'", action_name);
                }
                result = POLKIT_RESULT_UNKNOWN;
                goto out;
        }

        polkit_policy_file_entry_debug (pfe);

        /* check if the config file specifies a result */
        result = polkit_config_can_session_do_action (pk_context->config, action, session);
        if (result != POLKIT_RESULT_UNKNOWN)
                goto found;

        /* if no, just use the defaults */
        policy_default = polkit_policy_file_entry_get_default (pfe);
        if (policy_default == NULL) {
                g_warning ("no default policy for action!");
                goto out;
        }
        result = polkit_policy_default_can_session_do_action (policy_default, action, session);

found:
        /* Never return UNKNOWN to user */
        if (result == POLKIT_RESULT_UNKNOWN)
                result = POLKIT_RESULT_NO;

out:
        _pk_debug ("... result was %s", polkit_result_to_string_representation (result));
        return result;
}

/**
 * polkit_context_can_caller_do_action:
 * @pk_context: the PolicyKit context
 * @action: the type of access to check for
 * @caller: the caller in question
 *
 * Determine if a given caller can do a given action.
 *
 * Returns: A #PolKitResult specifying if, and how, the caller can
 * do a specific action
 */
PolKitResult
polkit_context_can_caller_do_action (PolKitContext   *pk_context,
                                     PolKitAction    *action,
                                     PolKitCaller    *caller)
{
        PolKitPolicyCache *cache;
        PolKitPolicyFileEntry *pfe;
        PolKitResult result;
        PolKitPolicyDefault *policy_default;

        result = POLKIT_RESULT_NO;
        g_return_val_if_fail (pk_context != NULL, result);

        if (action == NULL || caller == NULL)
                goto out;

        cache = polkit_context_get_policy_cache (pk_context);
        if (cache == NULL)
                goto out;

        /* now validate the incoming objects */
        if (!polkit_action_validate (action))
                goto out;
        if (!polkit_caller_validate (caller))
                goto out;

        _pk_debug ("entering polkit_can_caller_do_action()");
        polkit_action_debug (action);
        polkit_caller_debug (caller);

        pfe = polkit_policy_cache_get_entry (cache, action);
        if (pfe == NULL) {
                char *action_name;
                if (!polkit_action_get_action_id (action, &action_name)) {
                        g_warning ("given action has no name");
                } else {
                        g_warning ("no action with name '%s'", action_name);
                }
                result = POLKIT_RESULT_UNKNOWN;
                goto out;
        }

        polkit_policy_file_entry_debug (pfe);

        /* first, check if the grant database specifies a result */
        result = _polkit_grantdb_check_can_caller_do_action (pk_context, action, caller);
        if (result != POLKIT_RESULT_UNKNOWN)
                goto found;

        /* second, check if the config file specifies a result */
        result = polkit_config_can_caller_do_action (pk_context->config, action, caller);
        if (result != POLKIT_RESULT_UNKNOWN)
                goto found;

        /* if no, just use the defaults */
        policy_default = polkit_policy_file_entry_get_default (pfe);
        if (policy_default == NULL) {
                g_warning ("no default policy for action!");
                goto out;
        }
        result = polkit_policy_default_can_caller_do_action (policy_default, action, caller);

found:

        /* Never return UNKNOWN to user */
        if (result == POLKIT_RESULT_UNKNOWN)
                result = POLKIT_RESULT_NO;
out:
        _pk_debug ("... result was %s", polkit_result_to_string_representation (result));
        return result;
}