policy: fix: add missing free
[platform/upstream/dbus.git] / bus / policy.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* policy.c  Bus security policy
3  *
4  * Copyright (C) 2003, 2004  Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #include <config.h>
25 #include "check.h"
26 #include "policy.h"
27 #include "services.h"
28 #include "test.h"
29 #include "utils.h"
30 #include "smack.h"
31 #include <dbus/dbus-list.h>
32 #include <dbus/dbus-hash.h>
33 #include <dbus/dbus-internals.h>
34
35 BusPolicyRule*
36 bus_policy_rule_new (BusPolicyRuleType type,
37                      BusPolicyRuleAccess access)
38 {
39   BusPolicyRule *rule;
40
41   rule = dbus_new0 (BusPolicyRule, 1);
42   if (rule == NULL)
43     return NULL;
44
45   rule->type = type;
46   rule->refcount = 1;
47   rule->access = access;
48
49   switch (rule->type)
50     {
51     case BUS_POLICY_RULE_USER:
52       rule->d.user.uid = DBUS_UID_UNSET;
53       break;
54     case BUS_POLICY_RULE_GROUP:
55       rule->d.group.gid = DBUS_GID_UNSET;
56       break;
57     case BUS_POLICY_RULE_SEND:
58       rule->d.send.message_type = DBUS_MESSAGE_TYPE_INVALID;
59       /* allow rules default to TRUE (only requested replies allowed)
60        * check rules default to TRUE (only requested replies are checked)
61        * deny rules default to FALSE (only unrequested replies denied)
62        */
63       rule->d.send.requested_reply = rule->access != BUS_POLICY_RULE_ACCESS_DENY;
64       break;
65     case BUS_POLICY_RULE_RECEIVE:
66       rule->d.receive.message_type = DBUS_MESSAGE_TYPE_INVALID;
67       /* allow rules default to TRUE (only requested replies allowed)
68        * check rules default to TRUE (only requested replies are checked)
69        * deny rules default to FALSE (only unrequested replies denied)
70        */
71       rule->d.receive.requested_reply = rule->access != BUS_POLICY_RULE_ACCESS_DENY;
72       break;
73     case BUS_POLICY_RULE_OWN:
74       break;
75     }
76   
77   return rule;
78 }
79
80 BusPolicyRule *
81 bus_policy_rule_ref (BusPolicyRule *rule)
82 {
83   _dbus_assert (rule->refcount > 0);
84
85   rule->refcount += 1;
86
87   return rule;
88 }
89
90 void
91 bus_policy_rule_unref (BusPolicyRule *rule)
92 {
93   _dbus_assert (rule->refcount > 0);
94
95   rule->refcount -= 1;
96   
97   if (rule->refcount == 0)
98     {
99       switch (rule->type)
100         {
101         case BUS_POLICY_RULE_SEND:
102           dbus_free (rule->d.send.path);
103           dbus_free (rule->d.send.interface);
104           dbus_free (rule->d.send.member);
105           dbus_free (rule->d.send.error);
106           dbus_free (rule->d.send.destination);
107           break;
108         case BUS_POLICY_RULE_RECEIVE:
109           dbus_free (rule->d.receive.path);
110           dbus_free (rule->d.receive.interface);
111           dbus_free (rule->d.receive.member);
112           dbus_free (rule->d.receive.error);
113           dbus_free (rule->d.receive.origin);
114           break;
115         case BUS_POLICY_RULE_OWN:
116           dbus_free (rule->d.own.service_name);
117           break;
118         case BUS_POLICY_RULE_USER:
119           break;
120         case BUS_POLICY_RULE_GROUP:
121           break;
122         }
123
124       dbus_free (rule->privilege);
125       dbus_free (rule);
126     }
127 }
128
129 struct BusPolicy
130 {
131   int refcount;
132
133   DBusList *default_rules;             /**< Default policy rules */
134   DBusList *mandatory_rules;           /**< Mandatory policy rules */
135   DBusHashTable *rules_by_uid;         /**< per-UID policy rules */
136   DBusHashTable *rules_by_gid;         /**< per-GID policy rules */
137   DBusHashTable *rules_by_smack_label; /**< per-SMACK label policy rules */
138   DBusList *at_console_true_rules;     /**< console user policy rules where at_console="true"*/
139   DBusList *at_console_false_rules;    /**< console user policy rules where at_console="false"*/
140 };
141
142 static void
143 free_rule_func (void *data,
144                 void *user_data)
145 {
146   BusPolicyRule *rule = data;
147
148   bus_policy_rule_unref (rule);
149 }
150
151 static void
152 free_rule_list_func (void *data)
153 {
154   DBusList **list = data;
155
156   if (list == NULL) /* DBusHashTable is on crack */
157     return;
158   
159   _dbus_list_foreach (list, free_rule_func, NULL);
160   
161   _dbus_list_clear (list);
162
163   dbus_free (list);
164 }
165
166 BusPolicy*
167 bus_policy_new (void)
168 {
169   BusPolicy *policy;
170
171   policy = dbus_new0 (BusPolicy, 1);
172   if (policy == NULL)
173     return NULL;
174
175   policy->refcount = 1;
176   
177   policy->rules_by_uid = _dbus_hash_table_new (DBUS_HASH_UINTPTR,
178                                                NULL,
179                                                free_rule_list_func);
180   if (policy->rules_by_uid == NULL)
181     goto failed;
182
183   policy->rules_by_gid = _dbus_hash_table_new (DBUS_HASH_UINTPTR,
184                                                NULL,
185                                                free_rule_list_func);
186   if (policy->rules_by_gid == NULL)
187     goto failed;
188
189 #ifdef DBUS_ENABLE_SMACK
190   policy->rules_by_smack_label = _dbus_hash_table_new (DBUS_HASH_STRING,
191                                                        (DBusFreeFunction) dbus_free,
192                                                        free_rule_list_func);
193   if (policy->rules_by_smack_label == NULL)
194     goto failed;
195 #endif
196
197   return policy;
198   
199  failed:
200   bus_policy_unref (policy);
201   return NULL;
202 }
203
204 BusPolicy *
205 bus_policy_ref (BusPolicy *policy)
206 {
207   _dbus_assert (policy->refcount > 0);
208
209   policy->refcount += 1;
210
211   return policy;
212 }
213
214 void
215 bus_policy_unref (BusPolicy *policy)
216 {
217   _dbus_assert (policy->refcount > 0);
218
219   policy->refcount -= 1;
220
221   if (policy->refcount == 0)
222     {
223       _dbus_list_foreach (&policy->default_rules, free_rule_func, NULL);
224       _dbus_list_clear (&policy->default_rules);
225
226       _dbus_list_foreach (&policy->mandatory_rules, free_rule_func, NULL);
227       _dbus_list_clear (&policy->mandatory_rules);
228
229       _dbus_list_foreach (&policy->at_console_true_rules, free_rule_func, NULL);
230       _dbus_list_clear (&policy->at_console_true_rules);
231
232       _dbus_list_foreach (&policy->at_console_false_rules, free_rule_func, NULL);
233       _dbus_list_clear (&policy->at_console_false_rules);
234
235       if (policy->rules_by_uid)
236         {
237           _dbus_hash_table_unref (policy->rules_by_uid);
238           policy->rules_by_uid = NULL;
239         }
240
241       if (policy->rules_by_gid)
242         {
243           _dbus_hash_table_unref (policy->rules_by_gid);
244           policy->rules_by_gid = NULL;
245         }
246
247       if (policy->rules_by_smack_label)
248         {
249           _dbus_hash_table_unref (policy->rules_by_smack_label);
250           policy->rules_by_smack_label = NULL;
251         }
252
253       dbus_free (policy);
254     }
255 }
256
257 static dbus_bool_t
258 add_list_to_client (DBusList        **list,
259                     BusClientPolicy  *client)
260 {
261   DBusList *link;
262
263   link = _dbus_list_get_first_link (list);
264   while (link != NULL)
265     {
266       BusPolicyRule *rule = link->data;
267       link = _dbus_list_get_next_link (list, link);
268
269       switch (rule->type)
270         {
271         case BUS_POLICY_RULE_USER:
272         case BUS_POLICY_RULE_GROUP:
273           /* These aren't per-connection policies */
274           break;
275
276         case BUS_POLICY_RULE_OWN:
277         case BUS_POLICY_RULE_SEND:
278         case BUS_POLICY_RULE_RECEIVE:
279           /* These are per-connection */
280           if (!bus_client_policy_append_rule (client, rule))
281             return FALSE;
282           break;
283         }
284     }
285   
286   return TRUE;
287 }
288
289 BusClientPolicy*
290 bus_policy_create_client_policy (BusPolicy      *policy,
291                                  DBusConnection *connection,
292                                  DBusError      *error)
293 {
294   BusClientPolicy *client;
295   dbus_uid_t uid;
296   dbus_bool_t at_console;
297
298   _dbus_assert (dbus_connection_get_is_authenticated (connection));
299   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
300   
301   client = bus_client_policy_new ();
302   if (client == NULL)
303     goto nomem;
304
305   if (!add_list_to_client (&policy->default_rules,
306                            client))
307     goto nomem;
308
309   /* we avoid the overhead of looking up user's groups
310    * if we don't have any group rules anyway
311    */
312   if (_dbus_hash_table_get_n_entries (policy->rules_by_gid) > 0)
313     {
314       unsigned long *groups;
315       int n_groups;
316       int i;
317       
318       if (!bus_connection_get_unix_groups (connection, &groups, &n_groups, error))
319         goto failed;
320       
321       i = 0;
322       while (i < n_groups)
323         {
324           DBusList **list;
325           
326           list = _dbus_hash_table_lookup_uintptr (policy->rules_by_gid,
327                                                 groups[i]);
328           
329           if (list != NULL)
330             {
331               if (!add_list_to_client (list, client))
332                 {
333                   dbus_free (groups);
334                   goto nomem;
335                 }
336             }
337           
338           ++i;
339         }
340
341       dbus_free (groups);
342     }
343   
344   if (dbus_connection_get_unix_user (connection, &uid))
345     {
346       if (_dbus_hash_table_get_n_entries (policy->rules_by_uid) > 0)
347         {
348           DBusList **list;
349           
350           list = _dbus_hash_table_lookup_uintptr (policy->rules_by_uid,
351                                                 uid);
352           
353           if (list != NULL)
354             {
355               if (!add_list_to_client (list, client))
356                 goto nomem;
357             }
358         }
359
360       /* Add console rules */
361       at_console = _dbus_unix_user_is_at_console (uid, error);
362       
363       if (at_console)
364         {
365           if (!add_list_to_client (&policy->at_console_true_rules, client))
366             goto nomem;
367         }
368       else if (dbus_error_is_set (error) == TRUE)
369         {
370           goto failed;
371         }
372       else if (!add_list_to_client (&policy->at_console_false_rules, client))
373         {
374           goto nomem;
375         }
376     }
377
378   if (policy->rules_by_smack_label &&
379       _dbus_hash_table_get_n_entries (policy->rules_by_smack_label) > 0)
380     {
381       DBusList **list;
382       dbus_bool_t nomem_err = FALSE;
383
384       list = bus_smack_generate_allowed_list(connection, policy->rules_by_smack_label, &nomem_err);
385
386       if (list != NULL)
387         {
388           nomem_err = !add_list_to_client (list, client);
389           _dbus_list_clear (list);
390           dbus_free(list);
391         }
392
393       if (nomem_err)
394         goto nomem;
395     }
396
397   if (!add_list_to_client (&policy->mandatory_rules,
398                            client))
399     goto nomem;
400
401   bus_client_policy_optimize (client);
402   
403   return client;
404
405  nomem:
406   BUS_SET_OOM (error);
407  failed:
408   _DBUS_ASSERT_ERROR_IS_SET (error);
409   if (client)
410     bus_client_policy_unref (client);
411   return NULL;
412 }
413
414 static dbus_bool_t
415 list_allows_user (dbus_bool_t           def,
416                   DBusList            **list,
417                   unsigned long         uid,
418                   const unsigned long  *group_ids,
419                   int                   n_group_ids)
420 {
421   DBusList *link;
422   dbus_bool_t allowed;
423   
424   allowed = def;
425
426   link = _dbus_list_get_first_link (list);
427   while (link != NULL)
428     {
429       BusPolicyRule *rule = link->data;
430       link = _dbus_list_get_next_link (list, link);
431
432       if (rule->type == BUS_POLICY_RULE_USER)
433         {
434           _dbus_verbose ("List %p user rule uid="DBUS_UID_FORMAT"\n",
435                          list, rule->d.user.uid);
436           
437           if (rule->d.user.uid == DBUS_UID_UNSET)
438             ; /* '*' wildcard */
439           else if (rule->d.user.uid != uid)
440             continue;
441         }
442       else if (rule->type == BUS_POLICY_RULE_GROUP)
443         {
444           _dbus_verbose ("List %p group rule gid="DBUS_GID_FORMAT"\n",
445                          list, rule->d.group.gid);
446           
447           if (rule->d.group.gid == DBUS_GID_UNSET)
448             ;  /* '*' wildcard */
449           else
450             {
451               int i;
452               
453               i = 0;
454               while (i < n_group_ids)
455                 {
456                   if (rule->d.group.gid == group_ids[i])
457                     break;
458                   ++i;
459                 }
460               
461               if (i == n_group_ids)
462                 continue;
463             }
464         }
465       else
466         continue;
467
468       /* We don't intend to support <check user="..." /> and <check group="..." />
469          rules. They are treated like deny.
470       */
471       allowed = rule->access == BUS_POLICY_RULE_ACCESS_ALLOW;
472     }
473   
474   return allowed;
475 }
476
477 dbus_bool_t
478 bus_policy_allow_unix_user (BusPolicy        *policy,
479                             unsigned long     uid)
480 {
481   dbus_bool_t allowed;
482   unsigned long *group_ids;
483   int n_group_ids;
484
485   /* On OOM or error we always reject the user */
486   if (!_dbus_unix_groups_from_uid (uid, &group_ids, &n_group_ids))
487     {
488       _dbus_verbose ("Did not get any groups for UID %lu\n",
489                      uid);
490       return FALSE;
491     }
492
493   /* Default to "user owning bus" can connect */
494   allowed = _dbus_unix_user_is_process_owner (uid);
495
496   allowed = list_allows_user (allowed,
497                               &policy->default_rules,
498                               uid,
499                               group_ids, n_group_ids);
500
501   allowed = list_allows_user (allowed,
502                               &policy->mandatory_rules,
503                               uid,
504                               group_ids, n_group_ids);
505
506   dbus_free (group_ids);
507
508   _dbus_verbose ("UID %lu allowed = %d\n", uid, allowed);
509   
510   return allowed;
511 }
512
513 /* For now this is never actually called because the default
514  * DBusConnection behavior of 'same user that owns the bus can
515  * connect' is all it would do. Set the windows user function in
516  * connection.c if the config file ever supports doing something
517  * interesting here.
518  */
519 dbus_bool_t
520 bus_policy_allow_windows_user (BusPolicy        *policy,
521                                const char       *windows_sid)
522 {
523   /* Windows has no policies here since only the session bus
524    * is really used for now, so just checking that the
525    * connecting person is the same as the bus owner is fine.
526    */
527   return _dbus_windows_user_is_process_owner (windows_sid);
528 }
529
530 dbus_bool_t
531 bus_policy_append_default_rule (BusPolicy      *policy,
532                                 BusPolicyRule  *rule)
533 {
534   if (!_dbus_list_append (&policy->default_rules, rule))
535     return FALSE;
536
537   bus_policy_rule_ref (rule);
538
539   return TRUE;
540 }
541
542 dbus_bool_t
543 bus_policy_append_mandatory_rule (BusPolicy      *policy,
544                                   BusPolicyRule  *rule)
545 {
546   if (!_dbus_list_append (&policy->mandatory_rules, rule))
547     return FALSE;
548
549   bus_policy_rule_ref (rule);
550
551   return TRUE;
552 }
553
554
555
556 static DBusList**
557 get_list (DBusHashTable *hash,
558           unsigned long  key)
559 {
560   DBusList **list;
561
562   list = _dbus_hash_table_lookup_uintptr (hash, key);
563
564   if (list == NULL)
565     {
566       list = dbus_new0 (DBusList*, 1);
567       if (list == NULL)
568         return NULL;
569
570       if (!_dbus_hash_table_insert_uintptr (hash, key, list))
571         {
572           dbus_free (list);
573           return NULL;
574         }
575     }
576
577   return list;
578 }
579
580 dbus_bool_t
581 bus_policy_append_user_rule (BusPolicy      *policy,
582                              dbus_uid_t      uid,
583                              BusPolicyRule  *rule)
584 {
585   DBusList **list;
586
587   list = get_list (policy->rules_by_uid, uid);
588
589   if (list == NULL)
590     return FALSE;
591
592   if (!_dbus_list_append (list, rule))
593     return FALSE;
594
595   bus_policy_rule_ref (rule);
596
597   return TRUE;
598 }
599
600 dbus_bool_t
601 bus_policy_append_group_rule (BusPolicy      *policy,
602                               dbus_gid_t      gid,
603                               BusPolicyRule  *rule)
604 {
605   DBusList **list;
606
607   list = get_list (policy->rules_by_gid, gid);
608
609   if (list == NULL)
610     return FALSE;
611
612   if (!_dbus_list_append (list, rule))
613     return FALSE;
614
615   bus_policy_rule_ref (rule);
616
617   return TRUE;
618 }
619
620 #ifdef DBUS_ENABLE_SMACK
621 static DBusList **
622 get_list_string (DBusHashTable *table,
623                  const char *key)
624 {
625   DBusList **list;
626
627   if (key == NULL)
628       return NULL;
629
630   list = _dbus_hash_table_lookup_string (table, key);
631
632   if (list == NULL)
633     {
634       char *new_key;
635
636       list = dbus_new0 (DBusList*, 1);
637       if (list == NULL)
638         return NULL;
639
640       new_key = _dbus_strdup (key);
641       if (new_key == NULL)
642         {
643           dbus_free (list);
644           return NULL;
645         }
646
647       if (!_dbus_hash_table_insert_string (table, new_key, list))
648         {
649           dbus_free (list);
650           dbus_free (new_key);
651           return NULL;
652         }
653     }
654
655   return list;
656 }
657 #endif
658
659 dbus_bool_t
660 bus_policy_append_smack_rule (BusPolicy      *policy,
661                               const char     *label,
662                               BusPolicyRule  *rule)
663 {
664 #ifdef DBUS_ENABLE_SMACK
665   DBusList **list;
666
667   list = get_list_string (policy->rules_by_smack_label, label);
668   if (list == NULL)
669     return FALSE;
670
671   if (!_dbus_list_append (list, rule))
672     return FALSE;
673
674   bus_policy_rule_ref (rule);
675 #endif
676
677   return TRUE;
678 }
679
680 dbus_bool_t
681 bus_policy_append_console_rule (BusPolicy      *policy,
682                                 dbus_bool_t     at_console,
683                                 BusPolicyRule  *rule)
684 {
685   if (at_console)
686     {
687       if (!_dbus_list_append (&policy->at_console_true_rules, rule))
688         return FALSE;
689     }
690     else
691     {
692       if (!_dbus_list_append (&policy->at_console_false_rules, rule))
693         return FALSE;
694     }
695
696   bus_policy_rule_ref (rule);
697
698   return TRUE;
699
700 }
701
702 static dbus_bool_t
703 append_copy_of_policy_list (DBusList **list,
704                             DBusList **to_append)
705 {
706   DBusList *link;
707   DBusList *tmp_list;
708
709   tmp_list = NULL;
710
711   /* Preallocate all our links */
712   link = _dbus_list_get_first_link (to_append);
713   while (link != NULL)
714     {
715       if (!_dbus_list_append (&tmp_list, link->data))
716         {
717           _dbus_list_clear (&tmp_list);
718           return FALSE;
719         }
720       
721       link = _dbus_list_get_next_link (to_append, link);
722     }
723
724   /* Now append them */
725   while ((link = _dbus_list_pop_first_link (&tmp_list)))
726     {
727       bus_policy_rule_ref (link->data);
728       _dbus_list_append_link (list, link);
729     }
730
731   return TRUE;
732 }
733
734 static dbus_bool_t
735 merge_id_hash (DBusHashTable *dest,
736                DBusHashTable *to_absorb)
737 {
738   DBusHashIter iter;
739   
740   _dbus_hash_iter_init (to_absorb, &iter);
741   while (_dbus_hash_iter_next (&iter))
742     {
743       unsigned long id = _dbus_hash_iter_get_uintptr_key (&iter);
744       DBusList **list = _dbus_hash_iter_get_value (&iter);
745       DBusList **target = get_list (dest, id);
746
747       if (target == NULL)
748         return FALSE;
749
750       if (!append_copy_of_policy_list (target, list))
751         return FALSE;
752     }
753
754   return TRUE;
755 }
756
757 #ifdef DBUS_ENABLE_SMACK
758 static dbus_bool_t
759 merge_string_hash (DBusHashTable *dest,
760                    DBusHashTable *to_absorb)
761 {
762   DBusHashIter iter;
763
764   _dbus_hash_iter_init (to_absorb, &iter);
765   while (_dbus_hash_iter_next (&iter))
766     {
767       const char *absorb_label = _dbus_hash_iter_get_string_key(&iter);
768       DBusList **list = _dbus_hash_iter_get_value (&iter);
769       DBusList **target = get_list_string (dest, absorb_label);
770
771       if (target == NULL)
772         return FALSE;
773
774       if (!append_copy_of_policy_list (target, list))
775         return FALSE;
776     }
777
778   return TRUE;
779 }
780 #endif
781
782 dbus_bool_t
783 bus_policy_merge (BusPolicy *policy,
784                   BusPolicy *to_absorb)
785 {
786   /* FIXME Not properly atomic, but as used for configuration files we
787    * don't rely on it quite so much.
788    */
789   
790   if (!append_copy_of_policy_list (&policy->default_rules,
791                                    &to_absorb->default_rules))
792     return FALSE;
793   
794   if (!append_copy_of_policy_list (&policy->mandatory_rules,
795                                    &to_absorb->mandatory_rules))
796     return FALSE;
797
798   if (!append_copy_of_policy_list (&policy->at_console_true_rules,
799                                    &to_absorb->at_console_true_rules))
800     return FALSE;
801
802   if (!append_copy_of_policy_list (&policy->at_console_false_rules,
803                                    &to_absorb->at_console_false_rules))
804     return FALSE;
805
806   if (!merge_id_hash (policy->rules_by_uid,
807                       to_absorb->rules_by_uid))
808     return FALSE;
809   
810   if (!merge_id_hash (policy->rules_by_gid,
811                       to_absorb->rules_by_gid))
812     return FALSE;
813
814 #ifdef DBUS_ENABLE_SMACK
815   if (!merge_string_hash (policy->rules_by_smack_label,
816                           to_absorb->rules_by_smack_label))
817     return FALSE;
818 #endif
819
820   return TRUE;
821 }
822
823 struct BusClientPolicy
824 {
825   int refcount;
826
827   DBusList *rules;
828 };
829
830 BusClientPolicy*
831 bus_client_policy_new (void)
832 {
833   BusClientPolicy *policy;
834
835   policy = dbus_new0 (BusClientPolicy, 1);
836   if (policy == NULL)
837     return NULL;
838
839   policy->refcount = 1;
840
841   return policy;
842 }
843
844 BusClientPolicy *
845 bus_client_policy_ref (BusClientPolicy *policy)
846 {
847   _dbus_assert (policy->refcount > 0);
848
849   policy->refcount += 1;
850
851   return policy;
852 }
853
854 static void
855 rule_unref_foreach (void *data,
856                     void *user_data)
857 {
858   BusPolicyRule *rule = data;
859
860   bus_policy_rule_unref (rule);
861 }
862
863 void
864 bus_client_policy_unref (BusClientPolicy *policy)
865 {
866   _dbus_assert (policy->refcount > 0);
867
868   policy->refcount -= 1;
869
870   if (policy->refcount == 0)
871     {
872       _dbus_list_foreach (&policy->rules,
873                           rule_unref_foreach,
874                           NULL);
875
876       _dbus_list_clear (&policy->rules);
877
878       dbus_free (policy);
879     }
880 }
881
882 static void
883 remove_rules_by_type_up_to (BusClientPolicy   *policy,
884                             BusPolicyRuleType  type,
885                             DBusList          *up_to)
886 {
887   DBusList *link;
888
889   link = _dbus_list_get_first_link (&policy->rules);
890   while (link != up_to)
891     {
892       BusPolicyRule *rule = link->data;
893       DBusList *next = _dbus_list_get_next_link (&policy->rules, link);
894
895       if (rule->type == type)
896         {
897           _dbus_list_remove_link (&policy->rules, link);
898           bus_policy_rule_unref (rule);
899         }
900       
901       link = next;
902     }
903 }
904
905 void
906 bus_client_policy_optimize (BusClientPolicy *policy)
907 {
908   DBusList *link;
909
910   /* The idea here is that if we have:
911    * 
912    * <allow send_interface="foo.bar"/>
913    * <deny send_interface="*"/>
914    *
915    * (for example) the deny will always override the allow.  So we
916    * delete the allow. Ditto for deny followed by allow, etc. This is
917    * a dumb thing to put in a config file, but the <include> feature
918    * of files allows for an "inheritance and override" pattern where
919    * it could make sense. If an included file wants to "start over"
920    * with a blanket deny, no point keeping the rules from the parent
921    * file.
922    */
923
924   _dbus_verbose ("Optimizing policy with %d rules\n",
925                  _dbus_list_get_length (&policy->rules));
926   
927   link = _dbus_list_get_first_link (&policy->rules);
928   while (link != NULL)
929     {
930       BusPolicyRule *rule;
931       DBusList *next;
932       dbus_bool_t remove_preceding;
933
934       next = _dbus_list_get_next_link (&policy->rules, link);
935       rule = link->data;
936       
937       remove_preceding = FALSE;
938
939       _dbus_assert (rule != NULL);
940       
941       switch (rule->type)
942         {
943         case BUS_POLICY_RULE_SEND:
944           remove_preceding =
945             rule->d.send.message_type == DBUS_MESSAGE_TYPE_INVALID &&
946             rule->d.send.path == NULL &&
947             rule->d.send.interface == NULL &&
948             rule->d.send.member == NULL &&
949             rule->d.send.error == NULL &&
950             rule->d.send.destination == NULL;
951           break;
952         case BUS_POLICY_RULE_RECEIVE:
953           remove_preceding =
954             rule->d.receive.message_type == DBUS_MESSAGE_TYPE_INVALID &&
955             rule->d.receive.path == NULL &&
956             rule->d.receive.interface == NULL &&
957             rule->d.receive.member == NULL &&
958             rule->d.receive.error == NULL &&
959             rule->d.receive.origin == NULL;
960           break;
961         case BUS_POLICY_RULE_OWN:
962           remove_preceding =
963             rule->d.own.service_name == NULL;
964           break;
965         case BUS_POLICY_RULE_USER:
966         case BUS_POLICY_RULE_GROUP:
967           _dbus_assert_not_reached ("invalid rule");
968           break;
969         }
970
971       if (remove_preceding)
972         remove_rules_by_type_up_to (policy, rule->type,
973                                     link);
974       
975       link = next;
976     }
977
978   _dbus_verbose ("After optimization, policy has %d rules\n",
979                  _dbus_list_get_length (&policy->rules));
980 }
981
982 dbus_bool_t
983 bus_client_policy_append_rule (BusClientPolicy *policy,
984                                BusPolicyRule   *rule)
985 {
986   _dbus_verbose ("Appending rule %p with type %d to policy %p\n",
987                  rule, rule->type, policy);
988   
989   if (!_dbus_list_append (&policy->rules, rule))
990     return FALSE;
991
992   bus_policy_rule_ref (rule);
993
994   return TRUE;
995 }
996
997 BusResult
998 bus_client_policy_check_can_send (DBusConnection      *sender,
999                                   BusClientPolicy     *policy,
1000                                   BusRegistry         *registry,
1001                                   dbus_bool_t          requested_reply,
1002                                   DBusConnection      *addressed_recipient,
1003                                   DBusConnection      *receiver,
1004                                   DBusMessage         *message,
1005                                   dbus_int32_t        *toggles,
1006                                   dbus_bool_t         *log,
1007                                   const char         **privilege_param,
1008                                   BusDeferredMessage **deferred_message)
1009 {
1010   DBusList *link;
1011   BusResult result;
1012   const char *privilege;
1013
1014   /* policy->rules is in the order the rules appeared
1015    * in the config file, i.e. last rule that applies wins
1016    */
1017
1018   _dbus_verbose ("  (policy) checking send rules\n");
1019   *toggles = 0;
1020   
1021   result = BUS_RESULT_FALSE;
1022   link = _dbus_list_get_first_link (&policy->rules);
1023   while (link != NULL)
1024     {
1025       BusPolicyRule *rule = link->data;
1026
1027       link = _dbus_list_get_next_link (&policy->rules, link);
1028       
1029       /* Rule is skipped if it specifies a different
1030        * message name from the message, or a different
1031        * destination from the message
1032        */
1033       
1034       if (rule->type != BUS_POLICY_RULE_SEND)
1035         {
1036           _dbus_verbose ("  (policy) skipping non-send rule\n");
1037           continue;
1038         }
1039
1040       if (rule->d.send.message_type != DBUS_MESSAGE_TYPE_INVALID)
1041         {
1042           if (dbus_message_get_type (message) != rule->d.send.message_type)
1043             {
1044               _dbus_verbose ("  (policy) skipping rule for different message type\n");
1045               continue;
1046             }
1047         }
1048
1049       /* If it's a reply, the requested_reply flag kicks in */
1050       if (dbus_message_get_reply_serial (message) != 0)
1051         {
1052           /* for allow or check requested_reply=true means the rule applies
1053            * only when reply was requested. requested_reply=false means the
1054            * rule always applies
1055            */
1056           if (!requested_reply && rule->access != BUS_POLICY_RULE_ACCESS_DENY && rule->d.send.requested_reply && !rule->d.send.eavesdrop)
1057             {
1058               _dbus_verbose ("  (policy) skipping %s rule since it only applies to requested replies and does not allow eavesdropping\n",
1059                   rule->access == BUS_POLICY_RULE_ACCESS_ALLOW ? "allow" : "check");
1060               continue;
1061             }
1062
1063           /* for deny, requested_reply=false means the rule applies only
1064            * when the reply was not requested. requested_reply=true means the
1065            * rule always applies.
1066            */
1067           if (requested_reply && rule->access == BUS_POLICY_RULE_ACCESS_DENY && !rule->d.send.requested_reply)
1068             {
1069               _dbus_verbose ("  (policy) skipping deny rule since it only applies to unrequested replies\n");
1070               continue;
1071             }
1072         }
1073       
1074       if (rule->d.send.path != NULL)
1075         {
1076           if (dbus_message_get_path (message) != NULL &&
1077               strcmp (dbus_message_get_path (message),
1078                       rule->d.send.path) != 0)
1079             {
1080               _dbus_verbose ("  (policy) skipping rule for different path\n");
1081               continue;
1082             }
1083         }
1084       
1085       if (rule->d.send.interface != NULL)
1086         {
1087           /* The interface is optional in messages. For allow rules, if the message
1088            * has no interface we want to skip the rule (and thus not allow);
1089            * for deny rules, if the message has no interface we want to use the
1090            * rule (and thus deny). Check rules are meant to be used like allow
1091            * rules (they can grant access, but not remove it), so we treat it like
1092            * allow here.
1093            */
1094           dbus_bool_t no_interface;
1095
1096           no_interface = dbus_message_get_interface (message) == NULL;
1097           
1098           if ((no_interface && rule->access != BUS_POLICY_RULE_ACCESS_DENY) ||
1099               (!no_interface && 
1100                strcmp (dbus_message_get_interface (message),
1101                        rule->d.send.interface) != 0))
1102             {
1103               _dbus_verbose ("  (policy) skipping rule for different interface\n");
1104               continue;
1105             }
1106         }
1107
1108       if (rule->d.send.member != NULL)
1109         {
1110           if (dbus_message_get_member (message) != NULL &&
1111               strcmp (dbus_message_get_member (message),
1112                       rule->d.send.member) != 0)
1113             {
1114               _dbus_verbose ("  (policy) skipping rule for different member\n");
1115               continue;
1116             }
1117         }
1118
1119       if (rule->d.send.error != NULL)
1120         {
1121           if (dbus_message_get_error_name (message) != NULL &&
1122               strcmp (dbus_message_get_error_name (message),
1123                       rule->d.send.error) != 0)
1124             {
1125               _dbus_verbose ("  (policy) skipping rule for different error name\n");
1126               continue;
1127             }
1128         }
1129       
1130       if (rule->d.send.destination != NULL)
1131         {
1132           /* receiver can be NULL for messages that are sent to the
1133            * message bus itself, we check the strings in that case as
1134            * built-in services don't have a DBusConnection but messages
1135            * to them have a destination service name.
1136            */
1137           if (receiver == NULL)
1138             {
1139               if (!dbus_message_has_destination (message,
1140                                                  rule->d.send.destination))
1141                 {
1142                   _dbus_verbose ("  (policy) skipping rule because message dest is not %s\n",
1143                                  rule->d.send.destination);
1144                   continue;
1145                 }
1146             }
1147           else
1148             {
1149               DBusString str;
1150               BusService *service;
1151               
1152               _dbus_string_init_const (&str, rule->d.send.destination);
1153               
1154               service = bus_registry_lookup (registry, &str);
1155               if (service == NULL)
1156                 {
1157                   _dbus_verbose ("  (policy) skipping rule because dest %s doesn't exist\n",
1158                                  rule->d.send.destination);
1159                   continue;
1160                 }
1161
1162               if (!bus_service_has_owner (service, receiver))
1163                 {
1164                   _dbus_verbose ("  (policy) skipping rule because dest %s isn't owned by receiver\n",
1165                                  rule->d.send.destination);
1166                   continue;
1167                 }
1168             }
1169         }
1170
1171       /* Use this rule */
1172       switch (rule->access)
1173         {
1174         case BUS_POLICY_RULE_ACCESS_ALLOW:
1175           result = BUS_RESULT_TRUE;
1176           break;
1177         case BUS_POLICY_RULE_ACCESS_DENY:
1178           result = BUS_RESULT_FALSE;
1179           break;
1180         case BUS_POLICY_RULE_ACCESS_CHECK:
1181           result = BUS_RESULT_LATER;
1182           privilege = rule->privilege;
1183           break;
1184         }
1185
1186       *log = rule->d.send.log;
1187       (*toggles)++;
1188
1189       _dbus_verbose ("  (policy) used rule, result now = %d\n",
1190                      result);
1191     }
1192
1193   if (result == BUS_RESULT_LATER)
1194     {
1195       BusContext *context = bus_connection_get_context(sender);
1196       BusCheck *check = bus_context_get_check(context);
1197
1198       result = bus_check_privilege(check, message, sender, addressed_recipient, receiver,
1199           privilege, BUS_DEFERRED_MESSAGE_CHECK_SEND, deferred_message);
1200       if (result == BUS_RESULT_LATER && deferred_message != NULL)
1201         bus_deferred_message_set_policy_check_info(*deferred_message, requested_reply,
1202             *toggles, privilege);
1203     }
1204   else
1205     privilege = NULL;
1206
1207   if (privilege_param != NULL)
1208     *privilege_param = privilege;
1209
1210   return result;
1211 }
1212
1213 /* See docs on what the args mean on bus_context_check_security_policy()
1214  * comment
1215  */
1216 BusResult
1217 bus_client_policy_check_can_receive (BusClientPolicy     *policy,
1218                                      BusRegistry         *registry,
1219                                      dbus_bool_t          requested_reply,
1220                                      DBusConnection      *sender,
1221                                      DBusConnection      *addressed_recipient,
1222                                      DBusConnection      *proposed_recipient,
1223                                      DBusMessage         *message,
1224                                      dbus_int32_t        *toggles,
1225                                      const char         **privilege_param,
1226                                      BusDeferredMessage **deferred_message)
1227 {
1228   DBusList *link;
1229   dbus_bool_t eavesdropping;
1230   BusResult result;
1231   const char *privilege;
1232
1233   eavesdropping =
1234     addressed_recipient != proposed_recipient &&
1235     dbus_message_get_destination (message) != NULL;
1236   
1237   /* policy->rules is in the order the rules appeared
1238    * in the config file, i.e. last rule that applies wins
1239    */
1240
1241   _dbus_verbose ("  (policy) checking receive rules, eavesdropping = %d\n", eavesdropping);
1242   *toggles = 0;
1243   
1244   result = BUS_RESULT_FALSE;
1245   link = _dbus_list_get_first_link (&policy->rules);
1246   while (link != NULL)
1247     {
1248       BusPolicyRule *rule = link->data;
1249
1250       link = _dbus_list_get_next_link (&policy->rules, link);      
1251       
1252       if (rule->type != BUS_POLICY_RULE_RECEIVE)
1253         {
1254           _dbus_verbose ("  (policy) skipping non-receive rule\n");
1255           continue;
1256         }
1257
1258       if (rule->d.receive.message_type != DBUS_MESSAGE_TYPE_INVALID)
1259         {
1260           if (dbus_message_get_type (message) != rule->d.receive.message_type)
1261             {
1262               _dbus_verbose ("  (policy) skipping rule for different message type\n");
1263               continue;
1264             }
1265         }
1266
1267
1268       /* for allow or check, eavesdrop=false means the rule doesn't apply when
1269        * eavesdropping. eavesdrop=true means the rule always applies
1270        */
1271       if (eavesdropping && rule->access != BUS_POLICY_RULE_ACCESS_DENY && !rule->d.receive.eavesdrop)
1272         {
1273           _dbus_verbose ("  (policy) skipping %s rule since it doesn't apply to eavesdropping\n",
1274               rule->access == BUS_POLICY_RULE_ACCESS_ALLOW ? "allow" : "check");
1275           continue;
1276         }
1277
1278       /* for deny, eavesdrop=true means the rule applies only when
1279        * eavesdropping; eavesdrop=false means always deny.
1280        */
1281       if (!eavesdropping && rule->access == BUS_POLICY_RULE_ACCESS_DENY && rule->d.receive.eavesdrop)
1282         {
1283           _dbus_verbose ("  (policy) skipping deny rule since it only applies to eavesdropping\n");
1284           continue;
1285         }
1286
1287       /* If it's a reply, the requested_reply flag kicks in */
1288       if (dbus_message_get_reply_serial (message) != 0)
1289         {
1290           /* for allow or check requested_reply=true means the rule applies
1291            * only when reply was requested. requested_reply=false means the
1292            * rule always applies
1293            */
1294           if (!requested_reply && rule->access != BUS_POLICY_RULE_ACCESS_DENY && rule->d.send.requested_reply && !rule->d.send.eavesdrop)
1295             {
1296               _dbus_verbose ("  (policy) skipping %s rule since it only applies to requested replies and does not allow eavesdropping\n",
1297                   rule->access == BUS_POLICY_RULE_ACCESS_DENY ? "allow" : "deny");
1298               continue;
1299             }
1300
1301           /* for deny, requested_reply=false means the rule applies only
1302            * when the reply was not requested. requested_reply=true means the
1303            * rule always applies.
1304            */
1305           if (requested_reply && rule->access == BUS_POLICY_RULE_ACCESS_DENY && !rule->d.receive.requested_reply)
1306             {
1307               _dbus_verbose ("  (policy) skipping deny rule since it only applies to unrequested replies\n");
1308               continue;
1309             }
1310         }
1311       
1312       if (rule->d.receive.path != NULL)
1313         {
1314           if (dbus_message_get_path (message) != NULL &&
1315               strcmp (dbus_message_get_path (message),
1316                       rule->d.receive.path) != 0)
1317             {
1318               _dbus_verbose ("  (policy) skipping rule for different path\n");
1319               continue;
1320             }
1321         }
1322       
1323       if (rule->d.receive.interface != NULL)
1324         {
1325           /* The interface is optional in messages. For allow rules, if the message
1326            * has no interface we want to skip the rule (and thus not allow);
1327            * for deny rules, if the message has no interface we want to use the
1328            * rule (and thus deny). Check rules are treated like allow rules.
1329            */
1330           dbus_bool_t no_interface;
1331
1332           no_interface = dbus_message_get_interface (message) == NULL;
1333           
1334           if ((no_interface && rule->access != BUS_POLICY_RULE_ACCESS_DENY) ||
1335               (!no_interface &&
1336                strcmp (dbus_message_get_interface (message),
1337                        rule->d.receive.interface) != 0))
1338             {
1339               _dbus_verbose ("  (policy) skipping rule for different interface\n");
1340               continue;
1341             }
1342         }      
1343
1344       if (rule->d.receive.member != NULL)
1345         {
1346           if (dbus_message_get_member (message) != NULL &&
1347               strcmp (dbus_message_get_member (message),
1348                       rule->d.receive.member) != 0)
1349             {
1350               _dbus_verbose ("  (policy) skipping rule for different member\n");
1351               continue;
1352             }
1353         }
1354
1355       if (rule->d.receive.error != NULL)
1356         {
1357           if (dbus_message_get_error_name (message) != NULL &&
1358               strcmp (dbus_message_get_error_name (message),
1359                       rule->d.receive.error) != 0)
1360             {
1361               _dbus_verbose ("  (policy) skipping rule for different error name\n");
1362               continue;
1363             }
1364         }
1365       
1366       if (rule->d.receive.origin != NULL)
1367         {          
1368           /* sender can be NULL for messages that originate from the
1369            * message bus itself, we check the strings in that case as
1370            * built-in services don't have a DBusConnection but will
1371            * still set the sender on their messages.
1372            */
1373           if (sender == NULL)
1374             {
1375               if (!dbus_message_has_sender (message,
1376                                             rule->d.receive.origin))
1377                 {
1378                   _dbus_verbose ("  (policy) skipping rule because message sender is not %s\n",
1379                                  rule->d.receive.origin);
1380                   continue;
1381                 }
1382             }
1383           else
1384             {
1385               BusService *service;
1386               DBusString str;
1387
1388               _dbus_string_init_const (&str, rule->d.receive.origin);
1389               
1390               service = bus_registry_lookup (registry, &str);
1391               
1392               if (service == NULL)
1393                 {
1394                   _dbus_verbose ("  (policy) skipping rule because origin %s doesn't exist\n",
1395                                  rule->d.receive.origin);
1396                   continue;
1397                 }
1398
1399               if (!bus_service_has_owner (service, sender))
1400                 {
1401                   _dbus_verbose ("  (policy) skipping rule because origin %s isn't owned by sender\n",
1402                                  rule->d.receive.origin);
1403                   continue;
1404                 }
1405             }
1406         }
1407       
1408       /* Use this rule */
1409       switch (rule->access)
1410       {
1411         case BUS_POLICY_RULE_ACCESS_ALLOW:
1412           result = BUS_RESULT_TRUE;
1413           break;
1414         case BUS_POLICY_RULE_ACCESS_DENY:
1415           result = BUS_RESULT_FALSE;
1416           break;
1417         case BUS_POLICY_RULE_ACCESS_CHECK:
1418           result = BUS_RESULT_LATER;
1419           privilege = rule->privilege;
1420           break;
1421       }
1422
1423       (*toggles)++;
1424
1425       _dbus_verbose ("  (policy) used rule, result now = %d\n",
1426                      result);
1427     }
1428
1429
1430   if (result == BUS_RESULT_LATER)
1431     {
1432       BusContext *context = bus_connection_get_context(proposed_recipient);
1433       BusCheck *check = bus_context_get_check(context);
1434
1435       result = bus_check_privilege(check, message, sender, addressed_recipient, proposed_recipient,
1436                  privilege, BUS_DEFERRED_MESSAGE_CHECK_RECEIVE, deferred_message);
1437       if (result == BUS_RESULT_LATER && deferred_message != NULL)
1438         bus_deferred_message_set_policy_check_info(*deferred_message, requested_reply,
1439                     *toggles, privilege);
1440     }
1441   else
1442       privilege = NULL;
1443
1444   if (privilege_param != NULL)
1445      *privilege_param = privilege;
1446
1447   return result;
1448 }
1449
1450
1451
1452 static BusResult
1453 bus_rules_check_can_own (DBusList *rules,
1454                          const DBusString *service_name,
1455                          DBusConnection   *connection,
1456                          DBusMessage      *message)
1457 {
1458   DBusList *link;
1459   BusResult result;
1460   const char *privilege;
1461   
1462   /* rules is in the order the rules appeared
1463    * in the config file, i.e. last rule that applies wins
1464    */
1465
1466   result = BUS_RESULT_FALSE;
1467   link = _dbus_list_get_first_link (&rules);
1468   while (link != NULL)
1469     {
1470       BusPolicyRule *rule = link->data;
1471
1472       link = _dbus_list_get_next_link (&rules, link);
1473       
1474       /* Rule is skipped if it specifies a different service name from
1475        * the desired one.
1476        */
1477       
1478       if (rule->type != BUS_POLICY_RULE_OWN)
1479         continue;
1480
1481       if (!rule->d.own.prefix && rule->d.own.service_name != NULL)
1482         {
1483           if (!_dbus_string_equal_c_str (service_name,
1484                                          rule->d.own.service_name))
1485             continue;
1486         }
1487       else if (rule->d.own.prefix)
1488         {
1489           const char *data;
1490           char next_char;
1491           if (!_dbus_string_starts_with_c_str (service_name,
1492                                                rule->d.own.service_name))
1493             continue;
1494
1495           data = _dbus_string_get_const_data (service_name);
1496           next_char = data[strlen (rule->d.own.service_name)];
1497           if (next_char != '\0' && next_char != '.')
1498             continue;
1499         }
1500
1501       /* Use this rule */
1502       switch (rule->access)
1503       {
1504       case BUS_POLICY_RULE_ACCESS_ALLOW:
1505         result = BUS_RESULT_TRUE;
1506         break;
1507       case BUS_POLICY_RULE_ACCESS_DENY:
1508         result = BUS_RESULT_FALSE;
1509         break;
1510       case BUS_POLICY_RULE_ACCESS_CHECK:
1511         result = BUS_RESULT_LATER;
1512         privilege = rule->privilege;
1513         break;
1514       }
1515     }
1516
1517   if (result == BUS_RESULT_LATER)
1518     {
1519       BusContext *context = bus_connection_get_context(connection);
1520       BusCheck *check = bus_context_get_check(context);
1521       BusDeferredMessage *deferred_message;
1522
1523       result = bus_check_privilege(check, message, connection, NULL, NULL,
1524           privilege, BUS_DEFERRED_MESSAGE_CHECK_OWN, &deferred_message);
1525       if (result == BUS_RESULT_LATER)
1526         {
1527           bus_deferred_message_disable_sender(deferred_message);
1528         }
1529     }
1530
1531   return result;
1532 }
1533
1534 BusResult
1535 bus_client_policy_check_can_own (BusClientPolicy  *policy,
1536                                  const DBusString *service_name,
1537                                  DBusConnection   *connection,
1538                                  DBusMessage      *message)
1539 {
1540   return bus_rules_check_can_own (policy->rules, service_name, connection, message);
1541 }
1542
1543 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1544 dbus_bool_t
1545 bus_policy_check_can_own (BusPolicy  *policy,
1546                           const DBusString *service_name)
1547 {
1548   return bus_rules_check_can_own (policy->default_rules, service_name, NULL, NULL);
1549 }
1550 #endif /* DBUS_ENABLE_EMBEDDED_TESTS */
1551