1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*-
2 * selinux.c SELinux security checks for D-Bus
4 * Author: Matthew Rickard <mjricka@epoch.ncsc.mil>
6 * Licensed under the Academic Free License version 2.1
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.
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.
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
23 #include <dbus/dbus-internals.h>
24 #include <dbus/dbus-string.h>
29 #include "config-parser.h"
32 #include <sys/types.h>
40 #include <selinux/selinux.h>
41 #include <selinux/avc.h>
42 #include <selinux/av_permissions.h>
43 #include <selinux/flask.h>
49 #endif /* HAVE_LIBAUDIT */
50 #endif /* HAVE_SELINUX */
52 #define BUS_SID_FROM_SELINUX(sid) ((BusSELinuxID*) (sid))
53 #define SELINUX_SID_FROM_BUS(sid) ((security_id_t) (sid))
56 /* Store the value telling us if SELinux is enabled in the kernel. */
57 static dbus_bool_t selinux_enabled = FALSE;
59 /* Store an avc_entry_ref to speed AVC decisions. */
60 static struct avc_entry_ref aeref;
62 /* Store the SID of the bus itself to use as the default. */
63 static security_id_t bus_sid = SECSID_WILD;
65 /* Thread to listen for SELinux status changes via netlink. */
66 static pthread_t avc_notify_thread;
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);
78 /* AVC callback structures for use in avc_init. */
79 static const struct avc_memory_callback mem_cb =
81 .func_malloc = dbus_malloc,
82 .func_free = dbus_free
84 static const struct avc_log_callback log_cb =
86 .func_log = log_callback,
87 .func_audit = log_audit_callback
89 static const struct avc_thread_callback thread_cb =
91 .func_create_thread = avc_create_thread,
92 .func_stop_thread = avc_stop_thread
94 static const struct avc_lock_callback lock_cb =
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
101 #endif /* HAVE_SELINUX */
104 * Log callback to log denial messages from the AVC.
105 * This is used in avc_init. Logs to both standard
108 * @param fmt the format string
109 * @param variable argument list
114 static int audit_fd = -1;
118 bus_selinux_audit_init(void)
121 audit_fd = audit_open ();
125 /* If kernel doesn't support audit, bail out */
126 if (errno == EINVAL || errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT)
128 /* If user bus, bail out */
129 if (errno == EPERM && getuid() != 0)
131 _dbus_warn ("Failed opening connection to the audit subsystem");
133 #endif /* HAVE_LIBAUDIT */
137 log_callback (const char *fmt, ...)
146 char buf[PATH_MAX*2];
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,
154 #endif /* HAVE_LIBAUDIT */
156 vsyslog (LOG_INFO, fmt, ap);
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.
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)
169 if (event == AVC_CALLBACK_RESET)
170 return raise (SIGHUP);
176 * Log any auxiliary data
179 log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
181 DBusString *audmsg = data;
183 if (bufleft > (size_t) _dbus_string_get_length(audmsg))
185 _dbus_string_copy_to_buffer_with_nul (audmsg, buf, bufleft);
191 _dbus_string_init_const(&s, "Buffer too small for audit message");
193 if (bufleft > (size_t) _dbus_string_get_length(&s))
194 _dbus_string_copy_to_buffer_with_nul (&s, buf, bufleft);
199 * Create thread to notify the AVC of enforcing and policy reload
200 * changes via netlink.
202 * @param run the thread run function
203 * @return pointer to the thread
206 avc_create_thread (void (*run) (void))
210 rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
213 _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
216 return &avc_notify_thread;
219 /* Stop AVC netlink thread. */
221 avc_stop_thread (void *thread)
223 pthread_cancel (*(pthread_t *) thread);
226 /* Allocate a new AVC lock. */
228 avc_alloc_lock (void)
230 pthread_mutex_t *avc_mutex;
232 avc_mutex = dbus_new (pthread_mutex_t, 1);
233 if (avc_mutex == NULL)
235 _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
238 pthread_mutex_init (avc_mutex, NULL);
243 /* Acquire an AVC lock. */
245 avc_get_lock (void *lock)
247 pthread_mutex_lock (lock);
250 /* Release an AVC lock. */
252 avc_release_lock (void *lock)
254 pthread_mutex_unlock (lock);
257 /* Free an AVC lock. */
259 avc_free_lock (void *lock)
261 pthread_mutex_destroy (lock);
264 #endif /* HAVE_SELINUX */
267 * Return whether or not SELinux is enabled; must be
268 * called after bus_selinux_init.
271 bus_selinux_enabled (void)
274 return selinux_enabled;
277 #endif /* HAVE_SELINUX */
281 * Do early initialization; determine whether SELinux is enabled.
284 bus_selinux_pre_init (void)
288 _dbus_assert (bus_sid == SECSID_WILD);
290 /* Determine if we are running an SELinux kernel. */
291 r = is_selinux_enabled ();
294 _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
295 _dbus_strerror (errno));
299 selinux_enabled = r != 0;
307 * Initialize the user space access vector cache (AVC) for D-Bus and set up
311 bus_selinux_full_init (void)
316 _dbus_assert (bus_sid == SECSID_WILD);
318 if (!selinux_enabled)
320 _dbus_verbose ("SELinux not enabled in this kernel.\n");
324 _dbus_verbose ("SELinux is enabled in this kernel.\n");
326 avc_entry_ref_init (&aeref);
327 if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
329 _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
334 openlog ("dbus", LOG_PERROR, LOG_USER);
335 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
338 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
339 NULL, NULL, 0, 0) < 0)
341 _dbus_warn ("Failed to add policy reload callback: %s\n",
342 _dbus_strerror (errno));
348 bus_sid = SECSID_WILD;
350 if (getcon (&bus_context) < 0)
352 _dbus_verbose ("Error getting context of bus: %s\n",
353 _dbus_strerror (errno));
357 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
359 _dbus_verbose ("Error getting SID from bus context: %s\n",
360 _dbus_strerror (errno));
361 freecon (bus_context);
365 freecon (bus_context);
367 #endif /* HAVE_SELINUX */
372 * Decrement SID reference count.
374 * @param sid the SID to decrement
377 bus_selinux_id_unref (BusSELinuxID *sid)
380 if (!selinux_enabled)
383 _dbus_assert (sid != NULL);
385 sidput (SELINUX_SID_FROM_BUS (sid));
386 #endif /* HAVE_SELINUX */
390 bus_selinux_id_ref (BusSELinuxID *sid)
393 if (!selinux_enabled)
396 _dbus_assert (sid != NULL);
398 sidget (SELINUX_SID_FROM_BUS (sid));
399 #endif /* HAVE_SELINUX */
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.
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.
420 bus_selinux_check (BusSELinuxID *sender_sid,
421 BusSELinuxID *override_sid,
422 security_class_t target_class,
423 access_vector_t requested,
426 if (!selinux_enabled)
429 /* Make the security check. AVC checks enforcing mode here as well. */
430 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
432 SELINUX_SID_FROM_BUS (override_sid) :
433 SELINUX_SID_FROM_BUS (bus_sid),
434 target_class, requested, &aeref, auxdata) < 0)
436 _dbus_verbose ("SELinux denying due to security policy.\n");
442 #endif /* HAVE_SELINUX */
445 * Returns true if the given connection can acquire a service,
446 * assuming the given security ID is needed for that service.
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.
453 bus_selinux_allows_acquire_service (DBusConnection *connection,
454 BusSELinuxID *service_sid,
455 const char *service_name,
459 BusSELinuxID *connection_sid;
464 if (!selinux_enabled)
467 connection_sid = bus_connection_get_selinux_id (connection);
468 if (!dbus_connection_get_unix_process_id (connection, &spid))
471 if (!_dbus_string_init (&auxdata))
474 if (!_dbus_string_append (&auxdata, "service="))
477 if (!_dbus_string_append (&auxdata, service_name))
482 if (!_dbus_string_append (&auxdata, " spid="))
485 if (!_dbus_string_append_uint (&auxdata, spid))
489 ret = bus_selinux_check (connection_sid,
495 _dbus_string_free (&auxdata);
499 _dbus_string_free (&auxdata);
505 #endif /* HAVE_SELINUX */
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"
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
519 bus_selinux_allows_send (DBusConnection *sender,
520 DBusConnection *proposed_recipient,
522 const char *interface,
524 const char *error_name,
525 const char *destination,
529 BusSELinuxID *recipient_sid;
530 BusSELinuxID *sender_sid;
531 unsigned long spid, tpid;
534 dbus_bool_t string_alloced;
536 if (!selinux_enabled)
539 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
541 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
544 string_alloced = FALSE;
545 if (!_dbus_string_init (&auxdata))
547 string_alloced = TRUE;
549 if (!_dbus_string_append (&auxdata, "msgtype="))
552 if (!_dbus_string_append (&auxdata, msgtype))
557 if (!_dbus_string_append (&auxdata, " interface="))
559 if (!_dbus_string_append (&auxdata, interface))
565 if (!_dbus_string_append (&auxdata, " member="))
567 if (!_dbus_string_append (&auxdata, member))
573 if (!_dbus_string_append (&auxdata, " error_name="))
575 if (!_dbus_string_append (&auxdata, error_name))
581 if (!_dbus_string_append (&auxdata, " dest="))
583 if (!_dbus_string_append (&auxdata, destination))
589 if (!_dbus_string_append (&auxdata, " spid="))
592 if (!_dbus_string_append_uint (&auxdata, spid))
598 if (!_dbus_string_append (&auxdata, " tpid="))
601 if (!_dbus_string_append_uint (&auxdata, tpid))
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);
610 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
612 ret = bus_selinux_check (sender_sid,
618 _dbus_string_free (&auxdata);
624 _dbus_string_free (&auxdata);
630 #endif /* HAVE_SELINUX */
634 bus_selinux_append_context (DBusMessage *message,
641 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
646 dbus_set_error (error, DBUS_ERROR_FAILED,
647 "Error getting context from SID: %s\n",
648 _dbus_strerror (errno));
651 if (!dbus_message_append_args (message,
658 _DBUS_SET_OOM (error);
669 * Gets the security context of a connection to the bus. It is up to
670 * the caller to freecon() when they are done.
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.
678 bus_connection_read_selinux_context (DBusConnection *connection,
683 if (!selinux_enabled)
686 _dbus_assert (connection != NULL);
688 if (!dbus_connection_get_unix_fd (connection, &fd))
690 _dbus_verbose ("Failed to get file descriptor of socket.\n");
694 if (getpeercon (fd, con) < 0)
696 _dbus_verbose ("Error getting context of socket peer: %s\n",
697 _dbus_strerror (errno));
701 _dbus_verbose ("Successfully read connection context.\n");
704 #endif /* HAVE_SELINUX */
707 * Read the SELinux ID from the connection.
709 * @param connection the connection to read from
710 * @returns the SID if successfully determined, #NULL otherwise.
713 bus_selinux_init_connection_id (DBusConnection *connection,
720 if (!selinux_enabled)
723 if (!bus_connection_read_selinux_context (connection, &con))
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");
731 _dbus_verbose ("Converting context to SID to store on connection\n");
733 if (avc_context_to_sid (con, &sid) < 0)
738 dbus_set_error (error, DBUS_ERROR_FAILED,
739 "Error getting SID from context \"%s\": %s\n",
740 con, _dbus_strerror (errno));
742 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
743 con, _dbus_strerror (errno));
750 return BUS_SID_FROM_SELINUX (sid);
753 #endif /* HAVE_SELINUX */
758 * Function for freeing hash table data. These SIDs
759 * should no longer be referenced.
762 bus_selinux_id_table_free_value (BusSELinuxID *sid)
765 /* NULL sometimes due to how DBusHashTable works */
767 bus_selinux_id_unref (sid);
768 #endif /* HAVE_SELINUX */
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.
776 * @returns the new table or #NULL if no memory
779 bus_selinux_id_table_new (void)
781 return _dbus_hash_table_new (DBUS_HASH_STRING,
782 (DBusFreeFunction) dbus_free,
783 (DBusFreeFunction) bus_selinux_id_table_free_value);
787 * Hashes a service name and service context into the service SID
788 * table as a string and a SID.
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
796 bus_selinux_id_table_insert (DBusHashTable *service_table,
797 const char *service_name,
798 const char *service_context)
805 if (!selinux_enabled)
811 key = _dbus_strdup (service_name);
815 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
823 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
824 (char *) service_context,
825 _dbus_strerror (errno));
829 if (!_dbus_hash_table_insert_string (service_table,
831 BUS_SID_FROM_SELINUX (sid)))
834 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
838 /* These are owned by the hash, so clear them to avoid unref */
845 if (sid != SECSID_WILD)
854 #endif /* HAVE_SELINUX */
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.
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
870 bus_selinux_id_table_lookup (DBusHashTable *service_table,
871 const DBusString *service_name)
876 sid = SECSID_WILD; /* default context */
878 if (!selinux_enabled)
881 _dbus_verbose ("Looking up service SID for %s\n",
882 _dbus_string_get_const_data (service_name));
884 sid = _dbus_hash_table_lookup_string (service_table,
885 _dbus_string_get_const_data (service_name));
887 if (sid == SECSID_WILD)
888 _dbus_verbose ("Service %s not found\n",
889 _dbus_string_get_const_data (service_name));
891 _dbus_verbose ("Service %s found\n",
892 _dbus_string_get_const_data (service_name));
894 return BUS_SID_FROM_SELINUX (sid);
895 #endif /* HAVE_SELINUX */
900 * Get the SELinux policy root. This is used to find the D-Bus
901 * specific config file within the policy.
904 bus_selinux_get_policy_root (void)
907 return selinux_policy_root ();
910 #endif /* HAVE_SELINUX */
914 * For debugging: Print out the current hash table of service SIDs.
917 bus_selinux_id_table_print (DBusHashTable *service_table)
919 #ifdef DBUS_ENABLE_VERBOSE_MODE
923 if (!selinux_enabled)
926 _dbus_verbose ("Service SID Table:\n");
927 _dbus_hash_iter_init (service_table, &iter);
928 while (_dbus_hash_iter_next (&iter))
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);
936 #endif /* HAVE_SELINUX */
937 #endif /* DBUS_ENABLE_VERBOSE_MODE */
941 #ifdef DBUS_ENABLE_VERBOSE_MODE
944 * Print out some AVC statistics.
947 bus_avc_print_stats (void)
949 struct avc_cache_stats cstats;
951 if (!selinux_enabled)
954 _dbus_verbose ("AVC Statistics:\n");
955 avc_cache_stats (&cstats);
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);
967 #endif /* HAVE_SELINUX */
968 #endif /* DBUS_ENABLE_VERBOSE_MODE */
972 * Destroy the AVC before we terminate.
975 bus_selinux_shutdown (void)
978 if (!selinux_enabled)
981 _dbus_verbose ("AVC shutdown\n");
983 if (bus_sid != SECSID_WILD)
986 bus_sid = SECSID_WILD;
988 #ifdef DBUS_ENABLE_VERBOSE_MODE
990 if (_dbus_is_verbose())
991 bus_avc_print_stats ();
993 #endif /* DBUS_ENABLE_VERBOSE_MODE */
997 audit_close (audit_fd);
998 #endif /* HAVE_LIBAUDIT */
1000 #endif /* HAVE_SELINUX */