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>
34 #include "config-parser.h"
40 #include <sys/types.h>
45 #include <selinux/selinux.h>
46 #include <selinux/avc.h>
47 #include <selinux/av_permissions.h>
48 #include <selinux/flask.h>
53 #endif /* HAVE_SELINUX */
57 #endif /* HAVE_LIBAUDIT */
59 #define BUS_SID_FROM_SELINUX(sid) ((BusSELinuxID*) (sid))
60 #define SELINUX_SID_FROM_BUS(sid) ((security_id_t) (sid))
63 /* Store the value telling us if SELinux is enabled in the kernel. */
64 static dbus_bool_t selinux_enabled = FALSE;
66 /* Store an avc_entry_ref to speed AVC decisions. */
67 static struct avc_entry_ref aeref;
69 /* Store the SID of the bus itself to use as the default. */
70 static security_id_t bus_sid = SECSID_WILD;
72 /* Thread to listen for SELinux status changes via netlink. */
73 static pthread_t avc_notify_thread;
75 /* Prototypes for AVC callback functions. */
76 static void log_callback (const char *fmt, ...);
77 static void log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft);
78 static void *avc_create_thread (void (*run) (void));
79 static void avc_stop_thread (void *thread);
80 static void *avc_alloc_lock (void);
81 static void avc_get_lock (void *lock);
82 static void avc_release_lock (void *lock);
83 static void avc_free_lock (void *lock);
85 /* AVC callback structures for use in avc_init. */
86 static const struct avc_memory_callback mem_cb =
88 .func_malloc = dbus_malloc,
89 .func_free = dbus_free
91 static const struct avc_log_callback log_cb =
93 .func_log = log_callback,
94 .func_audit = log_audit_callback
96 static const struct avc_thread_callback thread_cb =
98 .func_create_thread = avc_create_thread,
99 .func_stop_thread = avc_stop_thread
101 static const struct avc_lock_callback lock_cb =
103 .func_alloc_lock = avc_alloc_lock,
104 .func_get_lock = avc_get_lock,
105 .func_release_lock = avc_release_lock,
106 .func_free_lock = avc_free_lock
108 #endif /* HAVE_SELINUX */
111 * Log callback to log denial messages from the AVC.
112 * This is used in avc_init. Logs to both standard
115 * @param fmt the format string
116 * @param variable argument list
121 static int audit_fd = -1;
125 bus_selinux_audit_init(void)
128 audit_fd = audit_open ();
132 /* If kernel doesn't support audit, bail out */
133 if (errno == EINVAL || errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT)
135 /* If user bus, bail out */
136 if (errno == EPERM && getuid() != 0)
138 _dbus_warn ("Failed opening connection to the audit subsystem");
140 #endif /* HAVE_LIBAUDIT */
144 log_callback (const char *fmt, ...)
153 capng_get_caps_process();
154 if (capng_have_capability(CAPNG_EFFECTIVE, CAP_AUDIT_WRITE))
156 char buf[PATH_MAX*2];
158 /* FIXME: need to change this to show real user */
159 vsnprintf(buf, sizeof(buf), fmt, ap);
160 audit_log_user_avc_message(audit_fd, AUDIT_USER_AVC, buf, NULL, NULL,
165 #endif /* HAVE_LIBAUDIT */
167 vsyslog (LOG_USER | LOG_INFO, fmt, ap);
172 * On a policy reload we need to reparse the SELinux configuration file, since
173 * this could have changed. Send a SIGHUP to reload all configs.
176 policy_reload_callback (u_int32_t event, security_id_t ssid,
177 security_id_t tsid, security_class_t tclass,
178 access_vector_t perms, access_vector_t *out_retained)
180 if (event == AVC_CALLBACK_RESET)
181 return raise (SIGHUP);
187 * Log any auxiliary data
190 log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
192 DBusString *audmsg = data;
194 if (bufleft > (size_t) _dbus_string_get_length(audmsg))
196 _dbus_string_copy_to_buffer_with_nul (audmsg, buf, bufleft);
202 _dbus_string_init_const(&s, "Buffer too small for audit message");
204 if (bufleft > (size_t) _dbus_string_get_length(&s))
205 _dbus_string_copy_to_buffer_with_nul (&s, buf, bufleft);
210 * Create thread to notify the AVC of enforcing and policy reload
211 * changes via netlink.
213 * @param run the thread run function
214 * @return pointer to the thread
217 avc_create_thread (void (*run) (void))
221 rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
224 _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
227 return &avc_notify_thread;
230 /* Stop AVC netlink thread. */
232 avc_stop_thread (void *thread)
234 pthread_cancel (*(pthread_t *) thread);
237 /* Allocate a new AVC lock. */
239 avc_alloc_lock (void)
241 pthread_mutex_t *avc_mutex;
243 avc_mutex = dbus_new (pthread_mutex_t, 1);
244 if (avc_mutex == NULL)
246 _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
249 pthread_mutex_init (avc_mutex, NULL);
254 /* Acquire an AVC lock. */
256 avc_get_lock (void *lock)
258 pthread_mutex_lock (lock);
261 /* Release an AVC lock. */
263 avc_release_lock (void *lock)
265 pthread_mutex_unlock (lock);
268 /* Free an AVC lock. */
270 avc_free_lock (void *lock)
272 pthread_mutex_destroy (lock);
275 #endif /* HAVE_SELINUX */
278 * Return whether or not SELinux is enabled; must be
279 * called after bus_selinux_init.
282 bus_selinux_enabled (void)
285 return selinux_enabled;
288 #endif /* HAVE_SELINUX */
292 * Do early initialization; determine whether SELinux is enabled.
295 bus_selinux_pre_init (void)
299 _dbus_assert (bus_sid == SECSID_WILD);
301 /* Determine if we are running an SELinux kernel. */
302 r = is_selinux_enabled ();
305 _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
306 _dbus_strerror (errno));
310 selinux_enabled = r != 0;
318 * Initialize the user space access vector cache (AVC) for D-Bus and set up
322 bus_selinux_full_init (void)
327 _dbus_assert (bus_sid == SECSID_WILD);
329 if (!selinux_enabled)
331 _dbus_verbose ("SELinux not enabled in this kernel.\n");
335 _dbus_verbose ("SELinux is enabled in this kernel.\n");
337 avc_entry_ref_init (&aeref);
338 if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
340 _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
345 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
348 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
349 NULL, NULL, 0, 0) < 0)
351 _dbus_warn ("Failed to add policy reload callback: %s\n",
352 _dbus_strerror (errno));
358 bus_sid = SECSID_WILD;
360 if (getcon (&bus_context) < 0)
362 _dbus_verbose ("Error getting context of bus: %s\n",
363 _dbus_strerror (errno));
367 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
369 _dbus_verbose ("Error getting SID from bus context: %s\n",
370 _dbus_strerror (errno));
371 freecon (bus_context);
375 freecon (bus_context);
377 #endif /* HAVE_SELINUX */
382 * Decrement SID reference count.
384 * @param sid the SID to decrement
387 bus_selinux_id_unref (BusSELinuxID *sid)
390 if (!selinux_enabled)
393 _dbus_assert (sid != NULL);
395 sidput (SELINUX_SID_FROM_BUS (sid));
396 #endif /* HAVE_SELINUX */
400 bus_selinux_id_ref (BusSELinuxID *sid)
403 if (!selinux_enabled)
406 _dbus_assert (sid != NULL);
408 sidget (SELINUX_SID_FROM_BUS (sid));
409 #endif /* HAVE_SELINUX */
413 * Determine if the SELinux security policy allows the given sender
414 * security context to go to the given recipient security context.
415 * This function determines if the requested permissions are to be
416 * granted from the connection to the message bus or to another
417 * optionally supplied security identifier (e.g. for a service
418 * context). Currently these permissions are either send_msg or
419 * acquire_svc in the dbus class.
421 * @param sender_sid source security context
422 * @param override_sid is the target security context. If SECSID_WILD this will
423 * use the context of the bus itself (e.g. the default).
424 * @param target_class is the target security class.
425 * @param requested is the requested permissions.
426 * @returns #TRUE if security policy allows the send.
430 bus_selinux_check (BusSELinuxID *sender_sid,
431 BusSELinuxID *override_sid,
432 security_class_t target_class,
433 access_vector_t requested,
436 if (!selinux_enabled)
439 /* Make the security check. AVC checks enforcing mode here as well. */
440 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
442 SELINUX_SID_FROM_BUS (override_sid) :
443 SELINUX_SID_FROM_BUS (bus_sid),
444 target_class, requested, &aeref, auxdata) < 0)
449 _dbus_verbose ("SELinux denying due to security policy.\n");
452 _dbus_verbose ("SELinux denying due to invalid security context.\n");
455 _dbus_verbose ("SELinux denying due to: %s\n", _dbus_strerror (errno));
462 #endif /* HAVE_SELINUX */
465 * Returns true if the given connection can acquire a service,
466 * assuming the given security ID is needed for that service.
468 * @param connection connection that wants to own the service
469 * @param service_sid the SID of the service from the table
470 * @returns #TRUE if acquire is permitted.
473 bus_selinux_allows_acquire_service (DBusConnection *connection,
474 BusSELinuxID *service_sid,
475 const char *service_name,
479 BusSELinuxID *connection_sid;
484 if (!selinux_enabled)
487 connection_sid = bus_connection_get_selinux_id (connection);
488 if (!dbus_connection_get_unix_process_id (connection, &spid))
491 if (!_dbus_string_init (&auxdata))
494 if (!_dbus_string_append (&auxdata, "service="))
497 if (!_dbus_string_append (&auxdata, service_name))
502 if (!_dbus_string_append (&auxdata, " spid="))
505 if (!_dbus_string_append_uint (&auxdata, spid))
509 ret = bus_selinux_check (connection_sid,
515 _dbus_string_free (&auxdata);
519 _dbus_string_free (&auxdata);
525 #endif /* HAVE_SELINUX */
529 * Check if SELinux security controls allow the message to be sent to a
530 * particular connection based on the security context of the sender and
531 * that of the receiver. The destination connection need not be the
532 * addressed recipient, it could be an "eavesdropper"
534 * @param sender the sender of the message.
535 * @param proposed_recipient the connection the message is to be sent to.
536 * @returns whether to allow the send
539 bus_selinux_allows_send (DBusConnection *sender,
540 DBusConnection *proposed_recipient,
542 const char *interface,
544 const char *error_name,
545 const char *destination,
549 BusSELinuxID *recipient_sid;
550 BusSELinuxID *sender_sid;
551 unsigned long spid, tpid;
554 dbus_bool_t string_alloced;
556 if (!selinux_enabled)
559 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
561 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
564 string_alloced = FALSE;
565 if (!_dbus_string_init (&auxdata))
567 string_alloced = TRUE;
569 if (!_dbus_string_append (&auxdata, "msgtype="))
572 if (!_dbus_string_append (&auxdata, msgtype))
577 if (!_dbus_string_append (&auxdata, " interface="))
579 if (!_dbus_string_append (&auxdata, interface))
585 if (!_dbus_string_append (&auxdata, " member="))
587 if (!_dbus_string_append (&auxdata, member))
593 if (!_dbus_string_append (&auxdata, " error_name="))
595 if (!_dbus_string_append (&auxdata, error_name))
601 if (!_dbus_string_append (&auxdata, " dest="))
603 if (!_dbus_string_append (&auxdata, destination))
609 if (!_dbus_string_append (&auxdata, " spid="))
612 if (!_dbus_string_append_uint (&auxdata, spid))
618 if (!_dbus_string_append (&auxdata, " tpid="))
621 if (!_dbus_string_append_uint (&auxdata, tpid))
625 sender_sid = bus_connection_get_selinux_id (sender);
626 /* A NULL proposed_recipient means the bus itself. */
627 if (proposed_recipient)
628 recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
630 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
632 ret = bus_selinux_check (sender_sid,
638 _dbus_string_free (&auxdata);
644 _dbus_string_free (&auxdata);
650 #endif /* HAVE_SELINUX */
654 bus_selinux_append_context (DBusMessage *message,
661 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
666 dbus_set_error (error, DBUS_ERROR_FAILED,
667 "Error getting context from SID: %s\n",
668 _dbus_strerror (errno));
671 if (!dbus_message_append_args (message,
678 _DBUS_SET_OOM (error);
689 * Gets the security context of a connection to the bus. It is up to
690 * the caller to freecon() when they are done.
692 * @param connection the connection to get the context of.
693 * @param con the location to store the security context.
694 * @returns #TRUE if context is successfully obtained.
698 bus_connection_read_selinux_context (DBusConnection *connection,
703 if (!selinux_enabled)
706 _dbus_assert (connection != NULL);
708 if (!dbus_connection_get_unix_fd (connection, &fd))
710 _dbus_verbose ("Failed to get file descriptor of socket.\n");
714 if (getpeercon (fd, con) < 0)
716 _dbus_verbose ("Error getting context of socket peer: %s\n",
717 _dbus_strerror (errno));
721 _dbus_verbose ("Successfully read connection context.\n");
724 #endif /* HAVE_SELINUX */
727 * Read the SELinux ID from the connection.
729 * @param connection the connection to read from
730 * @returns the SID if successfully determined, #NULL otherwise.
733 bus_selinux_init_connection_id (DBusConnection *connection,
740 if (!selinux_enabled)
743 if (!bus_connection_read_selinux_context (connection, &con))
745 dbus_set_error (error, DBUS_ERROR_FAILED,
746 "Failed to read an SELinux context from connection");
747 _dbus_verbose ("Error getting peer context.\n");
751 _dbus_verbose ("Converting context to SID to store on connection\n");
753 if (avc_context_to_sid (con, &sid) < 0)
758 dbus_set_error (error, DBUS_ERROR_FAILED,
759 "Error getting SID from context \"%s\": %s\n",
760 con, _dbus_strerror (errno));
762 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
763 con, _dbus_strerror (errno));
770 return BUS_SID_FROM_SELINUX (sid);
773 #endif /* HAVE_SELINUX */
778 * Function for freeing hash table data. These SIDs
779 * should no longer be referenced.
782 bus_selinux_id_table_free_value (BusSELinuxID *sid)
785 /* NULL sometimes due to how DBusHashTable works */
787 bus_selinux_id_unref (sid);
788 #endif /* HAVE_SELINUX */
792 * Creates a new table mapping service names to security ID.
793 * A security ID is a "compiled" security context, a security
794 * context is just a string.
796 * @returns the new table or #NULL if no memory
799 bus_selinux_id_table_new (void)
801 return _dbus_hash_table_new (DBUS_HASH_STRING,
802 (DBusFreeFunction) dbus_free,
803 (DBusFreeFunction) bus_selinux_id_table_free_value);
807 * Hashes a service name and service context into the service SID
808 * table as a string and a SID.
810 * @param service_name is the name of the service.
811 * @param service_context is the context of the service.
812 * @param service_table is the table to hash them into.
813 * @return #FALSE if not enough memory
816 bus_selinux_id_table_insert (DBusHashTable *service_table,
817 const char *service_name,
818 const char *service_context)
825 if (!selinux_enabled)
831 key = _dbus_strdup (service_name);
835 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
843 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
844 (char *) service_context,
845 _dbus_strerror (errno));
849 if (!_dbus_hash_table_insert_string (service_table,
851 BUS_SID_FROM_SELINUX (sid)))
854 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
858 /* These are owned by the hash, so clear them to avoid unref */
865 if (sid != SECSID_WILD)
874 #endif /* HAVE_SELINUX */
879 * Find the security identifier associated with a particular service
880 * name. Return a pointer to this SID, or #NULL/SECSID_WILD if the
881 * service is not found in the hash table. This should be nearly a
882 * constant time operation. If SELinux support is not available,
883 * always return NULL.
885 * @param service_table the hash table to check for service name.
886 * @param service_name the name of the service to look for.
887 * @returns the SELinux ID associated with the service
890 bus_selinux_id_table_lookup (DBusHashTable *service_table,
891 const DBusString *service_name)
896 sid = SECSID_WILD; /* default context */
898 if (!selinux_enabled)
901 _dbus_verbose ("Looking up service SID for %s\n",
902 _dbus_string_get_const_data (service_name));
904 sid = _dbus_hash_table_lookup_string (service_table,
905 _dbus_string_get_const_data (service_name));
907 if (sid == SECSID_WILD)
908 _dbus_verbose ("Service %s not found\n",
909 _dbus_string_get_const_data (service_name));
911 _dbus_verbose ("Service %s found\n",
912 _dbus_string_get_const_data (service_name));
914 return BUS_SID_FROM_SELINUX (sid);
915 #endif /* HAVE_SELINUX */
920 * Get the SELinux policy root. This is used to find the D-Bus
921 * specific config file within the policy.
924 bus_selinux_get_policy_root (void)
927 return selinux_policy_root ();
930 #endif /* HAVE_SELINUX */
934 * For debugging: Print out the current hash table of service SIDs.
937 bus_selinux_id_table_print (DBusHashTable *service_table)
939 #if defined (DBUS_ENABLE_VERBOSE_MODE) && defined (HAVE_SELINUX)
942 if (!selinux_enabled)
945 _dbus_verbose ("Service SID Table:\n");
946 _dbus_hash_iter_init (service_table, &iter);
947 while (_dbus_hash_iter_next (&iter))
949 const char *key = _dbus_hash_iter_get_string_key (&iter);
950 security_id_t sid = _dbus_hash_iter_get_value (&iter);
951 _dbus_verbose ("The key is %s\n", key);
952 _dbus_verbose ("The context is %s\n", sid->ctx);
953 _dbus_verbose ("The refcount is %d\n", sid->refcnt);
955 #endif /* DBUS_ENABLE_VERBOSE_MODE && HAVE_SELINUX */
960 * Print out some AVC statistics.
964 bus_avc_print_stats (void)
966 #ifdef DBUS_ENABLE_VERBOSE_MODE
967 struct avc_cache_stats cstats;
969 if (!selinux_enabled)
972 _dbus_verbose ("AVC Statistics:\n");
973 avc_cache_stats (&cstats);
975 _dbus_verbose ("AVC Cache Statistics:\n");
976 _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
977 _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
978 _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
979 _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
980 _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
981 _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
982 _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
983 _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
984 #endif /* DBUS_ENABLE_VERBOSE_MODE */
986 #endif /* HAVE_SELINUX */
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 bus_avc_print_stats ();
1008 #ifdef HAVE_LIBAUDIT
1009 audit_close (audit_fd);
1010 #endif /* HAVE_LIBAUDIT */
1012 #endif /* HAVE_SELINUX */
1015 /* The !HAVE_LIBAUDIT case lives in dbus-sysdeps-util-unix.c */
1016 #ifdef HAVE_LIBAUDIT
1018 * Changes the user and group the bus is running as.
1020 * @param user the user to become
1021 * @param error return location for errors
1022 * @returns #FALSE on failure
1025 _dbus_change_to_daemon_user (const char *user,
1032 _dbus_string_init_const (&u, user);
1034 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
1036 dbus_set_error (error, DBUS_ERROR_FAILED,
1037 "User '%s' does not appear to exist?",
1042 /* If we were root */
1043 if (_dbus_geteuid () == 0)
1047 capng_clear (CAPNG_SELECT_BOTH);
1048 capng_update (CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
1050 rc = capng_change_id (uid, gid, CAPNG_DROP_SUPP_GRP);
1055 dbus_set_error (error, DBUS_ERROR_FAILED,
1056 "Failed to drop capabilities: %s\n",
1057 _dbus_strerror (errno));
1060 dbus_set_error (error, _dbus_error_from_errno (errno),
1061 "Failed to set GID to %lu: %s", gid,
1062 _dbus_strerror (errno));
1065 _dbus_warn ("Failed to drop supplementary groups: %s\n",
1066 _dbus_strerror (errno));
1069 dbus_set_error (error, _dbus_error_from_errno (errno),
1070 "Failed to set UID to %lu: %s", uid,
1071 _dbus_strerror (errno));
1074 dbus_set_error (error, _dbus_error_from_errno (errno),
1075 "Failed to unset keep-capabilities: %s\n",
1076 _dbus_strerror (errno));