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