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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include <dbus/dbus-internals.h>
26 #include <dbus/dbus-string.h>
28 #include <dbus/dbus-userdb.h>
35 #include "config-parser.h"
41 #include <sys/types.h>
46 #include <selinux/selinux.h>
47 #include <selinux/avc.h>
52 #endif /* HAVE_SELINUX */
55 #endif /* HAVE_LIBAUDIT */
57 #define BUS_SID_FROM_SELINUX(sid) ((BusSELinuxID*) (sid))
58 #define SELINUX_SID_FROM_BUS(sid) ((security_id_t) (sid))
61 /* Store the value telling us if SELinux is enabled in the kernel. */
62 static dbus_bool_t selinux_enabled = FALSE;
64 /* Store an avc_entry_ref to speed AVC decisions. */
65 static struct avc_entry_ref aeref;
67 /* Store the SID of the bus itself to use as the default. */
68 static security_id_t bus_sid = SECSID_WILD;
70 /* Thread to listen for SELinux status changes via netlink. */
71 static pthread_t avc_notify_thread;
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);
83 /* AVC callback structures for use in avc_init. */
84 static const struct avc_memory_callback mem_cb =
86 .func_malloc = dbus_malloc,
87 .func_free = dbus_free
89 static const struct avc_log_callback log_cb =
91 .func_log = log_callback,
92 .func_audit = log_audit_callback
94 static const struct avc_thread_callback thread_cb =
96 .func_create_thread = avc_create_thread,
97 .func_stop_thread = avc_stop_thread
99 static const struct avc_lock_callback lock_cb =
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
106 #endif /* HAVE_SELINUX */
109 * Log callback to log denial messages from the AVC.
110 * This is used in avc_init. Logs to both standard
113 * @param fmt the format string
114 * @param variable argument list
119 log_callback (const char *fmt, ...)
129 audit_fd = bus_audit_get_fd ();
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];
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,
145 #endif /* HAVE_LIBAUDIT */
147 vsyslog (LOG_USER | LOG_INFO, fmt, ap);
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.
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)
164 if (event == AVC_CALLBACK_RESET)
165 return raise (SIGHUP);
171 * Log any auxiliary data
174 log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
176 DBusString *audmsg = data;
178 if (bufleft > (size_t) _dbus_string_get_length(audmsg))
180 _dbus_string_copy_to_buffer_with_nul (audmsg, buf, bufleft);
186 _dbus_string_init_const(&s, "Buffer too small for audit message");
188 if (bufleft > (size_t) _dbus_string_get_length(&s))
189 _dbus_string_copy_to_buffer_with_nul (&s, buf, bufleft);
194 * Create thread to notify the AVC of enforcing and policy reload
195 * changes via netlink.
197 * @param run the thread run function
198 * @return pointer to the thread
201 avc_create_thread (void (*run) (void))
205 rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
208 _dbus_warn ("Failed to start AVC thread: %s", _dbus_strerror (rc));
211 return &avc_notify_thread;
214 /* Stop AVC netlink thread. */
216 avc_stop_thread (void *thread)
218 pthread_cancel (*(pthread_t *) thread);
221 /* Allocate a new AVC lock. */
223 avc_alloc_lock (void)
225 pthread_mutex_t *avc_mutex;
227 avc_mutex = dbus_new (pthread_mutex_t, 1);
228 if (avc_mutex == NULL)
230 _dbus_warn ("Could not create mutex: %s", _dbus_strerror (errno));
233 pthread_mutex_init (avc_mutex, NULL);
238 /* Acquire an AVC lock. */
240 avc_get_lock (void *lock)
242 pthread_mutex_lock (lock);
245 /* Release an AVC lock. */
247 avc_release_lock (void *lock)
249 pthread_mutex_unlock (lock);
252 /* Free an AVC lock. */
254 avc_free_lock (void *lock)
256 pthread_mutex_destroy (lock);
259 #endif /* HAVE_SELINUX */
262 * Return whether or not SELinux is enabled; must be
263 * called after bus_selinux_init.
266 bus_selinux_enabled (void)
269 return selinux_enabled;
272 #endif /* HAVE_SELINUX */
276 bus_selinux_get_self (void)
279 if(bus_selinux_enabled ())
280 return BUS_SID_FROM_SELINUX (bus_sid);
285 #endif /* HAVE_SELINUX */
289 * Do early initialization; determine whether SELinux is enabled.
292 bus_selinux_pre_init (void)
296 _dbus_assert (bus_sid == SECSID_WILD);
298 /* Determine if we are running an SELinux kernel. */
299 r = is_selinux_enabled ();
302 _dbus_warn ("Could not tell if SELinux is enabled: %s",
303 _dbus_strerror (errno));
307 selinux_enabled = r != 0;
315 * Private Flask definitions; the order of these constants must
316 * exactly match that of the structure array below!
318 /* security dbus class constants */
319 #define SECCLASS_DBUS 1
321 /* dbus's per access vector constants */
322 #define DBUS__ACQUIRE_SVC 1
323 #define DBUS__SEND_MSG 2
326 static struct security_class_mapping dbus_map[] = {
327 { "dbus", { "acquire_svc", "send_msg", NULL } },
330 #endif /* HAVE_SELINUX */
333 * Establish dynamic object class and permission mapping and
334 * initialize the user space access vector cache (AVC) for D-Bus and set up
338 bus_selinux_full_init (void)
343 _dbus_assert (bus_sid == SECSID_WILD);
345 if (!selinux_enabled)
347 _dbus_verbose ("SELinux not enabled in this kernel.\n");
351 _dbus_verbose ("SELinux is enabled in this kernel.\n");
353 if (selinux_set_mapping (dbus_map) < 0)
355 _dbus_warn ("Failed to set up security class mapping (selinux_set_mapping():%s).",
360 avc_entry_ref_init (&aeref);
361 if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
363 _dbus_warn ("Failed to start Access Vector Cache (AVC).");
368 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
371 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
372 NULL, NULL, 0, 0) < 0)
374 _dbus_warn ("Failed to add policy reload callback: %s",
375 _dbus_strerror (errno));
381 bus_sid = SECSID_WILD;
383 if (getcon (&bus_context) < 0)
385 _dbus_verbose ("Error getting context of bus: %s\n",
386 _dbus_strerror (errno));
390 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
392 _dbus_verbose ("Error getting SID from bus context: %s\n",
393 _dbus_strerror (errno));
394 freecon (bus_context);
398 freecon (bus_context);
400 #endif /* HAVE_SELINUX */
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.
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.
422 bus_selinux_check (BusSELinuxID *sender_sid,
423 BusSELinuxID *override_sid,
424 security_class_t target_class,
425 access_vector_t requested,
428 if (!selinux_enabled)
431 /* Make the security check. AVC checks enforcing mode here as well. */
432 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
434 SELINUX_SID_FROM_BUS (override_sid) :
436 target_class, requested, &aeref, auxdata) < 0)
441 _dbus_verbose ("SELinux denying due to security policy.\n");
444 _dbus_verbose ("SELinux denying due to invalid security context.\n");
447 _dbus_verbose ("SELinux denying due to: %s\n", _dbus_strerror (errno));
454 #endif /* HAVE_SELINUX */
457 * Returns true if the given connection can acquire a service,
458 * assuming the given security ID is needed for that service.
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.
465 bus_selinux_allows_acquire_service (DBusConnection *connection,
466 BusSELinuxID *service_sid,
467 const char *service_name,
471 BusSELinuxID *connection_sid;
476 if (!selinux_enabled)
479 connection_sid = bus_connection_get_selinux_id (connection);
480 if (!dbus_connection_get_unix_process_id (connection, &spid))
483 if (!_dbus_string_init (&auxdata))
486 if (!_dbus_string_append (&auxdata, "service="))
489 if (!_dbus_string_append (&auxdata, service_name))
494 if (!_dbus_string_append (&auxdata, " spid="))
497 if (!_dbus_string_append_uint (&auxdata, spid))
501 ret = bus_selinux_check (connection_sid,
507 _dbus_string_free (&auxdata);
511 _dbus_string_free (&auxdata);
517 #endif /* HAVE_SELINUX */
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"
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
531 bus_selinux_allows_send (DBusConnection *sender,
532 DBusConnection *proposed_recipient,
534 const char *interface,
536 const char *error_name,
537 const char *destination,
538 BusActivationEntry *activation_entry,
542 BusSELinuxID *recipient_sid;
543 BusSELinuxID *sender_sid;
544 unsigned long spid, tpid;
547 dbus_bool_t string_alloced;
549 if (!selinux_enabled)
552 /* We do not mediate activation attempts yet. */
553 if (activation_entry)
556 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
558 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
561 string_alloced = FALSE;
562 if (!_dbus_string_init (&auxdata))
564 string_alloced = TRUE;
566 if (!_dbus_string_append (&auxdata, "msgtype="))
569 if (!_dbus_string_append (&auxdata, msgtype))
574 if (!_dbus_string_append (&auxdata, " interface="))
576 if (!_dbus_string_append (&auxdata, interface))
582 if (!_dbus_string_append (&auxdata, " member="))
584 if (!_dbus_string_append (&auxdata, member))
590 if (!_dbus_string_append (&auxdata, " error_name="))
592 if (!_dbus_string_append (&auxdata, error_name))
598 if (!_dbus_string_append (&auxdata, " dest="))
600 if (!_dbus_string_append (&auxdata, destination))
606 if (!_dbus_string_append (&auxdata, " spid="))
609 if (!_dbus_string_append_uint (&auxdata, spid))
615 if (!_dbus_string_append (&auxdata, " tpid="))
618 if (!_dbus_string_append_uint (&auxdata, tpid))
622 sender_sid = bus_connection_get_selinux_id (sender);
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);
628 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
630 ret = bus_selinux_check (sender_sid,
636 _dbus_string_free (&auxdata);
642 _dbus_string_free (&auxdata);
648 #endif /* HAVE_SELINUX */
652 bus_selinux_append_context (DBusMessage *message,
659 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
664 dbus_set_error (error, DBUS_ERROR_FAILED,
665 "Error getting context from SID: %s\n",
666 _dbus_strerror (errno));
669 if (!dbus_message_append_args (message,
676 _DBUS_SET_OOM (error);
687 * Gets the security context of a connection to the bus. It is up to
688 * the caller to freecon() when they are done.
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.
696 bus_connection_read_selinux_context (DBusConnection *connection,
701 if (!selinux_enabled)
704 _dbus_assert (connection != NULL);
706 if (!dbus_connection_get_unix_fd (connection, &fd))
708 _dbus_verbose ("Failed to get file descriptor of socket.\n");
712 if (getpeercon (fd, con) < 0)
714 _dbus_verbose ("Error getting context of socket peer: %s\n",
715 _dbus_strerror (errno));
719 _dbus_verbose ("Successfully read connection context.\n");
722 #endif /* HAVE_SELINUX */
725 * Read the SELinux ID from the connection.
727 * @param connection the connection to read from
728 * @returns the SID if successfully determined, #NULL otherwise.
731 bus_selinux_init_connection_id (DBusConnection *connection,
738 if (!selinux_enabled)
741 if (!bus_connection_read_selinux_context (connection, &con))
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");
749 _dbus_verbose ("Converting context to SID to store on connection\n");
751 if (avc_context_to_sid (con, &sid) < 0)
756 dbus_set_error (error, DBUS_ERROR_FAILED,
757 "Error getting SID from context \"%s\": %s\n",
758 con, _dbus_strerror (errno));
760 _dbus_warn ("Error getting SID from context \"%s\": %s",
761 con, _dbus_strerror (errno));
768 return BUS_SID_FROM_SELINUX (sid);
771 #endif /* HAVE_SELINUX */
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.
779 * @returns the new table or #NULL if no memory
782 bus_selinux_id_table_new (void)
784 return _dbus_hash_table_new (DBUS_HASH_STRING,
785 (DBusFreeFunction) dbus_free, NULL);
789 * Hashes a service name and service context into the service SID
790 * table as a string and a SID.
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
798 bus_selinux_id_table_insert (DBusHashTable *service_table,
799 const char *service_name,
800 const char *service_context)
807 if (!selinux_enabled)
813 key = _dbus_strdup (service_name);
817 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
825 _dbus_warn ("Error getting SID from context \"%s\": %s",
826 (char *) service_context,
827 _dbus_strerror (errno));
831 if (!_dbus_hash_table_insert_string (service_table,
833 BUS_SID_FROM_SELINUX (sid)))
836 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
840 /* These are owned by the hash, so clear them to avoid unref */
853 #endif /* HAVE_SELINUX */
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.
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
869 bus_selinux_id_table_lookup (DBusHashTable *service_table,
870 const DBusString *service_name)
875 sid = SECSID_WILD; /* default context */
877 if (!selinux_enabled)
880 _dbus_verbose ("Looking up service SID for %s\n",
881 _dbus_string_get_const_data (service_name));
883 sid = _dbus_hash_table_lookup_string (service_table,
884 _dbus_string_get_const_data (service_name));
886 if (sid == SECSID_WILD)
887 _dbus_verbose ("Service %s not found\n",
888 _dbus_string_get_const_data (service_name));
890 _dbus_verbose ("Service %s found\n",
891 _dbus_string_get_const_data (service_name));
893 return BUS_SID_FROM_SELINUX (sid);
894 #endif /* HAVE_SELINUX */
899 * Get the SELinux policy root. This is used to find the D-Bus
900 * specific config file within the policy.
903 bus_selinux_get_policy_root (void)
906 return selinux_policy_root ();
909 #endif /* HAVE_SELINUX */
913 * For debugging: Print out the current hash table of service SIDs.
916 bus_selinux_id_table_print (DBusHashTable *service_table)
918 #if defined (DBUS_ENABLE_VERBOSE_MODE) && defined (HAVE_SELINUX)
921 if (!selinux_enabled)
924 _dbus_verbose ("Service SID Table:\n");
925 _dbus_hash_iter_init (service_table, &iter);
926 while (_dbus_hash_iter_next (&iter))
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);
934 #endif /* DBUS_ENABLE_VERBOSE_MODE && HAVE_SELINUX */
939 * Print out some AVC statistics.
943 bus_avc_print_stats (void)
945 #ifdef DBUS_ENABLE_VERBOSE_MODE
946 struct avc_cache_stats cstats;
948 if (!selinux_enabled)
951 _dbus_verbose ("AVC Statistics:\n");
952 avc_cache_stats (&cstats);
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 */
965 #endif /* HAVE_SELINUX */
968 * Destroy the AVC before we terminate.
971 bus_selinux_shutdown (void)
974 if (!selinux_enabled)
977 _dbus_verbose ("AVC shutdown\n");
979 if (bus_sid != SECSID_WILD)
981 bus_sid = SECSID_WILD;
983 bus_avc_print_stats ();
987 #endif /* HAVE_SELINUX */