1 /* -*- mode: C; c-file-style: "gnu" -*-
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>
39 #include <selinux/selinux.h>
40 #include <selinux/avc.h>
41 #include <selinux/av_permissions.h>
42 #include <selinux/flask.h>
48 #endif /* HAVE_LIBAUDIT */
49 #endif /* HAVE_SELINUX */
51 #define BUS_SID_FROM_SELINUX(sid) ((BusSELinuxID*) (sid))
52 #define SELINUX_SID_FROM_BUS(sid) ((security_id_t) (sid))
55 /* Store the value telling us if SELinux is enabled in the kernel. */
56 static dbus_bool_t selinux_enabled = FALSE;
58 /* Store an avc_entry_ref to speed AVC decisions. */
59 static struct avc_entry_ref aeref;
61 /* Store the SID of the bus itself to use as the default. */
62 static security_id_t bus_sid = SECSID_WILD;
64 /* Thread to listen for SELinux status changes via netlink. */
65 static pthread_t avc_notify_thread;
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);
77 /* AVC callback structures for use in avc_init. */
78 static const struct avc_memory_callback mem_cb =
80 .func_malloc = dbus_malloc,
81 .func_free = dbus_free
83 static const struct avc_log_callback log_cb =
85 .func_log = log_callback,
86 .func_audit = log_audit_callback
88 static const struct avc_thread_callback thread_cb =
90 .func_create_thread = avc_create_thread,
91 .func_stop_thread = avc_stop_thread
93 static const struct avc_lock_callback lock_cb =
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
100 #endif /* HAVE_SELINUX */
103 * Log callback to log denial messages from the AVC.
104 * This is used in avc_init. Logs to both standard
107 * @param fmt the format string
108 * @param variable argument list
113 static int audit_fd = -1;
120 audit_fd = audit_open ();
124 /* If kernel doesn't support audit, bail out */
125 if (errno == EINVAL || errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT)
127 /* If user bus, bail out */
128 if (errno == EPERM && getuid() != 0)
130 _dbus_warn ("Failed opening connection to the audit subsystem");
132 #endif /* HAVE_LIBAUDIT */
136 log_callback (const char *fmt, ...)
145 char buf[PATH_MAX*2];
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,
153 #endif /* HAVE_LIBAUDIT */
155 vsyslog (LOG_INFO, fmt, ap);
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.
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)
168 if (event == AVC_CALLBACK_RESET)
169 return raise (SIGHUP);
175 * Log any auxiliary data
178 log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
180 DBusString *audmsg = data;
181 _dbus_string_copy_to_buffer (audmsg, buf, bufleft);
185 * Create thread to notify the AVC of enforcing and policy reload
186 * changes via netlink.
188 * @param run the thread run function
189 * @return pointer to the thread
192 avc_create_thread (void (*run) (void))
196 rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
199 _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
202 return &avc_notify_thread;
205 /* Stop AVC netlink thread. */
207 avc_stop_thread (void *thread)
209 pthread_cancel (*(pthread_t *) thread);
212 /* Allocate a new AVC lock. */
214 avc_alloc_lock (void)
216 pthread_mutex_t *avc_mutex;
218 avc_mutex = dbus_new (pthread_mutex_t, 1);
219 if (avc_mutex == NULL)
221 _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
224 pthread_mutex_init (avc_mutex, NULL);
229 /* Acquire an AVC lock. */
231 avc_get_lock (void *lock)
233 pthread_mutex_lock (lock);
236 /* Release an AVC lock. */
238 avc_release_lock (void *lock)
240 pthread_mutex_unlock (lock);
243 /* Free an AVC lock. */
245 avc_free_lock (void *lock)
247 pthread_mutex_destroy (lock);
250 #endif /* HAVE_SELINUX */
253 * Return whether or not SELinux is enabled; must be
254 * called after bus_selinux_init.
257 bus_selinux_enabled (void)
260 return selinux_enabled;
263 #endif /* HAVE_SELINUX */
267 * Do early initialization; determine whether SELinux is enabled.
270 bus_selinux_pre_init (void)
274 _dbus_assert (bus_sid == SECSID_WILD);
276 /* Determine if we are running an SELinux kernel. */
277 r = is_selinux_enabled ();
280 _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
281 _dbus_strerror (errno));
285 selinux_enabled = r != 0;
293 * Initialize the user space access vector cache (AVC) for D-Bus and set up
297 bus_selinux_full_init (void)
302 _dbus_assert (bus_sid == SECSID_WILD);
304 if (!selinux_enabled)
306 _dbus_verbose ("SELinux not enabled in this kernel.\n");
310 _dbus_verbose ("SELinux is enabled in this kernel.\n");
312 avc_entry_ref_init (&aeref);
313 if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
315 _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
320 openlog ("dbus", LOG_PERROR, LOG_USER);
321 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
324 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
325 NULL, NULL, 0, 0) < 0)
327 _dbus_warn ("Failed to add policy reload callback: %s\n",
328 _dbus_strerror (errno));
334 bus_sid = SECSID_WILD;
336 if (getcon (&bus_context) < 0)
338 _dbus_verbose ("Error getting context of bus: %s\n",
339 _dbus_strerror (errno));
343 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
345 _dbus_verbose ("Error getting SID from bus context: %s\n",
346 _dbus_strerror (errno));
347 freecon (bus_context);
351 freecon (bus_context);
358 #endif /* HAVE_SELINUX */
362 * Decrement SID reference count.
364 * @param sid the SID to decrement
367 bus_selinux_id_unref (BusSELinuxID *sid)
370 if (!selinux_enabled)
373 _dbus_assert (sid != NULL);
375 sidput (SELINUX_SID_FROM_BUS (sid));
376 #endif /* HAVE_SELINUX */
380 bus_selinux_id_ref (BusSELinuxID *sid)
383 if (!selinux_enabled)
386 _dbus_assert (sid != NULL);
388 sidget (SELINUX_SID_FROM_BUS (sid));
389 #endif /* HAVE_SELINUX */
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.
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.
410 bus_selinux_check (BusSELinuxID *sender_sid,
411 BusSELinuxID *override_sid,
412 security_class_t target_class,
413 access_vector_t requested,
416 if (!selinux_enabled)
419 /* Make the security check. AVC checks enforcing mode here as well. */
420 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
422 SELINUX_SID_FROM_BUS (override_sid) :
423 SELINUX_SID_FROM_BUS (bus_sid),
424 target_class, requested, &aeref, auxdata) < 0)
426 _dbus_verbose ("SELinux denying due to security policy.\n");
432 #endif /* HAVE_SELINUX */
435 * Returns true if the given connection can acquire a service,
436 * assuming the given security ID is needed for that service.
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.
443 bus_selinux_allows_acquire_service (DBusConnection *connection,
444 BusSELinuxID *service_sid,
445 const char *service_name,
449 BusSELinuxID *connection_sid;
454 if (!selinux_enabled)
457 connection_sid = bus_connection_get_selinux_id (connection);
458 if (!dbus_connection_get_unix_process_id (connection, &spid))
461 if (!_dbus_string_init (&auxdata))
464 if (!_dbus_string_append (&auxdata, "service="))
467 if (!_dbus_string_append (&auxdata, service_name))
472 if (!_dbus_string_append (&auxdata, " spid="))
475 if (!_dbus_string_append_uint (&auxdata, spid))
479 ret = bus_selinux_check (connection_sid,
485 _dbus_string_free (&auxdata);
489 _dbus_string_free (&auxdata);
495 #endif /* HAVE_SELINUX */
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"
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
509 bus_selinux_allows_send (DBusConnection *sender,
510 DBusConnection *proposed_recipient,
512 const char *interface,
514 const char *error_name,
515 const char *destination,
519 BusSELinuxID *recipient_sid;
520 BusSELinuxID *sender_sid;
521 unsigned long spid, tpid;
524 dbus_bool_t string_alloced;
526 if (!selinux_enabled)
529 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
531 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
534 string_alloced = FALSE;
535 if (!_dbus_string_init (&auxdata))
537 string_alloced = TRUE;
539 if (!_dbus_string_append (&auxdata, "msgtype="))
542 if (!_dbus_string_append (&auxdata, msgtype))
547 if (!_dbus_string_append (&auxdata, " interface="))
549 if (!_dbus_string_append (&auxdata, interface))
555 if (!_dbus_string_append (&auxdata, " member="))
557 if (!_dbus_string_append (&auxdata, member))
563 if (!_dbus_string_append (&auxdata, " error_name="))
565 if (!_dbus_string_append (&auxdata, error_name))
571 if (!_dbus_string_append (&auxdata, " dest="))
573 if (!_dbus_string_append (&auxdata, destination))
579 if (!_dbus_string_append (&auxdata, " spid="))
582 if (!_dbus_string_append_uint (&auxdata, spid))
588 if (!_dbus_string_append (&auxdata, " tpid="))
591 if (!_dbus_string_append_uint (&auxdata, tpid))
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);
600 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
602 ret = bus_selinux_check (sender_sid,
608 _dbus_string_free (&auxdata);
614 _dbus_string_free (&auxdata);
620 #endif /* HAVE_SELINUX */
624 bus_selinux_append_context (DBusMessage *message,
631 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
636 dbus_set_error (error, DBUS_ERROR_FAILED,
637 "Error getting context from SID: %s\n",
638 _dbus_strerror (errno));
641 if (!dbus_message_append_args (message,
648 _DBUS_SET_OOM (error);
659 * Gets the security context of a connection to the bus. It is up to
660 * the caller to freecon() when they are done.
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.
668 bus_connection_read_selinux_context (DBusConnection *connection,
673 if (!selinux_enabled)
676 _dbus_assert (connection != NULL);
678 if (!dbus_connection_get_unix_fd (connection, &fd))
680 _dbus_verbose ("Failed to get file descriptor of socket.\n");
684 if (getpeercon (fd, con) < 0)
686 _dbus_verbose ("Error getting context of socket peer: %s\n",
687 _dbus_strerror (errno));
691 _dbus_verbose ("Successfully read connection context.\n");
694 #endif /* HAVE_SELINUX */
697 * Read the SELinux ID from the connection.
699 * @param connection the connection to read from
700 * @returns the SID if successfully determined, #NULL otherwise.
703 bus_selinux_init_connection_id (DBusConnection *connection,
710 if (!selinux_enabled)
713 if (!bus_connection_read_selinux_context (connection, &con))
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");
721 _dbus_verbose ("Converting context to SID to store on connection\n");
723 if (avc_context_to_sid (con, &sid) < 0)
728 dbus_set_error (error, DBUS_ERROR_FAILED,
729 "Error getting SID from context \"%s\": %s\n",
730 con, _dbus_strerror (errno));
732 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
733 con, _dbus_strerror (errno));
740 return BUS_SID_FROM_SELINUX (sid);
743 #endif /* HAVE_SELINUX */
748 * Function for freeing hash table data. These SIDs
749 * should no longer be referenced.
752 bus_selinux_id_table_free_value (BusSELinuxID *sid)
755 /* NULL sometimes due to how DBusHashTable works */
757 bus_selinux_id_unref (sid);
758 #endif /* HAVE_SELINUX */
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.
766 * @returns the new table or #NULL if no memory
769 bus_selinux_id_table_new (void)
771 return _dbus_hash_table_new (DBUS_HASH_STRING,
772 (DBusFreeFunction) dbus_free,
773 (DBusFreeFunction) bus_selinux_id_table_free_value);
777 * Hashes a service name and service context into the service SID
778 * table as a string and a SID.
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
786 bus_selinux_id_table_insert (DBusHashTable *service_table,
787 const char *service_name,
788 const char *service_context)
795 if (!selinux_enabled)
801 key = _dbus_strdup (service_name);
805 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
813 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
814 (char *) service_context,
815 _dbus_strerror (errno));
819 if (!_dbus_hash_table_insert_string (service_table,
821 BUS_SID_FROM_SELINUX (sid)))
824 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
828 /* These are owned by the hash, so clear them to avoid unref */
835 if (sid != SECSID_WILD)
844 #endif /* HAVE_SELINUX */
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.
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
860 bus_selinux_id_table_lookup (DBusHashTable *service_table,
861 const DBusString *service_name)
866 sid = SECSID_WILD; /* default context */
868 if (!selinux_enabled)
871 _dbus_verbose ("Looking up service SID for %s\n",
872 _dbus_string_get_const_data (service_name));
874 sid = _dbus_hash_table_lookup_string (service_table,
875 _dbus_string_get_const_data (service_name));
877 if (sid == SECSID_WILD)
878 _dbus_verbose ("Service %s not found\n",
879 _dbus_string_get_const_data (service_name));
881 _dbus_verbose ("Service %s found\n",
882 _dbus_string_get_const_data (service_name));
884 return BUS_SID_FROM_SELINUX (sid);
885 #endif /* HAVE_SELINUX */
890 * Get the SELinux policy root. This is used to find the D-Bus
891 * specific config file within the policy.
894 bus_selinux_get_policy_root (void)
897 return selinux_policy_root ();
900 #endif /* HAVE_SELINUX */
904 * For debugging: Print out the current hash table of service SIDs.
907 bus_selinux_id_table_print (DBusHashTable *service_table)
909 #ifdef DBUS_ENABLE_VERBOSE_MODE
913 if (!selinux_enabled)
916 _dbus_verbose ("Service SID Table:\n");
917 _dbus_hash_iter_init (service_table, &iter);
918 while (_dbus_hash_iter_next (&iter))
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);
926 #endif /* HAVE_SELINUX */
927 #endif /* DBUS_ENABLE_VERBOSE_MODE */
931 #ifdef DBUS_ENABLE_VERBOSE_MODE
934 * Print out some AVC statistics.
937 bus_avc_print_stats (void)
939 struct avc_cache_stats cstats;
941 if (!selinux_enabled)
944 _dbus_verbose ("AVC Statistics:\n");
945 avc_cache_stats (&cstats);
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);
957 #endif /* HAVE_SELINUX */
958 #endif /* DBUS_ENABLE_VERBOSE_MODE */
962 * Destroy the AVC before we terminate.
965 bus_selinux_shutdown (void)
968 if (!selinux_enabled)
971 _dbus_verbose ("AVC shutdown\n");
973 if (bus_sid != SECSID_WILD)
976 bus_sid = SECSID_WILD;
978 #ifdef DBUS_ENABLE_VERBOSE_MODE
980 if (_dbus_is_verbose())
981 bus_avc_print_stats ();
983 #endif /* DBUS_ENABLE_VERBOSE_MODE */
987 audit_close (audit_fd);
988 #endif /* HAVE_LIBAUDIT */
990 #endif /* HAVE_SELINUX */