1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* bus.c  message bus context object
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 "bus.h"
26 
27 #include <stdio.h>
28 #include <stdlib.h>
29 
30 #include "activation.h"
31 #include "connection.h"
32 #include "services.h"
33 #include "utils.h"
34 #include "policy.h"
35 #include "config-parser.h"
36 #include "signals.h"
37 #include "selinux.h"
38 #include "apparmor.h"
39 #include "audit.h"
40 #include "dir-watch.h"
41 #include <dbus/dbus-auth.h>
42 #include <dbus/dbus-list.h>
43 #include <dbus/dbus-hash.h>
44 #include <dbus/dbus-credentials.h>
45 #include <dbus/dbus-internals.h>
46 #include <dbus/dbus-server-protected.h>
47 
48 #ifdef DBUS_CYGWIN
49 #include <signal.h>
50 #endif
51 
52 struct BusContext
53 {
54   int refcount;
55   DBusGUID uuid;
56   char *config_file;
57   char *type;
58   char *servicehelper;
59   char *address;
60   char *pidfile;
61   char *user;
62   char *log_prefix;
63   DBusLoop *loop;
64   DBusList *servers;
65   BusConnections *connections;
66   BusActivation *activation;
67   BusRegistry *registry;
68   BusPolicy *policy;
69   BusMatchmaker *matchmaker;
70   BusLimits limits;
71   DBusRLimit *initial_fd_limit;
72   unsigned int fork : 1;
73   unsigned int syslog : 1;
74   unsigned int keep_umask : 1;
75   unsigned int allow_anonymous : 1;
76   unsigned int systemd_activation : 1;
77   dbus_bool_t watches_enabled;
78 };
79 
80 static dbus_int32_t server_data_slot = -1;
81 
82 typedef struct
83 {
84   BusContext *context;
85 } BusServerData;
86 
87 #define BUS_SERVER_DATA(server) (dbus_server_get_data ((server), server_data_slot))
88 
89 static BusContext*
server_get_context(DBusServer * server)90 server_get_context (DBusServer *server)
91 {
92   BusContext *context;
93   BusServerData *bd;
94 
95   /* this data slot was allocated by the BusContext */
96   _dbus_assert (server_data_slot >= 0);
97 
98   bd = BUS_SERVER_DATA (server);
99 
100   /* every DBusServer in the dbus-daemon has gone through setup_server() */
101   _dbus_assert (bd != NULL);
102 
103   context = bd->context;
104 
105   return context;
106 }
107 
108 static dbus_bool_t
add_server_watch(DBusWatch * watch,void * data)109 add_server_watch (DBusWatch  *watch,
110                   void       *data)
111 {
112   DBusServer *server = data;
113   BusContext *context;
114 
115   context = server_get_context (server);
116 
117   return _dbus_loop_add_watch (context->loop, watch);
118 }
119 
120 static void
remove_server_watch(DBusWatch * watch,void * data)121 remove_server_watch (DBusWatch  *watch,
122                      void       *data)
123 {
124   DBusServer *server = data;
125   BusContext *context;
126 
127   context = server_get_context (server);
128 
129   _dbus_loop_remove_watch (context->loop, watch);
130 }
131 
132 static void
toggle_server_watch(DBusWatch * watch,void * data)133 toggle_server_watch (DBusWatch  *watch,
134                      void       *data)
135 {
136   DBusServer *server = data;
137   BusContext *context;
138 
139   context = server_get_context (server);
140 
141   _dbus_loop_toggle_watch (context->loop, watch);
142 }
143 
144 static dbus_bool_t
add_server_timeout(DBusTimeout * timeout,void * data)145 add_server_timeout (DBusTimeout *timeout,
146                     void        *data)
147 {
148   DBusServer *server = data;
149   BusContext *context;
150 
151   context = server_get_context (server);
152 
153   return _dbus_loop_add_timeout (context->loop, timeout);
154 }
155 
156 static void
remove_server_timeout(DBusTimeout * timeout,void * data)157 remove_server_timeout (DBusTimeout *timeout,
158                        void        *data)
159 {
160   DBusServer *server = data;
161   BusContext *context;
162 
163   context = server_get_context (server);
164 
165   _dbus_loop_remove_timeout (context->loop, timeout);
166 }
167 
168 static void
new_connection_callback(DBusServer * server,DBusConnection * new_connection,void * data)169 new_connection_callback (DBusServer     *server,
170                          DBusConnection *new_connection,
171                          void           *data)
172 {
173   BusContext *context = data;
174 
175   /* If this fails it logs a warning, so we don't need to do that */
176   if (!bus_connections_setup_connection (context->connections, new_connection))
177     {
178       /* if we don't do this, it will get unref'd without
179        * being disconnected... kind of strange really
180        * that we have to do this, people won't get it right
181        * in general.
182        */
183       dbus_connection_close (new_connection);
184     }
185 
186   dbus_connection_set_max_received_size (new_connection,
187                                          context->limits.max_incoming_bytes);
188 
189   dbus_connection_set_max_message_size (new_connection,
190                                         context->limits.max_message_size);
191 
192   dbus_connection_set_max_received_unix_fds (new_connection,
193                                          context->limits.max_incoming_unix_fds);
194 
195   dbus_connection_set_max_message_unix_fds (new_connection,
196                                         context->limits.max_message_unix_fds);
197 
198   dbus_connection_set_allow_anonymous (new_connection,
199                                        context->allow_anonymous);
200 
201   /* on OOM, we won't have ref'd the connection so it will die. */
202 }
203 
204 static void
free_server_data(void * data)205 free_server_data (void *data)
206 {
207   BusServerData *bd = data;
208 
209   dbus_free (bd);
210 }
211 
212 static dbus_bool_t
setup_server(BusContext * context,DBusServer * server,char ** auth_mechanisms,DBusError * error)213 setup_server (BusContext *context,
214               DBusServer *server,
215               char      **auth_mechanisms,
216               DBusError  *error)
217 {
218   BusServerData *bd;
219 
220   bd = dbus_new0 (BusServerData, 1);
221   if (bd == NULL || !dbus_server_set_data (server,
222                                            server_data_slot,
223                                            bd, free_server_data))
224     {
225       dbus_free (bd);
226       BUS_SET_OOM (error);
227       return FALSE;
228     }
229 
230   bd->context = context;
231 
232   if (!dbus_server_set_auth_mechanisms (server, (const char**) auth_mechanisms))
233     {
234       BUS_SET_OOM (error);
235       return FALSE;
236     }
237 
238   dbus_server_set_new_connection_function (server,
239                                            new_connection_callback,
240                                            context, NULL);
241 
242   if (!dbus_server_set_watch_functions (server,
243                                         add_server_watch,
244                                         remove_server_watch,
245                                         toggle_server_watch,
246                                         server,
247                                         NULL))
248     {
249       BUS_SET_OOM (error);
250       return FALSE;
251     }
252 
253   if (!dbus_server_set_timeout_functions (server,
254                                           add_server_timeout,
255                                           remove_server_timeout,
256                                           NULL,
257                                           server, NULL))
258     {
259       BUS_SET_OOM (error);
260       return FALSE;
261     }
262 
263   return TRUE;
264 }
265 
266 /* This code only gets executed the first time the
267  * config files are parsed.  It is not executed
268  * when config files are reloaded.
269  */
270 static dbus_bool_t
process_config_first_time_only(BusContext * context,BusConfigParser * parser,const DBusString * address,BusContextFlags flags,DBusError * error)271 process_config_first_time_only (BusContext       *context,
272 				BusConfigParser  *parser,
273                                 const DBusString *address,
274                                 BusContextFlags   flags,
275 				DBusError        *error)
276 {
277   DBusString log_prefix;
278   DBusList *link;
279   DBusList **addresses;
280   const char *user, *pidfile;
281   char **auth_mechanisms;
282   DBusList **auth_mechanisms_list;
283   int len;
284   dbus_bool_t retval;
285   DBusLogFlags log_flags = DBUS_LOG_FLAGS_STDERR;
286 
287   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
288 
289   retval = FALSE;
290   auth_mechanisms = NULL;
291   pidfile = NULL;
292 
293   if (flags & BUS_CONTEXT_FLAG_SYSLOG_ALWAYS)
294     {
295       context->syslog = TRUE;
296       log_flags |= DBUS_LOG_FLAGS_SYSTEM_LOG;
297 
298       if (flags & BUS_CONTEXT_FLAG_SYSLOG_ONLY)
299         log_flags &= ~DBUS_LOG_FLAGS_STDERR;
300     }
301   else if (flags & BUS_CONTEXT_FLAG_SYSLOG_NEVER)
302     {
303       context->syslog = FALSE;
304     }
305   else
306     {
307       context->syslog = bus_config_parser_get_syslog (parser);
308 
309       if (context->syslog)
310         log_flags |= DBUS_LOG_FLAGS_SYSTEM_LOG;
311     }
312 
313   _dbus_init_system_log ("dbus-daemon", log_flags);
314 
315   if (flags & BUS_CONTEXT_FLAG_SYSTEMD_ACTIVATION)
316     context->systemd_activation = TRUE;
317   else
318     context->systemd_activation = FALSE;
319 
320   /* Check for an existing pid file. Of course this is a race;
321    * we'd have to use fcntl() locks on the pid file to
322    * avoid that. But we want to check for the pid file
323    * before overwriting any existing sockets, etc.
324    */
325 
326   if (flags & BUS_CONTEXT_FLAG_WRITE_PID_FILE)
327     pidfile = bus_config_parser_get_pidfile (parser);
328 
329   if (pidfile != NULL)
330     {
331       DBusString u;
332       DBusStat stbuf;
333 
334       _dbus_string_init_const (&u, pidfile);
335 
336       if (_dbus_stat (&u, &stbuf, NULL))
337         {
338 #ifdef DBUS_CYGWIN
339           DBusString p;
340           long /* int */ pid;
341 
342           _dbus_string_init (&p);
343           _dbus_file_get_contents(&p, &u, NULL);
344           _dbus_string_parse_int(&p, 0, &pid, NULL);
345           _dbus_string_free(&p);
346 
347           if ((kill((int)pid, 0))) {
348             dbus_set_error(NULL, DBUS_ERROR_FILE_EXISTS,
349                            "pid %ld not running, removing stale pid file\n",
350                            pid);
351             _dbus_delete_file(&u, NULL);
352           } else {
353 #endif
354           dbus_set_error (error, DBUS_ERROR_FAILED,
355 		                  "The pid file \"%s\" exists, if the message bus is not running, remove this file",
356                           pidfile);
357 	      goto failed;
358 #ifdef DBUS_CYGWIN
359           }
360 #endif
361         }
362     }
363 
364   /* keep around the pid filename so we can delete it later */
365   context->pidfile = _dbus_strdup (pidfile);
366 
367   /* note that type may be NULL */
368   context->type = _dbus_strdup (bus_config_parser_get_type (parser));
369   if (bus_config_parser_get_type (parser) != NULL && context->type == NULL)
370     goto oom;
371 
372   user = bus_config_parser_get_user (parser);
373   if (user != NULL)
374     {
375       context->user = _dbus_strdup (user);
376       if (context->user == NULL)
377         goto oom;
378     }
379 
380   /* Set up the prefix for syslog messages */
381   if (!_dbus_string_init (&log_prefix))
382     goto oom;
383   if (context->type && !strcmp (context->type, "system"))
384     {
385       if (!_dbus_string_append (&log_prefix, "[system] "))
386         goto oom;
387     }
388   else if (context->type && !strcmp (context->type, "session"))
389     {
390       DBusCredentials *credentials;
391 
392       credentials = _dbus_credentials_new_from_current_process ();
393       if (!credentials)
394         goto oom;
395       if (!_dbus_string_append (&log_prefix, "[session "))
396         {
397           _dbus_credentials_unref (credentials);
398           goto oom;
399         }
400       if (!_dbus_credentials_to_string_append (credentials, &log_prefix))
401         {
402           _dbus_credentials_unref (credentials);
403           goto oom;
404         }
405       if (!_dbus_string_append (&log_prefix, "] "))
406         {
407           _dbus_credentials_unref (credentials);
408           goto oom;
409         }
410       _dbus_credentials_unref (credentials);
411     }
412   if (!_dbus_string_steal_data (&log_prefix, &context->log_prefix))
413     goto oom;
414   _dbus_string_free (&log_prefix);
415 
416   /* Build an array of auth mechanisms */
417 
418   auth_mechanisms_list = bus_config_parser_get_mechanisms (parser);
419   len = _dbus_list_get_length (auth_mechanisms_list);
420 
421   if (len > 0)
422     {
423       int i;
424 
425       auth_mechanisms = dbus_new0 (char*, len + 1);
426       if (auth_mechanisms == NULL)
427         goto oom;
428 
429       i = 0;
430       link = _dbus_list_get_first_link (auth_mechanisms_list);
431       while (link != NULL)
432         {
433           DBusString name;
434           _dbus_string_init_const (&name, link->data);
435           if (!_dbus_auth_is_supported_mechanism (&name))
436             {
437               DBusString list;
438               if (!_dbus_string_init (&list))
439                 goto oom;
440 
441               if (!_dbus_auth_dump_supported_mechanisms (&list))
442                 {
443                   _dbus_string_free (&list);
444                   goto oom;
445                 }
446               dbus_set_error (error, DBUS_ERROR_FAILED,
447                               "Unsupported auth mechanism \"%s\" in bus config file detected. Supported mechanisms are \"%s\".",
448                               (char*)link->data,
449                               _dbus_string_get_const_data (&list));
450               _dbus_string_free (&list);
451               goto failed;
452             }
453           auth_mechanisms[i] = _dbus_strdup (link->data);
454           if (auth_mechanisms[i] == NULL)
455             goto oom;
456           link = _dbus_list_get_next_link (auth_mechanisms_list, link);
457           i += 1;
458         }
459     }
460   else
461     {
462       auth_mechanisms = NULL;
463     }
464 
465   /* Listen on our addresses */
466 
467   if (address)
468     {
469       DBusServer *server;
470 
471       server = dbus_server_listen (_dbus_string_get_const_data(address), error);
472       if (server == NULL)
473         {
474           _DBUS_ASSERT_ERROR_IS_SET (error);
475           goto failed;
476         }
477       else if (!setup_server (context, server, auth_mechanisms, error))
478         {
479           _DBUS_ASSERT_ERROR_IS_SET (error);
480           goto failed;
481         }
482 
483       if (!_dbus_list_append (&context->servers, server))
484         goto oom;
485     }
486   else
487     {
488       addresses = bus_config_parser_get_addresses (parser);
489 
490       link = _dbus_list_get_first_link (addresses);
491       while (link != NULL)
492         {
493           DBusServer *server;
494 
495           server = dbus_server_listen (link->data, error);
496           if (server == NULL)
497             {
498               _DBUS_ASSERT_ERROR_IS_SET (error);
499               goto failed;
500             }
501           else if (!setup_server (context, server, auth_mechanisms, error))
502             {
503               _DBUS_ASSERT_ERROR_IS_SET (error);
504               goto failed;
505             }
506 
507           if (!_dbus_list_append (&context->servers, server))
508             goto oom;
509 
510           link = _dbus_list_get_next_link (addresses, link);
511         }
512     }
513 
514   context->fork = bus_config_parser_get_fork (parser);
515   context->keep_umask = bus_config_parser_get_keep_umask (parser);
516   context->allow_anonymous = bus_config_parser_get_allow_anonymous (parser);
517 
518   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
519   retval = TRUE;
520 
521  failed:
522   dbus_free_string_array (auth_mechanisms);
523   return retval;
524 
525  oom:
526   BUS_SET_OOM (error);
527   dbus_free_string_array (auth_mechanisms);
528   return FALSE;
529 }
530 
531 /* This code gets executed every time the config files
532  * are parsed: both during BusContext construction
533  * and on reloads. This function is slightly screwy
534  * since it can do a "half reload" in out-of-memory
535  * situations. Realistically, unlikely to ever matter.
536  */
537 static dbus_bool_t
process_config_every_time(BusContext * context,BusConfigParser * parser,dbus_bool_t is_reload,DBusError * error)538 process_config_every_time (BusContext      *context,
539 			   BusConfigParser *parser,
540 			   dbus_bool_t      is_reload,
541 			   DBusError       *error)
542 {
543   DBusString full_address;
544   DBusList *link;
545   DBusList **dirs;
546   char *addr;
547   const char *servicehelper;
548   char *s;
549 
550   dbus_bool_t retval;
551 
552   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
553 
554   addr = NULL;
555   retval = FALSE;
556 
557   if (!_dbus_string_init (&full_address))
558     {
559       BUS_SET_OOM (error);
560       return FALSE;
561     }
562 
563   /* get our limits and timeout lengths */
564   bus_config_parser_get_limits (parser, &context->limits);
565 
566   if (context->policy)
567     bus_policy_unref (context->policy);
568   context->policy = bus_config_parser_steal_policy (parser);
569   _dbus_assert (context->policy != NULL);
570 
571   /* context->connections is NULL when creating new BusContext */
572   if (context->connections)
573     {
574       _dbus_verbose ("Reload policy rules for completed connections\n");
575       retval = bus_connections_reload_policy (context->connections, error);
576       if (!retval)
577         {
578           _DBUS_ASSERT_ERROR_IS_SET (error);
579           goto failed;
580         }
581     }
582 
583   /* We have to build the address backward, so that
584    * <listen> later in the config file have priority
585    */
586   link = _dbus_list_get_last_link (&context->servers);
587   while (link != NULL)
588     {
589       addr = dbus_server_get_address (link->data);
590       if (addr == NULL)
591         {
592           BUS_SET_OOM (error);
593           goto failed;
594         }
595 
596       if (_dbus_string_get_length (&full_address) > 0)
597         {
598           if (!_dbus_string_append (&full_address, ";"))
599             {
600               BUS_SET_OOM (error);
601               goto failed;
602             }
603         }
604 
605       if (!_dbus_string_append (&full_address, addr))
606         {
607           BUS_SET_OOM (error);
608           goto failed;
609         }
610 
611       dbus_free (addr);
612       addr = NULL;
613 
614       link = _dbus_list_get_prev_link (&context->servers, link);
615     }
616 
617   if (is_reload)
618     dbus_free (context->address);
619 
620   if (!_dbus_string_copy_data (&full_address, &context->address))
621     {
622       BUS_SET_OOM (error);
623       goto failed;
624     }
625 
626   /* get the service directories */
627   dirs = bus_config_parser_get_service_dirs (parser);
628 
629   /* and the service helper */
630   servicehelper = bus_config_parser_get_servicehelper (parser);
631 
632   s = _dbus_strdup(servicehelper);
633   if (s == NULL && servicehelper != NULL)
634     {
635       BUS_SET_OOM (error);
636       goto failed;
637     }
638   else
639     {
640       dbus_free(context->servicehelper);
641       context->servicehelper = s;
642     }
643 
644   /* Create activation subsystem */
645   if (context->activation)
646     {
647       if (!bus_activation_reload (context->activation, &full_address, dirs, error))
648         goto failed;
649     }
650   else
651     {
652       context->activation = bus_activation_new (context, &full_address, dirs, error);
653     }
654 
655   if (context->activation == NULL)
656     {
657       _DBUS_ASSERT_ERROR_IS_SET (error);
658       goto failed;
659     }
660 
661   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
662   retval = TRUE;
663 
664  failed:
665   _dbus_string_free (&full_address);
666 
667   if (addr)
668     dbus_free (addr);
669 
670   return retval;
671 }
672 
673 static void
raise_file_descriptor_limit(BusContext * context)674 raise_file_descriptor_limit (BusContext      *context)
675 {
676 #ifdef DBUS_UNIX
677   DBusError error = DBUS_ERROR_INIT;
678 
679   /* we only do this once */
680   if (context->initial_fd_limit != NULL)
681     return;
682 
683   context->initial_fd_limit = _dbus_rlimit_save_fd_limit (&error);
684 
685   if (context->initial_fd_limit == NULL)
686     {
687       bus_context_log (context, DBUS_SYSTEM_LOG_WARNING,
688                        "%s: %s", error.name, error.message);
689       dbus_error_free (&error);
690       return;
691     }
692 
693   /* We used to compute a suitable rlimit based on the configured number
694    * of connections, but that breaks down as soon as we allow fd-passing,
695    * because each connection is allowed to pass 64 fds to us, and if
696    * they all did, we'd hit kernel limits. We now hard-code a good
697    * limit that is enough to avoid DoS from anything short of multiple
698    * uids conspiring against us, much like systemd does.
699    */
700   if (!_dbus_rlimit_raise_fd_limit (&error))
701     {
702       bus_context_log (context, DBUS_SYSTEM_LOG_WARNING,
703                        "%s: %s", error.name, error.message);
704       dbus_error_free (&error);
705       return;
706     }
707 #endif
708 }
709 
710 static dbus_bool_t
process_config_postinit(BusContext * context,BusConfigParser * parser,DBusError * error)711 process_config_postinit (BusContext      *context,
712 			 BusConfigParser *parser,
713 			 DBusError       *error)
714 {
715   DBusHashTable *service_context_table;
716   DBusList *watched_dirs = NULL;
717 
718   service_context_table = bus_config_parser_steal_service_context_table (parser);
719   if (!bus_registry_set_service_context_table (context->registry,
720 					       service_context_table))
721     {
722       BUS_SET_OOM (error);
723       return FALSE;
724     }
725 
726   _dbus_hash_table_unref (service_context_table);
727 
728   /* We need to monitor both the configuration directories and directories
729    * containing .service files.
730    */
731   if (!bus_config_parser_get_watched_dirs (parser, &watched_dirs))
732     {
733       BUS_SET_OOM (error);
734       return FALSE;
735     }
736 
737   bus_set_watched_dirs (context, &watched_dirs);
738 
739   _dbus_list_clear (&watched_dirs);
740 
741   return TRUE;
742 }
743 
744 BusContext*
bus_context_new(const DBusString * config_file,BusContextFlags flags,DBusPipe * print_addr_pipe,DBusPipe * print_pid_pipe,const DBusString * address,DBusError * error)745 bus_context_new (const DBusString *config_file,
746                  BusContextFlags   flags,
747                  DBusPipe         *print_addr_pipe,
748                  DBusPipe         *print_pid_pipe,
749                  const DBusString *address,
750                  DBusError        *error)
751 {
752   BusContext *context;
753   BusConfigParser *parser;
754 
755   _dbus_assert ((flags & BUS_CONTEXT_FLAG_FORK_NEVER) == 0 ||
756                 (flags & BUS_CONTEXT_FLAG_FORK_ALWAYS) == 0);
757 
758   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
759 
760   context = NULL;
761   parser = NULL;
762 
763   if (!dbus_server_allocate_data_slot (&server_data_slot))
764     {
765       BUS_SET_OOM (error);
766       return NULL;
767     }
768 
769   context = dbus_new0 (BusContext, 1);
770   if (context == NULL)
771     {
772       BUS_SET_OOM (error);
773       goto failed;
774     }
775   context->refcount = 1;
776 
777   if (!_dbus_generate_uuid (&context->uuid, error))
778     goto failed;
779 
780   if (!_dbus_string_copy_data (config_file, &context->config_file))
781     {
782       BUS_SET_OOM (error);
783       goto failed;
784     }
785 
786   context->loop = _dbus_loop_new ();
787   if (context->loop == NULL)
788     {
789       BUS_SET_OOM (error);
790       goto failed;
791     }
792 
793   context->watches_enabled = TRUE;
794 
795   context->registry = bus_registry_new (context);
796   if (context->registry == NULL)
797     {
798       BUS_SET_OOM (error);
799       goto failed;
800     }
801 
802   parser = bus_config_load (config_file, TRUE, NULL, error);
803   if (parser == NULL)
804     {
805       _DBUS_ASSERT_ERROR_IS_SET (error);
806       goto failed;
807     }
808 
809   if (!process_config_first_time_only (context, parser, address, flags, error))
810     {
811       _DBUS_ASSERT_ERROR_IS_SET (error);
812       goto failed;
813     }
814   if (!process_config_every_time (context, parser, FALSE, error))
815     {
816       _DBUS_ASSERT_ERROR_IS_SET (error);
817       goto failed;
818     }
819 
820   /* we need another ref of the server data slot for the context
821    * to own
822    */
823   if (!dbus_server_allocate_data_slot (&server_data_slot))
824     _dbus_assert_not_reached ("second ref of server data slot failed");
825 
826   /* Note that we don't know whether the print_addr_pipe is
827    * one of the sockets we're using to listen on, or some
828    * other random thing. But I think the answer is "don't do
829    * that then"
830    */
831   if (print_addr_pipe != NULL && _dbus_pipe_is_valid (print_addr_pipe))
832     {
833       DBusString addr;
834       const char *a = bus_context_get_address (context);
835       int bytes;
836 
837       _dbus_assert (a != NULL);
838       if (!_dbus_string_init (&addr))
839         {
840           BUS_SET_OOM (error);
841           goto failed;
842         }
843 
844       if (!_dbus_string_append (&addr, a) ||
845           !_dbus_string_append (&addr, "\n"))
846         {
847           _dbus_string_free (&addr);
848           BUS_SET_OOM (error);
849           goto failed;
850         }
851 
852       bytes = _dbus_string_get_length (&addr);
853       if (_dbus_pipe_write (print_addr_pipe, &addr, 0, bytes, error) != bytes)
854         {
855           /* pipe write returns an error on failure but not short write */
856           if (error != NULL && !dbus_error_is_set (error))
857             {
858               dbus_set_error (error, DBUS_ERROR_FAILED,
859                               "Printing message bus address: did not write all bytes\n");
860             }
861           _dbus_string_free (&addr);
862           goto failed;
863         }
864 
865       if (!_dbus_pipe_is_stdout_or_stderr (print_addr_pipe))
866         _dbus_pipe_close (print_addr_pipe, NULL);
867 
868       _dbus_string_free (&addr);
869     }
870 
871   context->connections = bus_connections_new (context);
872   if (context->connections == NULL)
873     {
874       BUS_SET_OOM (error);
875       goto failed;
876     }
877 
878   context->matchmaker = bus_matchmaker_new ();
879   if (context->matchmaker == NULL)
880     {
881       BUS_SET_OOM (error);
882       goto failed;
883     }
884 
885   /* check user before we fork */
886   if (context->user != NULL)
887     {
888       if (!_dbus_verify_daemon_user (context->user))
889         {
890           dbus_set_error (error, DBUS_ERROR_FAILED,
891                           "Could not get UID and GID for username \"%s\"",
892                           context->user);
893           goto failed;
894         }
895     }
896 
897   /* Now become a daemon if appropriate and write out pid file in any case */
898   {
899     DBusString u;
900 
901     if (context->pidfile)
902       _dbus_string_init_const (&u, context->pidfile);
903 
904     if (((flags & BUS_CONTEXT_FLAG_FORK_NEVER) == 0 && context->fork) ||
905         (flags & BUS_CONTEXT_FLAG_FORK_ALWAYS))
906       {
907         _dbus_verbose ("Forking and becoming daemon\n");
908 
909         if (!_dbus_become_daemon (context->pidfile ? &u : NULL,
910                                   print_pid_pipe,
911                                   error,
912                                   context->keep_umask))
913           {
914             _DBUS_ASSERT_ERROR_IS_SET (error);
915             goto failed;
916           }
917       }
918     else
919       {
920         _dbus_verbose ("Fork not requested\n");
921 
922         /* Need to write PID file and to PID pipe for ourselves,
923          * not for the child process. This is a no-op if the pidfile
924          * is NULL and print_pid_pipe is NULL.
925          */
926         if (!_dbus_write_pid_to_file_and_pipe (context->pidfile ? &u : NULL,
927                                                print_pid_pipe,
928                                                _dbus_getpid (),
929                                                error))
930           {
931             _DBUS_ASSERT_ERROR_IS_SET (error);
932             goto failed;
933           }
934       }
935   }
936 
937   if (print_pid_pipe && _dbus_pipe_is_valid (print_pid_pipe) &&
938       !_dbus_pipe_is_stdout_or_stderr (print_pid_pipe))
939     _dbus_pipe_close (print_pid_pipe, NULL);
940 
941   /* Raise the file descriptor limits before dropping the privileges
942    * required to do so.
943    */
944   raise_file_descriptor_limit (context);
945 
946   /* Here we change our credentials if required,
947    * as soon as we've set up our sockets and pidfile.
948    * This must be done before initializing LSMs, so that the netlink
949    * monitoring thread started by avc_init() will not lose CAP_AUDIT_WRITE
950    * when the main thread calls setuid().
951    * https://bugs.freedesktop.org/show_bug.cgi?id=92832
952    */
953   if (context->user != NULL)
954     {
955       if (!_dbus_change_to_daemon_user (context->user, error))
956 	{
957 	  _DBUS_ASSERT_ERROR_IS_SET (error);
958 	  goto failed;
959 	}
960     }
961 
962   /* Auditing should be initialized before LSMs, so that the LSMs are able
963    * to log audit-events that happen during their initialization.
964    */
965   bus_audit_init (context);
966 
967   if (!bus_selinux_full_init ())
968     {
969       bus_context_log (context, DBUS_SYSTEM_LOG_ERROR,
970                        "SELinux enabled but D-Bus initialization failed; "
971                        "check system log");
972       exit (1);
973     }
974 
975   if (!bus_apparmor_full_init (error))
976     {
977       _DBUS_ASSERT_ERROR_IS_SET (error);
978       goto failed;
979     }
980 
981   if (bus_apparmor_enabled ())
982     {
983       /* Only print AppArmor mediation message when syslog support is enabled */
984       if (context->syslog)
985         bus_context_log (context, DBUS_SYSTEM_LOG_INFO,
986                          "AppArmor D-Bus mediation is enabled\n");
987     }
988 
989   /* When SELinux is used, this must happen after bus_selinux_full_init()
990    * so that it has access to the access vector cache, which is required
991    * to process <associate/> elements.
992    * http://lists.freedesktop.org/archives/dbus/2008-October/010491.html
993    */
994   if (!process_config_postinit (context, parser, error))
995     {
996       _DBUS_ASSERT_ERROR_IS_SET (error);
997       goto failed;
998     }
999 
1000   if (parser != NULL)
1001     {
1002       bus_config_parser_unref (parser);
1003       parser = NULL;
1004     }
1005 
1006   dbus_server_free_data_slot (&server_data_slot);
1007 
1008   return context;
1009 
1010  failed:
1011   if (parser != NULL)
1012     bus_config_parser_unref (parser);
1013   if (context != NULL)
1014     bus_context_unref (context);
1015 
1016   if (server_data_slot >= 0)
1017     dbus_server_free_data_slot (&server_data_slot);
1018 
1019   return NULL;
1020 }
1021 
1022 dbus_bool_t
bus_context_get_id(BusContext * context,DBusString * uuid)1023 bus_context_get_id (BusContext       *context,
1024                     DBusString       *uuid)
1025 {
1026   return _dbus_uuid_encode (&context->uuid, uuid);
1027 }
1028 
1029 dbus_bool_t
bus_context_reload_config(BusContext * context,DBusError * error)1030 bus_context_reload_config (BusContext *context,
1031 			   DBusError  *error)
1032 {
1033   BusConfigParser *parser;
1034   DBusString config_file;
1035   dbus_bool_t ret;
1036 
1037   /* Flush the user database cache */
1038   _dbus_flush_caches ();
1039 
1040   ret = FALSE;
1041   _dbus_string_init_const (&config_file, context->config_file);
1042   parser = bus_config_load (&config_file, TRUE, NULL, error);
1043   if (parser == NULL)
1044     {
1045       _DBUS_ASSERT_ERROR_IS_SET (error);
1046       goto failed;
1047     }
1048 
1049   if (!process_config_every_time (context, parser, TRUE, error))
1050     {
1051       _DBUS_ASSERT_ERROR_IS_SET (error);
1052       goto failed;
1053     }
1054   if (!process_config_postinit (context, parser, error))
1055     {
1056       _DBUS_ASSERT_ERROR_IS_SET (error);
1057       goto failed;
1058     }
1059   ret = TRUE;
1060 
1061   bus_context_log (context, DBUS_SYSTEM_LOG_INFO, "Reloaded configuration");
1062  failed:
1063   if (!ret)
1064     bus_context_log (context, DBUS_SYSTEM_LOG_INFO, "Unable to reload configuration: %s", error->message);
1065   if (parser != NULL)
1066     bus_config_parser_unref (parser);
1067   return ret;
1068 }
1069 
1070 static void
shutdown_server(BusContext * context,DBusServer * server)1071 shutdown_server (BusContext *context,
1072                  DBusServer *server)
1073 {
1074   if (server == NULL ||
1075       !dbus_server_get_is_connected (server))
1076     return;
1077 
1078   if (!dbus_server_set_watch_functions (server,
1079                                         NULL, NULL, NULL,
1080                                         context,
1081                                         NULL))
1082     _dbus_assert_not_reached ("setting watch functions to NULL failed");
1083 
1084   if (!dbus_server_set_timeout_functions (server,
1085                                           NULL, NULL, NULL,
1086                                           context,
1087                                           NULL))
1088     _dbus_assert_not_reached ("setting timeout functions to NULL failed");
1089 
1090   dbus_server_disconnect (server);
1091 }
1092 
1093 void
bus_context_shutdown(BusContext * context)1094 bus_context_shutdown (BusContext  *context)
1095 {
1096   DBusList *link;
1097 
1098   link = _dbus_list_get_first_link (&context->servers);
1099   while (link != NULL)
1100     {
1101       shutdown_server (context, link->data);
1102 
1103       link = _dbus_list_get_next_link (&context->servers, link);
1104     }
1105 }
1106 
1107 BusContext *
bus_context_ref(BusContext * context)1108 bus_context_ref (BusContext *context)
1109 {
1110   _dbus_assert (context->refcount > 0);
1111   context->refcount += 1;
1112 
1113   return context;
1114 }
1115 
1116 void
bus_context_unref(BusContext * context)1117 bus_context_unref (BusContext *context)
1118 {
1119   _dbus_assert (context->refcount > 0);
1120   context->refcount -= 1;
1121 
1122   if (context->refcount == 0)
1123     {
1124       DBusList *link;
1125 
1126       _dbus_verbose ("Finalizing bus context %p\n", context);
1127 
1128       bus_context_shutdown (context);
1129 
1130       if (context->connections)
1131         {
1132           bus_connections_unref (context->connections);
1133           context->connections = NULL;
1134         }
1135 
1136       if (context->registry)
1137         {
1138           bus_registry_unref (context->registry);
1139           context->registry = NULL;
1140         }
1141 
1142       if (context->activation)
1143         {
1144           bus_activation_unref (context->activation);
1145           context->activation = NULL;
1146         }
1147 
1148       link = _dbus_list_get_first_link (&context->servers);
1149       while (link != NULL)
1150         {
1151           dbus_server_unref (link->data);
1152 
1153           link = _dbus_list_get_next_link (&context->servers, link);
1154         }
1155       _dbus_list_clear (&context->servers);
1156 
1157       if (context->policy)
1158         {
1159           bus_policy_unref (context->policy);
1160           context->policy = NULL;
1161         }
1162 
1163       if (context->loop)
1164         {
1165           _dbus_loop_unref (context->loop);
1166           context->loop = NULL;
1167         }
1168 
1169       if (context->matchmaker)
1170         {
1171           bus_matchmaker_unref (context->matchmaker);
1172           context->matchmaker = NULL;
1173         }
1174 
1175       dbus_free (context->config_file);
1176       dbus_free (context->log_prefix);
1177       dbus_free (context->type);
1178       dbus_free (context->address);
1179       dbus_free (context->user);
1180       dbus_free (context->servicehelper);
1181 
1182       if (context->pidfile)
1183 	{
1184           DBusString u;
1185           _dbus_string_init_const (&u, context->pidfile);
1186 
1187           /* Deliberately ignore errors here, since there's not much
1188 	   * we can do about it, and we're exiting anyways.
1189 	   */
1190 	  _dbus_delete_file (&u, NULL);
1191 
1192           dbus_free (context->pidfile);
1193 	}
1194 
1195       if (context->initial_fd_limit)
1196         _dbus_rlimit_free (context->initial_fd_limit);
1197 
1198       dbus_free (context);
1199 
1200       dbus_server_free_data_slot (&server_data_slot);
1201     }
1202 }
1203 
1204 /* type may be NULL */
1205 const char*
bus_context_get_type(BusContext * context)1206 bus_context_get_type (BusContext *context)
1207 {
1208   return context->type;
1209 }
1210 
1211 const char*
bus_context_get_address(BusContext * context)1212 bus_context_get_address (BusContext *context)
1213 {
1214   return context->address;
1215 }
1216 
1217 const char*
bus_context_get_servicehelper(BusContext * context)1218 bus_context_get_servicehelper (BusContext *context)
1219 {
1220   return context->servicehelper;
1221 }
1222 
1223 dbus_bool_t
bus_context_get_systemd_activation(BusContext * context)1224 bus_context_get_systemd_activation (BusContext *context)
1225 {
1226   return context->systemd_activation;
1227 }
1228 
1229 BusRegistry*
bus_context_get_registry(BusContext * context)1230 bus_context_get_registry (BusContext  *context)
1231 {
1232   return context->registry;
1233 }
1234 
1235 BusConnections*
bus_context_get_connections(BusContext * context)1236 bus_context_get_connections (BusContext  *context)
1237 {
1238   return context->connections;
1239 }
1240 
1241 BusActivation*
bus_context_get_activation(BusContext * context)1242 bus_context_get_activation (BusContext  *context)
1243 {
1244   return context->activation;
1245 }
1246 
1247 BusMatchmaker*
bus_context_get_matchmaker(BusContext * context)1248 bus_context_get_matchmaker (BusContext  *context)
1249 {
1250   return context->matchmaker;
1251 }
1252 
1253 DBusLoop*
bus_context_get_loop(BusContext * context)1254 bus_context_get_loop (BusContext *context)
1255 {
1256   return context->loop;
1257 }
1258 
1259 dbus_bool_t
bus_context_allow_unix_user(BusContext * context,unsigned long uid)1260 bus_context_allow_unix_user (BusContext   *context,
1261                              unsigned long uid)
1262 {
1263   return bus_policy_allow_unix_user (context->policy,
1264                                      uid);
1265 }
1266 
1267 /* For now this is never actually called because the default
1268  * DBusConnection behavior of 'same user that owns the bus can connect'
1269  * is all it would do.
1270  */
1271 dbus_bool_t
bus_context_allow_windows_user(BusContext * context,const char * windows_sid)1272 bus_context_allow_windows_user (BusContext       *context,
1273                                 const char       *windows_sid)
1274 {
1275   return bus_policy_allow_windows_user (context->policy,
1276                                         windows_sid);
1277 }
1278 
1279 BusPolicy *
bus_context_get_policy(BusContext * context)1280 bus_context_get_policy (BusContext *context)
1281 {
1282   return context->policy;
1283 }
1284 
1285 BusClientPolicy*
bus_context_create_client_policy(BusContext * context,DBusConnection * connection,DBusError * error)1286 bus_context_create_client_policy (BusContext      *context,
1287                                   DBusConnection  *connection,
1288                                   DBusError       *error)
1289 {
1290   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1291   return bus_policy_create_client_policy (context->policy, connection,
1292                                           error);
1293 }
1294 
1295 int
bus_context_get_activation_timeout(BusContext * context)1296 bus_context_get_activation_timeout (BusContext *context)
1297 {
1298 
1299   return context->limits.activation_timeout;
1300 }
1301 
1302 int
bus_context_get_auth_timeout(BusContext * context)1303 bus_context_get_auth_timeout (BusContext *context)
1304 {
1305   return context->limits.auth_timeout;
1306 }
1307 
1308 int
bus_context_get_pending_fd_timeout(BusContext * context)1309 bus_context_get_pending_fd_timeout (BusContext *context)
1310 {
1311   return context->limits.pending_fd_timeout;
1312 }
1313 
1314 int
bus_context_get_max_completed_connections(BusContext * context)1315 bus_context_get_max_completed_connections (BusContext *context)
1316 {
1317   return context->limits.max_completed_connections;
1318 }
1319 
1320 int
bus_context_get_max_incomplete_connections(BusContext * context)1321 bus_context_get_max_incomplete_connections (BusContext *context)
1322 {
1323   return context->limits.max_incomplete_connections;
1324 }
1325 
1326 int
bus_context_get_max_connections_per_user(BusContext * context)1327 bus_context_get_max_connections_per_user (BusContext *context)
1328 {
1329   return context->limits.max_connections_per_user;
1330 }
1331 
1332 int
bus_context_get_max_pending_activations(BusContext * context)1333 bus_context_get_max_pending_activations (BusContext *context)
1334 {
1335   return context->limits.max_pending_activations;
1336 }
1337 
1338 int
bus_context_get_max_services_per_connection(BusContext * context)1339 bus_context_get_max_services_per_connection (BusContext *context)
1340 {
1341   return context->limits.max_services_per_connection;
1342 }
1343 
1344 int
bus_context_get_max_match_rules_per_connection(BusContext * context)1345 bus_context_get_max_match_rules_per_connection (BusContext *context)
1346 {
1347   return context->limits.max_match_rules_per_connection;
1348 }
1349 
1350 int
bus_context_get_max_replies_per_connection(BusContext * context)1351 bus_context_get_max_replies_per_connection (BusContext *context)
1352 {
1353   return context->limits.max_replies_per_connection;
1354 }
1355 
1356 int
bus_context_get_reply_timeout(BusContext * context)1357 bus_context_get_reply_timeout (BusContext *context)
1358 {
1359   return context->limits.reply_timeout;
1360 }
1361 
1362 DBusRLimit *
bus_context_get_initial_fd_limit(BusContext * context)1363 bus_context_get_initial_fd_limit (BusContext *context)
1364 {
1365   return context->initial_fd_limit;
1366 }
1367 
1368 dbus_bool_t
bus_context_get_using_syslog(BusContext * context)1369 bus_context_get_using_syslog (BusContext *context)
1370 {
1371   return context->syslog;
1372 }
1373 
1374 void
bus_context_log(BusContext * context,DBusSystemLogSeverity severity,const char * msg,...)1375 bus_context_log (BusContext *context, DBusSystemLogSeverity severity, const char *msg, ...)
1376 {
1377   va_list args;
1378 
1379   va_start (args, msg);
1380 
1381   if (context->log_prefix)
1382     {
1383       DBusString full_msg;
1384 
1385       if (!_dbus_string_init (&full_msg))
1386         goto out;
1387       if (!_dbus_string_append (&full_msg, context->log_prefix))
1388         goto oom_out;
1389       if (!_dbus_string_append_printf_valist (&full_msg, msg, args))
1390         goto oom_out;
1391 
1392       _dbus_log (severity, "%s", _dbus_string_get_const_data (&full_msg));
1393     oom_out:
1394       _dbus_string_free (&full_msg);
1395     }
1396   else
1397     _dbus_logv (severity, msg, args);
1398 
1399 out:
1400   va_end (args);
1401 }
1402 
1403 static inline const char *
nonnull(const char * maybe_null,const char * if_null)1404 nonnull (const char *maybe_null,
1405          const char *if_null)
1406 {
1407   return (maybe_null ? maybe_null : if_null);
1408 }
1409 
1410 void
bus_context_log_literal(BusContext * context,DBusSystemLogSeverity severity,const char * msg)1411 bus_context_log_literal (BusContext            *context,
1412                          DBusSystemLogSeverity  severity,
1413                          const char            *msg)
1414 {
1415   _dbus_log (severity, "%s%s", nonnull (context->log_prefix, ""), msg);
1416 }
1417 
1418 void
bus_context_log_and_set_error(BusContext * context,DBusSystemLogSeverity severity,DBusError * error,const char * name,const char * msg,...)1419 bus_context_log_and_set_error (BusContext            *context,
1420                                DBusSystemLogSeverity  severity,
1421                                DBusError             *error,
1422                                const char            *name,
1423                                const char            *msg,
1424                                ...)
1425 {
1426   DBusError stack_error = DBUS_ERROR_INIT;
1427   va_list args;
1428 
1429   va_start (args, msg);
1430   _dbus_set_error_valist (&stack_error, name, msg, args);
1431   va_end (args);
1432 
1433   /* If we hit OOM while setting the error, this will syslog "out of memory"
1434    * which is itself an indication that something is seriously wrong */
1435   bus_context_log_literal (context, DBUS_SYSTEM_LOG_SECURITY,
1436                            stack_error.message);
1437 
1438   dbus_move_error (&stack_error, error);
1439 }
1440 
1441 /*
1442  * Log something about a message, usually that it was rejected.
1443  */
1444 static void
complain_about_message(BusContext * context,const char * error_name,const char * complaint,int matched_rules,DBusMessage * message,DBusConnection * sender,DBusConnection * proposed_recipient,dbus_bool_t requested_reply,dbus_bool_t log,DBusError * error)1445 complain_about_message (BusContext     *context,
1446                         const char     *error_name,
1447                         const char     *complaint,
1448                         int             matched_rules,
1449                         DBusMessage    *message,
1450                         DBusConnection *sender,
1451                         DBusConnection *proposed_recipient,
1452                         dbus_bool_t     requested_reply,
1453                         dbus_bool_t     log,
1454                         DBusError      *error)
1455 {
1456   DBusError stack_error = DBUS_ERROR_INIT;
1457   const char *sender_name;
1458   const char *sender_loginfo;
1459   const char *proposed_recipient_loginfo;
1460 
1461   if (error == NULL && !log)
1462     return;
1463 
1464   if (sender != NULL)
1465     {
1466       sender_name = bus_connection_get_name (sender);
1467       sender_loginfo = bus_connection_get_loginfo (sender);
1468     }
1469   else
1470     {
1471       sender_name = "(unset)";
1472       sender_loginfo = "(bus)";
1473     }
1474 
1475   if (proposed_recipient != NULL)
1476     proposed_recipient_loginfo = bus_connection_get_loginfo (proposed_recipient);
1477   else
1478     proposed_recipient_loginfo = "bus";
1479 
1480   dbus_set_error (&stack_error, error_name,
1481       "%s, %d matched rules; type=\"%s\", sender=\"%s\" (%s) "
1482       "interface=\"%s\" member=\"%s\" error name=\"%s\" "
1483       "requested_reply=\"%d\" destination=\"%s\" (%s)",
1484       complaint,
1485       matched_rules,
1486       dbus_message_type_to_string (dbus_message_get_type (message)),
1487       sender_name,
1488       sender_loginfo,
1489       nonnull (dbus_message_get_interface (message), "(unset)"),
1490       nonnull (dbus_message_get_member (message), "(unset)"),
1491       nonnull (dbus_message_get_error_name (message), "(unset)"),
1492       requested_reply,
1493       nonnull (dbus_message_get_destination (message), DBUS_SERVICE_DBUS),
1494       proposed_recipient_loginfo);
1495 
1496   /* If we hit OOM while setting the error, this will syslog "out of memory"
1497    * which is itself an indication that something is seriously wrong */
1498   if (log)
1499     bus_context_log_literal (context, DBUS_SYSTEM_LOG_SECURITY,
1500         stack_error.message);
1501 
1502   dbus_move_error (&stack_error, error);
1503 }
1504 
1505 /*
1506  * addressed_recipient is the recipient specified in the message.
1507  *
1508  * proposed_recipient is the recipient we're considering sending
1509  * to right this second, and may be an eavesdropper.
1510  *
1511  * sender is the sender of the message.
1512  *
1513  * NULL for sender definitely means the bus driver.
1514  *
1515  * NULL for proposed_recipient may mean the bus driver, or may mean
1516  * we are checking whether service-activation is allowed as a first
1517  * pass before all details of the activated service are known.
1518  *
1519  * NULL for addressed_recipient may mean the bus driver, or may mean
1520  * no destination was specified in the message (e.g. a signal).
1521  */
1522 dbus_bool_t
bus_context_check_security_policy(BusContext * context,BusTransaction * transaction,DBusConnection * sender,DBusConnection * addressed_recipient,DBusConnection * proposed_recipient,DBusMessage * message,BusActivationEntry * activation_entry,DBusError * error)1523 bus_context_check_security_policy (BusContext     *context,
1524                                    BusTransaction *transaction,
1525                                    DBusConnection *sender,
1526                                    DBusConnection *addressed_recipient,
1527                                    DBusConnection *proposed_recipient,
1528                                    DBusMessage    *message,
1529                                    BusActivationEntry *activation_entry,
1530                                    DBusError      *error)
1531 {
1532   const char *src, *dest;
1533   BusClientPolicy *sender_policy;
1534   BusClientPolicy *recipient_policy;
1535   dbus_int32_t toggles;
1536   dbus_bool_t log;
1537   int type;
1538   dbus_bool_t requested_reply;
1539 
1540   type = dbus_message_get_type (message);
1541   src = dbus_message_get_sender (message);
1542   dest = dbus_message_get_destination (message);
1543 
1544   /* dispatch.c was supposed to ensure these invariants */
1545   _dbus_assert (dest != NULL ||
1546                 type == DBUS_MESSAGE_TYPE_SIGNAL ||
1547                 (sender == NULL && !bus_connection_is_active (proposed_recipient)));
1548   _dbus_assert (type == DBUS_MESSAGE_TYPE_SIGNAL ||
1549                 addressed_recipient != NULL ||
1550                 activation_entry != NULL ||
1551                 strcmp (dest, DBUS_SERVICE_DBUS) == 0);
1552 
1553   switch (type)
1554     {
1555     case DBUS_MESSAGE_TYPE_METHOD_CALL:
1556     case DBUS_MESSAGE_TYPE_SIGNAL:
1557     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
1558     case DBUS_MESSAGE_TYPE_ERROR:
1559       break;
1560 
1561     default:
1562       _dbus_verbose ("security check disallowing message of unknown type %d\n",
1563                      type);
1564 
1565       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1566                       "Message bus will not accept messages of unknown type\n");
1567 
1568       return FALSE;
1569     }
1570 
1571   requested_reply = FALSE;
1572 
1573   if (sender != NULL)
1574     {
1575       if (bus_connection_is_active (sender))
1576         {
1577           sender_policy = bus_connection_get_policy (sender);
1578           _dbus_assert (sender_policy != NULL);
1579 
1580           /* Fill in requested_reply variable with TRUE if this is a
1581            * reply and the reply was pending.
1582            */
1583           if (dbus_message_get_reply_serial (message) != 0)
1584             {
1585               if (proposed_recipient != NULL /* not to the bus driver */ &&
1586                   addressed_recipient == proposed_recipient /* not eavesdropping */)
1587                 {
1588                   DBusError error2;
1589 
1590                   dbus_error_init (&error2);
1591                   requested_reply = bus_connections_check_reply (bus_connection_get_connections (sender),
1592                                                                  transaction,
1593                                                                  sender, addressed_recipient, message,
1594                                                                  &error2);
1595                   if (dbus_error_is_set (&error2))
1596                     {
1597                       dbus_move_error (&error2, error);
1598                       return FALSE;
1599                     }
1600                 }
1601             }
1602         }
1603       else
1604         {
1605           sender_policy = NULL;
1606         }
1607 
1608       /* First verify the SELinux access controls.  If allowed then
1609        * go on with the standard checks.
1610        */
1611       if (!bus_selinux_allows_send (sender, proposed_recipient,
1612 				    dbus_message_type_to_string (dbus_message_get_type (message)),
1613 				    dbus_message_get_interface (message),
1614 				    dbus_message_get_member (message),
1615 				    dbus_message_get_error_name (message),
1616 				    dest ? dest : DBUS_SERVICE_DBUS,
1617 				    activation_entry,
1618 				    error))
1619         {
1620           if (error != NULL && !dbus_error_is_set (error))
1621             {
1622               /* don't syslog this, just set the error: avc_has_perm should
1623                * have already written to either the audit log or syslog */
1624               complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1625                   "An SELinux policy prevents this sender from sending this "
1626                   "message to this recipient",
1627                   0, message, sender, proposed_recipient, FALSE, FALSE, error);
1628               _dbus_verbose ("SELinux security check denying send to service\n");
1629             }
1630 
1631           return FALSE;
1632         }
1633 
1634       /* next verify AppArmor access controls.  If allowed then
1635        * go on with the standard checks.
1636        */
1637       if (!bus_apparmor_allows_send (sender, proposed_recipient,
1638                                      requested_reply,
1639                                      bus_context_get_type (context),
1640                                      dbus_message_get_type (message),
1641                                      dbus_message_get_path (message),
1642                                      dbus_message_get_interface (message),
1643                                      dbus_message_get_member (message),
1644                                      dbus_message_get_error_name (message),
1645                                      dest ? dest : DBUS_SERVICE_DBUS,
1646                                      src ? src : DBUS_SERVICE_DBUS,
1647                                      activation_entry,
1648                                      error))
1649         return FALSE;
1650 
1651       if (!bus_connection_is_active (sender))
1652         {
1653           /* Policy for inactive connections is that they can only send
1654            * the hello message to the bus driver
1655            */
1656           if (proposed_recipient == NULL &&
1657               dbus_message_is_method_call (message,
1658                                            DBUS_INTERFACE_DBUS,
1659                                            "Hello"))
1660             {
1661               _dbus_verbose ("security check allowing %s message\n",
1662                              "Hello");
1663               return TRUE;
1664             }
1665           else
1666             {
1667               _dbus_verbose ("security check disallowing non-%s message\n",
1668                              "Hello");
1669 
1670               dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1671                               "Client tried to send a message other than %s without being registered",
1672                               "Hello");
1673 
1674               return FALSE;
1675             }
1676         }
1677     }
1678   else
1679     {
1680       sender_policy = NULL;
1681 
1682       /* If the sender is the bus driver, we assume any reply was a
1683        * requested reply as bus driver won't send bogus ones
1684        */
1685       if (addressed_recipient == proposed_recipient /* not eavesdropping */ &&
1686           dbus_message_get_reply_serial (message) != 0)
1687         requested_reply = TRUE;
1688     }
1689 
1690   _dbus_assert ((sender != NULL && sender_policy != NULL) ||
1691                 (sender == NULL && sender_policy == NULL));
1692 
1693   if (proposed_recipient != NULL)
1694     {
1695       /* only the bus driver can send to an inactive recipient (as it
1696        * owns no services, so other apps can't address it). Inactive
1697        * recipients can receive any message.
1698        */
1699       if (bus_connection_is_active (proposed_recipient))
1700         {
1701           recipient_policy = bus_connection_get_policy (proposed_recipient);
1702           _dbus_assert (recipient_policy != NULL);
1703         }
1704       else if (sender == NULL)
1705         {
1706           _dbus_verbose ("security check using NULL recipient policy for message from bus\n");
1707           recipient_policy = NULL;
1708         }
1709       else
1710         {
1711           _dbus_assert_not_reached ("a message was somehow sent to an inactive recipient from a source other than the message bus");
1712           recipient_policy = NULL;
1713         }
1714     }
1715   else
1716     recipient_policy = NULL;
1717 
1718   _dbus_assert ((proposed_recipient != NULL && recipient_policy != NULL) ||
1719                 (proposed_recipient != NULL && sender == NULL && recipient_policy == NULL) ||
1720                 (proposed_recipient == NULL && recipient_policy == NULL));
1721 
1722   log = FALSE;
1723   if (sender_policy &&
1724       !bus_client_policy_check_can_send (sender_policy,
1725                                          context->registry,
1726                                          requested_reply,
1727                                          proposed_recipient,
1728                                          message, &toggles, &log))
1729     {
1730       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1731           "Rejected send message", toggles,
1732           message, sender, proposed_recipient, requested_reply,
1733           (addressed_recipient == proposed_recipient), error);
1734       _dbus_verbose ("security policy disallowing message due to sender policy\n");
1735       return FALSE;
1736     }
1737 
1738   if (log)
1739     {
1740       /* We want to drop this message, and are only not doing so for backwards
1741        * compatibility. */
1742       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1743           "Would reject message", toggles,
1744           message, sender, proposed_recipient, requested_reply,
1745           TRUE, NULL);
1746     }
1747 
1748   if (recipient_policy &&
1749       !bus_client_policy_check_can_receive (recipient_policy,
1750                                             context->registry,
1751                                             requested_reply,
1752                                             sender,
1753                                             addressed_recipient, proposed_recipient,
1754                                             message, &toggles))
1755     {
1756       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1757           "Rejected receive message", toggles,
1758           message, sender, proposed_recipient, requested_reply,
1759           (addressed_recipient == proposed_recipient), error);
1760       _dbus_verbose ("security policy disallowing message due to recipient policy\n");
1761       return FALSE;
1762     }
1763 
1764   /* See if limits on size have been exceeded */
1765   if (proposed_recipient &&
1766       ((dbus_connection_get_outgoing_size (proposed_recipient) > context->limits.max_outgoing_bytes) ||
1767        (dbus_connection_get_outgoing_unix_fds (proposed_recipient) > context->limits.max_outgoing_unix_fds)))
1768     {
1769       complain_about_message (context, DBUS_ERROR_LIMITS_EXCEEDED,
1770           "Rejected: destination has a full message queue",
1771           0, message, sender, proposed_recipient, requested_reply, TRUE,
1772           error);
1773       _dbus_verbose ("security policy disallowing message due to full message queue\n");
1774       return FALSE;
1775     }
1776 
1777   /* Record that we will allow a reply here in the future (don't
1778    * bother if the recipient is the bus or this is an eavesdropping
1779    * connection). Only the addressed recipient may reply.
1780    *
1781    * This isn't done for activation attempts because they have no addressed
1782    * or proposed recipient; when we check whether to actually deliver the
1783    * message, later, we'll record the reply expectation at that point.
1784    */
1785   if (type == DBUS_MESSAGE_TYPE_METHOD_CALL &&
1786       sender &&
1787       addressed_recipient &&
1788       addressed_recipient == proposed_recipient && /* not eavesdropping */
1789       !bus_connections_expect_reply (bus_connection_get_connections (sender),
1790                                      transaction,
1791                                      sender, addressed_recipient,
1792                                      message, error))
1793     {
1794       _dbus_verbose ("Failed to record reply expectation or problem with the message expecting a reply\n");
1795       return FALSE;
1796     }
1797 
1798   _dbus_verbose ("security policy allowing message\n");
1799   return TRUE;
1800 }
1801 
1802 void
bus_context_check_all_watches(BusContext * context)1803 bus_context_check_all_watches (BusContext *context)
1804 {
1805   DBusList *link;
1806   dbus_bool_t enabled = TRUE;
1807 
1808   if (bus_connections_get_n_incomplete (context->connections) >=
1809       bus_context_get_max_incomplete_connections (context))
1810     {
1811       enabled = FALSE;
1812     }
1813 
1814   if (context->watches_enabled == enabled)
1815     return;
1816 
1817   context->watches_enabled = enabled;
1818 
1819   for (link = _dbus_list_get_first_link (&context->servers);
1820        link != NULL;
1821        link = _dbus_list_get_next_link (&context->servers, link))
1822     {
1823       /* A BusContext might contains several DBusServer (if there are
1824        * several <listen> configuration items) and a DBusServer might
1825        * contain several DBusWatch in its DBusWatchList (if getaddrinfo
1826        * returns several addresses on a dual IPv4-IPv6 stack or if
1827        * systemd passes several fds).
1828        * We want to enable/disable them all.
1829        */
1830       DBusServer *server = link->data;
1831       _dbus_server_toggle_all_watches (server, enabled);
1832     }
1833 }
1834