2007-06-15 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 <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 static 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   audit_init ();
354
355   return TRUE;
356 #else
357   return TRUE;
358 #endif /* HAVE_SELINUX */
359 }
360
361 /**
362  * Decrement SID reference count.
363  * 
364  * @param sid the SID to decrement
365  */
366 void
367 bus_selinux_id_unref (BusSELinuxID *sid)
368 {
369 #ifdef HAVE_SELINUX
370   if (!selinux_enabled)
371     return;
372
373   _dbus_assert (sid != NULL);
374   
375   sidput (SELINUX_SID_FROM_BUS (sid));
376 #endif /* HAVE_SELINUX */
377 }
378
379 void
380 bus_selinux_id_ref (BusSELinuxID *sid)
381 {
382 #ifdef HAVE_SELINUX
383   if (!selinux_enabled)
384     return;
385
386   _dbus_assert (sid != NULL);
387   
388   sidget (SELINUX_SID_FROM_BUS (sid));
389 #endif /* HAVE_SELINUX */
390 }
391
392 /**
393  * Determine if the SELinux security policy allows the given sender
394  * security context to go to the given recipient security context.
395  * This function determines if the requested permissions are to be
396  * granted from the connection to the message bus or to another
397  * optionally supplied security identifier (e.g. for a service
398  * context).  Currently these permissions are either send_msg or
399  * acquire_svc in the dbus class.
400  *
401  * @param sender_sid source security context
402  * @param override_sid is the target security context.  If SECSID_WILD this will
403  *        use the context of the bus itself (e.g. the default).
404  * @param target_class is the target security class.
405  * @param requested is the requested permissions.
406  * @returns #TRUE if security policy allows the send.
407  */
408 #ifdef HAVE_SELINUX
409 static dbus_bool_t
410 bus_selinux_check (BusSELinuxID        *sender_sid,
411                    BusSELinuxID        *override_sid,
412                    security_class_t     target_class,
413                    access_vector_t      requested,
414                    DBusString          *auxdata)
415 {
416   if (!selinux_enabled)
417     return TRUE;
418
419   /* Make the security check.  AVC checks enforcing mode here as well. */
420   if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
421                     override_sid ?
422                     SELINUX_SID_FROM_BUS (override_sid) :
423                     SELINUX_SID_FROM_BUS (bus_sid), 
424                     target_class, requested, &aeref, auxdata) < 0)
425     {
426       _dbus_verbose ("SELinux denying due to security policy.\n");
427       return FALSE;
428     }
429   else
430     return TRUE;
431 }
432 #endif /* HAVE_SELINUX */
433
434 /**
435  * Returns true if the given connection can acquire a service,
436  * assuming the given security ID is needed for that service.
437  *
438  * @param connection connection that wants to own the service
439  * @param service_sid the SID of the service from the table
440  * @returns #TRUE if acquire is permitted.
441  */
442 dbus_bool_t
443 bus_selinux_allows_acquire_service (DBusConnection     *connection,
444                                     BusSELinuxID       *service_sid,
445                                     const char         *service_name,
446                                     DBusError          *error)
447 {
448 #ifdef HAVE_SELINUX
449   BusSELinuxID *connection_sid;
450   unsigned long spid;
451   DBusString auxdata;
452   dbus_bool_t ret;
453   
454   if (!selinux_enabled)
455     return TRUE;
456   
457   connection_sid = bus_connection_get_selinux_id (connection);
458   if (!dbus_connection_get_unix_process_id (connection, &spid))
459     spid = 0;
460
461   if (!_dbus_string_init (&auxdata))
462     goto oom;
463  
464   if (!_dbus_string_append (&auxdata, "service="))
465     goto oom;
466
467   if (!_dbus_string_append (&auxdata, service_name))
468     goto oom;
469
470   if (spid)
471     {
472       if (!_dbus_string_append (&auxdata, " spid="))
473         goto oom;
474
475       if (!_dbus_string_append_uint (&auxdata, spid))
476         goto oom;
477     }
478   
479   ret = bus_selinux_check (connection_sid,
480                            service_sid,
481                            SECCLASS_DBUS,
482                            DBUS__ACQUIRE_SVC,
483                            &auxdata);
484
485   _dbus_string_free (&auxdata);
486   return ret;
487
488  oom:
489   _dbus_string_free (&auxdata);
490   BUS_SET_OOM (error);
491   return FALSE;
492
493 #else
494   return TRUE;
495 #endif /* HAVE_SELINUX */
496 }
497
498 /**
499  * Check if SELinux security controls allow the message to be sent to a
500  * particular connection based on the security context of the sender and
501  * that of the receiver. The destination connection need not be the
502  * addressed recipient, it could be an "eavesdropper"
503  *
504  * @param sender the sender of the message.
505  * @param proposed_recipient the connection the message is to be sent to.
506  * @returns whether to allow the send
507  */
508 dbus_bool_t
509 bus_selinux_allows_send (DBusConnection     *sender,
510                          DBusConnection     *proposed_recipient,
511                          const char         *msgtype,
512                          const char         *interface,
513                          const char         *member,
514                          const char         *error_name,
515                          const char         *destination,
516                          DBusError          *error)
517 {
518 #ifdef HAVE_SELINUX
519   BusSELinuxID *recipient_sid;
520   BusSELinuxID *sender_sid;
521   unsigned long spid, tpid;
522   DBusString auxdata;
523   dbus_bool_t ret;
524   dbus_bool_t string_alloced;
525
526   if (!selinux_enabled)
527     return TRUE;
528
529   if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
530     spid = 0;
531   if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
532     tpid = 0;
533
534   string_alloced = FALSE;
535   if (!_dbus_string_init (&auxdata))
536     goto oom;
537   string_alloced = TRUE;
538
539   if (!_dbus_string_append (&auxdata, "msgtype="))
540     goto oom;
541
542   if (!_dbus_string_append (&auxdata, msgtype))
543     goto oom;
544
545   if (interface)
546     {
547       if (!_dbus_string_append (&auxdata, " interface="))
548         goto oom;
549       if (!_dbus_string_append (&auxdata, interface))
550         goto oom;
551     }
552
553   if (member)
554     {
555       if (!_dbus_string_append (&auxdata, " member="))
556         goto oom;
557       if (!_dbus_string_append (&auxdata, member))
558         goto oom;
559     }
560
561   if (error_name)
562     {
563       if (!_dbus_string_append (&auxdata, " error_name="))
564         goto oom;
565       if (!_dbus_string_append (&auxdata, error_name))
566         goto oom;
567     }
568
569   if (destination)
570     {
571       if (!_dbus_string_append (&auxdata, " dest="))
572         goto oom;
573       if (!_dbus_string_append (&auxdata, destination))
574         goto oom;
575     }
576
577   if (spid)
578     {
579       if (!_dbus_string_append (&auxdata, " spid="))
580         goto oom;
581
582       if (!_dbus_string_append_uint (&auxdata, spid))
583         goto oom;
584     }
585
586   if (tpid)
587     {
588       if (!_dbus_string_append (&auxdata, " tpid="))
589         goto oom;
590
591       if (!_dbus_string_append_uint (&auxdata, tpid))
592         goto oom;
593     }
594
595   sender_sid = bus_connection_get_selinux_id (sender);
596   /* A NULL proposed_recipient means the bus itself. */
597   if (proposed_recipient)
598     recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
599   else
600     recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
601
602   ret = bus_selinux_check (sender_sid, 
603                            recipient_sid,
604                            SECCLASS_DBUS, 
605                            DBUS__SEND_MSG,
606                            &auxdata);
607
608   _dbus_string_free (&auxdata);
609
610   return ret;
611
612  oom:
613   if (string_alloced)
614     _dbus_string_free (&auxdata);
615   BUS_SET_OOM (error);
616   return FALSE;
617   
618 #else
619   return TRUE;
620 #endif /* HAVE_SELINUX */
621 }
622
623 dbus_bool_t
624 bus_selinux_append_context (DBusMessage    *message,
625                             BusSELinuxID   *sid,
626                             DBusError      *error)
627 {
628 #ifdef HAVE_SELINUX
629   char *context;
630
631   if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
632     {
633       if (errno == ENOMEM)
634         BUS_SET_OOM (error);
635       else
636         dbus_set_error (error, DBUS_ERROR_FAILED,
637                         "Error getting context from SID: %s\n",
638                         _dbus_strerror (errno));
639       return FALSE;
640     }
641   if (!dbus_message_append_args (message,
642                                  DBUS_TYPE_ARRAY,
643                                  DBUS_TYPE_BYTE,
644                                  &context,
645                                  strlen (context),
646                                  DBUS_TYPE_INVALID))
647     {
648       _DBUS_SET_OOM (error);
649       return FALSE;
650     }
651   freecon (context);
652   return TRUE;
653 #else
654   return TRUE;
655 #endif
656 }
657
658 /**
659  * Gets the security context of a connection to the bus. It is up to
660  * the caller to freecon() when they are done. 
661  *
662  * @param connection the connection to get the context of.
663  * @param con the location to store the security context.
664  * @returns #TRUE if context is successfully obtained.
665  */
666 #ifdef HAVE_SELINUX
667 static dbus_bool_t
668 bus_connection_read_selinux_context (DBusConnection     *connection,
669                                      char              **con)
670 {
671   int fd;
672
673   if (!selinux_enabled)
674     return FALSE;
675
676   _dbus_assert (connection != NULL);
677   
678   if (!dbus_connection_get_unix_fd (connection, &fd))
679     {
680       _dbus_verbose ("Failed to get file descriptor of socket.\n");
681       return FALSE;
682     }
683   
684   if (getpeercon (fd, con) < 0)
685     {
686       _dbus_verbose ("Error getting context of socket peer: %s\n",
687                      _dbus_strerror (errno));
688       return FALSE;
689     }
690   
691   _dbus_verbose ("Successfully read connection context.\n");
692   return TRUE;
693 }
694 #endif /* HAVE_SELINUX */
695
696 /**
697  * Read the SELinux ID from the connection.
698  *
699  * @param connection the connection to read from
700  * @returns the SID if successfully determined, #NULL otherwise.
701  */
702 BusSELinuxID*
703 bus_selinux_init_connection_id (DBusConnection *connection,
704                                 DBusError      *error)
705 {
706 #ifdef HAVE_SELINUX
707   char *con;
708   security_id_t sid;
709   
710   if (!selinux_enabled)
711     return NULL;
712
713   if (!bus_connection_read_selinux_context (connection, &con))
714     {
715       dbus_set_error (error, DBUS_ERROR_FAILED,
716                       "Failed to read an SELinux context from connection");
717       _dbus_verbose ("Error getting peer context.\n");
718       return NULL;
719     }
720
721   _dbus_verbose ("Converting context to SID to store on connection\n");
722
723   if (avc_context_to_sid (con, &sid) < 0)
724     {
725       if (errno == ENOMEM)
726         BUS_SET_OOM (error);
727       else
728         dbus_set_error (error, DBUS_ERROR_FAILED,
729                         "Error getting SID from context \"%s\": %s\n",
730                         con, _dbus_strerror (errno));
731       
732       _dbus_warn ("Error getting SID from context \"%s\": %s\n",
733                   con, _dbus_strerror (errno));
734       
735       freecon (con);
736       return NULL;
737     }
738  
739   freecon (con); 
740   return BUS_SID_FROM_SELINUX (sid);
741 #else
742   return NULL;
743 #endif /* HAVE_SELINUX */
744 }
745
746
747 /**
748  * Function for freeing hash table data.  These SIDs
749  * should no longer be referenced.
750  */
751 static void
752 bus_selinux_id_table_free_value (BusSELinuxID *sid)
753 {
754 #ifdef HAVE_SELINUX
755   /* NULL sometimes due to how DBusHashTable works */
756   if (sid)
757     bus_selinux_id_unref (sid);
758 #endif /* HAVE_SELINUX */
759 }
760
761 /**
762  * Creates a new table mapping service names to security ID.
763  * A security ID is a "compiled" security context, a security
764  * context is just a string.
765  *
766  * @returns the new table or #NULL if no memory
767  */
768 DBusHashTable*
769 bus_selinux_id_table_new (void)
770 {
771   return _dbus_hash_table_new (DBUS_HASH_STRING,
772                                (DBusFreeFunction) dbus_free,
773                                (DBusFreeFunction) bus_selinux_id_table_free_value);
774 }
775
776 /** 
777  * Hashes a service name and service context into the service SID
778  * table as a string and a SID.
779  *
780  * @param service_name is the name of the service.
781  * @param service_context is the context of the service.
782  * @param service_table is the table to hash them into.
783  * @return #FALSE if not enough memory
784  */
785 dbus_bool_t
786 bus_selinux_id_table_insert (DBusHashTable *service_table,
787                              const char    *service_name,
788                              const char    *service_context)
789 {
790 #ifdef HAVE_SELINUX
791   dbus_bool_t retval;
792   security_id_t sid;
793   char *key;
794
795   if (!selinux_enabled)
796     return TRUE;
797
798   sid = SECSID_WILD;
799   retval = FALSE;
800
801   key = _dbus_strdup (service_name);
802   if (key == NULL)
803     return retval;
804   
805   if (avc_context_to_sid ((char *) service_context, &sid) < 0)
806     {
807       if (errno == ENOMEM)
808         {
809           dbus_free (key);
810           return FALSE;
811         }
812
813       _dbus_warn ("Error getting SID from context \"%s\": %s\n",
814                   (char *) service_context,
815                   _dbus_strerror (errno));
816       goto out;
817     }
818
819   if (!_dbus_hash_table_insert_string (service_table,
820                                        key,
821                                        BUS_SID_FROM_SELINUX (sid)))
822     goto out;
823
824   _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
825                   key, 
826                   sid->ctx);
827
828   /* These are owned by the hash, so clear them to avoid unref */
829   key = NULL;
830   sid = SECSID_WILD;
831
832   retval = TRUE;
833   
834  out:
835   if (sid != SECSID_WILD)
836     sidput (sid);
837
838   if (key)
839     dbus_free (key);
840
841   return retval;
842 #else
843   return TRUE;
844 #endif /* HAVE_SELINUX */
845 }
846
847
848 /**
849  * Find the security identifier associated with a particular service
850  * name.  Return a pointer to this SID, or #NULL/SECSID_WILD if the
851  * service is not found in the hash table.  This should be nearly a
852  * constant time operation.  If SELinux support is not available,
853  * always return NULL.
854  *
855  * @param service_table the hash table to check for service name.
856  * @param service_name the name of the service to look for.
857  * @returns the SELinux ID associated with the service
858  */
859 BusSELinuxID*
860 bus_selinux_id_table_lookup (DBusHashTable    *service_table,
861                              const DBusString *service_name)
862 {
863 #ifdef HAVE_SELINUX
864   security_id_t sid;
865
866   sid = SECSID_WILD;     /* default context */
867
868   if (!selinux_enabled)
869     return NULL;
870   
871   _dbus_verbose ("Looking up service SID for %s\n",
872                  _dbus_string_get_const_data (service_name));
873
874   sid = _dbus_hash_table_lookup_string (service_table,
875                                         _dbus_string_get_const_data (service_name));
876
877   if (sid == SECSID_WILD)
878     _dbus_verbose ("Service %s not found\n", 
879                    _dbus_string_get_const_data (service_name));
880   else
881     _dbus_verbose ("Service %s found\n", 
882                    _dbus_string_get_const_data (service_name));
883
884   return BUS_SID_FROM_SELINUX (sid);
885 #endif /* HAVE_SELINUX */
886   return NULL;
887 }
888
889 /**
890  * Get the SELinux policy root.  This is used to find the D-Bus
891  * specific config file within the policy.
892  */
893 const char *
894 bus_selinux_get_policy_root (void)
895 {
896 #ifdef HAVE_SELINUX
897   return selinux_policy_root ();
898 #else
899   return NULL;
900 #endif /* HAVE_SELINUX */
901
902
903 /**
904  * For debugging:  Print out the current hash table of service SIDs.
905  */
906 void
907 bus_selinux_id_table_print (DBusHashTable *service_table)
908 {
909 #ifdef DBUS_ENABLE_VERBOSE_MODE
910 #ifdef HAVE_SELINUX
911   DBusHashIter iter;
912
913   if (!selinux_enabled)
914     return;
915   
916   _dbus_verbose ("Service SID Table:\n");
917   _dbus_hash_iter_init (service_table, &iter);
918   while (_dbus_hash_iter_next (&iter))
919     {
920       const char *key = _dbus_hash_iter_get_string_key (&iter);
921       security_id_t sid = _dbus_hash_iter_get_value (&iter);
922       _dbus_verbose ("The key is %s\n", key);
923       _dbus_verbose ("The context is %s\n", sid->ctx);
924       _dbus_verbose ("The refcount is %d\n", sid->refcnt);
925     }
926 #endif /* HAVE_SELINUX */
927 #endif /* DBUS_ENABLE_VERBOSE_MODE */
928 }
929
930
931 #ifdef DBUS_ENABLE_VERBOSE_MODE
932 #ifdef HAVE_SELINUX
933 /**
934  * Print out some AVC statistics.
935  */
936 static void
937 bus_avc_print_stats (void)
938 {
939   struct avc_cache_stats cstats;
940
941   if (!selinux_enabled)
942     return;
943   
944   _dbus_verbose ("AVC Statistics:\n");
945   avc_cache_stats (&cstats);
946   avc_av_stats ();
947   _dbus_verbose ("AVC Cache Statistics:\n");
948   _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
949   _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
950   _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
951   _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
952   _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
953   _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
954   _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
955   _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
956 }
957 #endif /* HAVE_SELINUX */
958 #endif /* DBUS_ENABLE_VERBOSE_MODE */
959
960
961 /**
962  * Destroy the AVC before we terminate.
963  */
964 void
965 bus_selinux_shutdown (void)
966 {
967 #ifdef HAVE_SELINUX
968   if (!selinux_enabled)
969     return;
970
971   _dbus_verbose ("AVC shutdown\n");
972
973   if (bus_sid != SECSID_WILD)
974     {
975       sidput (bus_sid);
976       bus_sid = SECSID_WILD;
977
978 #ifdef DBUS_ENABLE_VERBOSE_MODE
979  
980       if (_dbus_is_verbose()) 
981         bus_avc_print_stats ();
982  
983 #endif /* DBUS_ENABLE_VERBOSE_MODE */
984
985       avc_destroy ();
986 #ifdef HAVE_LIBAUDIT
987       audit_close (audit_fd);
988 #endif /* HAVE_LIBAUDIT */
989     }
990 #endif /* HAVE_SELINUX */
991 }
992