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