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
23 #include <dbus/dbus-internals.h>
24 #include <dbus/dbus-string.h>
25 #include <dbus/dbus-userdb.h>
30 #include "config-parser.h"
33 #include <sys/types.h>
41 #include <selinux/selinux.h>
42 #include <selinux/avc.h>
43 #include <selinux/av_permissions.h>
44 #include <selinux/flask.h>
52 #endif /* HAVE_LIBAUDIT */
53 #endif /* HAVE_SELINUX */
55 #define BUS_SID_FROM_SELINUX(sid) ((BusSELinuxID*) (sid))
56 #define SELINUX_SID_FROM_BUS(sid) ((security_id_t) (sid))
59 /* Store the value telling us if SELinux is enabled in the kernel. */
60 static dbus_bool_t selinux_enabled = FALSE;
62 /* Store an avc_entry_ref to speed AVC decisions. */
63 static struct avc_entry_ref aeref;
65 /* Store the SID of the bus itself to use as the default. */
66 static security_id_t bus_sid = SECSID_WILD;
68 /* Thread to listen for SELinux status changes via netlink. */
69 static pthread_t avc_notify_thread;
71 /* Prototypes for AVC callback functions. */
72 static void log_callback (const char *fmt, ...);
73 static void log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft);
74 static void *avc_create_thread (void (*run) (void));
75 static void avc_stop_thread (void *thread);
76 static void *avc_alloc_lock (void);
77 static void avc_get_lock (void *lock);
78 static void avc_release_lock (void *lock);
79 static void avc_free_lock (void *lock);
81 /* AVC callback structures for use in avc_init. */
82 static const struct avc_memory_callback mem_cb =
84 .func_malloc = dbus_malloc,
85 .func_free = dbus_free
87 static const struct avc_log_callback log_cb =
89 .func_log = log_callback,
90 .func_audit = log_audit_callback
92 static const struct avc_thread_callback thread_cb =
94 .func_create_thread = avc_create_thread,
95 .func_stop_thread = avc_stop_thread
97 static const struct avc_lock_callback lock_cb =
99 .func_alloc_lock = avc_alloc_lock,
100 .func_get_lock = avc_get_lock,
101 .func_release_lock = avc_release_lock,
102 .func_free_lock = avc_free_lock
104 #endif /* HAVE_SELINUX */
107 * Log callback to log denial messages from the AVC.
108 * This is used in avc_init. Logs to both standard
111 * @param fmt the format string
112 * @param variable argument list
117 static int audit_fd = -1;
121 bus_selinux_audit_init(void)
124 audit_fd = audit_open ();
128 /* If kernel doesn't support audit, bail out */
129 if (errno == EINVAL || errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT)
131 /* If user bus, bail out */
132 if (errno == EPERM && getuid() != 0)
134 _dbus_warn ("Failed opening connection to the audit subsystem");
136 #endif /* HAVE_LIBAUDIT */
140 log_callback (const char *fmt, ...)
149 capng_get_caps_process();
150 if (capng_have_capability(CAPNG_EFFECTIVE, CAP_AUDIT_WRITE))
152 char buf[PATH_MAX*2];
154 /* FIXME: need to change this to show real user */
155 vsnprintf(buf, sizeof(buf), fmt, ap);
156 audit_log_user_avc_message(audit_fd, AUDIT_USER_AVC, buf, NULL, NULL,
161 #endif /* HAVE_LIBAUDIT */
163 vsyslog (LOG_INFO, fmt, ap);
168 * On a policy reload we need to reparse the SELinux configuration file, since
169 * this could have changed. Send a SIGHUP to reload all configs.
172 policy_reload_callback (u_int32_t event, security_id_t ssid,
173 security_id_t tsid, security_class_t tclass,
174 access_vector_t perms, access_vector_t *out_retained)
176 if (event == AVC_CALLBACK_RESET)
177 return raise (SIGHUP);
183 * Log any auxiliary data
186 log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
188 DBusString *audmsg = data;
190 if (bufleft > (size_t) _dbus_string_get_length(audmsg))
192 _dbus_string_copy_to_buffer_with_nul (audmsg, buf, bufleft);
198 _dbus_string_init_const(&s, "Buffer too small for audit message");
200 if (bufleft > (size_t) _dbus_string_get_length(&s))
201 _dbus_string_copy_to_buffer_with_nul (&s, buf, bufleft);
206 * Create thread to notify the AVC of enforcing and policy reload
207 * changes via netlink.
209 * @param run the thread run function
210 * @return pointer to the thread
213 avc_create_thread (void (*run) (void))
217 rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
220 _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
223 return &avc_notify_thread;
226 /* Stop AVC netlink thread. */
228 avc_stop_thread (void *thread)
230 pthread_cancel (*(pthread_t *) thread);
233 /* Allocate a new AVC lock. */
235 avc_alloc_lock (void)
237 pthread_mutex_t *avc_mutex;
239 avc_mutex = dbus_new (pthread_mutex_t, 1);
240 if (avc_mutex == NULL)
242 _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
245 pthread_mutex_init (avc_mutex, NULL);
250 /* Acquire an AVC lock. */
252 avc_get_lock (void *lock)
254 pthread_mutex_lock (lock);
257 /* Release an AVC lock. */
259 avc_release_lock (void *lock)
261 pthread_mutex_unlock (lock);
264 /* Free an AVC lock. */
266 avc_free_lock (void *lock)
268 pthread_mutex_destroy (lock);
271 #endif /* HAVE_SELINUX */
274 * Return whether or not SELinux is enabled; must be
275 * called after bus_selinux_init.
278 bus_selinux_enabled (void)
281 return selinux_enabled;
284 #endif /* HAVE_SELINUX */
288 * Do early initialization; determine whether SELinux is enabled.
291 bus_selinux_pre_init (void)
295 _dbus_assert (bus_sid == SECSID_WILD);
297 /* Determine if we are running an SELinux kernel. */
298 r = is_selinux_enabled ();
301 _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
302 _dbus_strerror (errno));
306 selinux_enabled = r != 0;
314 * Initialize the user space access vector cache (AVC) for D-Bus and set up
318 bus_selinux_full_init (void)
323 _dbus_assert (bus_sid == SECSID_WILD);
325 if (!selinux_enabled)
327 _dbus_verbose ("SELinux not enabled in this kernel.\n");
331 _dbus_verbose ("SELinux is enabled in this kernel.\n");
333 avc_entry_ref_init (&aeref);
334 if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
336 _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
341 openlog ("dbus", LOG_PERROR, LOG_USER);
342 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
345 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
346 NULL, NULL, 0, 0) < 0)
348 _dbus_warn ("Failed to add policy reload callback: %s\n",
349 _dbus_strerror (errno));
355 bus_sid = SECSID_WILD;
357 if (getcon (&bus_context) < 0)
359 _dbus_verbose ("Error getting context of bus: %s\n",
360 _dbus_strerror (errno));
364 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
366 _dbus_verbose ("Error getting SID from bus context: %s\n",
367 _dbus_strerror (errno));
368 freecon (bus_context);
372 freecon (bus_context);
374 #endif /* HAVE_SELINUX */
379 * Decrement SID reference count.
381 * @param sid the SID to decrement
384 bus_selinux_id_unref (BusSELinuxID *sid)
387 if (!selinux_enabled)
390 _dbus_assert (sid != NULL);
392 sidput (SELINUX_SID_FROM_BUS (sid));
393 #endif /* HAVE_SELINUX */
397 bus_selinux_id_ref (BusSELinuxID *sid)
400 if (!selinux_enabled)
403 _dbus_assert (sid != NULL);
405 sidget (SELINUX_SID_FROM_BUS (sid));
406 #endif /* HAVE_SELINUX */
410 * Determine if the SELinux security policy allows the given sender
411 * security context to go to the given recipient security context.
412 * This function determines if the requested permissions are to be
413 * granted from the connection to the message bus or to another
414 * optionally supplied security identifier (e.g. for a service
415 * context). Currently these permissions are either send_msg or
416 * acquire_svc in the dbus class.
418 * @param sender_sid source security context
419 * @param override_sid is the target security context. If SECSID_WILD this will
420 * use the context of the bus itself (e.g. the default).
421 * @param target_class is the target security class.
422 * @param requested is the requested permissions.
423 * @returns #TRUE if security policy allows the send.
427 bus_selinux_check (BusSELinuxID *sender_sid,
428 BusSELinuxID *override_sid,
429 security_class_t target_class,
430 access_vector_t requested,
433 if (!selinux_enabled)
436 /* Make the security check. AVC checks enforcing mode here as well. */
437 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
439 SELINUX_SID_FROM_BUS (override_sid) :
440 SELINUX_SID_FROM_BUS (bus_sid),
441 target_class, requested, &aeref, auxdata) < 0)
446 _dbus_verbose ("SELinux denying due to security policy.\n");
449 _dbus_verbose ("SELinux denying due to invalid security context.\n");
452 _dbus_verbose ("SELinux denying due to: %s\n", _dbus_strerror (errno));
459 #endif /* HAVE_SELINUX */
462 * Returns true if the given connection can acquire a service,
463 * assuming the given security ID is needed for that service.
465 * @param connection connection that wants to own the service
466 * @param service_sid the SID of the service from the table
467 * @returns #TRUE if acquire is permitted.
470 bus_selinux_allows_acquire_service (DBusConnection *connection,
471 BusSELinuxID *service_sid,
472 const char *service_name,
476 BusSELinuxID *connection_sid;
481 if (!selinux_enabled)
484 connection_sid = bus_connection_get_selinux_id (connection);
485 if (!dbus_connection_get_unix_process_id (connection, &spid))
488 if (!_dbus_string_init (&auxdata))
491 if (!_dbus_string_append (&auxdata, "service="))
494 if (!_dbus_string_append (&auxdata, service_name))
499 if (!_dbus_string_append (&auxdata, " spid="))
502 if (!_dbus_string_append_uint (&auxdata, spid))
506 ret = bus_selinux_check (connection_sid,
512 _dbus_string_free (&auxdata);
516 _dbus_string_free (&auxdata);
522 #endif /* HAVE_SELINUX */
526 * Check if SELinux security controls allow the message to be sent to a
527 * particular connection based on the security context of the sender and
528 * that of the receiver. The destination connection need not be the
529 * addressed recipient, it could be an "eavesdropper"
531 * @param sender the sender of the message.
532 * @param proposed_recipient the connection the message is to be sent to.
533 * @returns whether to allow the send
536 bus_selinux_allows_send (DBusConnection *sender,
537 DBusConnection *proposed_recipient,
539 const char *interface,
541 const char *error_name,
542 const char *destination,
546 BusSELinuxID *recipient_sid;
547 BusSELinuxID *sender_sid;
548 unsigned long spid, tpid;
551 dbus_bool_t string_alloced;
553 if (!selinux_enabled)
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);
623 /* A NULL proposed_recipient means the bus itself. */
624 if (proposed_recipient)
625 recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
627 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
629 ret = bus_selinux_check (sender_sid,
635 _dbus_string_free (&auxdata);
641 _dbus_string_free (&auxdata);
647 #endif /* HAVE_SELINUX */
651 bus_selinux_append_context (DBusMessage *message,
658 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
663 dbus_set_error (error, DBUS_ERROR_FAILED,
664 "Error getting context from SID: %s\n",
665 _dbus_strerror (errno));
668 if (!dbus_message_append_args (message,
675 _DBUS_SET_OOM (error);
686 * Gets the security context of a connection to the bus. It is up to
687 * the caller to freecon() when they are done.
689 * @param connection the connection to get the context of.
690 * @param con the location to store the security context.
691 * @returns #TRUE if context is successfully obtained.
695 bus_connection_read_selinux_context (DBusConnection *connection,
700 if (!selinux_enabled)
703 _dbus_assert (connection != NULL);
705 if (!dbus_connection_get_unix_fd (connection, &fd))
707 _dbus_verbose ("Failed to get file descriptor of socket.\n");
711 if (getpeercon (fd, con) < 0)
713 _dbus_verbose ("Error getting context of socket peer: %s\n",
714 _dbus_strerror (errno));
718 _dbus_verbose ("Successfully read connection context.\n");
721 #endif /* HAVE_SELINUX */
724 * Read the SELinux ID from the connection.
726 * @param connection the connection to read from
727 * @returns the SID if successfully determined, #NULL otherwise.
730 bus_selinux_init_connection_id (DBusConnection *connection,
737 if (!selinux_enabled)
740 if (!bus_connection_read_selinux_context (connection, &con))
742 dbus_set_error (error, DBUS_ERROR_FAILED,
743 "Failed to read an SELinux context from connection");
744 _dbus_verbose ("Error getting peer context.\n");
748 _dbus_verbose ("Converting context to SID to store on connection\n");
750 if (avc_context_to_sid (con, &sid) < 0)
755 dbus_set_error (error, DBUS_ERROR_FAILED,
756 "Error getting SID from context \"%s\": %s\n",
757 con, _dbus_strerror (errno));
759 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
760 con, _dbus_strerror (errno));
767 return BUS_SID_FROM_SELINUX (sid);
770 #endif /* HAVE_SELINUX */
775 * Function for freeing hash table data. These SIDs
776 * should no longer be referenced.
779 bus_selinux_id_table_free_value (BusSELinuxID *sid)
782 /* NULL sometimes due to how DBusHashTable works */
784 bus_selinux_id_unref (sid);
785 #endif /* HAVE_SELINUX */
789 * Creates a new table mapping service names to security ID.
790 * A security ID is a "compiled" security context, a security
791 * context is just a string.
793 * @returns the new table or #NULL if no memory
796 bus_selinux_id_table_new (void)
798 return _dbus_hash_table_new (DBUS_HASH_STRING,
799 (DBusFreeFunction) dbus_free,
800 (DBusFreeFunction) bus_selinux_id_table_free_value);
804 * Hashes a service name and service context into the service SID
805 * table as a string and a SID.
807 * @param service_name is the name of the service.
808 * @param service_context is the context of the service.
809 * @param service_table is the table to hash them into.
810 * @return #FALSE if not enough memory
813 bus_selinux_id_table_insert (DBusHashTable *service_table,
814 const char *service_name,
815 const char *service_context)
822 if (!selinux_enabled)
828 key = _dbus_strdup (service_name);
832 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
840 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
841 (char *) service_context,
842 _dbus_strerror (errno));
846 if (!_dbus_hash_table_insert_string (service_table,
848 BUS_SID_FROM_SELINUX (sid)))
851 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
855 /* These are owned by the hash, so clear them to avoid unref */
862 if (sid != SECSID_WILD)
871 #endif /* HAVE_SELINUX */
876 * Find the security identifier associated with a particular service
877 * name. Return a pointer to this SID, or #NULL/SECSID_WILD if the
878 * service is not found in the hash table. This should be nearly a
879 * constant time operation. If SELinux support is not available,
880 * always return NULL.
882 * @param service_table the hash table to check for service name.
883 * @param service_name the name of the service to look for.
884 * @returns the SELinux ID associated with the service
887 bus_selinux_id_table_lookup (DBusHashTable *service_table,
888 const DBusString *service_name)
893 sid = SECSID_WILD; /* default context */
895 if (!selinux_enabled)
898 _dbus_verbose ("Looking up service SID for %s\n",
899 _dbus_string_get_const_data (service_name));
901 sid = _dbus_hash_table_lookup_string (service_table,
902 _dbus_string_get_const_data (service_name));
904 if (sid == SECSID_WILD)
905 _dbus_verbose ("Service %s not found\n",
906 _dbus_string_get_const_data (service_name));
908 _dbus_verbose ("Service %s found\n",
909 _dbus_string_get_const_data (service_name));
911 return BUS_SID_FROM_SELINUX (sid);
912 #endif /* HAVE_SELINUX */
917 * Get the SELinux policy root. This is used to find the D-Bus
918 * specific config file within the policy.
921 bus_selinux_get_policy_root (void)
924 return selinux_policy_root ();
927 #endif /* HAVE_SELINUX */
931 * For debugging: Print out the current hash table of service SIDs.
934 bus_selinux_id_table_print (DBusHashTable *service_table)
936 #ifdef DBUS_ENABLE_VERBOSE_MODE
940 if (!selinux_enabled)
943 _dbus_verbose ("Service SID Table:\n");
944 _dbus_hash_iter_init (service_table, &iter);
945 while (_dbus_hash_iter_next (&iter))
947 const char *key = _dbus_hash_iter_get_string_key (&iter);
948 security_id_t sid = _dbus_hash_iter_get_value (&iter);
949 _dbus_verbose ("The key is %s\n", key);
950 _dbus_verbose ("The context is %s\n", sid->ctx);
951 _dbus_verbose ("The refcount is %d\n", sid->refcnt);
953 #endif /* HAVE_SELINUX */
954 #endif /* DBUS_ENABLE_VERBOSE_MODE */
958 #ifdef DBUS_ENABLE_VERBOSE_MODE
961 * Print out some AVC statistics.
964 bus_avc_print_stats (void)
966 struct avc_cache_stats cstats;
968 if (!selinux_enabled)
971 _dbus_verbose ("AVC Statistics:\n");
972 avc_cache_stats (&cstats);
974 _dbus_verbose ("AVC Cache Statistics:\n");
975 _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
976 _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
977 _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
978 _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
979 _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
980 _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
981 _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
982 _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
984 #endif /* HAVE_SELINUX */
985 #endif /* DBUS_ENABLE_VERBOSE_MODE */
989 * Destroy the AVC before we terminate.
992 bus_selinux_shutdown (void)
995 if (!selinux_enabled)
998 _dbus_verbose ("AVC shutdown\n");
1000 if (bus_sid != SECSID_WILD)
1003 bus_sid = SECSID_WILD;
1005 #ifdef DBUS_ENABLE_VERBOSE_MODE
1007 if (_dbus_is_verbose())
1008 bus_avc_print_stats ();
1010 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1013 #ifdef HAVE_LIBAUDIT
1014 audit_close (audit_fd);
1015 #endif /* HAVE_LIBAUDIT */
1017 #endif /* HAVE_SELINUX */
1021 * Changes the user and group the bus is running as.
1023 * @param user the user to become
1024 * @param error return location for errors
1025 * @returns #FALSE on failure
1028 _dbus_change_to_daemon_user (const char *user,
1035 _dbus_string_init_const (&u, user);
1037 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
1039 dbus_set_error (error, DBUS_ERROR_FAILED,
1040 "User '%s' does not appear to exist?",
1045 #ifdef HAVE_LIBAUDIT
1046 /* If we were root */
1047 if (_dbus_geteuid () == 0)
1051 capng_clear (CAPNG_SELECT_BOTH);
1052 capng_update (CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
1054 rc = capng_change_id (uid, gid, 0);
1059 dbus_set_error (error, DBUS_ERROR_FAILED,
1060 "Failed to drop capabilities: %s\n",
1061 _dbus_strerror (errno));
1064 dbus_set_error (error, _dbus_error_from_errno (errno),
1065 "Failed to set GID to %lu: %s", gid,
1066 _dbus_strerror (errno));
1069 _dbus_warn ("Failed to drop supplementary groups: %s\n",
1070 _dbus_strerror (errno));
1073 dbus_set_error (error, _dbus_error_from_errno (errno),
1074 "Failed to set UID to %lu: %s", uid,
1075 _dbus_strerror (errno));
1078 dbus_set_error (error, _dbus_error_from_errno (errno),
1079 "Failed to unset keep-capabilities: %s\n",
1080 _dbus_strerror (errno));
1087 /* setgroups() only works if we are a privileged process,
1088 * so we don't return error on failure; the only possible
1089 * failure is that we don't have perms to do it.
1091 * not sure this is right, maybe if setuid()
1092 * is going to work then setgroups() should also work.
1094 if (setgroups (0, NULL) < 0)
1095 _dbus_warn ("Failed to drop supplementary groups: %s\n",
1096 _dbus_strerror (errno));
1098 /* Set GID first, or the setuid may remove our permission
1101 if (setgid (gid) < 0)
1103 dbus_set_error (error, _dbus_error_from_errno (errno),
1104 "Failed to set GID to %lu: %s", gid,
1105 _dbus_strerror (errno));
1109 if (setuid (uid) < 0)
1111 dbus_set_error (error, _dbus_error_from_errno (errno),
1112 "Failed to set UID to %lu: %s", uid,
1113 _dbus_strerror (errno));
1116 #endif /* !HAVE_LIBAUDIT */