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