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>
26 #include <dbus/dbus-userdb.h>
32 #include "config-parser.h"
35 #include <sys/types.h>
43 #include <selinux/selinux.h>
44 #include <selinux/avc.h>
45 #include <selinux/av_permissions.h>
46 #include <selinux/flask.h>
54 #endif /* HAVE_LIBAUDIT */
55 #endif /* HAVE_SELINUX */
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, ...);
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 static int audit_fd = -1;
123 bus_selinux_audit_init(void)
126 audit_fd = audit_open ();
130 /* If kernel doesn't support audit, bail out */
131 if (errno == EINVAL || errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT)
133 /* If user bus, bail out */
134 if (errno == EPERM && getuid() != 0)
136 _dbus_warn ("Failed opening connection to the audit subsystem");
138 #endif /* HAVE_LIBAUDIT */
142 log_callback (const char *fmt, ...)
151 capng_get_caps_process();
152 if (capng_have_capability(CAPNG_EFFECTIVE, CAP_AUDIT_WRITE))
154 char buf[PATH_MAX*2];
156 /* FIXME: need to change this to show real user */
157 vsnprintf(buf, sizeof(buf), fmt, ap);
158 audit_log_user_avc_message(audit_fd, AUDIT_USER_AVC, buf, NULL, NULL,
163 #endif /* HAVE_LIBAUDIT */
165 vsyslog (LOG_INFO, fmt, ap);
170 * On a policy reload we need to reparse the SELinux configuration file, since
171 * this could have changed. Send a SIGHUP to reload all configs.
174 policy_reload_callback (u_int32_t event, security_id_t ssid,
175 security_id_t tsid, security_class_t tclass,
176 access_vector_t perms, access_vector_t *out_retained)
178 if (event == AVC_CALLBACK_RESET)
179 return raise (SIGHUP);
185 * Log any auxiliary data
188 log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
190 DBusString *audmsg = data;
192 if (bufleft > (size_t) _dbus_string_get_length(audmsg))
194 _dbus_string_copy_to_buffer_with_nul (audmsg, buf, bufleft);
200 _dbus_string_init_const(&s, "Buffer too small for audit message");
202 if (bufleft > (size_t) _dbus_string_get_length(&s))
203 _dbus_string_copy_to_buffer_with_nul (&s, buf, bufleft);
208 * Create thread to notify the AVC of enforcing and policy reload
209 * changes via netlink.
211 * @param run the thread run function
212 * @return pointer to the thread
215 avc_create_thread (void (*run) (void))
219 rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
222 _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
225 return &avc_notify_thread;
228 /* Stop AVC netlink thread. */
230 avc_stop_thread (void *thread)
232 pthread_cancel (*(pthread_t *) thread);
235 /* Allocate a new AVC lock. */
237 avc_alloc_lock (void)
239 pthread_mutex_t *avc_mutex;
241 avc_mutex = dbus_new (pthread_mutex_t, 1);
242 if (avc_mutex == NULL)
244 _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
247 pthread_mutex_init (avc_mutex, NULL);
252 /* Acquire an AVC lock. */
254 avc_get_lock (void *lock)
256 pthread_mutex_lock (lock);
259 /* Release an AVC lock. */
261 avc_release_lock (void *lock)
263 pthread_mutex_unlock (lock);
266 /* Free an AVC lock. */
268 avc_free_lock (void *lock)
270 pthread_mutex_destroy (lock);
273 #endif /* HAVE_SELINUX */
276 * Return whether or not SELinux is enabled; must be
277 * called after bus_selinux_init.
280 bus_selinux_enabled (void)
283 return selinux_enabled;
286 #endif /* HAVE_SELINUX */
290 * Do early initialization; determine whether SELinux is enabled.
293 bus_selinux_pre_init (void)
297 _dbus_assert (bus_sid == SECSID_WILD);
299 /* Determine if we are running an SELinux kernel. */
300 r = is_selinux_enabled ();
303 _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
304 _dbus_strerror (errno));
308 selinux_enabled = r != 0;
316 * Initialize the user space access vector cache (AVC) for D-Bus and set up
320 bus_selinux_full_init (void)
325 _dbus_assert (bus_sid == SECSID_WILD);
327 if (!selinux_enabled)
329 _dbus_verbose ("SELinux not enabled in this kernel.\n");
333 _dbus_verbose ("SELinux is enabled in this kernel.\n");
335 avc_entry_ref_init (&aeref);
336 if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
338 _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
343 openlog ("dbus", LOG_PERROR, LOG_USER);
344 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
347 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
348 NULL, NULL, 0, 0) < 0)
350 _dbus_warn ("Failed to add policy reload callback: %s\n",
351 _dbus_strerror (errno));
357 bus_sid = SECSID_WILD;
359 if (getcon (&bus_context) < 0)
361 _dbus_verbose ("Error getting context of bus: %s\n",
362 _dbus_strerror (errno));
366 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
368 _dbus_verbose ("Error getting SID from bus context: %s\n",
369 _dbus_strerror (errno));
370 freecon (bus_context);
374 freecon (bus_context);
376 #endif /* HAVE_SELINUX */
381 * Decrement SID reference count.
383 * @param sid the SID to decrement
386 bus_selinux_id_unref (BusSELinuxID *sid)
389 if (!selinux_enabled)
392 _dbus_assert (sid != NULL);
394 sidput (SELINUX_SID_FROM_BUS (sid));
395 #endif /* HAVE_SELINUX */
399 bus_selinux_id_ref (BusSELinuxID *sid)
402 if (!selinux_enabled)
405 _dbus_assert (sid != NULL);
407 sidget (SELINUX_SID_FROM_BUS (sid));
408 #endif /* HAVE_SELINUX */
412 * Determine if the SELinux security policy allows the given sender
413 * security context to go to the given recipient security context.
414 * This function determines if the requested permissions are to be
415 * granted from the connection to the message bus or to another
416 * optionally supplied security identifier (e.g. for a service
417 * context). Currently these permissions are either send_msg or
418 * acquire_svc in the dbus class.
420 * @param sender_sid source security context
421 * @param override_sid is the target security context. If SECSID_WILD this will
422 * use the context of the bus itself (e.g. the default).
423 * @param target_class is the target security class.
424 * @param requested is the requested permissions.
425 * @returns #TRUE if security policy allows the send.
429 bus_selinux_check (BusSELinuxID *sender_sid,
430 BusSELinuxID *override_sid,
431 security_class_t target_class,
432 access_vector_t requested,
435 if (!selinux_enabled)
438 /* Make the security check. AVC checks enforcing mode here as well. */
439 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
441 SELINUX_SID_FROM_BUS (override_sid) :
442 SELINUX_SID_FROM_BUS (bus_sid),
443 target_class, requested, &aeref, auxdata) < 0)
448 _dbus_verbose ("SELinux denying due to security policy.\n");
451 _dbus_verbose ("SELinux denying due to invalid security context.\n");
454 _dbus_verbose ("SELinux denying due to: %s\n", _dbus_strerror (errno));
461 #endif /* HAVE_SELINUX */
464 * Returns true if the given connection can acquire a service,
465 * assuming the given security ID is needed for that service.
467 * @param connection connection that wants to own the service
468 * @param service_sid the SID of the service from the table
469 * @returns #TRUE if acquire is permitted.
472 bus_selinux_allows_acquire_service (DBusConnection *connection,
473 BusSELinuxID *service_sid,
474 const char *service_name,
478 BusSELinuxID *connection_sid;
483 if (!selinux_enabled)
486 connection_sid = bus_connection_get_selinux_id (connection);
487 if (!dbus_connection_get_unix_process_id (connection, &spid))
490 if (!_dbus_string_init (&auxdata))
493 if (!_dbus_string_append (&auxdata, "service="))
496 if (!_dbus_string_append (&auxdata, service_name))
501 if (!_dbus_string_append (&auxdata, " spid="))
504 if (!_dbus_string_append_uint (&auxdata, spid))
508 ret = bus_selinux_check (connection_sid,
514 _dbus_string_free (&auxdata);
518 _dbus_string_free (&auxdata);
524 #endif /* HAVE_SELINUX */
528 * Check if SELinux security controls allow the message to be sent to a
529 * particular connection based on the security context of the sender and
530 * that of the receiver. The destination connection need not be the
531 * addressed recipient, it could be an "eavesdropper"
533 * @param sender the sender of the message.
534 * @param proposed_recipient the connection the message is to be sent to.
535 * @returns whether to allow the send
538 bus_selinux_allows_send (DBusConnection *sender,
539 DBusConnection *proposed_recipient,
541 const char *interface,
543 const char *error_name,
544 const char *destination,
548 BusSELinuxID *recipient_sid;
549 BusSELinuxID *sender_sid;
550 unsigned long spid, tpid;
553 dbus_bool_t string_alloced;
555 if (!selinux_enabled)
558 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
560 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
563 string_alloced = FALSE;
564 if (!_dbus_string_init (&auxdata))
566 string_alloced = TRUE;
568 if (!_dbus_string_append (&auxdata, "msgtype="))
571 if (!_dbus_string_append (&auxdata, msgtype))
576 if (!_dbus_string_append (&auxdata, " interface="))
578 if (!_dbus_string_append (&auxdata, interface))
584 if (!_dbus_string_append (&auxdata, " member="))
586 if (!_dbus_string_append (&auxdata, member))
592 if (!_dbus_string_append (&auxdata, " error_name="))
594 if (!_dbus_string_append (&auxdata, error_name))
600 if (!_dbus_string_append (&auxdata, " dest="))
602 if (!_dbus_string_append (&auxdata, destination))
608 if (!_dbus_string_append (&auxdata, " spid="))
611 if (!_dbus_string_append_uint (&auxdata, spid))
617 if (!_dbus_string_append (&auxdata, " tpid="))
620 if (!_dbus_string_append_uint (&auxdata, tpid))
624 sender_sid = bus_connection_get_selinux_id (sender);
625 /* A NULL proposed_recipient means the bus itself. */
626 if (proposed_recipient)
627 recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
629 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
631 ret = bus_selinux_check (sender_sid,
637 _dbus_string_free (&auxdata);
643 _dbus_string_free (&auxdata);
649 #endif /* HAVE_SELINUX */
653 bus_selinux_append_context (DBusMessage *message,
660 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
665 dbus_set_error (error, DBUS_ERROR_FAILED,
666 "Error getting context from SID: %s\n",
667 _dbus_strerror (errno));
670 if (!dbus_message_append_args (message,
677 _DBUS_SET_OOM (error);
688 * Gets the security context of a connection to the bus. It is up to
689 * the caller to freecon() when they are done.
691 * @param connection the connection to get the context of.
692 * @param con the location to store the security context.
693 * @returns #TRUE if context is successfully obtained.
697 bus_connection_read_selinux_context (DBusConnection *connection,
702 if (!selinux_enabled)
705 _dbus_assert (connection != NULL);
707 if (!dbus_connection_get_unix_fd (connection, &fd))
709 _dbus_verbose ("Failed to get file descriptor of socket.\n");
713 if (getpeercon (fd, con) < 0)
715 _dbus_verbose ("Error getting context of socket peer: %s\n",
716 _dbus_strerror (errno));
720 _dbus_verbose ("Successfully read connection context.\n");
723 #endif /* HAVE_SELINUX */
726 * Read the SELinux ID from the connection.
728 * @param connection the connection to read from
729 * @returns the SID if successfully determined, #NULL otherwise.
732 bus_selinux_init_connection_id (DBusConnection *connection,
739 if (!selinux_enabled)
742 if (!bus_connection_read_selinux_context (connection, &con))
744 dbus_set_error (error, DBUS_ERROR_FAILED,
745 "Failed to read an SELinux context from connection");
746 _dbus_verbose ("Error getting peer context.\n");
750 _dbus_verbose ("Converting context to SID to store on connection\n");
752 if (avc_context_to_sid (con, &sid) < 0)
757 dbus_set_error (error, DBUS_ERROR_FAILED,
758 "Error getting SID from context \"%s\": %s\n",
759 con, _dbus_strerror (errno));
761 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
762 con, _dbus_strerror (errno));
769 return BUS_SID_FROM_SELINUX (sid);
772 #endif /* HAVE_SELINUX */
777 * Function for freeing hash table data. These SIDs
778 * should no longer be referenced.
781 bus_selinux_id_table_free_value (BusSELinuxID *sid)
784 /* NULL sometimes due to how DBusHashTable works */
786 bus_selinux_id_unref (sid);
787 #endif /* HAVE_SELINUX */
791 * Creates a new table mapping service names to security ID.
792 * A security ID is a "compiled" security context, a security
793 * context is just a string.
795 * @returns the new table or #NULL if no memory
798 bus_selinux_id_table_new (void)
800 return _dbus_hash_table_new (DBUS_HASH_STRING,
801 (DBusFreeFunction) dbus_free,
802 (DBusFreeFunction) bus_selinux_id_table_free_value);
806 * Hashes a service name and service context into the service SID
807 * table as a string and a SID.
809 * @param service_name is the name of the service.
810 * @param service_context is the context of the service.
811 * @param service_table is the table to hash them into.
812 * @return #FALSE if not enough memory
815 bus_selinux_id_table_insert (DBusHashTable *service_table,
816 const char *service_name,
817 const char *service_context)
824 if (!selinux_enabled)
830 key = _dbus_strdup (service_name);
834 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
842 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
843 (char *) service_context,
844 _dbus_strerror (errno));
848 if (!_dbus_hash_table_insert_string (service_table,
850 BUS_SID_FROM_SELINUX (sid)))
853 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
857 /* These are owned by the hash, so clear them to avoid unref */
864 if (sid != SECSID_WILD)
873 #endif /* HAVE_SELINUX */
878 * Find the security identifier associated with a particular service
879 * name. Return a pointer to this SID, or #NULL/SECSID_WILD if the
880 * service is not found in the hash table. This should be nearly a
881 * constant time operation. If SELinux support is not available,
882 * always return NULL.
884 * @param service_table the hash table to check for service name.
885 * @param service_name the name of the service to look for.
886 * @returns the SELinux ID associated with the service
889 bus_selinux_id_table_lookup (DBusHashTable *service_table,
890 const DBusString *service_name)
895 sid = SECSID_WILD; /* default context */
897 if (!selinux_enabled)
900 _dbus_verbose ("Looking up service SID for %s\n",
901 _dbus_string_get_const_data (service_name));
903 sid = _dbus_hash_table_lookup_string (service_table,
904 _dbus_string_get_const_data (service_name));
906 if (sid == SECSID_WILD)
907 _dbus_verbose ("Service %s not found\n",
908 _dbus_string_get_const_data (service_name));
910 _dbus_verbose ("Service %s found\n",
911 _dbus_string_get_const_data (service_name));
913 return BUS_SID_FROM_SELINUX (sid);
914 #endif /* HAVE_SELINUX */
919 * Get the SELinux policy root. This is used to find the D-Bus
920 * specific config file within the policy.
923 bus_selinux_get_policy_root (void)
926 return selinux_policy_root ();
929 #endif /* HAVE_SELINUX */
933 * For debugging: Print out the current hash table of service SIDs.
936 bus_selinux_id_table_print (DBusHashTable *service_table)
938 #ifdef DBUS_ENABLE_VERBOSE_MODE
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 /* HAVE_SELINUX */
956 #endif /* DBUS_ENABLE_VERBOSE_MODE */
960 #ifdef DBUS_ENABLE_VERBOSE_MODE
963 * Print out some AVC statistics.
966 bus_avc_print_stats (void)
968 struct avc_cache_stats cstats;
970 if (!selinux_enabled)
973 _dbus_verbose ("AVC Statistics:\n");
974 avc_cache_stats (&cstats);
976 _dbus_verbose ("AVC Cache Statistics:\n");
977 _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
978 _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
979 _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
980 _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
981 _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
982 _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
983 _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
984 _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
986 #endif /* HAVE_SELINUX */
987 #endif /* DBUS_ENABLE_VERBOSE_MODE */
991 * Destroy the AVC before we terminate.
994 bus_selinux_shutdown (void)
997 if (!selinux_enabled)
1000 _dbus_verbose ("AVC shutdown\n");
1002 if (bus_sid != SECSID_WILD)
1005 bus_sid = SECSID_WILD;
1007 #ifdef DBUS_ENABLE_VERBOSE_MODE
1009 if (_dbus_is_verbose())
1010 bus_avc_print_stats ();
1012 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1015 #ifdef HAVE_LIBAUDIT
1016 audit_close (audit_fd);
1017 #endif /* HAVE_LIBAUDIT */
1019 #endif /* HAVE_SELINUX */
1024 * Changes the user and group the bus is running as.
1026 * @param user the user to become
1027 * @param error return location for errors
1028 * @returns #FALSE on failure
1031 _dbus_change_to_daemon_user (const char *user,
1038 _dbus_string_init_const (&u, user);
1040 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
1042 dbus_set_error (error, DBUS_ERROR_FAILED,
1043 "User '%s' does not appear to exist?",
1048 #ifdef HAVE_LIBAUDIT
1049 /* If we were root */
1050 if (_dbus_geteuid () == 0)
1054 capng_clear (CAPNG_SELECT_BOTH);
1055 capng_update (CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
1057 rc = capng_change_id (uid, gid, 0);
1062 dbus_set_error (error, DBUS_ERROR_FAILED,
1063 "Failed to drop capabilities: %s\n",
1064 _dbus_strerror (errno));
1067 dbus_set_error (error, _dbus_error_from_errno (errno),
1068 "Failed to set GID to %lu: %s", gid,
1069 _dbus_strerror (errno));
1072 _dbus_warn ("Failed to drop supplementary groups: %s\n",
1073 _dbus_strerror (errno));
1076 dbus_set_error (error, _dbus_error_from_errno (errno),
1077 "Failed to set UID to %lu: %s", uid,
1078 _dbus_strerror (errno));
1081 dbus_set_error (error, _dbus_error_from_errno (errno),
1082 "Failed to unset keep-capabilities: %s\n",
1083 _dbus_strerror (errno));
1090 /* setgroups() only works if we are a privileged process,
1091 * so we don't return error on failure; the only possible
1092 * failure is that we don't have perms to do it.
1094 * not sure this is right, maybe if setuid()
1095 * is going to work then setgroups() should also work.
1097 if (setgroups (0, NULL) < 0)
1098 _dbus_warn ("Failed to drop supplementary groups: %s\n",
1099 _dbus_strerror (errno));
1101 /* Set GID first, or the setuid may remove our permission
1104 if (setgid (gid) < 0)
1106 dbus_set_error (error, _dbus_error_from_errno (errno),
1107 "Failed to set GID to %lu: %s", gid,
1108 _dbus_strerror (errno));
1112 if (setuid (uid) < 0)
1114 dbus_set_error (error, _dbus_error_from_errno (errno),
1115 "Failed to set UID to %lu: %s", uid,
1116 _dbus_strerror (errno));
1119 #endif /* !HAVE_LIBAUDIT */