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)
439 _dbus_verbose ("SELinux denying due to security policy.\n");
442 _dbus_verbose ("SELinux denying due to invalid security context.\n");
445 _dbus_verbose ("SELinux denying due to: %s\n", _dbus_strerror (errno));
452 #endif /* HAVE_SELINUX */
455 * Returns true if the given connection can acquire a service,
456 * assuming the given security ID is needed for that service.
458 * @param connection connection that wants to own the service
459 * @param service_sid the SID of the service from the table
460 * @returns #TRUE if acquire is permitted.
463 bus_selinux_allows_acquire_service (DBusConnection *connection,
464 BusSELinuxID *service_sid,
465 const char *service_name,
469 BusSELinuxID *connection_sid;
474 if (!selinux_enabled)
477 connection_sid = bus_connection_get_selinux_id (connection);
478 if (!dbus_connection_get_unix_process_id (connection, &spid))
481 if (!_dbus_string_init (&auxdata))
484 if (!_dbus_string_append (&auxdata, "service="))
487 if (!_dbus_string_append (&auxdata, service_name))
492 if (!_dbus_string_append (&auxdata, " spid="))
495 if (!_dbus_string_append_uint (&auxdata, spid))
499 ret = bus_selinux_check (connection_sid,
505 _dbus_string_free (&auxdata);
509 _dbus_string_free (&auxdata);
515 #endif /* HAVE_SELINUX */
519 * Check if SELinux security controls allow the message to be sent to a
520 * particular connection based on the security context of the sender and
521 * that of the receiver. The destination connection need not be the
522 * addressed recipient, it could be an "eavesdropper"
524 * @param sender the sender of the message.
525 * @param proposed_recipient the connection the message is to be sent to.
526 * @returns whether to allow the send
529 bus_selinux_allows_send (DBusConnection *sender,
530 DBusConnection *proposed_recipient,
532 const char *interface,
534 const char *error_name,
535 const char *destination,
539 BusSELinuxID *recipient_sid;
540 BusSELinuxID *sender_sid;
541 unsigned long spid, tpid;
544 dbus_bool_t string_alloced;
546 if (!selinux_enabled)
549 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
551 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
554 string_alloced = FALSE;
555 if (!_dbus_string_init (&auxdata))
557 string_alloced = TRUE;
559 if (!_dbus_string_append (&auxdata, "msgtype="))
562 if (!_dbus_string_append (&auxdata, msgtype))
567 if (!_dbus_string_append (&auxdata, " interface="))
569 if (!_dbus_string_append (&auxdata, interface))
575 if (!_dbus_string_append (&auxdata, " member="))
577 if (!_dbus_string_append (&auxdata, member))
583 if (!_dbus_string_append (&auxdata, " error_name="))
585 if (!_dbus_string_append (&auxdata, error_name))
591 if (!_dbus_string_append (&auxdata, " dest="))
593 if (!_dbus_string_append (&auxdata, destination))
599 if (!_dbus_string_append (&auxdata, " spid="))
602 if (!_dbus_string_append_uint (&auxdata, spid))
608 if (!_dbus_string_append (&auxdata, " tpid="))
611 if (!_dbus_string_append_uint (&auxdata, tpid))
615 sender_sid = bus_connection_get_selinux_id (sender);
616 /* A NULL proposed_recipient means the bus itself. */
617 if (proposed_recipient)
618 recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
620 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
622 ret = bus_selinux_check (sender_sid,
628 _dbus_string_free (&auxdata);
634 _dbus_string_free (&auxdata);
640 #endif /* HAVE_SELINUX */
644 bus_selinux_append_context (DBusMessage *message,
651 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
656 dbus_set_error (error, DBUS_ERROR_FAILED,
657 "Error getting context from SID: %s\n",
658 _dbus_strerror (errno));
661 if (!dbus_message_append_args (message,
668 _DBUS_SET_OOM (error);
679 * Gets the security context of a connection to the bus. It is up to
680 * the caller to freecon() when they are done.
682 * @param connection the connection to get the context of.
683 * @param con the location to store the security context.
684 * @returns #TRUE if context is successfully obtained.
688 bus_connection_read_selinux_context (DBusConnection *connection,
693 if (!selinux_enabled)
696 _dbus_assert (connection != NULL);
698 if (!dbus_connection_get_unix_fd (connection, &fd))
700 _dbus_verbose ("Failed to get file descriptor of socket.\n");
704 if (getpeercon (fd, con) < 0)
706 _dbus_verbose ("Error getting context of socket peer: %s\n",
707 _dbus_strerror (errno));
711 _dbus_verbose ("Successfully read connection context.\n");
714 #endif /* HAVE_SELINUX */
717 * Read the SELinux ID from the connection.
719 * @param connection the connection to read from
720 * @returns the SID if successfully determined, #NULL otherwise.
723 bus_selinux_init_connection_id (DBusConnection *connection,
730 if (!selinux_enabled)
733 if (!bus_connection_read_selinux_context (connection, &con))
735 dbus_set_error (error, DBUS_ERROR_FAILED,
736 "Failed to read an SELinux context from connection");
737 _dbus_verbose ("Error getting peer context.\n");
741 _dbus_verbose ("Converting context to SID to store on connection\n");
743 if (avc_context_to_sid (con, &sid) < 0)
748 dbus_set_error (error, DBUS_ERROR_FAILED,
749 "Error getting SID from context \"%s\": %s\n",
750 con, _dbus_strerror (errno));
752 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
753 con, _dbus_strerror (errno));
760 return BUS_SID_FROM_SELINUX (sid);
763 #endif /* HAVE_SELINUX */
768 * Function for freeing hash table data. These SIDs
769 * should no longer be referenced.
772 bus_selinux_id_table_free_value (BusSELinuxID *sid)
775 /* NULL sometimes due to how DBusHashTable works */
777 bus_selinux_id_unref (sid);
778 #endif /* HAVE_SELINUX */
782 * Creates a new table mapping service names to security ID.
783 * A security ID is a "compiled" security context, a security
784 * context is just a string.
786 * @returns the new table or #NULL if no memory
789 bus_selinux_id_table_new (void)
791 return _dbus_hash_table_new (DBUS_HASH_STRING,
792 (DBusFreeFunction) dbus_free,
793 (DBusFreeFunction) bus_selinux_id_table_free_value);
797 * Hashes a service name and service context into the service SID
798 * table as a string and a SID.
800 * @param service_name is the name of the service.
801 * @param service_context is the context of the service.
802 * @param service_table is the table to hash them into.
803 * @return #FALSE if not enough memory
806 bus_selinux_id_table_insert (DBusHashTable *service_table,
807 const char *service_name,
808 const char *service_context)
815 if (!selinux_enabled)
821 key = _dbus_strdup (service_name);
825 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
833 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
834 (char *) service_context,
835 _dbus_strerror (errno));
839 if (!_dbus_hash_table_insert_string (service_table,
841 BUS_SID_FROM_SELINUX (sid)))
844 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
848 /* These are owned by the hash, so clear them to avoid unref */
855 if (sid != SECSID_WILD)
864 #endif /* HAVE_SELINUX */
869 * Find the security identifier associated with a particular service
870 * name. Return a pointer to this SID, or #NULL/SECSID_WILD if the
871 * service is not found in the hash table. This should be nearly a
872 * constant time operation. If SELinux support is not available,
873 * always return NULL.
875 * @param service_table the hash table to check for service name.
876 * @param service_name the name of the service to look for.
877 * @returns the SELinux ID associated with the service
880 bus_selinux_id_table_lookup (DBusHashTable *service_table,
881 const DBusString *service_name)
886 sid = SECSID_WILD; /* default context */
888 if (!selinux_enabled)
891 _dbus_verbose ("Looking up service SID for %s\n",
892 _dbus_string_get_const_data (service_name));
894 sid = _dbus_hash_table_lookup_string (service_table,
895 _dbus_string_get_const_data (service_name));
897 if (sid == SECSID_WILD)
898 _dbus_verbose ("Service %s not found\n",
899 _dbus_string_get_const_data (service_name));
901 _dbus_verbose ("Service %s found\n",
902 _dbus_string_get_const_data (service_name));
904 return BUS_SID_FROM_SELINUX (sid);
905 #endif /* HAVE_SELINUX */
910 * Get the SELinux policy root. This is used to find the D-Bus
911 * specific config file within the policy.
914 bus_selinux_get_policy_root (void)
917 return selinux_policy_root ();
920 #endif /* HAVE_SELINUX */
924 * For debugging: Print out the current hash table of service SIDs.
927 bus_selinux_id_table_print (DBusHashTable *service_table)
929 #ifdef DBUS_ENABLE_VERBOSE_MODE
933 if (!selinux_enabled)
936 _dbus_verbose ("Service SID Table:\n");
937 _dbus_hash_iter_init (service_table, &iter);
938 while (_dbus_hash_iter_next (&iter))
940 const char *key = _dbus_hash_iter_get_string_key (&iter);
941 security_id_t sid = _dbus_hash_iter_get_value (&iter);
942 _dbus_verbose ("The key is %s\n", key);
943 _dbus_verbose ("The context is %s\n", sid->ctx);
944 _dbus_verbose ("The refcount is %d\n", sid->refcnt);
946 #endif /* HAVE_SELINUX */
947 #endif /* DBUS_ENABLE_VERBOSE_MODE */
951 #ifdef DBUS_ENABLE_VERBOSE_MODE
954 * Print out some AVC statistics.
957 bus_avc_print_stats (void)
959 struct avc_cache_stats cstats;
961 if (!selinux_enabled)
964 _dbus_verbose ("AVC Statistics:\n");
965 avc_cache_stats (&cstats);
967 _dbus_verbose ("AVC Cache Statistics:\n");
968 _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
969 _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
970 _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
971 _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
972 _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
973 _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
974 _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
975 _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
977 #endif /* HAVE_SELINUX */
978 #endif /* DBUS_ENABLE_VERBOSE_MODE */
982 * Destroy the AVC before we terminate.
985 bus_selinux_shutdown (void)
988 if (!selinux_enabled)
991 _dbus_verbose ("AVC shutdown\n");
993 if (bus_sid != SECSID_WILD)
996 bus_sid = SECSID_WILD;
998 #ifdef DBUS_ENABLE_VERBOSE_MODE
1000 if (_dbus_is_verbose())
1001 bus_avc_print_stats ();
1003 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1006 #ifdef HAVE_LIBAUDIT
1007 audit_close (audit_fd);
1008 #endif /* HAVE_LIBAUDIT */
1010 #endif /* HAVE_SELINUX */