1 /* -*- mode: C; c-file-style: "gnu" -*-
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"
35 #include <selinux/selinux.h>
36 #include <selinux/avc.h>
37 #include <selinux/av_permissions.h>
38 #include <selinux/flask.h>
43 #endif /* HAVE_LIBAUDIT */
44 #endif /* HAVE_SELINUX */
46 #define BUS_SID_FROM_SELINUX(sid) ((BusSELinuxID*) (sid))
47 #define SELINUX_SID_FROM_BUS(sid) ((security_id_t) (sid))
50 /* Store the value telling us if SELinux is enabled in the kernel. */
51 static dbus_bool_t selinux_enabled = FALSE;
53 /* Store an avc_entry_ref to speed AVC decisions. */
54 static struct avc_entry_ref aeref;
56 /* Store the SID of the bus itself to use as the default. */
57 static security_id_t bus_sid = SECSID_WILD;
59 /* Thread to listen for SELinux status changes via netlink. */
60 static pthread_t avc_notify_thread;
62 /* Prototypes for AVC callback functions. */
63 static void log_callback (const char *fmt, ...);
64 static void log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft);
65 static void *avc_create_thread (void (*run) (void));
66 static void avc_stop_thread (void *thread);
67 static void *avc_alloc_lock (void);
68 static void avc_get_lock (void *lock);
69 static void avc_release_lock (void *lock);
70 static void avc_free_lock (void *lock);
72 /* AVC callback structures for use in avc_init. */
73 static const struct avc_memory_callback mem_cb =
75 .func_malloc = dbus_malloc,
76 .func_free = dbus_free
78 static const struct avc_log_callback log_cb =
80 .func_log = log_callback,
81 .func_audit = log_audit_callback
83 static const struct avc_thread_callback thread_cb =
85 .func_create_thread = avc_create_thread,
86 .func_stop_thread = avc_stop_thread
88 static const struct avc_lock_callback lock_cb =
90 .func_alloc_lock = avc_alloc_lock,
91 .func_get_lock = avc_get_lock,
92 .func_release_lock = avc_release_lock,
93 .func_free_lock = avc_free_lock
95 #endif /* HAVE_SELINUX */
98 * Log callback to log denial messages from the AVC.
99 * This is used in avc_init. Logs to both standard
102 * @param fmt the format string
103 * @param variable argument list
108 static int audit_fd = -1;
115 audit_fd = audit_open ();
119 /* If kernel doesn't support audit, bail out */
120 if (errno == EINVAL || errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT)
122 /* If user bus, bail out */
123 if (errno == EPERM && getuid() != 0)
125 _dbus_warn ("Failed opening connection to the audit subsystem");
127 #endif /* HAVE_LIBAUDIT */
131 log_callback (const char *fmt, ...)
140 char buf[PATH_MAX*2];
142 /* FIXME: need to change this to show real user */
143 vsnprintf(buf, sizeof(buf), fmt, ap);
144 audit_log_user_avc_message(audit_fd, AUDIT_USER_AVC, buf, NULL, NULL,
148 #endif /* HAVE_LIBAUDIT */
150 vsyslog (LOG_INFO, fmt, ap);
155 * On a policy reload we need to reparse the SELinux configuration file, since
156 * this could have changed. Send a SIGHUP to reload all configs.
159 policy_reload_callback (u_int32_t event, security_id_t ssid,
160 security_id_t tsid, security_class_t tclass,
161 access_vector_t perms, access_vector_t *out_retained)
163 if (event == AVC_CALLBACK_RESET)
164 return raise (SIGHUP);
170 * Log any auxiliary data
173 log_audit_callback (void *data, security_class_t class, char *buf, size_t bufleft)
175 DBusString *audmsg = data;
176 _dbus_string_copy_to_buffer (audmsg, buf, bufleft);
180 * Create thread to notify the AVC of enforcing and policy reload
181 * changes via netlink.
183 * @param run the thread run function
184 * @return pointer to the thread
187 avc_create_thread (void (*run) (void))
191 rc = pthread_create (&avc_notify_thread, NULL, (void *(*) (void *)) run, NULL);
194 _dbus_warn ("Failed to start AVC thread: %s\n", _dbus_strerror (rc));
197 return &avc_notify_thread;
200 /* Stop AVC netlink thread. */
202 avc_stop_thread (void *thread)
204 pthread_cancel (*(pthread_t *) thread);
207 /* Allocate a new AVC lock. */
209 avc_alloc_lock (void)
211 pthread_mutex_t *avc_mutex;
213 avc_mutex = dbus_new (pthread_mutex_t, 1);
214 if (avc_mutex == NULL)
216 _dbus_warn ("Could not create mutex: %s\n", _dbus_strerror (errno));
219 pthread_mutex_init (avc_mutex, NULL);
224 /* Acquire an AVC lock. */
226 avc_get_lock (void *lock)
228 pthread_mutex_lock (lock);
231 /* Release an AVC lock. */
233 avc_release_lock (void *lock)
235 pthread_mutex_unlock (lock);
238 /* Free an AVC lock. */
240 avc_free_lock (void *lock)
242 pthread_mutex_destroy (lock);
245 #endif /* HAVE_SELINUX */
248 * Return whether or not SELinux is enabled; must be
249 * called after bus_selinux_init.
252 bus_selinux_enabled (void)
255 return selinux_enabled;
258 #endif /* HAVE_SELINUX */
262 * Do early initialization; determine whether SELinux is enabled.
265 bus_selinux_pre_init (void)
269 _dbus_assert (bus_sid == SECSID_WILD);
271 /* Determine if we are running an SELinux kernel. */
272 r = is_selinux_enabled ();
275 _dbus_warn ("Could not tell if SELinux is enabled: %s\n",
276 _dbus_strerror (errno));
280 selinux_enabled = r != 0;
288 * Initialize the user space access vector cache (AVC) for D-Bus and set up
292 bus_selinux_full_init (void)
297 _dbus_assert (bus_sid == SECSID_WILD);
299 if (!selinux_enabled)
301 _dbus_verbose ("SELinux not enabled in this kernel.\n");
305 _dbus_verbose ("SELinux is enabled in this kernel.\n");
307 avc_entry_ref_init (&aeref);
308 if (avc_init ("avc", &mem_cb, &log_cb, &thread_cb, &lock_cb) < 0)
310 _dbus_warn ("Failed to start Access Vector Cache (AVC).\n");
315 openlog ("dbus", LOG_PERROR, LOG_USER);
316 _dbus_verbose ("Access Vector Cache (AVC) started.\n");
319 if (avc_add_callback (policy_reload_callback, AVC_CALLBACK_RESET,
320 NULL, NULL, 0, 0) < 0)
322 _dbus_warn ("Failed to add policy reload callback: %s\n",
323 _dbus_strerror (errno));
329 bus_sid = SECSID_WILD;
331 if (getcon (&bus_context) < 0)
333 _dbus_verbose ("Error getting context of bus: %s\n",
334 _dbus_strerror (errno));
338 if (avc_context_to_sid (bus_context, &bus_sid) < 0)
340 _dbus_verbose ("Error getting SID from bus context: %s\n",
341 _dbus_strerror (errno));
342 freecon (bus_context);
346 freecon (bus_context);
353 #endif /* HAVE_SELINUX */
357 * Decrement SID reference count.
359 * @param sid the SID to decrement
362 bus_selinux_id_unref (BusSELinuxID *sid)
365 if (!selinux_enabled)
368 _dbus_assert (sid != NULL);
370 sidput (SELINUX_SID_FROM_BUS (sid));
371 #endif /* HAVE_SELINUX */
375 bus_selinux_id_ref (BusSELinuxID *sid)
378 if (!selinux_enabled)
381 _dbus_assert (sid != NULL);
383 sidget (SELINUX_SID_FROM_BUS (sid));
384 #endif /* HAVE_SELINUX */
388 * Determine if the SELinux security policy allows the given sender
389 * security context to go to the given recipient security context.
390 * This function determines if the requested permissions are to be
391 * granted from the connection to the message bus or to another
392 * optionally supplied security identifier (e.g. for a service
393 * context). Currently these permissions are either send_msg or
394 * acquire_svc in the dbus class.
396 * @param sender_sid source security context
397 * @param override_sid is the target security context. If SECSID_WILD this will
398 * use the context of the bus itself (e.g. the default).
399 * @param target_class is the target security class.
400 * @param requested is the requested permissions.
401 * @returns #TRUE if security policy allows the send.
405 bus_selinux_check (BusSELinuxID *sender_sid,
406 BusSELinuxID *override_sid,
407 security_class_t target_class,
408 access_vector_t requested,
411 if (!selinux_enabled)
414 /* Make the security check. AVC checks enforcing mode here as well. */
415 if (avc_has_perm (SELINUX_SID_FROM_BUS (sender_sid),
417 SELINUX_SID_FROM_BUS (override_sid) :
418 SELINUX_SID_FROM_BUS (bus_sid),
419 target_class, requested, &aeref, auxdata) < 0)
421 _dbus_verbose ("SELinux denying due to security policy.\n");
427 #endif /* HAVE_SELINUX */
430 * Returns true if the given connection can acquire a service,
431 * assuming the given security ID is needed for that service.
433 * @param connection connection that wants to own the service
434 * @param service_sid the SID of the service from the table
435 * @returns #TRUE if acquire is permitted.
438 bus_selinux_allows_acquire_service (DBusConnection *connection,
439 BusSELinuxID *service_sid,
440 const char *service_name,
444 BusSELinuxID *connection_sid;
449 if (!selinux_enabled)
452 connection_sid = bus_connection_get_selinux_id (connection);
453 if (!dbus_connection_get_unix_process_id (connection, &spid))
456 if (!_dbus_string_init (&auxdata))
459 if (!_dbus_string_append (&auxdata, "service="))
462 if (!_dbus_string_append (&auxdata, service_name))
467 if (!_dbus_string_append (&auxdata, " spid="))
470 if (!_dbus_string_append_uint (&auxdata, spid))
474 ret = bus_selinux_check (connection_sid,
480 _dbus_string_free (&auxdata);
484 _dbus_string_free (&auxdata);
490 #endif /* HAVE_SELINUX */
494 * Check if SELinux security controls allow the message to be sent to a
495 * particular connection based on the security context of the sender and
496 * that of the receiver. The destination connection need not be the
497 * addressed recipient, it could be an "eavesdropper"
499 * @param sender the sender of the message.
500 * @param proposed_recipient the connection the message is to be sent to.
501 * @returns whether to allow the send
504 bus_selinux_allows_send (DBusConnection *sender,
505 DBusConnection *proposed_recipient,
507 const char *interface,
509 const char *error_name,
510 const char *destination,
514 BusSELinuxID *recipient_sid;
515 BusSELinuxID *sender_sid;
516 unsigned long spid, tpid;
519 dbus_bool_t string_alloced;
521 if (!selinux_enabled)
524 if (!sender || !dbus_connection_get_unix_process_id (sender, &spid))
526 if (!proposed_recipient || !dbus_connection_get_unix_process_id (proposed_recipient, &tpid))
529 string_alloced = FALSE;
530 if (!_dbus_string_init (&auxdata))
532 string_alloced = TRUE;
534 if (!_dbus_string_append (&auxdata, "msgtype="))
537 if (!_dbus_string_append (&auxdata, msgtype))
542 if (!_dbus_string_append (&auxdata, " interface="))
544 if (!_dbus_string_append (&auxdata, interface))
550 if (!_dbus_string_append (&auxdata, " member="))
552 if (!_dbus_string_append (&auxdata, member))
558 if (!_dbus_string_append (&auxdata, " error_name="))
560 if (!_dbus_string_append (&auxdata, error_name))
566 if (!_dbus_string_append (&auxdata, " dest="))
568 if (!_dbus_string_append (&auxdata, destination))
574 if (!_dbus_string_append (&auxdata, " spid="))
577 if (!_dbus_string_append_uint (&auxdata, spid))
583 if (!_dbus_string_append (&auxdata, " tpid="))
586 if (!_dbus_string_append_uint (&auxdata, tpid))
590 sender_sid = bus_connection_get_selinux_id (sender);
591 /* A NULL proposed_recipient means the bus itself. */
592 if (proposed_recipient)
593 recipient_sid = bus_connection_get_selinux_id (proposed_recipient);
595 recipient_sid = BUS_SID_FROM_SELINUX (bus_sid);
597 ret = bus_selinux_check (sender_sid,
603 _dbus_string_free (&auxdata);
609 _dbus_string_free (&auxdata);
615 #endif /* HAVE_SELINUX */
619 bus_selinux_append_context (DBusMessage *message,
626 if (avc_sid_to_context (SELINUX_SID_FROM_BUS (sid), &context) < 0)
631 dbus_set_error (error, DBUS_ERROR_FAILED,
632 "Error getting context from SID: %s\n",
633 _dbus_strerror (errno));
636 if (!dbus_message_append_args (message,
643 _DBUS_SET_OOM (error);
654 * Gets the security context of a connection to the bus. It is up to
655 * the caller to freecon() when they are done.
657 * @param connection the connection to get the context of.
658 * @param con the location to store the security context.
659 * @returns #TRUE if context is successfully obtained.
663 bus_connection_read_selinux_context (DBusConnection *connection,
668 if (!selinux_enabled)
671 _dbus_assert (connection != NULL);
673 if (!dbus_connection_get_unix_fd (connection, &fd))
675 _dbus_verbose ("Failed to get file descriptor of socket.\n");
679 if (getpeercon (fd, con) < 0)
681 _dbus_verbose ("Error getting context of socket peer: %s\n",
682 _dbus_strerror (errno));
686 _dbus_verbose ("Successfully read connection context.\n");
689 #endif /* HAVE_SELINUX */
692 * Read the SELinux ID from the connection.
694 * @param connection the connection to read from
695 * @returns the SID if successfully determined, #NULL otherwise.
698 bus_selinux_init_connection_id (DBusConnection *connection,
705 if (!selinux_enabled)
708 if (!bus_connection_read_selinux_context (connection, &con))
710 dbus_set_error (error, DBUS_ERROR_FAILED,
711 "Failed to read an SELinux context from connection");
712 _dbus_verbose ("Error getting peer context.\n");
716 _dbus_verbose ("Converting context to SID to store on connection\n");
718 if (avc_context_to_sid (con, &sid) < 0)
723 dbus_set_error (error, DBUS_ERROR_FAILED,
724 "Error getting SID from context \"%s\": %s\n",
725 con, _dbus_strerror (errno));
727 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
728 con, _dbus_strerror (errno));
735 return BUS_SID_FROM_SELINUX (sid);
738 #endif /* HAVE_SELINUX */
743 * Function for freeing hash table data. These SIDs
744 * should no longer be referenced.
747 bus_selinux_id_table_free_value (BusSELinuxID *sid)
750 /* NULL sometimes due to how DBusHashTable works */
752 bus_selinux_id_unref (sid);
753 #endif /* HAVE_SELINUX */
757 * Creates a new table mapping service names to security ID.
758 * A security ID is a "compiled" security context, a security
759 * context is just a string.
761 * @returns the new table or #NULL if no memory
764 bus_selinux_id_table_new (void)
766 return _dbus_hash_table_new (DBUS_HASH_STRING,
767 (DBusFreeFunction) dbus_free,
768 (DBusFreeFunction) bus_selinux_id_table_free_value);
772 * Hashes a service name and service context into the service SID
773 * table as a string and a SID.
775 * @param service_name is the name of the service.
776 * @param service_context is the context of the service.
777 * @param service_table is the table to hash them into.
778 * @return #FALSE if not enough memory
781 bus_selinux_id_table_insert (DBusHashTable *service_table,
782 const char *service_name,
783 const char *service_context)
790 if (!selinux_enabled)
796 key = _dbus_strdup (service_name);
800 if (avc_context_to_sid ((char *) service_context, &sid) < 0)
808 _dbus_warn ("Error getting SID from context \"%s\": %s\n",
809 (char *) service_context,
810 _dbus_strerror (errno));
814 if (!_dbus_hash_table_insert_string (service_table,
816 BUS_SID_FROM_SELINUX (sid)))
819 _dbus_verbose ("Parsed \tservice: %s \n\t\tcontext: %s\n",
823 /* These are owned by the hash, so clear them to avoid unref */
830 if (sid != SECSID_WILD)
839 #endif /* HAVE_SELINUX */
844 * Find the security identifier associated with a particular service
845 * name. Return a pointer to this SID, or #NULL/SECSID_WILD if the
846 * service is not found in the hash table. This should be nearly a
847 * constant time operation. If SELinux support is not available,
848 * always return NULL.
850 * @param service_table the hash table to check for service name.
851 * @param service_name the name of the service to look for.
852 * @returns the SELinux ID associated with the service
855 bus_selinux_id_table_lookup (DBusHashTable *service_table,
856 const DBusString *service_name)
861 sid = SECSID_WILD; /* default context */
863 if (!selinux_enabled)
866 _dbus_verbose ("Looking up service SID for %s\n",
867 _dbus_string_get_const_data (service_name));
869 sid = _dbus_hash_table_lookup_string (service_table,
870 _dbus_string_get_const_data (service_name));
872 if (sid == SECSID_WILD)
873 _dbus_verbose ("Service %s not found\n",
874 _dbus_string_get_const_data (service_name));
876 _dbus_verbose ("Service %s found\n",
877 _dbus_string_get_const_data (service_name));
879 return BUS_SID_FROM_SELINUX (sid);
880 #endif /* HAVE_SELINUX */
885 * Get the SELinux policy root. This is used to find the D-Bus
886 * specific config file within the policy.
889 bus_selinux_get_policy_root (void)
892 return selinux_policy_root ();
895 #endif /* HAVE_SELINUX */
899 * For debugging: Print out the current hash table of service SIDs.
902 bus_selinux_id_table_print (DBusHashTable *service_table)
904 #ifdef DBUS_ENABLE_VERBOSE_MODE
908 if (!selinux_enabled)
911 _dbus_verbose ("Service SID Table:\n");
912 _dbus_hash_iter_init (service_table, &iter);
913 while (_dbus_hash_iter_next (&iter))
915 const char *key = _dbus_hash_iter_get_string_key (&iter);
916 security_id_t sid = _dbus_hash_iter_get_value (&iter);
917 _dbus_verbose ("The key is %s\n", key);
918 _dbus_verbose ("The context is %s\n", sid->ctx);
919 _dbus_verbose ("The refcount is %d\n", sid->refcnt);
921 #endif /* HAVE_SELINUX */
922 #endif /* DBUS_ENABLE_VERBOSE_MODE */
926 #ifdef DBUS_ENABLE_VERBOSE_MODE
929 * Print out some AVC statistics.
932 bus_avc_print_stats (void)
934 struct avc_cache_stats cstats;
936 if (!selinux_enabled)
939 _dbus_verbose ("AVC Statistics:\n");
940 avc_cache_stats (&cstats);
942 _dbus_verbose ("AVC Cache Statistics:\n");
943 _dbus_verbose ("Entry lookups: %d\n", cstats.entry_lookups);
944 _dbus_verbose ("Entry hits: %d\n", cstats.entry_hits);
945 _dbus_verbose ("Entry misses %d\n", cstats.entry_misses);
946 _dbus_verbose ("Entry discards: %d\n", cstats.entry_discards);
947 _dbus_verbose ("CAV lookups: %d\n", cstats.cav_lookups);
948 _dbus_verbose ("CAV hits: %d\n", cstats.cav_hits);
949 _dbus_verbose ("CAV probes: %d\n", cstats.cav_probes);
950 _dbus_verbose ("CAV misses: %d\n", cstats.cav_misses);
952 #endif /* HAVE_SELINUX */
953 #endif /* DBUS_ENABLE_VERBOSE_MODE */
957 * Destroy the AVC before we terminate.
960 bus_selinux_shutdown (void)
963 if (!selinux_enabled)
966 _dbus_verbose ("AVC shutdown\n");
968 if (bus_sid != SECSID_WILD)
971 bus_sid = SECSID_WILD;
973 #ifdef DBUS_ENABLE_VERBOSE_MODE
975 if (_dbus_is_verbose())
976 bus_avc_print_stats ();
978 #endif /* DBUS_ENABLE_VERBOSE_MODE */
982 audit_close (audit_fd);
983 #endif /* HAVE_LIBAUDIT */
985 #endif /* HAVE_SELINUX */