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_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 openlog ("dbus", LOG_PERROR, LOG_USER);
346 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
349 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
350 NULL, NULL, 0, 0) < 0)
352 _dbus_warn ("Failed to add policy reload callback: %s\n",
353 _dbus_strerror (errno));
359 bus_sid = SECSID_WILD;
361 if (getcon (&bus_context) < 0)
363 _dbus_verbose ("Error getting context of bus: %s\n",
364 _dbus_strerror (errno));
368 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
370 _dbus_verbose ("Error getting SID from bus context: %s\n",
371 _dbus_strerror (errno));
372 freecon (bus_context);
376 freecon (bus_context);
378 #endif /* HAVE_SELINUX */
383 * Decrement SID reference count.
385 * @param sid the SID to decrement
388 bus_selinux_id_unref (BusSELinuxID *sid)
391 if (!selinux_enabled)
394 _dbus_assert (sid != NULL);
396 sidput (SELINUX_SID_FROM_BUS (sid));
397 #endif /* HAVE_SELINUX */
401 bus_selinux_id_ref (BusSELinuxID *sid)
404 if (!selinux_enabled)
407 _dbus_assert (sid != NULL);
409 sidget (SELINUX_SID_FROM_BUS (sid));
410 #endif /* HAVE_SELINUX */
414 * Determine if the SELinux security policy allows the given sender
415 * security context to go to the given recipient security context.
416 * This function determines if the requested permissions are to be
417 * granted from the connection to the message bus or to another
418 * optionally supplied security identifier (e.g. for a service
419 * context). Currently these permissions are either send_msg or
420 * acquire_svc in the dbus class.
422 * @param sender_sid source security context
423 * @param override_sid is the target security context. If SECSID_WILD this will
424 * use the context of the bus itself (e.g. the default).
425 * @param target_class is the target security class.
426 * @param requested is the requested permissions.
427 * @returns #TRUE if security policy allows the send.
431 bus_selinux_check (BusSELinuxID *sender_sid,
432 BusSELinuxID *override_sid,
433 security_class_t target_class,
434 access_vector_t requested,
437 if (!selinux_enabled)
440 /* Make the security check. AVC checks enforcing mode here as well. */
441 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
443 SELINUX_SID_FROM_BUS (override_sid) :
444 SELINUX_SID_FROM_BUS (bus_sid),
445 target_class, requested, &aeref, auxdata) < 0)
450 _dbus_verbose ("SELinux denying due to security policy.\n");
453 _dbus_verbose ("SELinux denying due to invalid security context.\n");
456 _dbus_verbose ("SELinux denying due to: %s\n", _dbus_strerror (errno));
463 #endif /* HAVE_SELINUX */
466 * Returns true if the given connection can acquire a service,
467 * assuming the given security ID is needed for that service.
469 * @param connection connection that wants to own the service
470 * @param service_sid the SID of the service from the table
471 * @returns #TRUE if acquire is permitted.
474 bus_selinux_allows_acquire_service (DBusConnection *connection,
475 BusSELinuxID *service_sid,
476 const char *service_name,
480 BusSELinuxID *connection_sid;
485 if (!selinux_enabled)
488 connection_sid = bus_connection_get_selinux_id (connection);
489 if (!dbus_connection_get_unix_process_id (connection, &spid))
492 if (!_dbus_string_init (&auxdata))
495 if (!_dbus_string_append (&auxdata, "service="))
498 if (!_dbus_string_append (&auxdata, service_name))
503 if (!_dbus_string_append (&auxdata, " spid="))
506 if (!_dbus_string_append_uint (&auxdata, spid))
510 ret = bus_selinux_check (connection_sid,
516 _dbus_string_free (&auxdata);
520 _dbus_string_free (&auxdata);
526 #endif /* HAVE_SELINUX */
530 * Check if SELinux security controls allow the message to be sent to a
531 * particular connection based on the security context of the sender and
532 * that of the receiver. The destination connection need not be the
533 * addressed recipient, it could be an "eavesdropper"
535 * @param sender the sender of the message.
536 * @param proposed_recipient the connection the message is to be sent to.
537 * @returns whether to allow the send
540 bus_selinux_allows_send (DBusConnection *sender,
541 DBusConnection *proposed_recipient,
543 const char *interface,
545 const char *error_name,
546 const char *destination,
550 BusSELinuxID *recipient_sid;
551 BusSELinuxID *sender_sid;
552 unsigned long spid, tpid;
555 dbus_bool_t string_alloced;
557 if (!selinux_enabled)
560 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
562 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
565 string_alloced = FALSE;
566 if (!_dbus_string_init (&auxdata))
568 string_alloced = TRUE;
570 if (!_dbus_string_append (&auxdata, "msgtype="))
573 if (!_dbus_string_append (&auxdata, msgtype))
578 if (!_dbus_string_append (&auxdata, " interface="))
580 if (!_dbus_string_append (&auxdata, interface))
586 if (!_dbus_string_append (&auxdata, " member="))
588 if (!_dbus_string_append (&auxdata, member))
594 if (!_dbus_string_append (&auxdata, " error_name="))
596 if (!_dbus_string_append (&auxdata, error_name))
602 if (!_dbus_string_append (&auxdata, " dest="))
604 if (!_dbus_string_append (&auxdata, destination))
610 if (!_dbus_string_append (&auxdata, " spid="))
613 if (!_dbus_string_append_uint (&auxdata, spid))
619 if (!_dbus_string_append (&auxdata, " tpid="))
622 if (!_dbus_string_append_uint (&auxdata, tpid))
626 sender_sid = bus_connection_get_selinux_id (sender);
627 /* A NULL proposed_recipient means the bus itself. */
628 if (proposed_recipient)
629 recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
631 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
633 ret = bus_selinux_check (sender_sid,
639 _dbus_string_free (&auxdata);
645 _dbus_string_free (&auxdata);
651 #endif /* HAVE_SELINUX */
655 bus_selinux_append_context (DBusMessage *message,
662 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
667 dbus_set_error (error, DBUS_ERROR_FAILED,
668 "Error getting context from SID: %s\n",
669 _dbus_strerror (errno));
672 if (!dbus_message_append_args (message,
679 _DBUS_SET_OOM (error);
690 * Gets the security context of a connection to the bus. It is up to
691 * the caller to freecon() when they are done.
693 * @param connection the connection to get the context of.
694 * @param con the location to store the security context.
695 * @returns #TRUE if context is successfully obtained.
699 bus_connection_read_selinux_context (DBusConnection *connection,
704 if (!selinux_enabled)
707 _dbus_assert (connection != NULL);
709 if (!dbus_connection_get_unix_fd (connection, &fd))
711 _dbus_verbose ("Failed to get file descriptor of socket.\n");
715 if (getpeercon (fd, con) < 0)
717 _dbus_verbose ("Error getting context of socket peer: %s\n",
718 _dbus_strerror (errno));
722 _dbus_verbose ("Successfully read connection context.\n");
725 #endif /* HAVE_SELINUX */
728 * Read the SELinux ID from the connection.
730 * @param connection the connection to read from
731 * @returns the SID if successfully determined, #NULL otherwise.
734 bus_selinux_init_connection_id (DBusConnection *connection,
741 if (!selinux_enabled)
744 if (!bus_connection_read_selinux_context (connection, &con))
746 dbus_set_error (error, DBUS_ERROR_FAILED,
747 "Failed to read an SELinux context from connection");
748 _dbus_verbose ("Error getting peer context.\n");
752 _dbus_verbose ("Converting context to SID to store on connection\n");
754 if (avc_context_to_sid (con, &sid) < 0)
759 dbus_set_error (error, DBUS_ERROR_FAILED,
760 "Error getting SID from context \"%s\": %s\n",
761 con, _dbus_strerror (errno));
763 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
764 con, _dbus_strerror (errno));
771 return BUS_SID_FROM_SELINUX (sid);
774 #endif /* HAVE_SELINUX */
779 * Function for freeing hash table data. These SIDs
780 * should no longer be referenced.
783 bus_selinux_id_table_free_value (BusSELinuxID *sid)
786 /* NULL sometimes due to how DBusHashTable works */
788 bus_selinux_id_unref (sid);
789 #endif /* HAVE_SELINUX */
793 * Creates a new table mapping service names to security ID.
794 * A security ID is a "compiled" security context, a security
795 * context is just a string.
797 * @returns the new table or #NULL if no memory
800 bus_selinux_id_table_new (void)
802 return _dbus_hash_table_new (DBUS_HASH_STRING,
803 (DBusFreeFunction) dbus_free,
804 (DBusFreeFunction) bus_selinux_id_table_free_value);
808 * Hashes a service name and service context into the service SID
809 * table as a string and a SID.
811 * @param service_name is the name of the service.
812 * @param service_context is the context of the service.
813 * @param service_table is the table to hash them into.
814 * @return #FALSE if not enough memory
817 bus_selinux_id_table_insert (DBusHashTable *service_table,
818 const char *service_name,
819 const char *service_context)
826 if (!selinux_enabled)
832 key = _dbus_strdup (service_name);
836 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
844 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
845 (char *) service_context,
846 _dbus_strerror (errno));
850 if (!_dbus_hash_table_insert_string (service_table,
852 BUS_SID_FROM_SELINUX (sid)))
855 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
859 /* These are owned by the hash, so clear them to avoid unref */
866 if (sid != SECSID_WILD)
875 #endif /* HAVE_SELINUX */
880 * Find the security identifier associated with a particular service
881 * name. Return a pointer to this SID, or #NULL/SECSID_WILD if the
882 * service is not found in the hash table. This should be nearly a
883 * constant time operation. If SELinux support is not available,
884 * always return NULL.
886 * @param service_table the hash table to check for service name.
887 * @param service_name the name of the service to look for.
888 * @returns the SELinux ID associated with the service
891 bus_selinux_id_table_lookup (DBusHashTable *service_table,
892 const DBusString *service_name)
897 sid = SECSID_WILD; /* default context */
899 if (!selinux_enabled)
902 _dbus_verbose ("Looking up service SID for %s\n",
903 _dbus_string_get_const_data (service_name));
905 sid = _dbus_hash_table_lookup_string (service_table,
906 _dbus_string_get_const_data (service_name));
908 if (sid == SECSID_WILD)
909 _dbus_verbose ("Service %s not found\n",
910 _dbus_string_get_const_data (service_name));
912 _dbus_verbose ("Service %s found\n",
913 _dbus_string_get_const_data (service_name));
915 return BUS_SID_FROM_SELINUX (sid);
916 #endif /* HAVE_SELINUX */
921 * Get the SELinux policy root. This is used to find the D-Bus
922 * specific config file within the policy.
925 bus_selinux_get_policy_root (void)
928 return selinux_policy_root ();
931 #endif /* HAVE_SELINUX */
935 * For debugging: Print out the current hash table of service SIDs.
938 bus_selinux_id_table_print (DBusHashTable *service_table)
940 #ifdef DBUS_ENABLE_VERBOSE_MODE
944 if (!selinux_enabled)
947 _dbus_verbose ("Service SID Table:\n");
948 _dbus_hash_iter_init (service_table, &iter);
949 while (_dbus_hash_iter_next (&iter))
951 const char *key = _dbus_hash_iter_get_string_key (&iter);
952 security_id_t sid = _dbus_hash_iter_get_value (&iter);
953 _dbus_verbose ("The key is %s\n", key);
954 _dbus_verbose ("The context is %s\n", sid->ctx);
955 _dbus_verbose ("The refcount is %d\n", sid->refcnt);
957 #endif /* HAVE_SELINUX */
958 #endif /* DBUS_ENABLE_VERBOSE_MODE */
962 #ifdef DBUS_ENABLE_VERBOSE_MODE
965 * Print out some AVC statistics.
968 bus_avc_print_stats (void)
970 struct avc_cache_stats cstats;
972 if (!selinux_enabled)
975 _dbus_verbose ("AVC Statistics:\n");
976 avc_cache_stats (&cstats);
978 _dbus_verbose ("AVC Cache Statistics:\n");
979 _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
980 _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
981 _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
982 _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
983 _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
984 _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
985 _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
986 _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
988 #endif /* HAVE_SELINUX */
989 #endif /* DBUS_ENABLE_VERBOSE_MODE */
993 * Destroy the AVC before we terminate.
996 bus_selinux_shutdown (void)
999 if (!selinux_enabled)
1002 _dbus_verbose ("AVC shutdown\n");
1004 if (bus_sid != SECSID_WILD)
1007 bus_sid = SECSID_WILD;
1009 #ifdef DBUS_ENABLE_VERBOSE_MODE
1011 if (_dbus_is_verbose())
1012 bus_avc_print_stats ();
1014 #endif /* DBUS_ENABLE_VERBOSE_MODE */
1017 #ifdef HAVE_LIBAUDIT
1018 audit_close (audit_fd);
1019 #endif /* HAVE_LIBAUDIT */
1021 #endif /* HAVE_SELINUX */
1024 /* The !HAVE_LIBAUDIT case lives in dbus-sysdeps-util-unix.c */
1025 #ifdef HAVE_LIBAUDIT
1027 * Changes the user and group the bus is running as.
1029 * @param user the user to become
1030 * @param error return location for errors
1031 * @returns #FALSE on failure
1034 _dbus_change_to_daemon_user (const char *user,
1041 _dbus_string_init_const (&u, user);
1043 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
1045 dbus_set_error (error, DBUS_ERROR_FAILED,
1046 "User '%s' does not appear to exist?",
1051 /* If we were root */
1052 if (_dbus_geteuid () == 0)
1056 capng_clear (CAPNG_SELECT_BOTH);
1057 capng_update (CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
1059 rc = capng_change_id (uid, gid, 0);
1064 dbus_set_error (error, DBUS_ERROR_FAILED,
1065 "Failed to drop capabilities: %s\n",
1066 _dbus_strerror (errno));
1069 dbus_set_error (error, _dbus_error_from_errno (errno),
1070 "Failed to set GID to %lu: %s", gid,
1071 _dbus_strerror (errno));
1074 _dbus_warn ("Failed to drop supplementary groups: %s\n",
1075 _dbus_strerror (errno));
1078 dbus_set_error (error, _dbus_error_from_errno (errno),
1079 "Failed to set UID to %lu: %s", uid,
1080 _dbus_strerror (errno));
1083 dbus_set_error (error, _dbus_error_from_errno (errno),
1084 "Failed to unset keep-capabilities: %s\n",
1085 _dbus_strerror (errno));