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