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