Merge branch 'dbus-1.2'
[platform/upstream/dbus.git] / bus / selinux.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
2  * selinux.c  SELinux security checks for D-Bus
3  *
4  * Author: Matthew Rickard <mjricka@epoch.ncsc.mil>
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 #include <dbus/dbus-internals.h>
24 #include <dbus/dbus-string.h>
25 #ifndef DBUS_WIN
26 #include <dbus/dbus-userdb.h>
27 #endif
28 #include "selinux.h"
29 #include "services.h"
30 #include "policy.h"
31 #include "utils.h"
32 #include "config-parser.h"
33
34 #ifdef HAVE_ERRNO_H
35 #include <errno.h>
36 #endif
37 #ifdef HAVE_SELINUX
38 #include <sys/types.h>
39 #include <unistd.h>
40 #include <limits.h>
41 #include <pthread.h>
42 #include <syslog.h>
43 #include <selinux/selinux.h>
44 #include <selinux/avc.h>
45 #include <selinux/av_permissions.h>
46 #include <selinux/flask.h>
47 #include <signal.h>
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <grp.h>
51 #endif /* HAVE_SELINUX */
52 #ifdef HAVE_LIBAUDIT
53 #include <cap-ng.h>
54 #include <libaudit.h>
55 #endif /* HAVE_LIBAUDIT */
56
57 #define BUS_SID_FROM_SELINUX(sid)  ((BusSELinuxID*) (sid))
58 #define SELINUX_SID_FROM_BUS(sid)  ((security_id_t) (sid))
59
60 #ifdef HAVE_SELINUX
61 /* Store the value telling us if SELinux is enabled in the kernel. */
62 static dbus_bool_t selinux_enabled = FALSE;
63
64 /* Store an avc_entry_ref to speed AVC decisions. */
65 static struct avc_entry_ref aeref;
66
67 /* Store the SID of the bus itself to use as the default. */
68 static security_id_t bus_sid = SECSID_WILD;
69
70 /* Thread to listen for SELinux status changes via netlink. */
71 static pthread_t avc_notify_thread;
72
73 /* Prototypes for AVC callback functions.  */
74 static void log_callback (const char *fmt, ...);
75 static void log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft);
76 static void *avc_create_thread (void (*run) (void));
77 static void avc_stop_thread (void *thread);
78 static void *avc_alloc_lock (void);
79 static void avc_get_lock (void *lock);
80 static void avc_release_lock (void *lock);
81 static void avc_free_lock (void *lock);
82
83 /* AVC callback structures for use in avc_init.  */
84 static const struct avc_memory_callback mem_cb =
85 {
86   .func_malloc = dbus_malloc,
87   .func_free = dbus_free
88 };
89 static const struct avc_log_callback log_cb =
90 {
91   .func_log = log_callback,
92   .func_audit = log_audit_callback
93 };
94 static const struct avc_thread_callback thread_cb =
95 {
96   .func_create_thread = avc_create_thread,
97   .func_stop_thread = avc_stop_thread
98 };
99 static const struct avc_lock_callback lock_cb =
100 {
101   .func_alloc_lock = avc_alloc_lock,
102   .func_get_lock = avc_get_lock,
103   .func_release_lock = avc_release_lock,
104   .func_free_lock = avc_free_lock
105 };
106 #endif /* HAVE_SELINUX */
107
108 /**
109  * Log callback to log denial messages from the AVC.
110  * This is used in avc_init.  Logs to both standard
111  * error and syslogd.
112  *
113  * @param fmt the format string
114  * @param variable argument list
115  */
116 #ifdef HAVE_SELINUX
117
118 #ifdef HAVE_LIBAUDIT
119 static int audit_fd = -1;
120 #endif
121
122 void
123 bus_selinux_audit_init(void)
124 {
125 #ifdef HAVE_LIBAUDIT  
126   audit_fd = audit_open ();
127
128   if (audit_fd < 0)
129     {
130       /* If kernel doesn't support audit, bail out */
131       if (errno == EINVAL || errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT)
132         return;
133       /* If user bus, bail out */
134       if (errno == EPERM && getuid() != 0)
135         return;
136       _dbus_warn ("Failed opening connection to the audit subsystem");
137     }
138 #endif /* HAVE_LIBAUDIT */
139 }
140
141 static void 
142 log_callback (const char *fmt, ...) 
143 {
144   va_list ap;
145
146   va_start(ap, fmt);
147
148 #ifdef HAVE_LIBAUDIT
149   if (audit_fd >= 0)
150   {
151     capng_get_caps_process();
152     if (capng_have_capability(CAPNG_EFFECTIVE, CAP_AUDIT_WRITE))
153     {
154       char buf[PATH_MAX*2];
155     
156       /* FIXME: need to change this to show real user */
157       vsnprintf(buf, sizeof(buf), fmt, ap);
158       audit_log_user_avc_message(audit_fd, AUDIT_USER_AVC, buf, NULL, NULL,
159                                NULL, getuid());
160       return;
161     }
162   }
163 #endif /* HAVE_LIBAUDIT */
164   
165   vsyslog (LOG_INFO, fmt, ap);
166   va_end(ap);
167 }
168
169 /**
170  * On a policy reload we need to reparse the SELinux configuration file, since
171  * this could have changed.  Send a SIGHUP to reload all configs.
172  */
173 static int
174 policy_reload_callback (u_int32_t event, security_id_t ssid, 
175                         security_id_t tsid, security_class_t tclass, 
176                         access_vector_t perms, access_vector_t *out_retained)
177 {
178   if (event == AVC_CALLBACK_RESET)
179     return raise (SIGHUP);
180   
181   return 0;
182 }
183
184 /**
185  * Log any auxiliary data 
186  */
187 static void
188 log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
189 {
190   DBusString *audmsg = data;
191
192   if (bufleft > (size_t) _dbus_string_get_length(audmsg))
193     {
194       _dbus_string_copy_to_buffer_with_nul (audmsg, buf, bufleft);
195     }
196   else
197     {
198       DBusString s;
199
200       _dbus_string_init_const(&s, "Buffer too small for audit message");
201
202       if (bufleft > (size_t) _dbus_string_get_length(&s))
203         _dbus_string_copy_to_buffer_with_nul (&s, buf, bufleft);
204     }
205 }
206
207 /**
208  * Create thread to notify the AVC of enforcing and policy reload
209  * changes via netlink.
210  *
211  * @param run the thread run function
212  * @return pointer to the thread
213  */
214 static void *
215 avc_create_thread (void (*run) (void))
216 {
217   int rc;
218
219   rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
220   if (rc != 0)
221     {
222       _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
223       exit (1);
224     }
225   return &avc_notify_thread;
226 }
227
228 /* Stop AVC netlink thread.  */
229 static void
230 avc_stop_thread (void *thread)
231 {
232   pthread_cancel (*(pthread_t *) thread);
233 }
234
235 /* Allocate a new AVC lock.  */
236 static void *
237 avc_alloc_lock (void)
238 {
239   pthread_mutex_t *avc_mutex;
240
241   avc_mutex = dbus_new (pthread_mutex_t, 1);
242   if (avc_mutex == NULL)
243     {
244       _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
245       exit (1);
246     }
247   pthread_mutex_init (avc_mutex, NULL);
248
249   return avc_mutex;
250 }
251
252 /* Acquire an AVC lock.  */
253 static void
254 avc_get_lock (void *lock)
255 {
256   pthread_mutex_lock (lock);
257 }
258
259 /* Release an AVC lock.  */
260 static void
261 avc_release_lock (void *lock)
262 {
263   pthread_mutex_unlock (lock);
264 }
265
266 /* Free an AVC lock.  */
267 static void
268 avc_free_lock (void *lock)
269 {
270   pthread_mutex_destroy (lock);
271   dbus_free (lock);
272 }
273 #endif /* HAVE_SELINUX */
274
275 /**
276  * Return whether or not SELinux is enabled; must be
277  * called after bus_selinux_init.
278  */
279 dbus_bool_t
280 bus_selinux_enabled (void)
281 {
282 #ifdef HAVE_SELINUX
283   return selinux_enabled;
284 #else
285   return FALSE;
286 #endif /* HAVE_SELINUX */
287 }
288
289 /**
290  * Do early initialization; determine whether SELinux is enabled.
291  */
292 dbus_bool_t
293 bus_selinux_pre_init (void)
294 {
295 #ifdef HAVE_SELINUX
296   int r;
297   _dbus_assert (bus_sid == SECSID_WILD);
298   
299   /* Determine if we are running an SELinux kernel. */
300   r = is_selinux_enabled ();
301   if (r < 0)
302     {
303       _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
304                   _dbus_strerror (errno));
305       return FALSE;
306     }
307
308   selinux_enabled = r != 0;
309   return TRUE;
310 #else
311   return TRUE;
312 #endif
313 }
314
315 /**
316  * Initialize the user space access vector cache (AVC) for D-Bus and set up
317  * logging callbacks.
318  */
319 dbus_bool_t
320 bus_selinux_full_init (void)
321 {
322 #ifdef HAVE_SELINUX
323   char *bus_context;
324
325   _dbus_assert (bus_sid == SECSID_WILD);
326   
327   if (!selinux_enabled)
328     {
329       _dbus_verbose ("SELinux not enabled in this kernel.\n");
330       return TRUE;
331     }
332
333   _dbus_verbose ("SELinux is enabled in this kernel.\n");
334
335   avc_entry_ref_init (&aeref);
336   if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
337     {
338       _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
339       return FALSE;
340     }
341   else
342     {
343       openlog ("dbus", LOG_PERROR, LOG_USER);
344       _dbus_verbose ("Access Vector Cache (AVC) started.\n");
345     }
346
347   if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
348                        NULL, NULL, 0, 0) < 0)
349     {
350       _dbus_warn ("Failed to add policy reload callback: %s\n",
351                   _dbus_strerror (errno));
352       avc_destroy ();
353       return FALSE;
354     }
355
356   bus_context = NULL;
357   bus_sid = SECSID_WILD;
358
359   if (getcon (&bus_context) < 0)
360     {
361       _dbus_verbose ("Error getting context of bus: %s\n",
362                      _dbus_strerror (errno));
363       return FALSE;
364     }
365       
366   if (avc_context_to_sid (bus_context, &bus_sid) < 0)
367     {
368       _dbus_verbose ("Error getting SID from bus context: %s\n",
369                      _dbus_strerror (errno));
370       freecon (bus_context);
371       return FALSE;
372     }
373
374   freecon (bus_context);
375   
376 #endif /* HAVE_SELINUX */
377   return TRUE;
378 }
379
380 /**
381  * Decrement SID reference count.
382  * 
383  * @param sid the SID to decrement
384  */
385 void
386 bus_selinux_id_unref (BusSELinuxID *sid)
387 {
388 #ifdef HAVE_SELINUX
389   if (!selinux_enabled)
390     return;
391
392   _dbus_assert (sid != NULL);
393   
394   sidput (SELINUX_SID_FROM_BUS (sid));
395 #endif /* HAVE_SELINUX */
396 }
397
398 void
399 bus_selinux_id_ref (BusSELinuxID *sid)
400 {
401 #ifdef HAVE_SELINUX
402   if (!selinux_enabled)
403     return;
404
405   _dbus_assert (sid != NULL);
406   
407   sidget (SELINUX_SID_FROM_BUS (sid));
408 #endif /* HAVE_SELINUX */
409 }
410
411 /**
412  * Determine if the SELinux security policy allows the given sender
413  * security context to go to the given recipient security context.
414  * This function determines if the requested permissions are to be
415  * granted from the connection to the message bus or to another
416  * optionally supplied security identifier (e.g. for a service
417  * context).  Currently these permissions are either send_msg or
418  * acquire_svc in the dbus class.
419  *
420  * @param sender_sid source security context
421  * @param override_sid is the target security context.  If SECSID_WILD this will
422  *        use the context of the bus itself (e.g. the default).
423  * @param target_class is the target security class.
424  * @param requested is the requested permissions.
425  * @returns #TRUE if security policy allows the send.
426  */
427 #ifdef HAVE_SELINUX
428 static dbus_bool_t
429 bus_selinux_check (BusSELinuxID        *sender_sid,
430                    BusSELinuxID        *override_sid,
431                    security_class_t     target_class,
432                    access_vector_t      requested,
433                    DBusString          *auxdata)
434 {
435   if (!selinux_enabled)
436     return TRUE;
437
438   /* Make the security check.  AVC checks enforcing mode here as well. */
439   if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
440                     override_sid ?
441                     SELINUX_SID_FROM_BUS (override_sid) :
442                     SELINUX_SID_FROM_BUS (bus_sid), 
443                     target_class, requested, &aeref, auxdata) < 0)
444     {
445     switch (errno)
446       {
447       case EACCES:
448         _dbus_verbose ("SELinux denying due to security policy.\n");
449         return FALSE;
450       case EINVAL:
451         _dbus_verbose ("SELinux denying due to invalid security context.\n");
452         return FALSE;
453       default:
454         _dbus_verbose ("SELinux denying due to: %s\n", _dbus_strerror (errno));
455         return FALSE;
456       }
457     }
458   else
459     return TRUE;
460 }
461 #endif /* HAVE_SELINUX */
462
463 /**
464  * Returns true if the given connection can acquire a service,
465  * assuming the given security ID is needed for that service.
466  *
467  * @param connection connection that wants to own the service
468  * @param service_sid the SID of the service from the table
469  * @returns #TRUE if acquire is permitted.
470  */
471 dbus_bool_t
472 bus_selinux_allows_acquire_service (DBusConnection     *connection,
473                                     BusSELinuxID       *service_sid,
474                                     const char         *service_name,
475                                     DBusError          *error)
476 {
477 #ifdef HAVE_SELINUX
478   BusSELinuxID *connection_sid;
479   unsigned long spid;
480   DBusString auxdata;
481   dbus_bool_t ret;
482   
483   if (!selinux_enabled)
484     return TRUE;
485   
486   connection_sid = bus_connection_get_selinux_id (connection);
487   if (!dbus_connection_get_unix_process_id (connection, &spid))
488     spid = 0;
489
490   if (!_dbus_string_init (&auxdata))
491     goto oom;
492  
493   if (!_dbus_string_append (&auxdata, "service="))
494     goto oom;
495
496   if (!_dbus_string_append (&auxdata, service_name))
497     goto oom;
498
499   if (spid)
500     {
501       if (!_dbus_string_append (&auxdata, " spid="))
502         goto oom;
503
504       if (!_dbus_string_append_uint (&auxdata, spid))
505         goto oom;
506     }
507   
508   ret = bus_selinux_check (connection_sid,
509                            service_sid,
510                            SECCLASS_DBUS,
511                            DBUS__ACQUIRE_SVC,
512                            &auxdata);
513
514   _dbus_string_free (&auxdata);
515   return ret;
516
517  oom:
518   _dbus_string_free (&auxdata);
519   BUS_SET_OOM (error);
520   return FALSE;
521
522 #else
523   return TRUE;
524 #endif /* HAVE_SELINUX */
525 }
526
527 /**
528  * Check if SELinux security controls allow the message to be sent to a
529  * particular connection based on the security context of the sender and
530  * that of the receiver. The destination connection need not be the
531  * addressed recipient, it could be an "eavesdropper"
532  *
533  * @param sender the sender of the message.
534  * @param proposed_recipient the connection the message is to be sent to.
535  * @returns whether to allow the send
536  */
537 dbus_bool_t
538 bus_selinux_allows_send (DBusConnection     *sender,
539                          DBusConnection     *proposed_recipient,
540                          const char         *msgtype,
541                          const char         *interface,
542                          const char         *member,
543                          const char         *error_name,
544                          const char         *destination,
545                          DBusError          *error)
546 {
547 #ifdef HAVE_SELINUX
548   BusSELinuxID *recipient_sid;
549   BusSELinuxID *sender_sid;
550   unsigned long spid, tpid;
551   DBusString auxdata;
552   dbus_bool_t ret;
553   dbus_bool_t string_alloced;
554
555   if (!selinux_enabled)
556     return TRUE;
557
558   if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
559     spid = 0;
560   if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
561     tpid = 0;
562
563   string_alloced = FALSE;
564   if (!_dbus_string_init (&auxdata))
565     goto oom;
566   string_alloced = TRUE;
567
568   if (!_dbus_string_append (&auxdata, "msgtype="))
569     goto oom;
570
571   if (!_dbus_string_append (&auxdata, msgtype))
572     goto oom;
573
574   if (interface)
575     {
576       if (!_dbus_string_append (&auxdata, " interface="))
577         goto oom;
578       if (!_dbus_string_append (&auxdata, interface))
579         goto oom;
580     }
581
582   if (member)
583     {
584       if (!_dbus_string_append (&auxdata, " member="))
585         goto oom;
586       if (!_dbus_string_append (&auxdata, member))
587         goto oom;
588     }
589
590   if (error_name)
591     {
592       if (!_dbus_string_append (&auxdata, " error_name="))
593         goto oom;
594       if (!_dbus_string_append (&auxdata, error_name))
595         goto oom;
596     }
597
598   if (destination)
599     {
600       if (!_dbus_string_append (&auxdata, " dest="))
601         goto oom;
602       if (!_dbus_string_append (&auxdata, destination))
603         goto oom;
604     }
605
606   if (spid)
607     {
608       if (!_dbus_string_append (&auxdata, " spid="))
609         goto oom;
610
611       if (!_dbus_string_append_uint (&auxdata, spid))
612         goto oom;
613     }
614
615   if (tpid)
616     {
617       if (!_dbus_string_append (&auxdata, " tpid="))
618         goto oom;
619
620       if (!_dbus_string_append_uint (&auxdata, tpid))
621         goto oom;
622     }
623
624   sender_sid = bus_connection_get_selinux_id (sender);
625   /* A NULL proposed_recipient means the bus itself. */
626   if (proposed_recipient)
627     recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
628   else
629     recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
630
631   ret = bus_selinux_check (sender_sid, 
632                            recipient_sid,
633                            SECCLASS_DBUS, 
634                            DBUS__SEND_MSG,
635                            &auxdata);
636
637   _dbus_string_free (&auxdata);
638
639   return ret;
640
641  oom:
642   if (string_alloced)
643     _dbus_string_free (&auxdata);
644   BUS_SET_OOM (error);
645   return FALSE;
646   
647 #else
648   return TRUE;
649 #endif /* HAVE_SELINUX */
650 }
651
652 dbus_bool_t
653 bus_selinux_append_context (DBusMessage    *message,
654                             BusSELinuxID   *sid,
655                             DBusError      *error)
656 {
657 #ifdef HAVE_SELINUX
658   char *context;
659
660   if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
661     {
662       if (errno == ENOMEM)
663         BUS_SET_OOM (error);
664       else
665         dbus_set_error (error, DBUS_ERROR_FAILED,
666                         "Error getting context from SID: %s\n",
667                         _dbus_strerror (errno));
668       return FALSE;
669     }
670   if (!dbus_message_append_args (message,
671                                  DBUS_TYPE_ARRAY,
672                                  DBUS_TYPE_BYTE,
673                                  &context,
674                                  strlen (context),
675                                  DBUS_TYPE_INVALID))
676     {
677       _DBUS_SET_OOM (error);
678       return FALSE;
679     }
680   freecon (context);
681   return TRUE;
682 #else
683   return TRUE;
684 #endif
685 }
686
687 /**
688  * Gets the security context of a connection to the bus. It is up to
689  * the caller to freecon() when they are done. 
690  *
691  * @param connection the connection to get the context of.
692  * @param con the location to store the security context.
693  * @returns #TRUE if context is successfully obtained.
694  */
695 #ifdef HAVE_SELINUX
696 static dbus_bool_t
697 bus_connection_read_selinux_context (DBusConnection     *connection,
698                                      char              **con)
699 {
700   int fd;
701
702   if (!selinux_enabled)
703     return FALSE;
704
705   _dbus_assert (connection != NULL);
706   
707   if (!dbus_connection_get_unix_fd (connection, &fd))
708     {
709       _dbus_verbose ("Failed to get file descriptor of socket.\n");
710       return FALSE;
711     }
712   
713   if (getpeercon (fd, con) < 0)
714     {
715       _dbus_verbose ("Error getting context of socket peer: %s\n",
716                      _dbus_strerror (errno));
717       return FALSE;
718     }
719   
720   _dbus_verbose ("Successfully read connection context.\n");
721   return TRUE;
722 }
723 #endif /* HAVE_SELINUX */
724
725 /**
726  * Read the SELinux ID from the connection.
727  *
728  * @param connection the connection to read from
729  * @returns the SID if successfully determined, #NULL otherwise.
730  */
731 BusSELinuxID*
732 bus_selinux_init_connection_id (DBusConnection *connection,
733                                 DBusError      *error)
734 {
735 #ifdef HAVE_SELINUX
736   char *con;
737   security_id_t sid;
738   
739   if (!selinux_enabled)
740     return NULL;
741
742   if (!bus_connection_read_selinux_context (connection, &con))
743     {
744       dbus_set_error (error, DBUS_ERROR_FAILED,
745                       "Failed to read an SELinux context from connection");
746       _dbus_verbose ("Error getting peer context.\n");
747       return NULL;
748     }
749
750   _dbus_verbose ("Converting context to SID to store on connection\n");
751
752   if (avc_context_to_sid (con, &sid) < 0)
753     {
754       if (errno == ENOMEM)
755         BUS_SET_OOM (error);
756       else
757         dbus_set_error (error, DBUS_ERROR_FAILED,
758                         "Error getting SID from context \"%s\": %s\n",
759                         con, _dbus_strerror (errno));
760       
761       _dbus_warn ("Error getting SID from context \"%s\": %s\n",
762                   con, _dbus_strerror (errno));
763       
764       freecon (con);
765       return NULL;
766     }
767  
768   freecon (con); 
769   return BUS_SID_FROM_SELINUX (sid);
770 #else
771   return NULL;
772 #endif /* HAVE_SELINUX */
773 }
774
775
776 /**
777  * Function for freeing hash table data.  These SIDs
778  * should no longer be referenced.
779  */
780 static void
781 bus_selinux_id_table_free_value (BusSELinuxID *sid)
782 {
783 #ifdef HAVE_SELINUX
784   /* NULL sometimes due to how DBusHashTable works */
785   if (sid)
786     bus_selinux_id_unref (sid);
787 #endif /* HAVE_SELINUX */
788 }
789
790 /**
791  * Creates a new table mapping service names to security ID.
792  * A security ID is a "compiled" security context, a security
793  * context is just a string.
794  *
795  * @returns the new table or #NULL if no memory
796  */
797 DBusHashTable*
798 bus_selinux_id_table_new (void)
799 {
800   return _dbus_hash_table_new (DBUS_HASH_STRING,
801                                (DBusFreeFunction) dbus_free,
802                                (DBusFreeFunction) bus_selinux_id_table_free_value);
803 }
804
805 /** 
806  * Hashes a service name and service context into the service SID
807  * table as a string and a SID.
808  *
809  * @param service_name is the name of the service.
810  * @param service_context is the context of the service.
811  * @param service_table is the table to hash them into.
812  * @return #FALSE if not enough memory
813  */
814 dbus_bool_t
815 bus_selinux_id_table_insert (DBusHashTable *service_table,
816                              const char    *service_name,
817                              const char    *service_context)
818 {
819 #ifdef HAVE_SELINUX
820   dbus_bool_t retval;
821   security_id_t sid;
822   char *key;
823
824   if (!selinux_enabled)
825     return TRUE;
826
827   sid = SECSID_WILD;
828   retval = FALSE;
829
830   key = _dbus_strdup (service_name);
831   if (key == NULL)
832     return retval;
833   
834   if (avc_context_to_sid ((char *) service_context, &sid) < 0)
835     {
836       if (errno == ENOMEM)
837         {
838           dbus_free (key);
839           return FALSE;
840         }
841
842       _dbus_warn ("Error getting SID from context \"%s\": %s\n",
843                   (char *) service_context,
844                   _dbus_strerror (errno));
845       goto out;
846     }
847
848   if (!_dbus_hash_table_insert_string (service_table,
849                                        key,
850                                        BUS_SID_FROM_SELINUX (sid)))
851     goto out;
852
853   _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
854                   key, 
855                   sid->ctx);
856
857   /* These are owned by the hash, so clear them to avoid unref */
858   key = NULL;
859   sid = SECSID_WILD;
860
861   retval = TRUE;
862   
863  out:
864   if (sid != SECSID_WILD)
865     sidput (sid);
866
867   if (key)
868     dbus_free (key);
869
870   return retval;
871 #else
872   return TRUE;
873 #endif /* HAVE_SELINUX */
874 }
875
876
877 /**
878  * Find the security identifier associated with a particular service
879  * name.  Return a pointer to this SID, or #NULL/SECSID_WILD if the
880  * service is not found in the hash table.  This should be nearly a
881  * constant time operation.  If SELinux support is not available,
882  * always return NULL.
883  *
884  * @param service_table the hash table to check for service name.
885  * @param service_name the name of the service to look for.
886  * @returns the SELinux ID associated with the service
887  */
888 BusSELinuxID*
889 bus_selinux_id_table_lookup (DBusHashTable    *service_table,
890                              const DBusString *service_name)
891 {
892 #ifdef HAVE_SELINUX
893   security_id_t sid;
894
895   sid = SECSID_WILD;     /* default context */
896
897   if (!selinux_enabled)
898     return NULL;
899   
900   _dbus_verbose ("Looking up service SID for %s\n",
901                  _dbus_string_get_const_data (service_name));
902
903   sid = _dbus_hash_table_lookup_string (service_table,
904                                         _dbus_string_get_const_data (service_name));
905
906   if (sid == SECSID_WILD)
907     _dbus_verbose ("Service %s not found\n", 
908                    _dbus_string_get_const_data (service_name));
909   else
910     _dbus_verbose ("Service %s found\n", 
911                    _dbus_string_get_const_data (service_name));
912
913   return BUS_SID_FROM_SELINUX (sid);
914 #endif /* HAVE_SELINUX */
915   return NULL;
916 }
917
918 /**
919  * Get the SELinux policy root.  This is used to find the D-Bus
920  * specific config file within the policy.
921  */
922 const char *
923 bus_selinux_get_policy_root (void)
924 {
925 #ifdef HAVE_SELINUX
926   return selinux_policy_root ();
927 #else
928   return NULL;
929 #endif /* HAVE_SELINUX */
930
931
932 /**
933  * For debugging:  Print out the current hash table of service SIDs.
934  */
935 void
936 bus_selinux_id_table_print (DBusHashTable *service_table)
937 {
938 #ifdef DBUS_ENABLE_VERBOSE_MODE
939 #ifdef HAVE_SELINUX
940   DBusHashIter iter;
941
942   if (!selinux_enabled)
943     return;
944   
945   _dbus_verbose ("Service SID Table:\n");
946   _dbus_hash_iter_init (service_table, &iter);
947   while (_dbus_hash_iter_next (&iter))
948     {
949       const char *key = _dbus_hash_iter_get_string_key (&iter);
950       security_id_t sid = _dbus_hash_iter_get_value (&iter);
951       _dbus_verbose ("The key is %s\n", key);
952       _dbus_verbose ("The context is %s\n", sid->ctx);
953       _dbus_verbose ("The refcount is %d\n", sid->refcnt);
954     }
955 #endif /* HAVE_SELINUX */
956 #endif /* DBUS_ENABLE_VERBOSE_MODE */
957 }
958
959
960 #ifdef DBUS_ENABLE_VERBOSE_MODE
961 #ifdef HAVE_SELINUX
962 /**
963  * Print out some AVC statistics.
964  */
965 static void
966 bus_avc_print_stats (void)
967 {
968   struct avc_cache_stats cstats;
969
970   if (!selinux_enabled)
971     return;
972   
973   _dbus_verbose ("AVC Statistics:\n");
974   avc_cache_stats (&cstats);
975   avc_av_stats ();
976   _dbus_verbose ("AVC Cache Statistics:\n");
977   _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
978   _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
979   _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
980   _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
981   _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
982   _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
983   _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
984   _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
985 }
986 #endif /* HAVE_SELINUX */
987 #endif /* DBUS_ENABLE_VERBOSE_MODE */
988
989
990 /**
991  * Destroy the AVC before we terminate.
992  */
993 void
994 bus_selinux_shutdown (void)
995 {
996 #ifdef HAVE_SELINUX
997   if (!selinux_enabled)
998     return;
999
1000   _dbus_verbose ("AVC shutdown\n");
1001
1002   if (bus_sid != SECSID_WILD)
1003     {
1004       sidput (bus_sid);
1005       bus_sid = SECSID_WILD;
1006
1007 #ifdef DBUS_ENABLE_VERBOSE_MODE
1008  
1009       if (_dbus_is_verbose()) 
1010         bus_avc_print_stats ();
1011  
1012 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1013
1014       avc_destroy ();
1015 #ifdef HAVE_LIBAUDIT
1016       audit_close (audit_fd);
1017 #endif /* HAVE_LIBAUDIT */
1018     }
1019 #endif /* HAVE_SELINUX */
1020 }
1021
1022 /* The !HAVE_LIBAUDIT case lives in dbus-sysdeps-util-unix.c */
1023 #ifdef HAVE_LIBAUDIT
1024 /**
1025  * Changes the user and group the bus is running as.
1026  *
1027  * @param user the user to become
1028  * @param error return location for errors
1029  * @returns #FALSE on failure
1030  */
1031 dbus_bool_t
1032 _dbus_change_to_daemon_user  (const char    *user,
1033                               DBusError     *error)
1034 {
1035   dbus_uid_t uid;
1036   dbus_gid_t gid;
1037   DBusString u;
1038
1039   _dbus_string_init_const (&u, user);
1040
1041   if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
1042     {
1043       dbus_set_error (error, DBUS_ERROR_FAILED,
1044                       "User '%s' does not appear to exist?",
1045                       user);
1046       return FALSE;
1047     }
1048
1049   /* If we were root */
1050   if (_dbus_geteuid () == 0)
1051     {
1052       int rc;
1053
1054       capng_clear (CAPNG_SELECT_BOTH);
1055       capng_update (CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
1056                     CAP_AUDIT_WRITE);
1057       rc = capng_change_id (uid, gid, 0);
1058       if (rc)
1059         {
1060           switch (rc) {
1061             default:
1062               dbus_set_error (error, DBUS_ERROR_FAILED,
1063                               "Failed to drop capabilities: %s\n",
1064                               _dbus_strerror (errno));
1065               break;
1066             case -4:
1067               dbus_set_error (error, _dbus_error_from_errno (errno),
1068                               "Failed to set GID to %lu: %s", gid,
1069                               _dbus_strerror (errno));
1070               break;
1071             case -5:
1072               _dbus_warn ("Failed to drop supplementary groups: %s\n",
1073                           _dbus_strerror (errno));
1074               break;
1075             case -6:
1076               dbus_set_error (error, _dbus_error_from_errno (errno),
1077                               "Failed to set UID to %lu: %s", uid,
1078                               _dbus_strerror (errno));
1079               break;
1080             case -7:
1081               dbus_set_error (error, _dbus_error_from_errno (errno),
1082                               "Failed to unset keep-capabilities: %s\n",
1083                               _dbus_strerror (errno));
1084               break;
1085           }
1086           return FALSE;
1087         }
1088     }
1089
1090  return TRUE;
1091 }
1092 #endif